1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the PPCISelLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PPCISelLowering.h"
14 #include "MCTargetDesc/PPCPredicates.h"
15 #include "PPC.h"
16 #include "PPCCCState.h"
17 #include "PPCCallingConv.h"
18 #include "PPCFrameLowering.h"
19 #include "PPCInstrInfo.h"
20 #include "PPCMachineFunctionInfo.h"
21 #include "PPCPerfectShuffle.h"
22 #include "PPCRegisterInfo.h"
23 #include "PPCSubtarget.h"
24 #include "PPCTargetMachine.h"
25 #include "llvm/ADT/APFloat.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/None.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/CodeGen/CallingConvLower.h"
38 #include "llvm/CodeGen/ISDOpcodes.h"
39 #include "llvm/CodeGen/MachineBasicBlock.h"
40 #include "llvm/CodeGen/MachineFrameInfo.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineInstr.h"
43 #include "llvm/CodeGen/MachineInstrBuilder.h"
44 #include "llvm/CodeGen/MachineJumpTableInfo.h"
45 #include "llvm/CodeGen/MachineLoopInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineOperand.h"
48 #include "llvm/CodeGen/MachineRegisterInfo.h"
49 #include "llvm/CodeGen/RuntimeLibcalls.h"
50 #include "llvm/CodeGen/SelectionDAG.h"
51 #include "llvm/CodeGen/SelectionDAGNodes.h"
52 #include "llvm/CodeGen/TargetInstrInfo.h"
53 #include "llvm/CodeGen/TargetLowering.h"
54 #include "llvm/CodeGen/TargetRegisterInfo.h"
55 #include "llvm/CodeGen/ValueTypes.h"
56 #include "llvm/IR/CallSite.h"
57 #include "llvm/IR/CallingConv.h"
58 #include "llvm/IR/Constant.h"
59 #include "llvm/IR/Constants.h"
60 #include "llvm/IR/DataLayout.h"
61 #include "llvm/IR/DebugLoc.h"
62 #include "llvm/IR/DerivedTypes.h"
63 #include "llvm/IR/Function.h"
64 #include "llvm/IR/GlobalValue.h"
65 #include "llvm/IR/IRBuilder.h"
66 #include "llvm/IR/Instructions.h"
67 #include "llvm/IR/Intrinsics.h"
68 #include "llvm/IR/Module.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/IR/Use.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/MC/MCExpr.h"
73 #include "llvm/MC/MCRegisterInfo.h"
74 #include "llvm/Support/AtomicOrdering.h"
75 #include "llvm/Support/BranchProbability.h"
76 #include "llvm/Support/Casting.h"
77 #include "llvm/Support/CodeGen.h"
78 #include "llvm/Support/CommandLine.h"
79 #include "llvm/Support/Compiler.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/ErrorHandling.h"
82 #include "llvm/Support/Format.h"
83 #include "llvm/Support/KnownBits.h"
84 #include "llvm/Support/MachineValueType.h"
85 #include "llvm/Support/MathExtras.h"
86 #include "llvm/Support/raw_ostream.h"
87 #include "llvm/Target/TargetMachine.h"
88 #include "llvm/Target/TargetOptions.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstdint>
92 #include <iterator>
93 #include <list>
94 #include <utility>
95 #include <vector>
96 
97 using namespace llvm;
98 
99 #define DEBUG_TYPE "ppc-lowering"
100 
101 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
102 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
103 
104 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
105 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
106 
107 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
108 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
109 
110 static cl::opt<bool> DisableSCO("disable-ppc-sco",
111 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
112 
113 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
114 cl::desc("enable quad precision float support on ppc"), cl::Hidden);
115 
116 STATISTIC(NumTailCalls, "Number of tail calls");
117 STATISTIC(NumSiblingCalls, "Number of sibling calls");
118 
119 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
120 
121 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
122 
123 // FIXME: Remove this once the bug has been fixed!
124 extern cl::opt<bool> ANDIGlueBug;
125 
126 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
127                                      const PPCSubtarget &STI)
128     : TargetLowering(TM), Subtarget(STI) {
129   // Use _setjmp/_longjmp instead of setjmp/longjmp.
130   setUseUnderscoreSetJmp(true);
131   setUseUnderscoreLongJmp(true);
132 
133   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
134   // arguments are at least 4/8 bytes aligned.
135   bool isPPC64 = Subtarget.isPPC64();
136   setMinStackArgumentAlignment(isPPC64 ? 8:4);
137 
138   // Set up the register classes.
139   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
140   if (!useSoftFloat()) {
141     if (hasSPE()) {
142       addRegisterClass(MVT::f32, &PPC::SPE4RCRegClass);
143       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
144     } else {
145       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
146       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
147     }
148   }
149 
150   // Match BITREVERSE to customized fast code sequence in the td file.
151   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
152   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
153 
154   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
155   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
156 
157   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
158   for (MVT VT : MVT::integer_valuetypes()) {
159     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
160     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
161   }
162 
163   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
164 
165   // PowerPC has pre-inc load and store's.
166   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
167   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
168   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
169   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
170   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
171   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
172   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
173   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
174   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
175   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
176   if (!Subtarget.hasSPE()) {
177     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
178     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
179     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
180     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
181   }
182 
183   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
184   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
185   for (MVT VT : ScalarIntVTs) {
186     setOperationAction(ISD::ADDC, VT, Legal);
187     setOperationAction(ISD::ADDE, VT, Legal);
188     setOperationAction(ISD::SUBC, VT, Legal);
189     setOperationAction(ISD::SUBE, VT, Legal);
190   }
191 
192   if (Subtarget.useCRBits()) {
193     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
194 
195     if (isPPC64 || Subtarget.hasFPCVT()) {
196       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
197       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
198                          isPPC64 ? MVT::i64 : MVT::i32);
199       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
200       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
201                         isPPC64 ? MVT::i64 : MVT::i32);
202     } else {
203       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
204       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
205     }
206 
207     // PowerPC does not support direct load/store of condition registers.
208     setOperationAction(ISD::LOAD, MVT::i1, Custom);
209     setOperationAction(ISD::STORE, MVT::i1, Custom);
210 
211     // FIXME: Remove this once the ANDI glue bug is fixed:
212     if (ANDIGlueBug)
213       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
214 
215     for (MVT VT : MVT::integer_valuetypes()) {
216       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
217       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
218       setTruncStoreAction(VT, MVT::i1, Expand);
219     }
220 
221     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
222   }
223 
224   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
225   // PPC (the libcall is not available).
226   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
227   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
228 
229   // We do not currently implement these libm ops for PowerPC.
230   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
231   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
232   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
233   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
234   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
235   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
236 
237   // PowerPC has no SREM/UREM instructions unless we are on P9
238   // On P9 we may use a hardware instruction to compute the remainder.
239   // The instructions are not legalized directly because in the cases where the
240   // result of both the remainder and the division is required it is more
241   // efficient to compute the remainder from the result of the division rather
242   // than use the remainder instruction.
243   if (Subtarget.isISA3_0()) {
244     setOperationAction(ISD::SREM, MVT::i32, Custom);
245     setOperationAction(ISD::UREM, MVT::i32, Custom);
246     setOperationAction(ISD::SREM, MVT::i64, Custom);
247     setOperationAction(ISD::UREM, MVT::i64, Custom);
248   } else {
249     setOperationAction(ISD::SREM, MVT::i32, Expand);
250     setOperationAction(ISD::UREM, MVT::i32, Expand);
251     setOperationAction(ISD::SREM, MVT::i64, Expand);
252     setOperationAction(ISD::UREM, MVT::i64, Expand);
253   }
254 
255   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
256   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
257   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
258   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
259   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
260   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
261   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
262   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
263   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
264 
265   // We don't support sin/cos/sqrt/fmod/pow
266   setOperationAction(ISD::FSIN , MVT::f64, Expand);
267   setOperationAction(ISD::FCOS , MVT::f64, Expand);
268   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
269   setOperationAction(ISD::FREM , MVT::f64, Expand);
270   setOperationAction(ISD::FPOW , MVT::f64, Expand);
271   setOperationAction(ISD::FSIN , MVT::f32, Expand);
272   setOperationAction(ISD::FCOS , MVT::f32, Expand);
273   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
274   setOperationAction(ISD::FREM , MVT::f32, Expand);
275   setOperationAction(ISD::FPOW , MVT::f32, Expand);
276   if (Subtarget.hasSPE()) {
277     setOperationAction(ISD::FMA  , MVT::f64, Expand);
278     setOperationAction(ISD::FMA  , MVT::f32, Expand);
279   } else {
280     setOperationAction(ISD::FMA  , MVT::f64, Legal);
281     setOperationAction(ISD::FMA  , MVT::f32, Legal);
282   }
283 
284   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
285 
286   // If we're enabling GP optimizations, use hardware square root
287   if (!Subtarget.hasFSQRT() &&
288       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
289         Subtarget.hasFRE()))
290     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
291 
292   if (!Subtarget.hasFSQRT() &&
293       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
294         Subtarget.hasFRES()))
295     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
296 
297   if (Subtarget.hasFCPSGN()) {
298     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
299     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
300   } else {
301     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
302     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
303   }
304 
305   if (Subtarget.hasFPRND()) {
306     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
307     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
308     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
309     setOperationAction(ISD::FROUND, MVT::f64, Legal);
310 
311     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
312     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
313     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
314     setOperationAction(ISD::FROUND, MVT::f32, Legal);
315   }
316 
317   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
318   // to speed up scalar BSWAP64.
319   // CTPOP or CTTZ were introduced in P8/P9 respectively
320   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
321   if (Subtarget.hasP9Vector())
322     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
323   else
324     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
325   if (Subtarget.isISA3_0()) {
326     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
327     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
328   } else {
329     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
330     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
331   }
332 
333   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
334     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
335     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
336   } else {
337     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
338     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
339   }
340 
341   // PowerPC does not have ROTR
342   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
343   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
344 
345   if (!Subtarget.useCRBits()) {
346     // PowerPC does not have Select
347     setOperationAction(ISD::SELECT, MVT::i32, Expand);
348     setOperationAction(ISD::SELECT, MVT::i64, Expand);
349     setOperationAction(ISD::SELECT, MVT::f32, Expand);
350     setOperationAction(ISD::SELECT, MVT::f64, Expand);
351   }
352 
353   // PowerPC wants to turn select_cc of FP into fsel when possible.
354   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
355   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
356 
357   // PowerPC wants to optimize integer setcc a bit
358   if (!Subtarget.useCRBits())
359     setOperationAction(ISD::SETCC, MVT::i32, Custom);
360 
361   // PowerPC does not have BRCOND which requires SetCC
362   if (!Subtarget.useCRBits())
363     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
364 
365   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
366 
367   if (Subtarget.hasSPE()) {
368     // SPE has built-in conversions
369     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
370     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
371     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
372   } else {
373     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
374     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
375 
376     // PowerPC does not have [U|S]INT_TO_FP
377     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
378     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
379   }
380 
381   if (Subtarget.hasDirectMove() && isPPC64) {
382     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
383     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
384     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
385     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
386   } else {
387     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
388     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
389     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
390     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
391   }
392 
393   // We cannot sextinreg(i1).  Expand to shifts.
394   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
395 
396   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
397   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
398   // support continuation, user-level threading, and etc.. As a result, no
399   // other SjLj exception interfaces are implemented and please don't build
400   // your own exception handling based on them.
401   // LLVM/Clang supports zero-cost DWARF exception handling.
402   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
403   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
404 
405   // We want to legalize GlobalAddress and ConstantPool nodes into the
406   // appropriate instructions to materialize the address.
407   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
408   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
409   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
410   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
411   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
412   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
413   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
414   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
415   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
416   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
417 
418   // TRAP is legal.
419   setOperationAction(ISD::TRAP, MVT::Other, Legal);
420 
421   // TRAMPOLINE is custom lowered.
422   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
423   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
424 
425   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
426   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
427 
428   if (Subtarget.isSVR4ABI()) {
429     if (isPPC64) {
430       // VAARG always uses double-word chunks, so promote anything smaller.
431       setOperationAction(ISD::VAARG, MVT::i1, Promote);
432       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
433       setOperationAction(ISD::VAARG, MVT::i8, Promote);
434       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
435       setOperationAction(ISD::VAARG, MVT::i16, Promote);
436       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
437       setOperationAction(ISD::VAARG, MVT::i32, Promote);
438       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
439       setOperationAction(ISD::VAARG, MVT::Other, Expand);
440     } else {
441       // VAARG is custom lowered with the 32-bit SVR4 ABI.
442       setOperationAction(ISD::VAARG, MVT::Other, Custom);
443       setOperationAction(ISD::VAARG, MVT::i64, Custom);
444     }
445   } else
446     setOperationAction(ISD::VAARG, MVT::Other, Expand);
447 
448   if (Subtarget.isSVR4ABI() && !isPPC64)
449     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
450     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
451   else
452     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
453 
454   // Use the default implementation.
455   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
456   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
457   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
458   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
459   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
460   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
461   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
462   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
463   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
464 
465   // We want to custom lower some of our intrinsics.
466   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
467 
468   // To handle counter-based loop conditions.
469   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
470 
471   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
472   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
473   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
474   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
475 
476   // Comparisons that require checking two conditions.
477   if (Subtarget.hasSPE()) {
478     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
479     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
480     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
481     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
482   }
483   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
484   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
485   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
486   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
487   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
488   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
489   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
490   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
491   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
492   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
493   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
494   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
495 
496   if (Subtarget.has64BitSupport()) {
497     // They also have instructions for converting between i64 and fp.
498     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
499     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
500     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
501     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
502     // This is just the low 32 bits of a (signed) fp->i64 conversion.
503     // We cannot do this with Promote because i64 is not a legal type.
504     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
505 
506     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
507       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
508   } else {
509     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
510     if (Subtarget.hasSPE())
511       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
512     else
513       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
514   }
515 
516   // With the instructions enabled under FPCVT, we can do everything.
517   if (Subtarget.hasFPCVT()) {
518     if (Subtarget.has64BitSupport()) {
519       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
520       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
521       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
522       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
523     }
524 
525     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
526     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
527     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
528     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
529   }
530 
531   if (Subtarget.use64BitRegs()) {
532     // 64-bit PowerPC implementations can support i64 types directly
533     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
534     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
535     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
536     // 64-bit PowerPC wants to expand i128 shifts itself.
537     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
538     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
539     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
540   } else {
541     // 32-bit PowerPC wants to expand i64 shifts itself.
542     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
543     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
544     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
545   }
546 
547   if (Subtarget.hasAltivec()) {
548     // First set operation action for all vector types to expand. Then we
549     // will selectively turn on ones that can be effectively codegen'd.
550     for (MVT VT : MVT::vector_valuetypes()) {
551       // add/sub are legal for all supported vector VT's.
552       setOperationAction(ISD::ADD, VT, Legal);
553       setOperationAction(ISD::SUB, VT, Legal);
554 
555       // Vector instructions introduced in P8
556       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
557         setOperationAction(ISD::CTPOP, VT, Legal);
558         setOperationAction(ISD::CTLZ, VT, Legal);
559       }
560       else {
561         setOperationAction(ISD::CTPOP, VT, Expand);
562         setOperationAction(ISD::CTLZ, VT, Expand);
563       }
564 
565       // Vector instructions introduced in P9
566       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
567         setOperationAction(ISD::CTTZ, VT, Legal);
568       else
569         setOperationAction(ISD::CTTZ, VT, Expand);
570 
571       // We promote all shuffles to v16i8.
572       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
573       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
574 
575       // We promote all non-typed operations to v4i32.
576       setOperationAction(ISD::AND   , VT, Promote);
577       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
578       setOperationAction(ISD::OR    , VT, Promote);
579       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
580       setOperationAction(ISD::XOR   , VT, Promote);
581       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
582       setOperationAction(ISD::LOAD  , VT, Promote);
583       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
584       setOperationAction(ISD::SELECT, VT, Promote);
585       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
586       setOperationAction(ISD::VSELECT, VT, Legal);
587       setOperationAction(ISD::SELECT_CC, VT, Promote);
588       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
589       setOperationAction(ISD::STORE, VT, Promote);
590       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
591 
592       // No other operations are legal.
593       setOperationAction(ISD::MUL , VT, Expand);
594       setOperationAction(ISD::SDIV, VT, Expand);
595       setOperationAction(ISD::SREM, VT, Expand);
596       setOperationAction(ISD::UDIV, VT, Expand);
597       setOperationAction(ISD::UREM, VT, Expand);
598       setOperationAction(ISD::FDIV, VT, Expand);
599       setOperationAction(ISD::FREM, VT, Expand);
600       setOperationAction(ISD::FNEG, VT, Expand);
601       setOperationAction(ISD::FSQRT, VT, Expand);
602       setOperationAction(ISD::FLOG, VT, Expand);
603       setOperationAction(ISD::FLOG10, VT, Expand);
604       setOperationAction(ISD::FLOG2, VT, Expand);
605       setOperationAction(ISD::FEXP, VT, Expand);
606       setOperationAction(ISD::FEXP2, VT, Expand);
607       setOperationAction(ISD::FSIN, VT, Expand);
608       setOperationAction(ISD::FCOS, VT, Expand);
609       setOperationAction(ISD::FABS, VT, Expand);
610       setOperationAction(ISD::FFLOOR, VT, Expand);
611       setOperationAction(ISD::FCEIL,  VT, Expand);
612       setOperationAction(ISD::FTRUNC, VT, Expand);
613       setOperationAction(ISD::FRINT,  VT, Expand);
614       setOperationAction(ISD::FNEARBYINT, VT, Expand);
615       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
616       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
617       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
618       setOperationAction(ISD::MULHU, VT, Expand);
619       setOperationAction(ISD::MULHS, VT, Expand);
620       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
621       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
622       setOperationAction(ISD::UDIVREM, VT, Expand);
623       setOperationAction(ISD::SDIVREM, VT, Expand);
624       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
625       setOperationAction(ISD::FPOW, VT, Expand);
626       setOperationAction(ISD::BSWAP, VT, Expand);
627       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
628       setOperationAction(ISD::ROTL, VT, Expand);
629       setOperationAction(ISD::ROTR, VT, Expand);
630 
631       for (MVT InnerVT : MVT::vector_valuetypes()) {
632         setTruncStoreAction(VT, InnerVT, Expand);
633         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
634         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
635         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
636       }
637     }
638 
639     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
640       setOperationAction(ISD::ABS, VT, Custom);
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     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
647     // are cheap, so handle them before they get expanded to scalar.
648     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
649     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
650     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
651     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
652     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
653 
654     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
655     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
656     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
657     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
658     setOperationAction(ISD::SELECT, MVT::v4i32,
659                        Subtarget.useCRBits() ? Legal : Expand);
660     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
661     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
662     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
663     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
664     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
665     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
666     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
667     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
668     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
669 
670     // Without hasP8Altivec set, v2i64 SMAX isn't available.
671     // But ABS custom lowering requires SMAX support.
672     if (!Subtarget.hasP8Altivec())
673       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
674 
675     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
676     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
677     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
678     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
679 
680     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
681     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
682 
683     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
684       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
685       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
686     }
687 
688     if (Subtarget.hasP8Altivec())
689       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
690     else
691       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
692 
693     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
694     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
695 
696     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
697     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
698 
699     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
700     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
701     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
702     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
703 
704     // Altivec does not contain unordered floating-point compare instructions
705     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
706     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
707     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
708     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
709 
710     if (Subtarget.hasVSX()) {
711       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
712       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
713       if (Subtarget.hasP8Vector()) {
714         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
715         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
716       }
717       if (Subtarget.hasDirectMove() && isPPC64) {
718         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
719         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
720         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
721         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
722         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
723         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
724         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
725         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
726       }
727       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
728 
729       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
730       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
731       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
732       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
733       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
734 
735       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
736 
737       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
738       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
739 
740       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
741       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
742 
743       // Share the Altivec comparison restrictions.
744       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
745       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
746       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
747       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
748 
749       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
750       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
751 
752       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
753 
754       if (Subtarget.hasP8Vector())
755         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
756 
757       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
758 
759       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
760       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
761       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
762 
763       if (Subtarget.hasP8Altivec()) {
764         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
765         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
766         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
767 
768         // 128 bit shifts can be accomplished via 3 instructions for SHL and
769         // SRL, but not for SRA because of the instructions available:
770         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
771         // doing
772         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
773         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
774         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
775 
776         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
777       }
778       else {
779         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
780         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
781         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
782 
783         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
784 
785         // VSX v2i64 only supports non-arithmetic operations.
786         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
787         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
788       }
789 
790       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
791       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
792       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
793       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
794 
795       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
796 
797       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
798       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
799       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
800       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
801 
802       // Custom handling for partial vectors of integers converted to
803       // floating point. We already have optimal handling for v2i32 through
804       // the DAG combine, so those aren't necessary.
805       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
806       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
807       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
808       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
809       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
810       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
811       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
812       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
813 
814       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
815       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
816       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
817       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
818 
819       if (Subtarget.hasDirectMove())
820         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
821       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
822 
823       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
824     }
825 
826     if (Subtarget.hasP8Altivec()) {
827       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
828       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
829     }
830 
831     if (Subtarget.hasP9Vector()) {
832       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
833       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
834 
835       // 128 bit shifts can be accomplished via 3 instructions for SHL and
836       // SRL, but not for SRA because of the instructions available:
837       // VS{RL} and VS{RL}O.
838       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
839       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
840       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
841 
842       if (EnableQuadPrecision) {
843         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
844         setOperationAction(ISD::FADD, MVT::f128, Legal);
845         setOperationAction(ISD::FSUB, MVT::f128, Legal);
846         setOperationAction(ISD::FDIV, MVT::f128, Legal);
847         setOperationAction(ISD::FMUL, MVT::f128, Legal);
848         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
849         // No extending loads to f128 on PPC.
850         for (MVT FPT : MVT::fp_valuetypes())
851           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
852         setOperationAction(ISD::FMA, MVT::f128, Legal);
853         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
854         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
855         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
856         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
857         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
858         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
859 
860         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
861         setOperationAction(ISD::FRINT, MVT::f128, Legal);
862         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
863         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
864         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
865         setOperationAction(ISD::FROUND, MVT::f128, Legal);
866 
867         setOperationAction(ISD::SELECT, MVT::f128, Expand);
868         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
869         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
870         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
871         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
872         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
873         // No implementation for these ops for PowerPC.
874         setOperationAction(ISD::FSIN , MVT::f128, Expand);
875         setOperationAction(ISD::FCOS , MVT::f128, Expand);
876         setOperationAction(ISD::FPOW, MVT::f128, Expand);
877         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
878         setOperationAction(ISD::FREM, MVT::f128, Expand);
879       }
880       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
881 
882     }
883 
884     if (Subtarget.hasP9Altivec()) {
885       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
886       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
887     }
888   }
889 
890   if (Subtarget.hasQPX()) {
891     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
892     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
893     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
894     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
895 
896     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
897     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
898 
899     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
900     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
901 
902     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
903     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
904 
905     if (!Subtarget.useCRBits())
906       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
907     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
908 
909     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
910     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
911     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
912     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
913     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
914     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
915     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
916 
917     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
918     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
919 
920     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
921     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
922     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
923 
924     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
925     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
926     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
927     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
928     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
929     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
930     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
931     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
932     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
933     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
934 
935     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
936     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
937 
938     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
939     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
940 
941     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
942 
943     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
944     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
945     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
946     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
947 
948     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
949     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
950 
951     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
952     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
953 
954     if (!Subtarget.useCRBits())
955       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
956     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
957 
958     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
959     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
960     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
961     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
962     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
963     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
964     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
965 
966     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
967     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
968 
969     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
970     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
971     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
972     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
973     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
974     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
975     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
976     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
977     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
978     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
979 
980     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
981     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
982 
983     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
984     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
985 
986     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
987 
988     setOperationAction(ISD::AND , MVT::v4i1, Legal);
989     setOperationAction(ISD::OR , MVT::v4i1, Legal);
990     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
991 
992     if (!Subtarget.useCRBits())
993       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
994     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
995 
996     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
997     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
998 
999     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1000     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1001     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1002     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1003     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1004     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1005     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1006 
1007     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1008     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1009 
1010     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1011 
1012     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1013     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1014     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1015     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1016 
1017     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1018     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1019     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1020     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1021 
1022     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1023     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1024 
1025     // These need to set FE_INEXACT, and so cannot be vectorized here.
1026     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1027     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1028 
1029     if (TM.Options.UnsafeFPMath) {
1030       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1031       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1032 
1033       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1034       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1035     } else {
1036       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1037       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1038 
1039       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1040       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1041     }
1042   }
1043 
1044   if (Subtarget.has64BitSupport())
1045     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1046 
1047   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1048 
1049   if (!isPPC64) {
1050     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1051     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1052   }
1053 
1054   setBooleanContents(ZeroOrOneBooleanContent);
1055 
1056   if (Subtarget.hasAltivec()) {
1057     // Altivec instructions set fields to all zeros or all ones.
1058     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1059   }
1060 
1061   if (!isPPC64) {
1062     // These libcalls are not available in 32-bit.
1063     setLibcallName(RTLIB::SHL_I128, nullptr);
1064     setLibcallName(RTLIB::SRL_I128, nullptr);
1065     setLibcallName(RTLIB::SRA_I128, nullptr);
1066   }
1067 
1068   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1069 
1070   // We have target-specific dag combine patterns for the following nodes:
1071   setTargetDAGCombine(ISD::ADD);
1072   setTargetDAGCombine(ISD::SHL);
1073   setTargetDAGCombine(ISD::SRA);
1074   setTargetDAGCombine(ISD::SRL);
1075   setTargetDAGCombine(ISD::MUL);
1076   setTargetDAGCombine(ISD::SINT_TO_FP);
1077   setTargetDAGCombine(ISD::BUILD_VECTOR);
1078   if (Subtarget.hasFPCVT())
1079     setTargetDAGCombine(ISD::UINT_TO_FP);
1080   setTargetDAGCombine(ISD::LOAD);
1081   setTargetDAGCombine(ISD::STORE);
1082   setTargetDAGCombine(ISD::BR_CC);
1083   if (Subtarget.useCRBits())
1084     setTargetDAGCombine(ISD::BRCOND);
1085   setTargetDAGCombine(ISD::BSWAP);
1086   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1087   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1088   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1089 
1090   setTargetDAGCombine(ISD::SIGN_EXTEND);
1091   setTargetDAGCombine(ISD::ZERO_EXTEND);
1092   setTargetDAGCombine(ISD::ANY_EXTEND);
1093 
1094   setTargetDAGCombine(ISD::TRUNCATE);
1095 
1096   if (Subtarget.useCRBits()) {
1097     setTargetDAGCombine(ISD::TRUNCATE);
1098     setTargetDAGCombine(ISD::SETCC);
1099     setTargetDAGCombine(ISD::SELECT_CC);
1100   }
1101 
1102   // Use reciprocal estimates.
1103   if (TM.Options.UnsafeFPMath) {
1104     setTargetDAGCombine(ISD::FDIV);
1105     setTargetDAGCombine(ISD::FSQRT);
1106   }
1107 
1108   if (Subtarget.hasP9Altivec()) {
1109     setTargetDAGCombine(ISD::ABS);
1110     setTargetDAGCombine(ISD::VSELECT);
1111   }
1112 
1113   // Darwin long double math library functions have $LDBL128 appended.
1114   if (Subtarget.isDarwin()) {
1115     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1116     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1117     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1118     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1119     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1120     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1121     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1122     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1123     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1124     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1125   }
1126 
1127   if (EnableQuadPrecision) {
1128     setLibcallName(RTLIB::LOG_F128, "logf128");
1129     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1130     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1131     setLibcallName(RTLIB::EXP_F128, "expf128");
1132     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1133     setLibcallName(RTLIB::SIN_F128, "sinf128");
1134     setLibcallName(RTLIB::COS_F128, "cosf128");
1135     setLibcallName(RTLIB::POW_F128, "powf128");
1136     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1137     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1138     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1139     setLibcallName(RTLIB::REM_F128, "fmodf128");
1140   }
1141 
1142   // With 32 condition bits, we don't need to sink (and duplicate) compares
1143   // aggressively in CodeGenPrep.
1144   if (Subtarget.useCRBits()) {
1145     setHasMultipleConditionRegisters();
1146     setJumpIsExpensive();
1147   }
1148 
1149   setMinFunctionAlignment(2);
1150   if (Subtarget.isDarwin())
1151     setPrefFunctionAlignment(4);
1152 
1153   switch (Subtarget.getDarwinDirective()) {
1154   default: break;
1155   case PPC::DIR_970:
1156   case PPC::DIR_A2:
1157   case PPC::DIR_E500:
1158   case PPC::DIR_E500mc:
1159   case PPC::DIR_E5500:
1160   case PPC::DIR_PWR4:
1161   case PPC::DIR_PWR5:
1162   case PPC::DIR_PWR5X:
1163   case PPC::DIR_PWR6:
1164   case PPC::DIR_PWR6X:
1165   case PPC::DIR_PWR7:
1166   case PPC::DIR_PWR8:
1167   case PPC::DIR_PWR9:
1168     setPrefFunctionAlignment(4);
1169     setPrefLoopAlignment(4);
1170     break;
1171   }
1172 
1173   if (Subtarget.enableMachineScheduler())
1174     setSchedulingPreference(Sched::Source);
1175   else
1176     setSchedulingPreference(Sched::Hybrid);
1177 
1178   computeRegisterProperties(STI.getRegisterInfo());
1179 
1180   // The Freescale cores do better with aggressive inlining of memcpy and
1181   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1182   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1183       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1184     MaxStoresPerMemset = 32;
1185     MaxStoresPerMemsetOptSize = 16;
1186     MaxStoresPerMemcpy = 32;
1187     MaxStoresPerMemcpyOptSize = 8;
1188     MaxStoresPerMemmove = 32;
1189     MaxStoresPerMemmoveOptSize = 8;
1190   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1191     // The A2 also benefits from (very) aggressive inlining of memcpy and
1192     // friends. The overhead of a the function call, even when warm, can be
1193     // over one hundred cycles.
1194     MaxStoresPerMemset = 128;
1195     MaxStoresPerMemcpy = 128;
1196     MaxStoresPerMemmove = 128;
1197     MaxLoadsPerMemcmp = 128;
1198   } else {
1199     MaxLoadsPerMemcmp = 8;
1200     MaxLoadsPerMemcmpOptSize = 4;
1201   }
1202 }
1203 
1204 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1205 /// the desired ByVal argument alignment.
1206 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1207                              unsigned MaxMaxAlign) {
1208   if (MaxAlign == MaxMaxAlign)
1209     return;
1210   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1211     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1212       MaxAlign = 32;
1213     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1214       MaxAlign = 16;
1215   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1216     unsigned EltAlign = 0;
1217     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1218     if (EltAlign > MaxAlign)
1219       MaxAlign = EltAlign;
1220   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1221     for (auto *EltTy : STy->elements()) {
1222       unsigned EltAlign = 0;
1223       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1224       if (EltAlign > MaxAlign)
1225         MaxAlign = EltAlign;
1226       if (MaxAlign == MaxMaxAlign)
1227         break;
1228     }
1229   }
1230 }
1231 
1232 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1233 /// function arguments in the caller parameter area.
1234 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1235                                                   const DataLayout &DL) const {
1236   // Darwin passes everything on 4 byte boundary.
1237   if (Subtarget.isDarwin())
1238     return 4;
1239 
1240   // 16byte and wider vectors are passed on 16byte boundary.
1241   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1242   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1243   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1244     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1245   return Align;
1246 }
1247 
1248 unsigned PPCTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1249                                                           CallingConv:: ID CC,
1250                                                           EVT VT) const {
1251   if (Subtarget.hasSPE() && VT == MVT::f64)
1252     return 2;
1253   return PPCTargetLowering::getNumRegisters(Context, VT);
1254 }
1255 
1256 MVT PPCTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1257                                                      CallingConv:: ID CC,
1258                                                      EVT VT) const {
1259   if (Subtarget.hasSPE() && VT == MVT::f64)
1260     return MVT::i32;
1261   return PPCTargetLowering::getRegisterType(Context, VT);
1262 }
1263 
1264 bool PPCTargetLowering::useSoftFloat() const {
1265   return Subtarget.useSoftFloat();
1266 }
1267 
1268 bool PPCTargetLowering::hasSPE() const {
1269   return Subtarget.hasSPE();
1270 }
1271 
1272 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1273   switch ((PPCISD::NodeType)Opcode) {
1274   case PPCISD::FIRST_NUMBER:    break;
1275   case PPCISD::FSEL:            return "PPCISD::FSEL";
1276   case PPCISD::FCFID:           return "PPCISD::FCFID";
1277   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1278   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1279   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1280   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1281   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1282   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1283   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1284   case PPCISD::FP_TO_UINT_IN_VSR:
1285                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1286   case PPCISD::FP_TO_SINT_IN_VSR:
1287                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1288   case PPCISD::FRE:             return "PPCISD::FRE";
1289   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1290   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1291   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1292   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1293   case PPCISD::VPERM:           return "PPCISD::VPERM";
1294   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1295   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1296   case PPCISD::XXREVERSE:       return "PPCISD::XXREVERSE";
1297   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1298   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1299   case PPCISD::CMPB:            return "PPCISD::CMPB";
1300   case PPCISD::Hi:              return "PPCISD::Hi";
1301   case PPCISD::Lo:              return "PPCISD::Lo";
1302   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1303   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1304   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1305   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1306   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1307   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1308   case PPCISD::SRL:             return "PPCISD::SRL";
1309   case PPCISD::SRA:             return "PPCISD::SRA";
1310   case PPCISD::SHL:             return "PPCISD::SHL";
1311   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1312   case PPCISD::CALL:            return "PPCISD::CALL";
1313   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1314   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1315   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1316   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1317   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1318   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1319   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1320   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1321   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1322   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1323   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1324   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1325   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1326   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1327   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1328   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1329   case PPCISD::VCMP:            return "PPCISD::VCMP";
1330   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1331   case PPCISD::LBRX:            return "PPCISD::LBRX";
1332   case PPCISD::STBRX:           return "PPCISD::STBRX";
1333   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1334   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1335   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1336   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1337   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1338   case PPCISD::SExtVElems:      return "PPCISD::SExtVElems";
1339   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1340   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1341   case PPCISD::ST_VSR_SCAL_INT:
1342                                 return "PPCISD::ST_VSR_SCAL_INT";
1343   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1344   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1345   case PPCISD::BDZ:             return "PPCISD::BDZ";
1346   case PPCISD::MFFS:            return "PPCISD::MFFS";
1347   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1348   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1349   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1350   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1351   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1352   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1353   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1354   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1355   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1356   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1357   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1358   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1359   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1360   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1361   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1362   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1363   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1364   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1365   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1366   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1367   case PPCISD::SC:              return "PPCISD::SC";
1368   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1369   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1370   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1371   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1372   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1373   case PPCISD::VABSD:           return "PPCISD::VABSD";
1374   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1375   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1376   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1377   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1378   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1379   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1380   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1381   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1382   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1383   case PPCISD::FP_EXTEND_LH:    return "PPCISD::FP_EXTEND_LH";
1384   }
1385   return nullptr;
1386 }
1387 
1388 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1389                                           EVT VT) const {
1390   if (!VT.isVector())
1391     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1392 
1393   if (Subtarget.hasQPX())
1394     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1395 
1396   return VT.changeVectorElementTypeToInteger();
1397 }
1398 
1399 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1400   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1401   return true;
1402 }
1403 
1404 //===----------------------------------------------------------------------===//
1405 // Node matching predicates, for use by the tblgen matching code.
1406 //===----------------------------------------------------------------------===//
1407 
1408 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1409 static bool isFloatingPointZero(SDValue Op) {
1410   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1411     return CFP->getValueAPF().isZero();
1412   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1413     // Maybe this has already been legalized into the constant pool?
1414     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1415       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1416         return CFP->getValueAPF().isZero();
1417   }
1418   return false;
1419 }
1420 
1421 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1422 /// true if Op is undef or if it matches the specified value.
1423 static bool isConstantOrUndef(int Op, int Val) {
1424   return Op < 0 || Op == Val;
1425 }
1426 
1427 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1428 /// VPKUHUM instruction.
1429 /// The ShuffleKind distinguishes between big-endian operations with
1430 /// two different inputs (0), either-endian operations with two identical
1431 /// inputs (1), and little-endian operations with two different inputs (2).
1432 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1433 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1434                                SelectionDAG &DAG) {
1435   bool IsLE = DAG.getDataLayout().isLittleEndian();
1436   if (ShuffleKind == 0) {
1437     if (IsLE)
1438       return false;
1439     for (unsigned i = 0; i != 16; ++i)
1440       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1441         return false;
1442   } else if (ShuffleKind == 2) {
1443     if (!IsLE)
1444       return false;
1445     for (unsigned i = 0; i != 16; ++i)
1446       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1447         return false;
1448   } else if (ShuffleKind == 1) {
1449     unsigned j = IsLE ? 0 : 1;
1450     for (unsigned i = 0; i != 8; ++i)
1451       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1452           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1453         return false;
1454   }
1455   return true;
1456 }
1457 
1458 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1459 /// VPKUWUM instruction.
1460 /// The ShuffleKind distinguishes between big-endian operations with
1461 /// two different inputs (0), either-endian operations with two identical
1462 /// inputs (1), and little-endian operations with two different inputs (2).
1463 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1464 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1465                                SelectionDAG &DAG) {
1466   bool IsLE = DAG.getDataLayout().isLittleEndian();
1467   if (ShuffleKind == 0) {
1468     if (IsLE)
1469       return false;
1470     for (unsigned i = 0; i != 16; i += 2)
1471       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1472           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1473         return false;
1474   } else if (ShuffleKind == 2) {
1475     if (!IsLE)
1476       return false;
1477     for (unsigned i = 0; i != 16; i += 2)
1478       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1479           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1480         return false;
1481   } else if (ShuffleKind == 1) {
1482     unsigned j = IsLE ? 0 : 2;
1483     for (unsigned i = 0; i != 8; i += 2)
1484       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1485           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1486           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1487           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1488         return false;
1489   }
1490   return true;
1491 }
1492 
1493 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1494 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1495 /// current subtarget.
1496 ///
1497 /// The ShuffleKind distinguishes between big-endian operations with
1498 /// two different inputs (0), either-endian operations with two identical
1499 /// inputs (1), and little-endian operations with two different inputs (2).
1500 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1501 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1502                                SelectionDAG &DAG) {
1503   const PPCSubtarget& Subtarget =
1504     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1505   if (!Subtarget.hasP8Vector())
1506     return false;
1507 
1508   bool IsLE = DAG.getDataLayout().isLittleEndian();
1509   if (ShuffleKind == 0) {
1510     if (IsLE)
1511       return false;
1512     for (unsigned i = 0; i != 16; i += 4)
1513       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1514           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1515           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1516           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1517         return false;
1518   } else if (ShuffleKind == 2) {
1519     if (!IsLE)
1520       return false;
1521     for (unsigned i = 0; i != 16; i += 4)
1522       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1523           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1524           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1525           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1526         return false;
1527   } else if (ShuffleKind == 1) {
1528     unsigned j = IsLE ? 0 : 4;
1529     for (unsigned i = 0; i != 8; i += 4)
1530       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1531           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1532           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1533           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1534           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1535           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1536           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1537           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1538         return false;
1539   }
1540   return true;
1541 }
1542 
1543 /// isVMerge - Common function, used to match vmrg* shuffles.
1544 ///
1545 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1546                      unsigned LHSStart, unsigned RHSStart) {
1547   if (N->getValueType(0) != MVT::v16i8)
1548     return false;
1549   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1550          "Unsupported merge size!");
1551 
1552   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1553     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1554       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1555                              LHSStart+j+i*UnitSize) ||
1556           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1557                              RHSStart+j+i*UnitSize))
1558         return false;
1559     }
1560   return true;
1561 }
1562 
1563 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1564 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1565 /// The ShuffleKind distinguishes between big-endian merges with two
1566 /// different inputs (0), either-endian merges with two identical inputs (1),
1567 /// and little-endian merges with two different inputs (2).  For the latter,
1568 /// the input operands are swapped (see PPCInstrAltivec.td).
1569 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1570                              unsigned ShuffleKind, SelectionDAG &DAG) {
1571   if (DAG.getDataLayout().isLittleEndian()) {
1572     if (ShuffleKind == 1) // unary
1573       return isVMerge(N, UnitSize, 0, 0);
1574     else if (ShuffleKind == 2) // swapped
1575       return isVMerge(N, UnitSize, 0, 16);
1576     else
1577       return false;
1578   } else {
1579     if (ShuffleKind == 1) // unary
1580       return isVMerge(N, UnitSize, 8, 8);
1581     else if (ShuffleKind == 0) // normal
1582       return isVMerge(N, UnitSize, 8, 24);
1583     else
1584       return false;
1585   }
1586 }
1587 
1588 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1589 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1590 /// The ShuffleKind distinguishes between big-endian merges with two
1591 /// different inputs (0), either-endian merges with two identical inputs (1),
1592 /// and little-endian merges with two different inputs (2).  For the latter,
1593 /// the input operands are swapped (see PPCInstrAltivec.td).
1594 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1595                              unsigned ShuffleKind, SelectionDAG &DAG) {
1596   if (DAG.getDataLayout().isLittleEndian()) {
1597     if (ShuffleKind == 1) // unary
1598       return isVMerge(N, UnitSize, 8, 8);
1599     else if (ShuffleKind == 2) // swapped
1600       return isVMerge(N, UnitSize, 8, 24);
1601     else
1602       return false;
1603   } else {
1604     if (ShuffleKind == 1) // unary
1605       return isVMerge(N, UnitSize, 0, 0);
1606     else if (ShuffleKind == 0) // normal
1607       return isVMerge(N, UnitSize, 0, 16);
1608     else
1609       return false;
1610   }
1611 }
1612 
1613 /**
1614  * Common function used to match vmrgew and vmrgow shuffles
1615  *
1616  * The indexOffset determines whether to look for even or odd words in
1617  * the shuffle mask. This is based on the of the endianness of the target
1618  * machine.
1619  *   - Little Endian:
1620  *     - Use offset of 0 to check for odd elements
1621  *     - Use offset of 4 to check for even elements
1622  *   - Big Endian:
1623  *     - Use offset of 0 to check for even elements
1624  *     - Use offset of 4 to check for odd elements
1625  * A detailed description of the vector element ordering for little endian and
1626  * big endian can be found at
1627  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1628  * Targeting your applications - what little endian and big endian IBM XL C/C++
1629  * compiler differences mean to you
1630  *
1631  * The mask to the shuffle vector instruction specifies the indices of the
1632  * elements from the two input vectors to place in the result. The elements are
1633  * numbered in array-access order, starting with the first vector. These vectors
1634  * are always of type v16i8, thus each vector will contain 16 elements of size
1635  * 8. More info on the shuffle vector can be found in the
1636  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1637  * Language Reference.
1638  *
1639  * The RHSStartValue indicates whether the same input vectors are used (unary)
1640  * or two different input vectors are used, based on the following:
1641  *   - If the instruction uses the same vector for both inputs, the range of the
1642  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1643  *     be 0.
1644  *   - If the instruction has two different vectors then the range of the
1645  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1646  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1647  *     to 31 specify elements in the second vector).
1648  *
1649  * \param[in] N The shuffle vector SD Node to analyze
1650  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1651  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1652  * vector to the shuffle_vector instruction
1653  * \return true iff this shuffle vector represents an even or odd word merge
1654  */
1655 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1656                      unsigned RHSStartValue) {
1657   if (N->getValueType(0) != MVT::v16i8)
1658     return false;
1659 
1660   for (unsigned i = 0; i < 2; ++i)
1661     for (unsigned j = 0; j < 4; ++j)
1662       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1663                              i*RHSStartValue+j+IndexOffset) ||
1664           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1665                              i*RHSStartValue+j+IndexOffset+8))
1666         return false;
1667   return true;
1668 }
1669 
1670 /**
1671  * Determine if the specified shuffle mask is suitable for the vmrgew or
1672  * vmrgow instructions.
1673  *
1674  * \param[in] N The shuffle vector SD Node to analyze
1675  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1676  * \param[in] ShuffleKind Identify the type of merge:
1677  *   - 0 = big-endian merge with two different inputs;
1678  *   - 1 = either-endian merge with two identical inputs;
1679  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1680  *     little-endian merges).
1681  * \param[in] DAG The current SelectionDAG
1682  * \return true iff this shuffle mask
1683  */
1684 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1685                               unsigned ShuffleKind, SelectionDAG &DAG) {
1686   if (DAG.getDataLayout().isLittleEndian()) {
1687     unsigned indexOffset = CheckEven ? 4 : 0;
1688     if (ShuffleKind == 1) // Unary
1689       return isVMerge(N, indexOffset, 0);
1690     else if (ShuffleKind == 2) // swapped
1691       return isVMerge(N, indexOffset, 16);
1692     else
1693       return false;
1694   }
1695   else {
1696     unsigned indexOffset = CheckEven ? 0 : 4;
1697     if (ShuffleKind == 1) // Unary
1698       return isVMerge(N, indexOffset, 0);
1699     else if (ShuffleKind == 0) // Normal
1700       return isVMerge(N, indexOffset, 16);
1701     else
1702       return false;
1703   }
1704   return false;
1705 }
1706 
1707 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1708 /// amount, otherwise return -1.
1709 /// The ShuffleKind distinguishes between big-endian operations with two
1710 /// different inputs (0), either-endian operations with two identical inputs
1711 /// (1), and little-endian operations with two different inputs (2).  For the
1712 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1713 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1714                              SelectionDAG &DAG) {
1715   if (N->getValueType(0) != MVT::v16i8)
1716     return -1;
1717 
1718   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1719 
1720   // Find the first non-undef value in the shuffle mask.
1721   unsigned i;
1722   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1723     /*search*/;
1724 
1725   if (i == 16) return -1;  // all undef.
1726 
1727   // Otherwise, check to see if the rest of the elements are consecutively
1728   // numbered from this value.
1729   unsigned ShiftAmt = SVOp->getMaskElt(i);
1730   if (ShiftAmt < i) return -1;
1731 
1732   ShiftAmt -= i;
1733   bool isLE = DAG.getDataLayout().isLittleEndian();
1734 
1735   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1736     // Check the rest of the elements to see if they are consecutive.
1737     for (++i; i != 16; ++i)
1738       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1739         return -1;
1740   } else if (ShuffleKind == 1) {
1741     // Check the rest of the elements to see if they are consecutive.
1742     for (++i; i != 16; ++i)
1743       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1744         return -1;
1745   } else
1746     return -1;
1747 
1748   if (isLE)
1749     ShiftAmt = 16 - ShiftAmt;
1750 
1751   return ShiftAmt;
1752 }
1753 
1754 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1755 /// specifies a splat of a single element that is suitable for input to
1756 /// VSPLTB/VSPLTH/VSPLTW.
1757 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1758   assert(N->getValueType(0) == MVT::v16i8 &&
1759          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1760 
1761   // The consecutive indices need to specify an element, not part of two
1762   // different elements.  So abandon ship early if this isn't the case.
1763   if (N->getMaskElt(0) % EltSize != 0)
1764     return false;
1765 
1766   // This is a splat operation if each element of the permute is the same, and
1767   // if the value doesn't reference the second vector.
1768   unsigned ElementBase = N->getMaskElt(0);
1769 
1770   // FIXME: Handle UNDEF elements too!
1771   if (ElementBase >= 16)
1772     return false;
1773 
1774   // Check that the indices are consecutive, in the case of a multi-byte element
1775   // splatted with a v16i8 mask.
1776   for (unsigned i = 1; i != EltSize; ++i)
1777     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1778       return false;
1779 
1780   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1781     if (N->getMaskElt(i) < 0) continue;
1782     for (unsigned j = 0; j != EltSize; ++j)
1783       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1784         return false;
1785   }
1786   return true;
1787 }
1788 
1789 /// Check that the mask is shuffling N byte elements. Within each N byte
1790 /// element of the mask, the indices could be either in increasing or
1791 /// decreasing order as long as they are consecutive.
1792 /// \param[in] N the shuffle vector SD Node to analyze
1793 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1794 /// Word/DoubleWord/QuadWord).
1795 /// \param[in] StepLen the delta indices number among the N byte element, if
1796 /// the mask is in increasing/decreasing order then it is 1/-1.
1797 /// \return true iff the mask is shuffling N byte elements.
1798 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1799                                    int StepLen) {
1800   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1801          "Unexpected element width.");
1802   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1803 
1804   unsigned NumOfElem = 16 / Width;
1805   unsigned MaskVal[16]; //  Width is never greater than 16
1806   for (unsigned i = 0; i < NumOfElem; ++i) {
1807     MaskVal[0] = N->getMaskElt(i * Width);
1808     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1809       return false;
1810     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1811       return false;
1812     }
1813 
1814     for (unsigned int j = 1; j < Width; ++j) {
1815       MaskVal[j] = N->getMaskElt(i * Width + j);
1816       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1817         return false;
1818       }
1819     }
1820   }
1821 
1822   return true;
1823 }
1824 
1825 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1826                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1827   if (!isNByteElemShuffleMask(N, 4, 1))
1828     return false;
1829 
1830   // Now we look at mask elements 0,4,8,12
1831   unsigned M0 = N->getMaskElt(0) / 4;
1832   unsigned M1 = N->getMaskElt(4) / 4;
1833   unsigned M2 = N->getMaskElt(8) / 4;
1834   unsigned M3 = N->getMaskElt(12) / 4;
1835   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1836   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1837 
1838   // Below, let H and L be arbitrary elements of the shuffle mask
1839   // where H is in the range [4,7] and L is in the range [0,3].
1840   // H, 1, 2, 3 or L, 5, 6, 7
1841   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1842       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1843     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1844     InsertAtByte = IsLE ? 12 : 0;
1845     Swap = M0 < 4;
1846     return true;
1847   }
1848   // 0, H, 2, 3 or 4, L, 6, 7
1849   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1850       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1851     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1852     InsertAtByte = IsLE ? 8 : 4;
1853     Swap = M1 < 4;
1854     return true;
1855   }
1856   // 0, 1, H, 3 or 4, 5, L, 7
1857   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1858       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1859     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1860     InsertAtByte = IsLE ? 4 : 8;
1861     Swap = M2 < 4;
1862     return true;
1863   }
1864   // 0, 1, 2, H or 4, 5, 6, L
1865   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1866       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1867     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1868     InsertAtByte = IsLE ? 0 : 12;
1869     Swap = M3 < 4;
1870     return true;
1871   }
1872 
1873   // If both vector operands for the shuffle are the same vector, the mask will
1874   // contain only elements from the first one and the second one will be undef.
1875   if (N->getOperand(1).isUndef()) {
1876     ShiftElts = 0;
1877     Swap = true;
1878     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1879     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1880       InsertAtByte = IsLE ? 12 : 0;
1881       return true;
1882     }
1883     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1884       InsertAtByte = IsLE ? 8 : 4;
1885       return true;
1886     }
1887     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1888       InsertAtByte = IsLE ? 4 : 8;
1889       return true;
1890     }
1891     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1892       InsertAtByte = IsLE ? 0 : 12;
1893       return true;
1894     }
1895   }
1896 
1897   return false;
1898 }
1899 
1900 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1901                                bool &Swap, bool IsLE) {
1902   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1903   // Ensure each byte index of the word is consecutive.
1904   if (!isNByteElemShuffleMask(N, 4, 1))
1905     return false;
1906 
1907   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1908   unsigned M0 = N->getMaskElt(0) / 4;
1909   unsigned M1 = N->getMaskElt(4) / 4;
1910   unsigned M2 = N->getMaskElt(8) / 4;
1911   unsigned M3 = N->getMaskElt(12) / 4;
1912 
1913   // If both vector operands for the shuffle are the same vector, the mask will
1914   // contain only elements from the first one and the second one will be undef.
1915   if (N->getOperand(1).isUndef()) {
1916     assert(M0 < 4 && "Indexing into an undef vector?");
1917     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1918       return false;
1919 
1920     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1921     Swap = false;
1922     return true;
1923   }
1924 
1925   // Ensure each word index of the ShuffleVector Mask is consecutive.
1926   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1927     return false;
1928 
1929   if (IsLE) {
1930     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1931       // Input vectors don't need to be swapped if the leading element
1932       // of the result is one of the 3 left elements of the second vector
1933       // (or if there is no shift to be done at all).
1934       Swap = false;
1935       ShiftElts = (8 - M0) % 8;
1936     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1937       // Input vectors need to be swapped if the leading element
1938       // of the result is one of the 3 left elements of the first vector
1939       // (or if we're shifting by 4 - thereby simply swapping the vectors).
1940       Swap = true;
1941       ShiftElts = (4 - M0) % 4;
1942     }
1943 
1944     return true;
1945   } else {                                          // BE
1946     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
1947       // Input vectors don't need to be swapped if the leading element
1948       // of the result is one of the 4 elements of the first vector.
1949       Swap = false;
1950       ShiftElts = M0;
1951     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
1952       // Input vectors need to be swapped if the leading element
1953       // of the result is one of the 4 elements of the right vector.
1954       Swap = true;
1955       ShiftElts = M0 - 4;
1956     }
1957 
1958     return true;
1959   }
1960 }
1961 
1962 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
1963   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1964 
1965   if (!isNByteElemShuffleMask(N, Width, -1))
1966     return false;
1967 
1968   for (int i = 0; i < 16; i += Width)
1969     if (N->getMaskElt(i) != i + Width - 1)
1970       return false;
1971 
1972   return true;
1973 }
1974 
1975 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
1976   return isXXBRShuffleMaskHelper(N, 2);
1977 }
1978 
1979 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
1980   return isXXBRShuffleMaskHelper(N, 4);
1981 }
1982 
1983 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
1984   return isXXBRShuffleMaskHelper(N, 8);
1985 }
1986 
1987 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
1988   return isXXBRShuffleMaskHelper(N, 16);
1989 }
1990 
1991 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
1992 /// if the inputs to the instruction should be swapped and set \p DM to the
1993 /// value for the immediate.
1994 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
1995 /// AND element 0 of the result comes from the first input (LE) or second input
1996 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
1997 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
1998 /// mask.
1999 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2000                                bool &Swap, bool IsLE) {
2001   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2002 
2003   // Ensure each byte index of the double word is consecutive.
2004   if (!isNByteElemShuffleMask(N, 8, 1))
2005     return false;
2006 
2007   unsigned M0 = N->getMaskElt(0) / 8;
2008   unsigned M1 = N->getMaskElt(8) / 8;
2009   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2010 
2011   // If both vector operands for the shuffle are the same vector, the mask will
2012   // contain only elements from the first one and the second one will be undef.
2013   if (N->getOperand(1).isUndef()) {
2014     if ((M0 | M1) < 2) {
2015       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2016       Swap = false;
2017       return true;
2018     } else
2019       return false;
2020   }
2021 
2022   if (IsLE) {
2023     if (M0 > 1 && M1 < 2) {
2024       Swap = false;
2025     } else if (M0 < 2 && M1 > 1) {
2026       M0 = (M0 + 2) % 4;
2027       M1 = (M1 + 2) % 4;
2028       Swap = true;
2029     } else
2030       return false;
2031 
2032     // Note: if control flow comes here that means Swap is already set above
2033     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2034     return true;
2035   } else { // BE
2036     if (M0 < 2 && M1 > 1) {
2037       Swap = false;
2038     } else if (M0 > 1 && M1 < 2) {
2039       M0 = (M0 + 2) % 4;
2040       M1 = (M1 + 2) % 4;
2041       Swap = true;
2042     } else
2043       return false;
2044 
2045     // Note: if control flow comes here that means Swap is already set above
2046     DM = (M0 << 1) + (M1 & 1);
2047     return true;
2048   }
2049 }
2050 
2051 
2052 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
2053 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
2054 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
2055                                 SelectionDAG &DAG) {
2056   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2057   assert(isSplatShuffleMask(SVOp, EltSize));
2058   if (DAG.getDataLayout().isLittleEndian())
2059     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2060   else
2061     return SVOp->getMaskElt(0) / EltSize;
2062 }
2063 
2064 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2065 /// by using a vspltis[bhw] instruction of the specified element size, return
2066 /// the constant being splatted.  The ByteSize field indicates the number of
2067 /// bytes of each element [124] -> [bhw].
2068 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2069   SDValue OpVal(nullptr, 0);
2070 
2071   // If ByteSize of the splat is bigger than the element size of the
2072   // build_vector, then we have a case where we are checking for a splat where
2073   // multiple elements of the buildvector are folded together into a single
2074   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2075   unsigned EltSize = 16/N->getNumOperands();
2076   if (EltSize < ByteSize) {
2077     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2078     SDValue UniquedVals[4];
2079     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2080 
2081     // See if all of the elements in the buildvector agree across.
2082     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2083       if (N->getOperand(i).isUndef()) continue;
2084       // If the element isn't a constant, bail fully out.
2085       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2086 
2087       if (!UniquedVals[i&(Multiple-1)].getNode())
2088         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2089       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2090         return SDValue();  // no match.
2091     }
2092 
2093     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2094     // either constant or undef values that are identical for each chunk.  See
2095     // if these chunks can form into a larger vspltis*.
2096 
2097     // Check to see if all of the leading entries are either 0 or -1.  If
2098     // neither, then this won't fit into the immediate field.
2099     bool LeadingZero = true;
2100     bool LeadingOnes = true;
2101     for (unsigned i = 0; i != Multiple-1; ++i) {
2102       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2103 
2104       LeadingZero &= isNullConstant(UniquedVals[i]);
2105       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2106     }
2107     // Finally, check the least significant entry.
2108     if (LeadingZero) {
2109       if (!UniquedVals[Multiple-1].getNode())
2110         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2111       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2112       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2113         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2114     }
2115     if (LeadingOnes) {
2116       if (!UniquedVals[Multiple-1].getNode())
2117         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2118       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2119       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2120         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2121     }
2122 
2123     return SDValue();
2124   }
2125 
2126   // Check to see if this buildvec has a single non-undef value in its elements.
2127   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2128     if (N->getOperand(i).isUndef()) continue;
2129     if (!OpVal.getNode())
2130       OpVal = N->getOperand(i);
2131     else if (OpVal != N->getOperand(i))
2132       return SDValue();
2133   }
2134 
2135   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2136 
2137   unsigned ValSizeInBytes = EltSize;
2138   uint64_t Value = 0;
2139   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2140     Value = CN->getZExtValue();
2141   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2142     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2143     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2144   }
2145 
2146   // If the splat value is larger than the element value, then we can never do
2147   // this splat.  The only case that we could fit the replicated bits into our
2148   // immediate field for would be zero, and we prefer to use vxor for it.
2149   if (ValSizeInBytes < ByteSize) return SDValue();
2150 
2151   // If the element value is larger than the splat value, check if it consists
2152   // of a repeated bit pattern of size ByteSize.
2153   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2154     return SDValue();
2155 
2156   // Properly sign extend the value.
2157   int MaskVal = SignExtend32(Value, ByteSize * 8);
2158 
2159   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2160   if (MaskVal == 0) return SDValue();
2161 
2162   // Finally, if this value fits in a 5 bit sext field, return it
2163   if (SignExtend32<5>(MaskVal) == MaskVal)
2164     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2165   return SDValue();
2166 }
2167 
2168 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2169 /// amount, otherwise return -1.
2170 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2171   EVT VT = N->getValueType(0);
2172   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2173     return -1;
2174 
2175   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2176 
2177   // Find the first non-undef value in the shuffle mask.
2178   unsigned i;
2179   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2180     /*search*/;
2181 
2182   if (i == 4) return -1;  // all undef.
2183 
2184   // Otherwise, check to see if the rest of the elements are consecutively
2185   // numbered from this value.
2186   unsigned ShiftAmt = SVOp->getMaskElt(i);
2187   if (ShiftAmt < i) return -1;
2188   ShiftAmt -= i;
2189 
2190   // Check the rest of the elements to see if they are consecutive.
2191   for (++i; i != 4; ++i)
2192     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2193       return -1;
2194 
2195   return ShiftAmt;
2196 }
2197 
2198 //===----------------------------------------------------------------------===//
2199 //  Addressing Mode Selection
2200 //===----------------------------------------------------------------------===//
2201 
2202 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2203 /// or 64-bit immediate, and if the value can be accurately represented as a
2204 /// sign extension from a 16-bit value.  If so, this returns true and the
2205 /// immediate.
2206 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2207   if (!isa<ConstantSDNode>(N))
2208     return false;
2209 
2210   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2211   if (N->getValueType(0) == MVT::i32)
2212     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2213   else
2214     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2215 }
2216 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2217   return isIntS16Immediate(Op.getNode(), Imm);
2218 }
2219 
2220 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2221 /// can be represented as an indexed [r+r] operation.  Returns false if it
2222 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2223 /// non-zero and N can be represented by a base register plus a signed 16-bit
2224 /// displacement, make a more precise judgement by checking (displacement % \p
2225 /// EncodingAlignment).
2226 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2227                                             SDValue &Index, SelectionDAG &DAG,
2228                                             unsigned EncodingAlignment) const {
2229   int16_t imm = 0;
2230   if (N.getOpcode() == ISD::ADD) {
2231     if (isIntS16Immediate(N.getOperand(1), imm) &&
2232         (!EncodingAlignment || !(imm % EncodingAlignment)))
2233       return false; // r+i
2234     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2235       return false;    // r+i
2236 
2237     Base = N.getOperand(0);
2238     Index = N.getOperand(1);
2239     return true;
2240   } else if (N.getOpcode() == ISD::OR) {
2241     if (isIntS16Immediate(N.getOperand(1), imm) &&
2242         (!EncodingAlignment || !(imm % EncodingAlignment)))
2243       return false; // r+i can fold it if we can.
2244 
2245     // If this is an or of disjoint bitfields, we can codegen this as an add
2246     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2247     // disjoint.
2248     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2249 
2250     if (LHSKnown.Zero.getBoolValue()) {
2251       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2252       // If all of the bits are known zero on the LHS or RHS, the add won't
2253       // carry.
2254       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2255         Base = N.getOperand(0);
2256         Index = N.getOperand(1);
2257         return true;
2258       }
2259     }
2260   }
2261 
2262   return false;
2263 }
2264 
2265 // If we happen to be doing an i64 load or store into a stack slot that has
2266 // less than a 4-byte alignment, then the frame-index elimination may need to
2267 // use an indexed load or store instruction (because the offset may not be a
2268 // multiple of 4). The extra register needed to hold the offset comes from the
2269 // register scavenger, and it is possible that the scavenger will need to use
2270 // an emergency spill slot. As a result, we need to make sure that a spill slot
2271 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2272 // stack slot.
2273 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2274   // FIXME: This does not handle the LWA case.
2275   if (VT != MVT::i64)
2276     return;
2277 
2278   // NOTE: We'll exclude negative FIs here, which come from argument
2279   // lowering, because there are no known test cases triggering this problem
2280   // using packed structures (or similar). We can remove this exclusion if
2281   // we find such a test case. The reason why this is so test-case driven is
2282   // because this entire 'fixup' is only to prevent crashes (from the
2283   // register scavenger) on not-really-valid inputs. For example, if we have:
2284   //   %a = alloca i1
2285   //   %b = bitcast i1* %a to i64*
2286   //   store i64* a, i64 b
2287   // then the store should really be marked as 'align 1', but is not. If it
2288   // were marked as 'align 1' then the indexed form would have been
2289   // instruction-selected initially, and the problem this 'fixup' is preventing
2290   // won't happen regardless.
2291   if (FrameIdx < 0)
2292     return;
2293 
2294   MachineFunction &MF = DAG.getMachineFunction();
2295   MachineFrameInfo &MFI = MF.getFrameInfo();
2296 
2297   unsigned Align = MFI.getObjectAlignment(FrameIdx);
2298   if (Align >= 4)
2299     return;
2300 
2301   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2302   FuncInfo->setHasNonRISpills();
2303 }
2304 
2305 /// Returns true if the address N can be represented by a base register plus
2306 /// a signed 16-bit displacement [r+imm], and if it is not better
2307 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2308 /// displacements that are multiples of that value.
2309 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2310                                             SDValue &Base,
2311                                             SelectionDAG &DAG,
2312                                             unsigned EncodingAlignment) const {
2313   // FIXME dl should come from parent load or store, not from address
2314   SDLoc dl(N);
2315   // If this can be more profitably realized as r+r, fail.
2316   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2317     return false;
2318 
2319   if (N.getOpcode() == ISD::ADD) {
2320     int16_t imm = 0;
2321     if (isIntS16Immediate(N.getOperand(1), imm) &&
2322         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2323       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2324       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2325         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2326         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2327       } else {
2328         Base = N.getOperand(0);
2329       }
2330       return true; // [r+i]
2331     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2332       // Match LOAD (ADD (X, Lo(G))).
2333       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2334              && "Cannot handle constant offsets yet!");
2335       Disp = N.getOperand(1).getOperand(0);  // The global address.
2336       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2337              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2338              Disp.getOpcode() == ISD::TargetConstantPool ||
2339              Disp.getOpcode() == ISD::TargetJumpTable);
2340       Base = N.getOperand(0);
2341       return true;  // [&g+r]
2342     }
2343   } else if (N.getOpcode() == ISD::OR) {
2344     int16_t imm = 0;
2345     if (isIntS16Immediate(N.getOperand(1), imm) &&
2346         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2347       // If this is an or of disjoint bitfields, we can codegen this as an add
2348       // (for better address arithmetic) if the LHS and RHS of the OR are
2349       // provably disjoint.
2350       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2351 
2352       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2353         // If all of the bits are known zero on the LHS or RHS, the add won't
2354         // carry.
2355         if (FrameIndexSDNode *FI =
2356               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2357           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2358           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2359         } else {
2360           Base = N.getOperand(0);
2361         }
2362         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2363         return true;
2364       }
2365     }
2366   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2367     // Loading from a constant address.
2368 
2369     // If this address fits entirely in a 16-bit sext immediate field, codegen
2370     // this as "d, 0"
2371     int16_t Imm;
2372     if (isIntS16Immediate(CN, Imm) &&
2373         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2374       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2375       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2376                              CN->getValueType(0));
2377       return true;
2378     }
2379 
2380     // Handle 32-bit sext immediates with LIS + addr mode.
2381     if ((CN->getValueType(0) == MVT::i32 ||
2382          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2383         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2384       int Addr = (int)CN->getZExtValue();
2385 
2386       // Otherwise, break this down into an LIS + disp.
2387       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2388 
2389       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2390                                    MVT::i32);
2391       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2392       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2393       return true;
2394     }
2395   }
2396 
2397   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2398   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2399     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2400     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2401   } else
2402     Base = N;
2403   return true;      // [r+0]
2404 }
2405 
2406 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2407 /// represented as an indexed [r+r] operation.
2408 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2409                                                 SDValue &Index,
2410                                                 SelectionDAG &DAG) const {
2411   // Check to see if we can easily represent this as an [r+r] address.  This
2412   // will fail if it thinks that the address is more profitably represented as
2413   // reg+imm, e.g. where imm = 0.
2414   if (SelectAddressRegReg(N, Base, Index, DAG))
2415     return true;
2416 
2417   // If the address is the result of an add, we will utilize the fact that the
2418   // address calculation includes an implicit add.  However, we can reduce
2419   // register pressure if we do not materialize a constant just for use as the
2420   // index register.  We only get rid of the add if it is not an add of a
2421   // value and a 16-bit signed constant and both have a single use.
2422   int16_t imm = 0;
2423   if (N.getOpcode() == ISD::ADD &&
2424       (!isIntS16Immediate(N.getOperand(1), imm) ||
2425        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2426     Base = N.getOperand(0);
2427     Index = N.getOperand(1);
2428     return true;
2429   }
2430 
2431   // Otherwise, do it the hard way, using R0 as the base register.
2432   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2433                          N.getValueType());
2434   Index = N;
2435   return true;
2436 }
2437 
2438 /// Returns true if we should use a direct load into vector instruction
2439 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2440 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2441 
2442   // If there are any other uses other than scalar to vector, then we should
2443   // keep it as a scalar load -> direct move pattern to prevent multiple
2444   // loads.
2445   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2446   if (!LD)
2447     return false;
2448 
2449   EVT MemVT = LD->getMemoryVT();
2450   if (!MemVT.isSimple())
2451     return false;
2452   switch(MemVT.getSimpleVT().SimpleTy) {
2453   case MVT::i64:
2454     break;
2455   case MVT::i32:
2456     if (!ST.hasP8Vector())
2457       return false;
2458     break;
2459   case MVT::i16:
2460   case MVT::i8:
2461     if (!ST.hasP9Vector())
2462       return false;
2463     break;
2464   default:
2465     return false;
2466   }
2467 
2468   SDValue LoadedVal(N, 0);
2469   if (!LoadedVal.hasOneUse())
2470     return false;
2471 
2472   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2473        UI != UE; ++UI)
2474     if (UI.getUse().get().getResNo() == 0 &&
2475         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2476       return false;
2477 
2478   return true;
2479 }
2480 
2481 /// getPreIndexedAddressParts - returns true by value, base pointer and
2482 /// offset pointer and addressing mode by reference if the node's address
2483 /// can be legally represented as pre-indexed load / store address.
2484 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2485                                                   SDValue &Offset,
2486                                                   ISD::MemIndexedMode &AM,
2487                                                   SelectionDAG &DAG) const {
2488   if (DisablePPCPreinc) return false;
2489 
2490   bool isLoad = true;
2491   SDValue Ptr;
2492   EVT VT;
2493   unsigned Alignment;
2494   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2495     Ptr = LD->getBasePtr();
2496     VT = LD->getMemoryVT();
2497     Alignment = LD->getAlignment();
2498   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2499     Ptr = ST->getBasePtr();
2500     VT  = ST->getMemoryVT();
2501     Alignment = ST->getAlignment();
2502     isLoad = false;
2503   } else
2504     return false;
2505 
2506   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2507   // instructions because we can fold these into a more efficient instruction
2508   // instead, (such as LXSD).
2509   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2510     return false;
2511   }
2512 
2513   // PowerPC doesn't have preinc load/store instructions for vectors (except
2514   // for QPX, which does have preinc r+r forms).
2515   if (VT.isVector()) {
2516     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2517       return false;
2518     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2519       AM = ISD::PRE_INC;
2520       return true;
2521     }
2522   }
2523 
2524   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2525     // Common code will reject creating a pre-inc form if the base pointer
2526     // is a frame index, or if N is a store and the base pointer is either
2527     // the same as or a predecessor of the value being stored.  Check for
2528     // those situations here, and try with swapped Base/Offset instead.
2529     bool Swap = false;
2530 
2531     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2532       Swap = true;
2533     else if (!isLoad) {
2534       SDValue Val = cast<StoreSDNode>(N)->getValue();
2535       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2536         Swap = true;
2537     }
2538 
2539     if (Swap)
2540       std::swap(Base, Offset);
2541 
2542     AM = ISD::PRE_INC;
2543     return true;
2544   }
2545 
2546   // LDU/STU can only handle immediates that are a multiple of 4.
2547   if (VT != MVT::i64) {
2548     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2549       return false;
2550   } else {
2551     // LDU/STU need an address with at least 4-byte alignment.
2552     if (Alignment < 4)
2553       return false;
2554 
2555     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2556       return false;
2557   }
2558 
2559   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2560     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2561     // sext i32 to i64 when addr mode is r+i.
2562     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2563         LD->getExtensionType() == ISD::SEXTLOAD &&
2564         isa<ConstantSDNode>(Offset))
2565       return false;
2566   }
2567 
2568   AM = ISD::PRE_INC;
2569   return true;
2570 }
2571 
2572 //===----------------------------------------------------------------------===//
2573 //  LowerOperation implementation
2574 //===----------------------------------------------------------------------===//
2575 
2576 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2577 /// and LoOpFlags to the target MO flags.
2578 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2579                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2580                                const GlobalValue *GV = nullptr) {
2581   HiOpFlags = PPCII::MO_HA;
2582   LoOpFlags = PPCII::MO_LO;
2583 
2584   // Don't use the pic base if not in PIC relocation model.
2585   if (IsPIC) {
2586     HiOpFlags |= PPCII::MO_PIC_FLAG;
2587     LoOpFlags |= PPCII::MO_PIC_FLAG;
2588   }
2589 
2590   // If this is a reference to a global value that requires a non-lazy-ptr, make
2591   // sure that instruction lowering adds it.
2592   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2593     HiOpFlags |= PPCII::MO_NLP_FLAG;
2594     LoOpFlags |= PPCII::MO_NLP_FLAG;
2595 
2596     if (GV->hasHiddenVisibility()) {
2597       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2598       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2599     }
2600   }
2601 }
2602 
2603 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2604                              SelectionDAG &DAG) {
2605   SDLoc DL(HiPart);
2606   EVT PtrVT = HiPart.getValueType();
2607   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2608 
2609   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2610   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2611 
2612   // With PIC, the first instruction is actually "GR+hi(&G)".
2613   if (isPIC)
2614     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2615                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2616 
2617   // Generate non-pic code that has direct accesses to the constant pool.
2618   // The address of the global is just (hi(&g)+lo(&g)).
2619   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2620 }
2621 
2622 static void setUsesTOCBasePtr(MachineFunction &MF) {
2623   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2624   FuncInfo->setUsesTOCBasePtr();
2625 }
2626 
2627 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2628   setUsesTOCBasePtr(DAG.getMachineFunction());
2629 }
2630 
2631 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2632                            SDValue GA) {
2633   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2634   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2635                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2636 
2637   SDValue Ops[] = { GA, Reg };
2638   return DAG.getMemIntrinsicNode(
2639       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2640       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2641       MachineMemOperand::MOLoad);
2642 }
2643 
2644 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2645                                              SelectionDAG &DAG) const {
2646   EVT PtrVT = Op.getValueType();
2647   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2648   const Constant *C = CP->getConstVal();
2649 
2650   // 64-bit SVR4 ABI code is always position-independent.
2651   // The actual address of the GlobalValue is stored in the TOC.
2652   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2653     setUsesTOCBasePtr(DAG);
2654     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2655     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2656   }
2657 
2658   unsigned MOHiFlag, MOLoFlag;
2659   bool IsPIC = isPositionIndependent();
2660   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2661 
2662   if (IsPIC && Subtarget.isSVR4ABI()) {
2663     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2664                                            PPCII::MO_PIC_FLAG);
2665     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2666   }
2667 
2668   SDValue CPIHi =
2669     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2670   SDValue CPILo =
2671     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2672   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2673 }
2674 
2675 // For 64-bit PowerPC, prefer the more compact relative encodings.
2676 // This trades 32 bits per jump table entry for one or two instructions
2677 // on the jump site.
2678 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2679   if (isJumpTableRelative())
2680     return MachineJumpTableInfo::EK_LabelDifference32;
2681 
2682   return TargetLowering::getJumpTableEncoding();
2683 }
2684 
2685 bool PPCTargetLowering::isJumpTableRelative() const {
2686   if (Subtarget.isPPC64())
2687     return true;
2688   return TargetLowering::isJumpTableRelative();
2689 }
2690 
2691 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2692                                                     SelectionDAG &DAG) const {
2693   if (!Subtarget.isPPC64())
2694     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2695 
2696   switch (getTargetMachine().getCodeModel()) {
2697   case CodeModel::Small:
2698   case CodeModel::Medium:
2699     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2700   default:
2701     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2702                        getPointerTy(DAG.getDataLayout()));
2703   }
2704 }
2705 
2706 const MCExpr *
2707 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2708                                                 unsigned JTI,
2709                                                 MCContext &Ctx) const {
2710   if (!Subtarget.isPPC64())
2711     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2712 
2713   switch (getTargetMachine().getCodeModel()) {
2714   case CodeModel::Small:
2715   case CodeModel::Medium:
2716     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2717   default:
2718     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2719   }
2720 }
2721 
2722 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2723   EVT PtrVT = Op.getValueType();
2724   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2725 
2726   // 64-bit SVR4 ABI code is always position-independent.
2727   // The actual address of the GlobalValue is stored in the TOC.
2728   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2729     setUsesTOCBasePtr(DAG);
2730     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2731     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2732   }
2733 
2734   unsigned MOHiFlag, MOLoFlag;
2735   bool IsPIC = isPositionIndependent();
2736   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2737 
2738   if (IsPIC && Subtarget.isSVR4ABI()) {
2739     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2740                                         PPCII::MO_PIC_FLAG);
2741     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2742   }
2743 
2744   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2745   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2746   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2747 }
2748 
2749 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2750                                              SelectionDAG &DAG) const {
2751   EVT PtrVT = Op.getValueType();
2752   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2753   const BlockAddress *BA = BASDN->getBlockAddress();
2754 
2755   // 64-bit SVR4 ABI code is always position-independent.
2756   // The actual BlockAddress is stored in the TOC.
2757   if (Subtarget.isSVR4ABI() &&
2758       (Subtarget.isPPC64() || isPositionIndependent())) {
2759     if (Subtarget.isPPC64())
2760       setUsesTOCBasePtr(DAG);
2761     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2762     return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA);
2763   }
2764 
2765   unsigned MOHiFlag, MOLoFlag;
2766   bool IsPIC = isPositionIndependent();
2767   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2768   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2769   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2770   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2771 }
2772 
2773 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2774                                               SelectionDAG &DAG) const {
2775   // FIXME: TLS addresses currently use medium model code sequences,
2776   // which is the most useful form.  Eventually support for small and
2777   // large models could be added if users need it, at the cost of
2778   // additional complexity.
2779   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2780   if (DAG.getTarget().useEmulatedTLS())
2781     return LowerToTLSEmulatedModel(GA, DAG);
2782 
2783   SDLoc dl(GA);
2784   const GlobalValue *GV = GA->getGlobal();
2785   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2786   bool is64bit = Subtarget.isPPC64();
2787   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2788   PICLevel::Level picLevel = M->getPICLevel();
2789 
2790   const TargetMachine &TM = getTargetMachine();
2791   TLSModel::Model Model = TM.getTLSModel(GV);
2792 
2793   if (Model == TLSModel::LocalExec) {
2794     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2795                                                PPCII::MO_TPREL_HA);
2796     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2797                                                PPCII::MO_TPREL_LO);
2798     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2799                              : DAG.getRegister(PPC::R2, MVT::i32);
2800 
2801     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2802     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2803   }
2804 
2805   if (Model == TLSModel::InitialExec) {
2806     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2807     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2808                                                 PPCII::MO_TLS);
2809     SDValue GOTPtr;
2810     if (is64bit) {
2811       setUsesTOCBasePtr(DAG);
2812       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2813       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2814                            PtrVT, GOTReg, TGA);
2815     } else {
2816       if (!TM.isPositionIndependent())
2817         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2818       else if (picLevel == PICLevel::SmallPIC)
2819         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2820       else
2821         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2822     }
2823     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2824                                    PtrVT, TGA, GOTPtr);
2825     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2826   }
2827 
2828   if (Model == TLSModel::GeneralDynamic) {
2829     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2830     SDValue GOTPtr;
2831     if (is64bit) {
2832       setUsesTOCBasePtr(DAG);
2833       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2834       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2835                                    GOTReg, TGA);
2836     } else {
2837       if (picLevel == PICLevel::SmallPIC)
2838         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2839       else
2840         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2841     }
2842     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2843                        GOTPtr, TGA, TGA);
2844   }
2845 
2846   if (Model == TLSModel::LocalDynamic) {
2847     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2848     SDValue GOTPtr;
2849     if (is64bit) {
2850       setUsesTOCBasePtr(DAG);
2851       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2852       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2853                            GOTReg, TGA);
2854     } else {
2855       if (picLevel == PICLevel::SmallPIC)
2856         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2857       else
2858         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2859     }
2860     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2861                                   PtrVT, GOTPtr, TGA, TGA);
2862     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2863                                       PtrVT, TLSAddr, TGA);
2864     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2865   }
2866 
2867   llvm_unreachable("Unknown TLS model!");
2868 }
2869 
2870 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2871                                               SelectionDAG &DAG) const {
2872   EVT PtrVT = Op.getValueType();
2873   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2874   SDLoc DL(GSDN);
2875   const GlobalValue *GV = GSDN->getGlobal();
2876 
2877   // 64-bit SVR4 ABI code is always position-independent.
2878   // The actual address of the GlobalValue is stored in the TOC.
2879   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2880     setUsesTOCBasePtr(DAG);
2881     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2882     return getTOCEntry(DAG, DL, true, GA);
2883   }
2884 
2885   unsigned MOHiFlag, MOLoFlag;
2886   bool IsPIC = isPositionIndependent();
2887   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2888 
2889   if (IsPIC && Subtarget.isSVR4ABI()) {
2890     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2891                                             GSDN->getOffset(),
2892                                             PPCII::MO_PIC_FLAG);
2893     return getTOCEntry(DAG, DL, false, GA);
2894   }
2895 
2896   SDValue GAHi =
2897     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2898   SDValue GALo =
2899     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2900 
2901   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2902 
2903   // If the global reference is actually to a non-lazy-pointer, we have to do an
2904   // extra load to get the address of the global.
2905   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2906     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2907   return Ptr;
2908 }
2909 
2910 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2911   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2912   SDLoc dl(Op);
2913 
2914   if (Op.getValueType() == MVT::v2i64) {
2915     // When the operands themselves are v2i64 values, we need to do something
2916     // special because VSX has no underlying comparison operations for these.
2917     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2918       // Equality can be handled by casting to the legal type for Altivec
2919       // comparisons, everything else needs to be expanded.
2920       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2921         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2922                  DAG.getSetCC(dl, MVT::v4i32,
2923                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2924                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2925                    CC));
2926       }
2927 
2928       return SDValue();
2929     }
2930 
2931     // We handle most of these in the usual way.
2932     return Op;
2933   }
2934 
2935   // If we're comparing for equality to zero, expose the fact that this is
2936   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2937   // fold the new nodes.
2938   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2939     return V;
2940 
2941   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2942     // Leave comparisons against 0 and -1 alone for now, since they're usually
2943     // optimized.  FIXME: revisit this when we can custom lower all setcc
2944     // optimizations.
2945     if (C->isAllOnesValue() || C->isNullValue())
2946       return SDValue();
2947   }
2948 
2949   // If we have an integer seteq/setne, turn it into a compare against zero
2950   // by xor'ing the rhs with the lhs, which is faster than setting a
2951   // condition register, reading it back out, and masking the correct bit.  The
2952   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2953   // the result to other bit-twiddling opportunities.
2954   EVT LHSVT = Op.getOperand(0).getValueType();
2955   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2956     EVT VT = Op.getValueType();
2957     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2958                                 Op.getOperand(1));
2959     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2960   }
2961   return SDValue();
2962 }
2963 
2964 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2965   SDNode *Node = Op.getNode();
2966   EVT VT = Node->getValueType(0);
2967   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2968   SDValue InChain = Node->getOperand(0);
2969   SDValue VAListPtr = Node->getOperand(1);
2970   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2971   SDLoc dl(Node);
2972 
2973   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2974 
2975   // gpr_index
2976   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2977                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2978   InChain = GprIndex.getValue(1);
2979 
2980   if (VT == MVT::i64) {
2981     // Check if GprIndex is even
2982     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2983                                  DAG.getConstant(1, dl, MVT::i32));
2984     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2985                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2986     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2987                                           DAG.getConstant(1, dl, MVT::i32));
2988     // Align GprIndex to be even if it isn't
2989     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2990                            GprIndex);
2991   }
2992 
2993   // fpr index is 1 byte after gpr
2994   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2995                                DAG.getConstant(1, dl, MVT::i32));
2996 
2997   // fpr
2998   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2999                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3000   InChain = FprIndex.getValue(1);
3001 
3002   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3003                                        DAG.getConstant(8, dl, MVT::i32));
3004 
3005   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3006                                         DAG.getConstant(4, dl, MVT::i32));
3007 
3008   // areas
3009   SDValue OverflowArea =
3010       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3011   InChain = OverflowArea.getValue(1);
3012 
3013   SDValue RegSaveArea =
3014       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3015   InChain = RegSaveArea.getValue(1);
3016 
3017   // select overflow_area if index > 8
3018   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3019                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3020 
3021   // adjustment constant gpr_index * 4/8
3022   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3023                                     VT.isInteger() ? GprIndex : FprIndex,
3024                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3025                                                     MVT::i32));
3026 
3027   // OurReg = RegSaveArea + RegConstant
3028   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3029                                RegConstant);
3030 
3031   // Floating types are 32 bytes into RegSaveArea
3032   if (VT.isFloatingPoint())
3033     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3034                          DAG.getConstant(32, dl, MVT::i32));
3035 
3036   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3037   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3038                                    VT.isInteger() ? GprIndex : FprIndex,
3039                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3040                                                    MVT::i32));
3041 
3042   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3043                               VT.isInteger() ? VAListPtr : FprPtr,
3044                               MachinePointerInfo(SV), MVT::i8);
3045 
3046   // determine if we should load from reg_save_area or overflow_area
3047   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3048 
3049   // increase overflow_area by 4/8 if gpr/fpr > 8
3050   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3051                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3052                                           dl, MVT::i32));
3053 
3054   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3055                              OverflowAreaPlusN);
3056 
3057   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3058                               MachinePointerInfo(), MVT::i32);
3059 
3060   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3061 }
3062 
3063 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3064   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3065 
3066   // We have to copy the entire va_list struct:
3067   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3068   return DAG.getMemcpy(Op.getOperand(0), Op,
3069                        Op.getOperand(1), Op.getOperand(2),
3070                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
3071                        false, MachinePointerInfo(), MachinePointerInfo());
3072 }
3073 
3074 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3075                                                   SelectionDAG &DAG) const {
3076   return Op.getOperand(0);
3077 }
3078 
3079 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3080                                                 SelectionDAG &DAG) const {
3081   SDValue Chain = Op.getOperand(0);
3082   SDValue Trmp = Op.getOperand(1); // trampoline
3083   SDValue FPtr = Op.getOperand(2); // nested function
3084   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3085   SDLoc dl(Op);
3086 
3087   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3088   bool isPPC64 = (PtrVT == MVT::i64);
3089   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3090 
3091   TargetLowering::ArgListTy Args;
3092   TargetLowering::ArgListEntry Entry;
3093 
3094   Entry.Ty = IntPtrTy;
3095   Entry.Node = Trmp; Args.push_back(Entry);
3096 
3097   // TrampSize == (isPPC64 ? 48 : 40);
3098   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3099                                isPPC64 ? MVT::i64 : MVT::i32);
3100   Args.push_back(Entry);
3101 
3102   Entry.Node = FPtr; Args.push_back(Entry);
3103   Entry.Node = Nest; Args.push_back(Entry);
3104 
3105   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3106   TargetLowering::CallLoweringInfo CLI(DAG);
3107   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3108       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3109       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3110 
3111   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3112   return CallResult.second;
3113 }
3114 
3115 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3116   MachineFunction &MF = DAG.getMachineFunction();
3117   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3118   EVT PtrVT = getPointerTy(MF.getDataLayout());
3119 
3120   SDLoc dl(Op);
3121 
3122   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
3123     // vastart just stores the address of the VarArgsFrameIndex slot into the
3124     // memory location argument.
3125     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3126     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3127     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3128                         MachinePointerInfo(SV));
3129   }
3130 
3131   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3132   // We suppose the given va_list is already allocated.
3133   //
3134   // typedef struct {
3135   //  char gpr;     /* index into the array of 8 GPRs
3136   //                 * stored in the register save area
3137   //                 * gpr=0 corresponds to r3,
3138   //                 * gpr=1 to r4, etc.
3139   //                 */
3140   //  char fpr;     /* index into the array of 8 FPRs
3141   //                 * stored in the register save area
3142   //                 * fpr=0 corresponds to f1,
3143   //                 * fpr=1 to f2, etc.
3144   //                 */
3145   //  char *overflow_arg_area;
3146   //                /* location on stack that holds
3147   //                 * the next overflow argument
3148   //                 */
3149   //  char *reg_save_area;
3150   //               /* where r3:r10 and f1:f8 (if saved)
3151   //                * are stored
3152   //                */
3153   // } va_list[1];
3154 
3155   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3156   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3157   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3158                                             PtrVT);
3159   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3160                                  PtrVT);
3161 
3162   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3163   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3164 
3165   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3166   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3167 
3168   uint64_t FPROffset = 1;
3169   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3170 
3171   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3172 
3173   // Store first byte : number of int regs
3174   SDValue firstStore =
3175       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3176                         MachinePointerInfo(SV), MVT::i8);
3177   uint64_t nextOffset = FPROffset;
3178   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3179                                   ConstFPROffset);
3180 
3181   // Store second byte : number of float regs
3182   SDValue secondStore =
3183       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3184                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3185   nextOffset += StackOffset;
3186   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3187 
3188   // Store second word : arguments given on stack
3189   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3190                                     MachinePointerInfo(SV, nextOffset));
3191   nextOffset += FrameOffset;
3192   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3193 
3194   // Store third word : arguments given in registers
3195   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3196                       MachinePointerInfo(SV, nextOffset));
3197 }
3198 
3199 /// FPR - The set of FP registers that should be allocated for arguments,
3200 /// on Darwin.
3201 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3202                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3203                                 PPC::F11, PPC::F12, PPC::F13};
3204 
3205 /// QFPR - The set of QPX registers that should be allocated for arguments.
3206 static const MCPhysReg QFPR[] = {
3207     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3208     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3209 
3210 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3211 /// the stack.
3212 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3213                                        unsigned PtrByteSize) {
3214   unsigned ArgSize = ArgVT.getStoreSize();
3215   if (Flags.isByVal())
3216     ArgSize = Flags.getByValSize();
3217 
3218   // Round up to multiples of the pointer size, except for array members,
3219   // which are always packed.
3220   if (!Flags.isInConsecutiveRegs())
3221     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3222 
3223   return ArgSize;
3224 }
3225 
3226 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3227 /// on the stack.
3228 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3229                                             ISD::ArgFlagsTy Flags,
3230                                             unsigned PtrByteSize) {
3231   unsigned Align = PtrByteSize;
3232 
3233   // Altivec parameters are padded to a 16 byte boundary.
3234   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3235       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3236       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3237       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3238     Align = 16;
3239   // QPX vector types stored in double-precision are padded to a 32 byte
3240   // boundary.
3241   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3242     Align = 32;
3243 
3244   // ByVal parameters are aligned as requested.
3245   if (Flags.isByVal()) {
3246     unsigned BVAlign = Flags.getByValAlign();
3247     if (BVAlign > PtrByteSize) {
3248       if (BVAlign % PtrByteSize != 0)
3249           llvm_unreachable(
3250             "ByVal alignment is not a multiple of the pointer size");
3251 
3252       Align = BVAlign;
3253     }
3254   }
3255 
3256   // Array members are always packed to their original alignment.
3257   if (Flags.isInConsecutiveRegs()) {
3258     // If the array member was split into multiple registers, the first
3259     // needs to be aligned to the size of the full type.  (Except for
3260     // ppcf128, which is only aligned as its f64 components.)
3261     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3262       Align = OrigVT.getStoreSize();
3263     else
3264       Align = ArgVT.getStoreSize();
3265   }
3266 
3267   return Align;
3268 }
3269 
3270 /// CalculateStackSlotUsed - Return whether this argument will use its
3271 /// stack slot (instead of being passed in registers).  ArgOffset,
3272 /// AvailableFPRs, and AvailableVRs must hold the current argument
3273 /// position, and will be updated to account for this argument.
3274 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3275                                    ISD::ArgFlagsTy Flags,
3276                                    unsigned PtrByteSize,
3277                                    unsigned LinkageSize,
3278                                    unsigned ParamAreaSize,
3279                                    unsigned &ArgOffset,
3280                                    unsigned &AvailableFPRs,
3281                                    unsigned &AvailableVRs, bool HasQPX) {
3282   bool UseMemory = false;
3283 
3284   // Respect alignment of argument on the stack.
3285   unsigned Align =
3286     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3287   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3288   // If there's no space left in the argument save area, we must
3289   // use memory (this check also catches zero-sized arguments).
3290   if (ArgOffset >= LinkageSize + ParamAreaSize)
3291     UseMemory = true;
3292 
3293   // Allocate argument on the stack.
3294   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3295   if (Flags.isInConsecutiveRegsLast())
3296     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3297   // If we overran the argument save area, we must use memory
3298   // (this check catches arguments passed partially in memory)
3299   if (ArgOffset > LinkageSize + ParamAreaSize)
3300     UseMemory = true;
3301 
3302   // However, if the argument is actually passed in an FPR or a VR,
3303   // we don't use memory after all.
3304   if (!Flags.isByVal()) {
3305     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3306         // QPX registers overlap with the scalar FP registers.
3307         (HasQPX && (ArgVT == MVT::v4f32 ||
3308                     ArgVT == MVT::v4f64 ||
3309                     ArgVT == MVT::v4i1)))
3310       if (AvailableFPRs > 0) {
3311         --AvailableFPRs;
3312         return false;
3313       }
3314     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3315         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3316         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3317         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3318       if (AvailableVRs > 0) {
3319         --AvailableVRs;
3320         return false;
3321       }
3322   }
3323 
3324   return UseMemory;
3325 }
3326 
3327 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3328 /// ensure minimum alignment required for target.
3329 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3330                                      unsigned NumBytes) {
3331   unsigned TargetAlign = Lowering->getStackAlignment();
3332   unsigned AlignMask = TargetAlign - 1;
3333   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3334   return NumBytes;
3335 }
3336 
3337 SDValue PPCTargetLowering::LowerFormalArguments(
3338     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3339     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3340     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3341   if (Subtarget.isSVR4ABI()) {
3342     if (Subtarget.isPPC64())
3343       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
3344                                          dl, DAG, InVals);
3345     else
3346       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
3347                                          dl, DAG, InVals);
3348   } else {
3349     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
3350                                        dl, DAG, InVals);
3351   }
3352 }
3353 
3354 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3355     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3356     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3357     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3358 
3359   // 32-bit SVR4 ABI Stack Frame Layout:
3360   //              +-----------------------------------+
3361   //        +-->  |            Back chain             |
3362   //        |     +-----------------------------------+
3363   //        |     | Floating-point register save area |
3364   //        |     +-----------------------------------+
3365   //        |     |    General register save area     |
3366   //        |     +-----------------------------------+
3367   //        |     |          CR save word             |
3368   //        |     +-----------------------------------+
3369   //        |     |         VRSAVE save word          |
3370   //        |     +-----------------------------------+
3371   //        |     |         Alignment padding         |
3372   //        |     +-----------------------------------+
3373   //        |     |     Vector register save area     |
3374   //        |     +-----------------------------------+
3375   //        |     |       Local variable space        |
3376   //        |     +-----------------------------------+
3377   //        |     |        Parameter list area        |
3378   //        |     +-----------------------------------+
3379   //        |     |           LR save word            |
3380   //        |     +-----------------------------------+
3381   // SP-->  +---  |            Back chain             |
3382   //              +-----------------------------------+
3383   //
3384   // Specifications:
3385   //   System V Application Binary Interface PowerPC Processor Supplement
3386   //   AltiVec Technology Programming Interface Manual
3387 
3388   MachineFunction &MF = DAG.getMachineFunction();
3389   MachineFrameInfo &MFI = MF.getFrameInfo();
3390   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3391 
3392   EVT PtrVT = getPointerTy(MF.getDataLayout());
3393   // Potential tail calls could cause overwriting of argument stack slots.
3394   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3395                        (CallConv == CallingConv::Fast));
3396   unsigned PtrByteSize = 4;
3397 
3398   // Assign locations to all of the incoming arguments.
3399   SmallVector<CCValAssign, 16> ArgLocs;
3400   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3401                  *DAG.getContext());
3402 
3403   // Reserve space for the linkage area on the stack.
3404   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3405   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3406   if (useSoftFloat() || hasSPE())
3407     CCInfo.PreAnalyzeFormalArguments(Ins);
3408 
3409   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3410   CCInfo.clearWasPPCF128();
3411 
3412   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3413     CCValAssign &VA = ArgLocs[i];
3414 
3415     // Arguments stored in registers.
3416     if (VA.isRegLoc()) {
3417       const TargetRegisterClass *RC;
3418       EVT ValVT = VA.getValVT();
3419 
3420       switch (ValVT.getSimpleVT().SimpleTy) {
3421         default:
3422           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3423         case MVT::i1:
3424         case MVT::i32:
3425           RC = &PPC::GPRCRegClass;
3426           break;
3427         case MVT::f32:
3428           if (Subtarget.hasP8Vector())
3429             RC = &PPC::VSSRCRegClass;
3430           else if (Subtarget.hasSPE())
3431             RC = &PPC::SPE4RCRegClass;
3432           else
3433             RC = &PPC::F4RCRegClass;
3434           break;
3435         case MVT::f64:
3436           if (Subtarget.hasVSX())
3437             RC = &PPC::VSFRCRegClass;
3438           else if (Subtarget.hasSPE())
3439             RC = &PPC::SPERCRegClass;
3440           else
3441             RC = &PPC::F8RCRegClass;
3442           break;
3443         case MVT::v16i8:
3444         case MVT::v8i16:
3445         case MVT::v4i32:
3446           RC = &PPC::VRRCRegClass;
3447           break;
3448         case MVT::v4f32:
3449           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3450           break;
3451         case MVT::v2f64:
3452         case MVT::v2i64:
3453           RC = &PPC::VRRCRegClass;
3454           break;
3455         case MVT::v4f64:
3456           RC = &PPC::QFRCRegClass;
3457           break;
3458         case MVT::v4i1:
3459           RC = &PPC::QBRCRegClass;
3460           break;
3461       }
3462 
3463       // Transform the arguments stored in physical registers into virtual ones.
3464       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3465       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3466                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
3467 
3468       if (ValVT == MVT::i1)
3469         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3470 
3471       InVals.push_back(ArgValue);
3472     } else {
3473       // Argument stored in memory.
3474       assert(VA.isMemLoc());
3475 
3476       // Get the extended size of the argument type in stack
3477       unsigned ArgSize = VA.getLocVT().getStoreSize();
3478       // Get the actual size of the argument type
3479       unsigned ObjSize = VA.getValVT().getStoreSize();
3480       unsigned ArgOffset = VA.getLocMemOffset();
3481       // Stack objects in PPC32 are right justified.
3482       ArgOffset += ArgSize - ObjSize;
3483       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, 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       LLVM_FALLTHROUGH;
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   // We do need to reserve X2 to appease the verifier for the PATCHPOINT.
5055   if (isSVR4ABI && isPPC64) {
5056     setUsesTOCBasePtr(DAG);
5057 
5058     // We cannot add X2 as an operand here for PATCHPOINT, because there is no
5059     // way to mark dependencies as implicit here. We will add the X2 dependency
5060     // in EmitInstrWithCustomInserter.
5061     if (!isPatchPoint)
5062       Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
5063   }
5064 
5065   return CallOpc;
5066 }
5067 
5068 SDValue PPCTargetLowering::LowerCallResult(
5069     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5070     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5071     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5072   SmallVector<CCValAssign, 16> RVLocs;
5073   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5074                     *DAG.getContext());
5075 
5076   CCRetInfo.AnalyzeCallResult(
5077       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5078                ? RetCC_PPC_Cold
5079                : RetCC_PPC);
5080 
5081   // Copy all of the result registers out of their specified physreg.
5082   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5083     CCValAssign &VA = RVLocs[i];
5084     assert(VA.isRegLoc() && "Can only return in registers!");
5085 
5086     SDValue Val = DAG.getCopyFromReg(Chain, dl,
5087                                      VA.getLocReg(), VA.getLocVT(), InFlag);
5088     Chain = Val.getValue(1);
5089     InFlag = Val.getValue(2);
5090 
5091     switch (VA.getLocInfo()) {
5092     default: llvm_unreachable("Unknown loc info!");
5093     case CCValAssign::Full: break;
5094     case CCValAssign::AExt:
5095       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5096       break;
5097     case CCValAssign::ZExt:
5098       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5099                         DAG.getValueType(VA.getValVT()));
5100       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5101       break;
5102     case CCValAssign::SExt:
5103       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5104                         DAG.getValueType(VA.getValVT()));
5105       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5106       break;
5107     }
5108 
5109     InVals.push_back(Val);
5110   }
5111 
5112   return Chain;
5113 }
5114 
5115 SDValue PPCTargetLowering::FinishCall(
5116     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
5117     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5118     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
5119     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5120     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5121     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5122   std::vector<EVT> NodeTys;
5123   SmallVector<SDValue, 8> Ops;
5124   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
5125                                  SPDiff, isTailCall, isPatchPoint, hasNest,
5126                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
5127 
5128   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5129   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
5130     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5131 
5132   // When performing tail call optimization the callee pops its arguments off
5133   // the stack. Account for this here so these bytes can be pushed back on in
5134   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5135   int BytesCalleePops =
5136     (CallConv == CallingConv::Fast &&
5137      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
5138 
5139   // Add a register mask operand representing the call-preserved registers.
5140   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5141   const uint32_t *Mask =
5142       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
5143   assert(Mask && "Missing call preserved mask for calling convention");
5144   Ops.push_back(DAG.getRegisterMask(Mask));
5145 
5146   if (InFlag.getNode())
5147     Ops.push_back(InFlag);
5148 
5149   // Emit tail call.
5150   if (isTailCall) {
5151     assert(((Callee.getOpcode() == ISD::Register &&
5152              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5153             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5154             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5155             isa<ConstantSDNode>(Callee)) &&
5156     "Expecting an global address, external symbol, absolute value or register");
5157 
5158     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5159     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
5160   }
5161 
5162   // Add a NOP immediately after the branch instruction when using the 64-bit
5163   // SVR4 or the AIX ABI.
5164   // At link time, if caller and callee are in a different module and
5165   // thus have a different TOC, the call will be replaced with a call to a stub
5166   // function which saves the current TOC, loads the TOC of the callee and
5167   // branches to the callee. The NOP will be replaced with a load instruction
5168   // which restores the TOC of the caller from the TOC save slot of the current
5169   // stack frame. If caller and callee belong to the same module (and have the
5170   // same TOC), the NOP will remain unchanged, or become some other NOP.
5171 
5172   MachineFunction &MF = DAG.getMachineFunction();
5173   if (!isTailCall && !isPatchPoint &&
5174       ((Subtarget.isSVR4ABI() && Subtarget.isPPC64()) ||
5175        Subtarget.isAIXABI())) {
5176     if (CallOpc == PPCISD::BCTRL) {
5177       if (Subtarget.isAIXABI())
5178         report_fatal_error("Indirect call on AIX is not implemented.");
5179 
5180       // This is a call through a function pointer.
5181       // Restore the caller TOC from the save area into R2.
5182       // See PrepareCall() for more information about calls through function
5183       // pointers in the 64-bit SVR4 ABI.
5184       // We are using a target-specific load with r2 hard coded, because the
5185       // result of a target-independent load would never go directly into r2,
5186       // since r2 is a reserved register (which prevents the register allocator
5187       // from allocating it), resulting in an additional register being
5188       // allocated and an unnecessary move instruction being generated.
5189       CallOpc = PPCISD::BCTRL_LOAD_TOC;
5190 
5191       EVT PtrVT = getPointerTy(DAG.getDataLayout());
5192       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
5193       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5194       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5195       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
5196 
5197       // The address needs to go after the chain input but before the flag (or
5198       // any other variadic arguments).
5199       Ops.insert(std::next(Ops.begin()), AddTOC);
5200     } else if (CallOpc == PPCISD::CALL &&
5201       !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) {
5202       // Otherwise insert NOP for non-local calls.
5203       CallOpc = PPCISD::CALL_NOP;
5204     }
5205   }
5206 
5207   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
5208   InFlag = Chain.getValue(1);
5209 
5210   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5211                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5212                              InFlag, dl);
5213   if (!Ins.empty())
5214     InFlag = Chain.getValue(1);
5215 
5216   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
5217                          Ins, dl, DAG, InVals);
5218 }
5219 
5220 SDValue
5221 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5222                              SmallVectorImpl<SDValue> &InVals) const {
5223   SelectionDAG &DAG                     = CLI.DAG;
5224   SDLoc &dl                             = CLI.DL;
5225   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5226   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5227   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5228   SDValue Chain                         = CLI.Chain;
5229   SDValue Callee                        = CLI.Callee;
5230   bool &isTailCall                      = CLI.IsTailCall;
5231   CallingConv::ID CallConv              = CLI.CallConv;
5232   bool isVarArg                         = CLI.IsVarArg;
5233   bool isPatchPoint                     = CLI.IsPatchPoint;
5234   ImmutableCallSite CS                  = CLI.CS;
5235 
5236   if (isTailCall) {
5237     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5238       isTailCall = false;
5239     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5240       isTailCall =
5241         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5242                                                  isVarArg, Outs, Ins, DAG);
5243     else
5244       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5245                                                      Ins, DAG);
5246     if (isTailCall) {
5247       ++NumTailCalls;
5248       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5249         ++NumSiblingCalls;
5250 
5251       assert(isa<GlobalAddressSDNode>(Callee) &&
5252              "Callee should be an llvm::Function object.");
5253       LLVM_DEBUG(
5254           const GlobalValue *GV =
5255               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5256           const unsigned Width =
5257               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5258           dbgs() << "TCO caller: "
5259                  << left_justify(DAG.getMachineFunction().getName(), Width)
5260                  << ", callee linkage: " << GV->getVisibility() << ", "
5261                  << GV->getLinkage() << "\n");
5262     }
5263   }
5264 
5265   if (!isTailCall && CS && CS.isMustTailCall())
5266     report_fatal_error("failed to perform tail call elimination on a call "
5267                        "site marked musttail");
5268 
5269   // When long calls (i.e. indirect calls) are always used, calls are always
5270   // made via function pointer. If we have a function name, first translate it
5271   // into a pointer.
5272   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5273       !isTailCall)
5274     Callee = LowerGlobalAddress(Callee, DAG);
5275 
5276   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5277     return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
5278                             isTailCall, isPatchPoint, Outs, OutVals, Ins,
5279                             dl, DAG, InVals, CS);
5280 
5281   if (Subtarget.isSVR4ABI())
5282     return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
5283                             isTailCall, isPatchPoint, Outs, OutVals, Ins,
5284                             dl, DAG, InVals, CS);
5285 
5286   if (Subtarget.isAIXABI())
5287     return LowerCall_AIX(Chain, Callee, CallConv, isVarArg,
5288                          isTailCall, isPatchPoint, Outs, OutVals, Ins,
5289                          dl, DAG, InVals, CS);
5290 
5291   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
5292                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
5293                           dl, DAG, InVals, CS);
5294 }
5295 
5296 SDValue PPCTargetLowering::LowerCall_32SVR4(
5297     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5298     bool isTailCall, bool isPatchPoint,
5299     const SmallVectorImpl<ISD::OutputArg> &Outs,
5300     const SmallVectorImpl<SDValue> &OutVals,
5301     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5302     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5303     ImmutableCallSite CS) const {
5304   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5305   // of the 32-bit SVR4 ABI stack frame layout.
5306 
5307   assert((CallConv == CallingConv::C ||
5308           CallConv == CallingConv::Cold ||
5309           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5310 
5311   unsigned PtrByteSize = 4;
5312 
5313   MachineFunction &MF = DAG.getMachineFunction();
5314 
5315   // Mark this function as potentially containing a function that contains a
5316   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5317   // and restoring the callers stack pointer in this functions epilog. This is
5318   // done because by tail calling the called function might overwrite the value
5319   // in this function's (MF) stack pointer stack slot 0(SP).
5320   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5321       CallConv == CallingConv::Fast)
5322     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5323 
5324   // Count how many bytes are to be pushed on the stack, including the linkage
5325   // area, parameter list area and the part of the local variable space which
5326   // contains copies of aggregates which are passed by value.
5327 
5328   // Assign locations to all of the outgoing arguments.
5329   SmallVector<CCValAssign, 16> ArgLocs;
5330   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5331 
5332   // Reserve space for the linkage area on the stack.
5333   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5334                        PtrByteSize);
5335   if (useSoftFloat())
5336     CCInfo.PreAnalyzeCallOperands(Outs);
5337 
5338   if (isVarArg) {
5339     // Handle fixed and variable vector arguments differently.
5340     // Fixed vector arguments go into registers as long as registers are
5341     // available. Variable vector arguments always go into memory.
5342     unsigned NumArgs = Outs.size();
5343 
5344     for (unsigned i = 0; i != NumArgs; ++i) {
5345       MVT ArgVT = Outs[i].VT;
5346       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5347       bool Result;
5348 
5349       if (Outs[i].IsFixed) {
5350         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5351                                CCInfo);
5352       } else {
5353         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5354                                       ArgFlags, CCInfo);
5355       }
5356 
5357       if (Result) {
5358 #ifndef NDEBUG
5359         errs() << "Call operand #" << i << " has unhandled type "
5360              << EVT(ArgVT).getEVTString() << "\n";
5361 #endif
5362         llvm_unreachable(nullptr);
5363       }
5364     }
5365   } else {
5366     // All arguments are treated the same.
5367     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5368   }
5369   CCInfo.clearWasPPCF128();
5370 
5371   // Assign locations to all of the outgoing aggregate by value arguments.
5372   SmallVector<CCValAssign, 16> ByValArgLocs;
5373   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5374 
5375   // Reserve stack space for the allocations in CCInfo.
5376   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5377 
5378   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5379 
5380   // Size of the linkage area, parameter list area and the part of the local
5381   // space variable where copies of aggregates which are passed by value are
5382   // stored.
5383   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5384 
5385   // Calculate by how many bytes the stack has to be adjusted in case of tail
5386   // call optimization.
5387   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5388 
5389   // Adjust the stack pointer for the new arguments...
5390   // These operations are automatically eliminated by the prolog/epilog pass
5391   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5392   SDValue CallSeqStart = Chain;
5393 
5394   // Load the return address and frame pointer so it can be moved somewhere else
5395   // later.
5396   SDValue LROp, FPOp;
5397   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5398 
5399   // Set up a copy of the stack pointer for use loading and storing any
5400   // arguments that may not fit in the registers available for argument
5401   // passing.
5402   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5403 
5404   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5405   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5406   SmallVector<SDValue, 8> MemOpChains;
5407 
5408   bool seenFloatArg = false;
5409   // Walk the register/memloc assignments, inserting copies/loads.
5410   for (unsigned i = 0, j = 0, e = ArgLocs.size();
5411        i != e;
5412        ++i) {
5413     CCValAssign &VA = ArgLocs[i];
5414     SDValue Arg = OutVals[i];
5415     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5416 
5417     if (Flags.isByVal()) {
5418       // Argument is an aggregate which is passed by value, thus we need to
5419       // create a copy of it in the local variable space of the current stack
5420       // frame (which is the stack frame of the caller) and pass the address of
5421       // this copy to the callee.
5422       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5423       CCValAssign &ByValVA = ByValArgLocs[j++];
5424       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5425 
5426       // Memory reserved in the local variable space of the callers stack frame.
5427       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5428 
5429       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5430       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5431                            StackPtr, PtrOff);
5432 
5433       // Create a copy of the argument in the local area of the current
5434       // stack frame.
5435       SDValue MemcpyCall =
5436         CreateCopyOfByValArgument(Arg, PtrOff,
5437                                   CallSeqStart.getNode()->getOperand(0),
5438                                   Flags, DAG, dl);
5439 
5440       // This must go outside the CALLSEQ_START..END.
5441       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5442                                                      SDLoc(MemcpyCall));
5443       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5444                              NewCallSeqStart.getNode());
5445       Chain = CallSeqStart = NewCallSeqStart;
5446 
5447       // Pass the address of the aggregate copy on the stack either in a
5448       // physical register or in the parameter list area of the current stack
5449       // frame to the callee.
5450       Arg = PtrOff;
5451     }
5452 
5453     // When useCRBits() is true, there can be i1 arguments.
5454     // It is because getRegisterType(MVT::i1) => MVT::i1,
5455     // and for other integer types getRegisterType() => MVT::i32.
5456     // Extend i1 and ensure callee will get i32.
5457     if (Arg.getValueType() == MVT::i1)
5458       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5459                         dl, MVT::i32, Arg);
5460 
5461     if (VA.isRegLoc()) {
5462       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5463       // Put argument in a physical register.
5464       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5465     } else {
5466       // Put argument in the parameter list area of the current stack frame.
5467       assert(VA.isMemLoc());
5468       unsigned LocMemOffset = VA.getLocMemOffset();
5469 
5470       if (!isTailCall) {
5471         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5472         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5473                              StackPtr, PtrOff);
5474 
5475         MemOpChains.push_back(
5476             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5477       } else {
5478         // Calculate and remember argument location.
5479         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5480                                  TailCallArguments);
5481       }
5482     }
5483   }
5484 
5485   if (!MemOpChains.empty())
5486     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5487 
5488   // Build a sequence of copy-to-reg nodes chained together with token chain
5489   // and flag operands which copy the outgoing args into the appropriate regs.
5490   SDValue InFlag;
5491   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5492     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5493                              RegsToPass[i].second, InFlag);
5494     InFlag = Chain.getValue(1);
5495   }
5496 
5497   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5498   // registers.
5499   if (isVarArg) {
5500     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5501     SDValue Ops[] = { Chain, InFlag };
5502 
5503     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5504                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5505 
5506     InFlag = Chain.getValue(1);
5507   }
5508 
5509   if (isTailCall)
5510     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5511                     TailCallArguments);
5512 
5513   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5514                     /* unused except on PPC64 ELFv1 */ false, DAG,
5515                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5516                     NumBytes, Ins, InVals, CS);
5517 }
5518 
5519 // Copy an argument into memory, being careful to do this outside the
5520 // call sequence for the call to which the argument belongs.
5521 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5522     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5523     SelectionDAG &DAG, const SDLoc &dl) const {
5524   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5525                         CallSeqStart.getNode()->getOperand(0),
5526                         Flags, DAG, dl);
5527   // The MEMCPY must go outside the CALLSEQ_START..END.
5528   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5529   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5530                                                  SDLoc(MemcpyCall));
5531   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5532                          NewCallSeqStart.getNode());
5533   return NewCallSeqStart;
5534 }
5535 
5536 SDValue PPCTargetLowering::LowerCall_64SVR4(
5537     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5538     bool isTailCall, bool isPatchPoint,
5539     const SmallVectorImpl<ISD::OutputArg> &Outs,
5540     const SmallVectorImpl<SDValue> &OutVals,
5541     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5542     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5543     ImmutableCallSite CS) const {
5544   bool isELFv2ABI = Subtarget.isELFv2ABI();
5545   bool isLittleEndian = Subtarget.isLittleEndian();
5546   unsigned NumOps = Outs.size();
5547   bool hasNest = false;
5548   bool IsSibCall = false;
5549 
5550   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5551   unsigned PtrByteSize = 8;
5552 
5553   MachineFunction &MF = DAG.getMachineFunction();
5554 
5555   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5556     IsSibCall = true;
5557 
5558   // Mark this function as potentially containing a function that contains a
5559   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5560   // and restoring the callers stack pointer in this functions epilog. This is
5561   // done because by tail calling the called function might overwrite the value
5562   // in this function's (MF) stack pointer stack slot 0(SP).
5563   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5564       CallConv == CallingConv::Fast)
5565     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5566 
5567   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5568          "fastcc not supported on varargs functions");
5569 
5570   // Count how many bytes are to be pushed on the stack, including the linkage
5571   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5572   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5573   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5574   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5575   unsigned NumBytes = LinkageSize;
5576   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5577   unsigned &QFPR_idx = FPR_idx;
5578 
5579   static const MCPhysReg GPR[] = {
5580     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5581     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5582   };
5583   static const MCPhysReg VR[] = {
5584     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5585     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5586   };
5587 
5588   const unsigned NumGPRs = array_lengthof(GPR);
5589   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5590   const unsigned NumVRs  = array_lengthof(VR);
5591   const unsigned NumQFPRs = NumFPRs;
5592 
5593   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5594   // can be passed to the callee in registers.
5595   // For the fast calling convention, there is another check below.
5596   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5597   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5598   if (!HasParameterArea) {
5599     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5600     unsigned AvailableFPRs = NumFPRs;
5601     unsigned AvailableVRs = NumVRs;
5602     unsigned NumBytesTmp = NumBytes;
5603     for (unsigned i = 0; i != NumOps; ++i) {
5604       if (Outs[i].Flags.isNest()) continue;
5605       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5606                                 PtrByteSize, LinkageSize, ParamAreaSize,
5607                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5608                                 Subtarget.hasQPX()))
5609         HasParameterArea = true;
5610     }
5611   }
5612 
5613   // When using the fast calling convention, we don't provide backing for
5614   // arguments that will be in registers.
5615   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5616 
5617   // Avoid allocating parameter area for fastcc functions if all the arguments
5618   // can be passed in the registers.
5619   if (CallConv == CallingConv::Fast)
5620     HasParameterArea = false;
5621 
5622   // Add up all the space actually used.
5623   for (unsigned i = 0; i != NumOps; ++i) {
5624     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5625     EVT ArgVT = Outs[i].VT;
5626     EVT OrigVT = Outs[i].ArgVT;
5627 
5628     if (Flags.isNest())
5629       continue;
5630 
5631     if (CallConv == CallingConv::Fast) {
5632       if (Flags.isByVal()) {
5633         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5634         if (NumGPRsUsed > NumGPRs)
5635           HasParameterArea = true;
5636       } else {
5637         switch (ArgVT.getSimpleVT().SimpleTy) {
5638         default: llvm_unreachable("Unexpected ValueType for argument!");
5639         case MVT::i1:
5640         case MVT::i32:
5641         case MVT::i64:
5642           if (++NumGPRsUsed <= NumGPRs)
5643             continue;
5644           break;
5645         case MVT::v4i32:
5646         case MVT::v8i16:
5647         case MVT::v16i8:
5648         case MVT::v2f64:
5649         case MVT::v2i64:
5650         case MVT::v1i128:
5651         case MVT::f128:
5652           if (++NumVRsUsed <= NumVRs)
5653             continue;
5654           break;
5655         case MVT::v4f32:
5656           // When using QPX, this is handled like a FP register, otherwise, it
5657           // is an Altivec register.
5658           if (Subtarget.hasQPX()) {
5659             if (++NumFPRsUsed <= NumFPRs)
5660               continue;
5661           } else {
5662             if (++NumVRsUsed <= NumVRs)
5663               continue;
5664           }
5665           break;
5666         case MVT::f32:
5667         case MVT::f64:
5668         case MVT::v4f64: // QPX
5669         case MVT::v4i1:  // QPX
5670           if (++NumFPRsUsed <= NumFPRs)
5671             continue;
5672           break;
5673         }
5674         HasParameterArea = true;
5675       }
5676     }
5677 
5678     /* Respect alignment of argument on the stack.  */
5679     unsigned Align =
5680       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5681     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5682 
5683     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5684     if (Flags.isInConsecutiveRegsLast())
5685       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5686   }
5687 
5688   unsigned NumBytesActuallyUsed = NumBytes;
5689 
5690   // In the old ELFv1 ABI,
5691   // the prolog code of the callee may store up to 8 GPR argument registers to
5692   // the stack, allowing va_start to index over them in memory if its varargs.
5693   // Because we cannot tell if this is needed on the caller side, we have to
5694   // conservatively assume that it is needed.  As such, make sure we have at
5695   // least enough stack space for the caller to store the 8 GPRs.
5696   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5697   // really requires memory operands, e.g. a vararg function.
5698   if (HasParameterArea)
5699     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5700   else
5701     NumBytes = LinkageSize;
5702 
5703   // Tail call needs the stack to be aligned.
5704   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5705       CallConv == CallingConv::Fast)
5706     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5707 
5708   int SPDiff = 0;
5709 
5710   // Calculate by how many bytes the stack has to be adjusted in case of tail
5711   // call optimization.
5712   if (!IsSibCall)
5713     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5714 
5715   // To protect arguments on the stack from being clobbered in a tail call,
5716   // force all the loads to happen before doing any other lowering.
5717   if (isTailCall)
5718     Chain = DAG.getStackArgumentTokenFactor(Chain);
5719 
5720   // Adjust the stack pointer for the new arguments...
5721   // These operations are automatically eliminated by the prolog/epilog pass
5722   if (!IsSibCall)
5723     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5724   SDValue CallSeqStart = Chain;
5725 
5726   // Load the return address and frame pointer so it can be move somewhere else
5727   // later.
5728   SDValue LROp, FPOp;
5729   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5730 
5731   // Set up a copy of the stack pointer for use loading and storing any
5732   // arguments that may not fit in the registers available for argument
5733   // passing.
5734   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5735 
5736   // Figure out which arguments are going to go in registers, and which in
5737   // memory.  Also, if this is a vararg function, floating point operations
5738   // must be stored to our stack, and loaded into integer regs as well, if
5739   // any integer regs are available for argument passing.
5740   unsigned ArgOffset = LinkageSize;
5741 
5742   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5743   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5744 
5745   SmallVector<SDValue, 8> MemOpChains;
5746   for (unsigned i = 0; i != NumOps; ++i) {
5747     SDValue Arg = OutVals[i];
5748     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5749     EVT ArgVT = Outs[i].VT;
5750     EVT OrigVT = Outs[i].ArgVT;
5751 
5752     // PtrOff will be used to store the current argument to the stack if a
5753     // register cannot be found for it.
5754     SDValue PtrOff;
5755 
5756     // We re-align the argument offset for each argument, except when using the
5757     // fast calling convention, when we need to make sure we do that only when
5758     // we'll actually use a stack slot.
5759     auto ComputePtrOff = [&]() {
5760       /* Respect alignment of argument on the stack.  */
5761       unsigned Align =
5762         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5763       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5764 
5765       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5766 
5767       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5768     };
5769 
5770     if (CallConv != CallingConv::Fast) {
5771       ComputePtrOff();
5772 
5773       /* Compute GPR index associated with argument offset.  */
5774       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5775       GPR_idx = std::min(GPR_idx, NumGPRs);
5776     }
5777 
5778     // Promote integers to 64-bit values.
5779     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5780       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5781       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5782       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5783     }
5784 
5785     // FIXME memcpy is used way more than necessary.  Correctness first.
5786     // Note: "by value" is code for passing a structure by value, not
5787     // basic types.
5788     if (Flags.isByVal()) {
5789       // Note: Size includes alignment padding, so
5790       //   struct x { short a; char b; }
5791       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5792       // These are the proper values we need for right-justifying the
5793       // aggregate in a parameter register.
5794       unsigned Size = Flags.getByValSize();
5795 
5796       // An empty aggregate parameter takes up no storage and no
5797       // registers.
5798       if (Size == 0)
5799         continue;
5800 
5801       if (CallConv == CallingConv::Fast)
5802         ComputePtrOff();
5803 
5804       // All aggregates smaller than 8 bytes must be passed right-justified.
5805       if (Size==1 || Size==2 || Size==4) {
5806         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5807         if (GPR_idx != NumGPRs) {
5808           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5809                                         MachinePointerInfo(), VT);
5810           MemOpChains.push_back(Load.getValue(1));
5811           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5812 
5813           ArgOffset += PtrByteSize;
5814           continue;
5815         }
5816       }
5817 
5818       if (GPR_idx == NumGPRs && Size < 8) {
5819         SDValue AddPtr = PtrOff;
5820         if (!isLittleEndian) {
5821           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5822                                           PtrOff.getValueType());
5823           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5824         }
5825         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5826                                                           CallSeqStart,
5827                                                           Flags, DAG, dl);
5828         ArgOffset += PtrByteSize;
5829         continue;
5830       }
5831       // Copy entire object into memory.  There are cases where gcc-generated
5832       // code assumes it is there, even if it could be put entirely into
5833       // registers.  (This is not what the doc says.)
5834 
5835       // FIXME: The above statement is likely due to a misunderstanding of the
5836       // documents.  All arguments must be copied into the parameter area BY
5837       // THE CALLEE in the event that the callee takes the address of any
5838       // formal argument.  That has not yet been implemented.  However, it is
5839       // reasonable to use the stack area as a staging area for the register
5840       // load.
5841 
5842       // Skip this for small aggregates, as we will use the same slot for a
5843       // right-justified copy, below.
5844       if (Size >= 8)
5845         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5846                                                           CallSeqStart,
5847                                                           Flags, DAG, dl);
5848 
5849       // When a register is available, pass a small aggregate right-justified.
5850       if (Size < 8 && GPR_idx != NumGPRs) {
5851         // The easiest way to get this right-justified in a register
5852         // is to copy the structure into the rightmost portion of a
5853         // local variable slot, then load the whole slot into the
5854         // register.
5855         // FIXME: The memcpy seems to produce pretty awful code for
5856         // small aggregates, particularly for packed ones.
5857         // FIXME: It would be preferable to use the slot in the
5858         // parameter save area instead of a new local variable.
5859         SDValue AddPtr = PtrOff;
5860         if (!isLittleEndian) {
5861           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5862           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5863         }
5864         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5865                                                           CallSeqStart,
5866                                                           Flags, DAG, dl);
5867 
5868         // Load the slot into the register.
5869         SDValue Load =
5870             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5871         MemOpChains.push_back(Load.getValue(1));
5872         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5873 
5874         // Done with this argument.
5875         ArgOffset += PtrByteSize;
5876         continue;
5877       }
5878 
5879       // For aggregates larger than PtrByteSize, copy the pieces of the
5880       // object that fit into registers from the parameter save area.
5881       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5882         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5883         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5884         if (GPR_idx != NumGPRs) {
5885           SDValue Load =
5886               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5887           MemOpChains.push_back(Load.getValue(1));
5888           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5889           ArgOffset += PtrByteSize;
5890         } else {
5891           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5892           break;
5893         }
5894       }
5895       continue;
5896     }
5897 
5898     switch (Arg.getSimpleValueType().SimpleTy) {
5899     default: llvm_unreachable("Unexpected ValueType for argument!");
5900     case MVT::i1:
5901     case MVT::i32:
5902     case MVT::i64:
5903       if (Flags.isNest()) {
5904         // The 'nest' parameter, if any, is passed in R11.
5905         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5906         hasNest = true;
5907         break;
5908       }
5909 
5910       // These can be scalar arguments or elements of an integer array type
5911       // passed directly.  Clang may use those instead of "byval" aggregate
5912       // types to avoid forcing arguments to memory unnecessarily.
5913       if (GPR_idx != NumGPRs) {
5914         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5915       } else {
5916         if (CallConv == CallingConv::Fast)
5917           ComputePtrOff();
5918 
5919         assert(HasParameterArea &&
5920                "Parameter area must exist to pass an argument in memory.");
5921         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5922                          true, isTailCall, false, MemOpChains,
5923                          TailCallArguments, dl);
5924         if (CallConv == CallingConv::Fast)
5925           ArgOffset += PtrByteSize;
5926       }
5927       if (CallConv != CallingConv::Fast)
5928         ArgOffset += PtrByteSize;
5929       break;
5930     case MVT::f32:
5931     case MVT::f64: {
5932       // These can be scalar arguments or elements of a float array type
5933       // passed directly.  The latter are used to implement ELFv2 homogenous
5934       // float aggregates.
5935 
5936       // Named arguments go into FPRs first, and once they overflow, the
5937       // remaining arguments go into GPRs and then the parameter save area.
5938       // Unnamed arguments for vararg functions always go to GPRs and
5939       // then the parameter save area.  For now, put all arguments to vararg
5940       // routines always in both locations (FPR *and* GPR or stack slot).
5941       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5942       bool NeededLoad = false;
5943 
5944       // First load the argument into the next available FPR.
5945       if (FPR_idx != NumFPRs)
5946         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5947 
5948       // Next, load the argument into GPR or stack slot if needed.
5949       if (!NeedGPROrStack)
5950         ;
5951       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5952         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5953         // once we support fp <-> gpr moves.
5954 
5955         // In the non-vararg case, this can only ever happen in the
5956         // presence of f32 array types, since otherwise we never run
5957         // out of FPRs before running out of GPRs.
5958         SDValue ArgVal;
5959 
5960         // Double values are always passed in a single GPR.
5961         if (Arg.getValueType() != MVT::f32) {
5962           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5963 
5964         // Non-array float values are extended and passed in a GPR.
5965         } else if (!Flags.isInConsecutiveRegs()) {
5966           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5967           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5968 
5969         // If we have an array of floats, we collect every odd element
5970         // together with its predecessor into one GPR.
5971         } else if (ArgOffset % PtrByteSize != 0) {
5972           SDValue Lo, Hi;
5973           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5974           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5975           if (!isLittleEndian)
5976             std::swap(Lo, Hi);
5977           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5978 
5979         // The final element, if even, goes into the first half of a GPR.
5980         } else if (Flags.isInConsecutiveRegsLast()) {
5981           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5982           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5983           if (!isLittleEndian)
5984             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5985                                  DAG.getConstant(32, dl, MVT::i32));
5986 
5987         // Non-final even elements are skipped; they will be handled
5988         // together the with subsequent argument on the next go-around.
5989         } else
5990           ArgVal = SDValue();
5991 
5992         if (ArgVal.getNode())
5993           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5994       } else {
5995         if (CallConv == CallingConv::Fast)
5996           ComputePtrOff();
5997 
5998         // Single-precision floating-point values are mapped to the
5999         // second (rightmost) word of the stack doubleword.
6000         if (Arg.getValueType() == MVT::f32 &&
6001             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6002           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6003           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6004         }
6005 
6006         assert(HasParameterArea &&
6007                "Parameter area must exist to pass an argument in memory.");
6008         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6009                          true, isTailCall, false, MemOpChains,
6010                          TailCallArguments, dl);
6011 
6012         NeededLoad = true;
6013       }
6014       // When passing an array of floats, the array occupies consecutive
6015       // space in the argument area; only round up to the next doubleword
6016       // at the end of the array.  Otherwise, each float takes 8 bytes.
6017       if (CallConv != CallingConv::Fast || NeededLoad) {
6018         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6019                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6020         if (Flags.isInConsecutiveRegsLast())
6021           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6022       }
6023       break;
6024     }
6025     case MVT::v4f32:
6026     case MVT::v4i32:
6027     case MVT::v8i16:
6028     case MVT::v16i8:
6029     case MVT::v2f64:
6030     case MVT::v2i64:
6031     case MVT::v1i128:
6032     case MVT::f128:
6033       if (!Subtarget.hasQPX()) {
6034       // These can be scalar arguments or elements of a vector array type
6035       // passed directly.  The latter are used to implement ELFv2 homogenous
6036       // vector aggregates.
6037 
6038       // For a varargs call, named arguments go into VRs or on the stack as
6039       // usual; unnamed arguments always go to the stack or the corresponding
6040       // GPRs when within range.  For now, we always put the value in both
6041       // locations (or even all three).
6042       if (isVarArg) {
6043         assert(HasParameterArea &&
6044                "Parameter area must exist if we have a varargs call.");
6045         // We could elide this store in the case where the object fits
6046         // entirely in R registers.  Maybe later.
6047         SDValue Store =
6048             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6049         MemOpChains.push_back(Store);
6050         if (VR_idx != NumVRs) {
6051           SDValue Load =
6052               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6053           MemOpChains.push_back(Load.getValue(1));
6054           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6055         }
6056         ArgOffset += 16;
6057         for (unsigned i=0; i<16; i+=PtrByteSize) {
6058           if (GPR_idx == NumGPRs)
6059             break;
6060           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6061                                    DAG.getConstant(i, dl, PtrVT));
6062           SDValue Load =
6063               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6064           MemOpChains.push_back(Load.getValue(1));
6065           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6066         }
6067         break;
6068       }
6069 
6070       // Non-varargs Altivec params go into VRs or on the stack.
6071       if (VR_idx != NumVRs) {
6072         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6073       } else {
6074         if (CallConv == CallingConv::Fast)
6075           ComputePtrOff();
6076 
6077         assert(HasParameterArea &&
6078                "Parameter area must exist to pass an argument in memory.");
6079         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6080                          true, isTailCall, true, MemOpChains,
6081                          TailCallArguments, dl);
6082         if (CallConv == CallingConv::Fast)
6083           ArgOffset += 16;
6084       }
6085 
6086       if (CallConv != CallingConv::Fast)
6087         ArgOffset += 16;
6088       break;
6089       } // not QPX
6090 
6091       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6092              "Invalid QPX parameter type");
6093 
6094       LLVM_FALLTHROUGH;
6095     case MVT::v4f64:
6096     case MVT::v4i1: {
6097       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6098       if (isVarArg) {
6099         assert(HasParameterArea &&
6100                "Parameter area must exist if we have a varargs call.");
6101         // We could elide this store in the case where the object fits
6102         // entirely in R registers.  Maybe later.
6103         SDValue Store =
6104             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6105         MemOpChains.push_back(Store);
6106         if (QFPR_idx != NumQFPRs) {
6107           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6108                                      PtrOff, MachinePointerInfo());
6109           MemOpChains.push_back(Load.getValue(1));
6110           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6111         }
6112         ArgOffset += (IsF32 ? 16 : 32);
6113         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6114           if (GPR_idx == NumGPRs)
6115             break;
6116           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6117                                    DAG.getConstant(i, dl, PtrVT));
6118           SDValue Load =
6119               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6120           MemOpChains.push_back(Load.getValue(1));
6121           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6122         }
6123         break;
6124       }
6125 
6126       // Non-varargs QPX params go into registers or on the stack.
6127       if (QFPR_idx != NumQFPRs) {
6128         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6129       } else {
6130         if (CallConv == CallingConv::Fast)
6131           ComputePtrOff();
6132 
6133         assert(HasParameterArea &&
6134                "Parameter area must exist to pass an argument in memory.");
6135         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6136                          true, isTailCall, true, MemOpChains,
6137                          TailCallArguments, dl);
6138         if (CallConv == CallingConv::Fast)
6139           ArgOffset += (IsF32 ? 16 : 32);
6140       }
6141 
6142       if (CallConv != CallingConv::Fast)
6143         ArgOffset += (IsF32 ? 16 : 32);
6144       break;
6145       }
6146     }
6147   }
6148 
6149   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6150          "mismatch in size of parameter area");
6151   (void)NumBytesActuallyUsed;
6152 
6153   if (!MemOpChains.empty())
6154     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6155 
6156   // Check if this is an indirect call (MTCTR/BCTRL).
6157   // See PrepareCall() for more information about calls through function
6158   // pointers in the 64-bit SVR4 ABI.
6159   if (!isTailCall && !isPatchPoint &&
6160       !isFunctionGlobalAddress(Callee) &&
6161       !isa<ExternalSymbolSDNode>(Callee)) {
6162     // Load r2 into a virtual register and store it to the TOC save area.
6163     setUsesTOCBasePtr(DAG);
6164     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6165     // TOC save area offset.
6166     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6167     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6168     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6169     Chain = DAG.getStore(
6170         Val.getValue(1), dl, Val, AddPtr,
6171         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6172     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6173     // This does not mean the MTCTR instruction must use R12; it's easier
6174     // to model this as an extra parameter, so do that.
6175     if (isELFv2ABI && !isPatchPoint)
6176       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6177   }
6178 
6179   // Build a sequence of copy-to-reg nodes chained together with token chain
6180   // and flag operands which copy the outgoing args into the appropriate regs.
6181   SDValue InFlag;
6182   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6183     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6184                              RegsToPass[i].second, InFlag);
6185     InFlag = Chain.getValue(1);
6186   }
6187 
6188   if (isTailCall && !IsSibCall)
6189     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6190                     TailCallArguments);
6191 
6192   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
6193                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
6194                     SPDiff, NumBytes, Ins, InVals, CS);
6195 }
6196 
6197 SDValue PPCTargetLowering::LowerCall_Darwin(
6198     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6199     bool isTailCall, bool isPatchPoint,
6200     const SmallVectorImpl<ISD::OutputArg> &Outs,
6201     const SmallVectorImpl<SDValue> &OutVals,
6202     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6203     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6204     ImmutableCallSite CS) const {
6205   unsigned NumOps = Outs.size();
6206 
6207   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6208   bool isPPC64 = PtrVT == MVT::i64;
6209   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6210 
6211   MachineFunction &MF = DAG.getMachineFunction();
6212 
6213   // Mark this function as potentially containing a function that contains a
6214   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6215   // and restoring the callers stack pointer in this functions epilog. This is
6216   // done because by tail calling the called function might overwrite the value
6217   // in this function's (MF) stack pointer stack slot 0(SP).
6218   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6219       CallConv == CallingConv::Fast)
6220     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6221 
6222   // Count how many bytes are to be pushed on the stack, including the linkage
6223   // area, and parameter passing area.  We start with 24/48 bytes, which is
6224   // prereserved space for [SP][CR][LR][3 x unused].
6225   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6226   unsigned NumBytes = LinkageSize;
6227 
6228   // Add up all the space actually used.
6229   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6230   // they all go in registers, but we must reserve stack space for them for
6231   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6232   // assigned stack space in order, with padding so Altivec parameters are
6233   // 16-byte aligned.
6234   unsigned nAltivecParamsAtEnd = 0;
6235   for (unsigned i = 0; i != NumOps; ++i) {
6236     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6237     EVT ArgVT = Outs[i].VT;
6238     // Varargs Altivec parameters are padded to a 16 byte boundary.
6239     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6240         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6241         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6242       if (!isVarArg && !isPPC64) {
6243         // Non-varargs Altivec parameters go after all the non-Altivec
6244         // parameters; handle those later so we know how much padding we need.
6245         nAltivecParamsAtEnd++;
6246         continue;
6247       }
6248       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6249       NumBytes = ((NumBytes+15)/16)*16;
6250     }
6251     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6252   }
6253 
6254   // Allow for Altivec parameters at the end, if needed.
6255   if (nAltivecParamsAtEnd) {
6256     NumBytes = ((NumBytes+15)/16)*16;
6257     NumBytes += 16*nAltivecParamsAtEnd;
6258   }
6259 
6260   // The prolog code of the callee may store up to 8 GPR argument registers to
6261   // the stack, allowing va_start to index over them in memory if its varargs.
6262   // Because we cannot tell if this is needed on the caller side, we have to
6263   // conservatively assume that it is needed.  As such, make sure we have at
6264   // least enough stack space for the caller to store the 8 GPRs.
6265   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6266 
6267   // Tail call needs the stack to be aligned.
6268   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6269       CallConv == CallingConv::Fast)
6270     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6271 
6272   // Calculate by how many bytes the stack has to be adjusted in case of tail
6273   // call optimization.
6274   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
6275 
6276   // To protect arguments on the stack from being clobbered in a tail call,
6277   // force all the loads to happen before doing any other lowering.
6278   if (isTailCall)
6279     Chain = DAG.getStackArgumentTokenFactor(Chain);
6280 
6281   // Adjust the stack pointer for the new arguments...
6282   // These operations are automatically eliminated by the prolog/epilog pass
6283   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6284   SDValue CallSeqStart = Chain;
6285 
6286   // Load the return address and frame pointer so it can be move somewhere else
6287   // later.
6288   SDValue LROp, FPOp;
6289   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6290 
6291   // Set up a copy of the stack pointer for use loading and storing any
6292   // arguments that may not fit in the registers available for argument
6293   // passing.
6294   SDValue StackPtr;
6295   if (isPPC64)
6296     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6297   else
6298     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6299 
6300   // Figure out which arguments are going to go in registers, and which in
6301   // memory.  Also, if this is a vararg function, floating point operations
6302   // must be stored to our stack, and loaded into integer regs as well, if
6303   // any integer regs are available for argument passing.
6304   unsigned ArgOffset = LinkageSize;
6305   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6306 
6307   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6308     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6309     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6310   };
6311   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6312     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6313     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6314   };
6315   static const MCPhysReg VR[] = {
6316     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6317     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6318   };
6319   const unsigned NumGPRs = array_lengthof(GPR_32);
6320   const unsigned NumFPRs = 13;
6321   const unsigned NumVRs  = array_lengthof(VR);
6322 
6323   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6324 
6325   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6326   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6327 
6328   SmallVector<SDValue, 8> MemOpChains;
6329   for (unsigned i = 0; i != NumOps; ++i) {
6330     SDValue Arg = OutVals[i];
6331     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6332 
6333     // PtrOff will be used to store the current argument to the stack if a
6334     // register cannot be found for it.
6335     SDValue PtrOff;
6336 
6337     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6338 
6339     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6340 
6341     // On PPC64, promote integers to 64-bit values.
6342     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6343       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6344       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6345       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6346     }
6347 
6348     // FIXME memcpy is used way more than necessary.  Correctness first.
6349     // Note: "by value" is code for passing a structure by value, not
6350     // basic types.
6351     if (Flags.isByVal()) {
6352       unsigned Size = Flags.getByValSize();
6353       // Very small objects are passed right-justified.  Everything else is
6354       // passed left-justified.
6355       if (Size==1 || Size==2) {
6356         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6357         if (GPR_idx != NumGPRs) {
6358           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6359                                         MachinePointerInfo(), VT);
6360           MemOpChains.push_back(Load.getValue(1));
6361           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6362 
6363           ArgOffset += PtrByteSize;
6364         } else {
6365           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6366                                           PtrOff.getValueType());
6367           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6368           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6369                                                             CallSeqStart,
6370                                                             Flags, DAG, dl);
6371           ArgOffset += PtrByteSize;
6372         }
6373         continue;
6374       }
6375       // Copy entire object into memory.  There are cases where gcc-generated
6376       // code assumes it is there, even if it could be put entirely into
6377       // registers.  (This is not what the doc says.)
6378       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6379                                                         CallSeqStart,
6380                                                         Flags, DAG, dl);
6381 
6382       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6383       // copy the pieces of the object that fit into registers from the
6384       // parameter save area.
6385       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6386         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6387         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6388         if (GPR_idx != NumGPRs) {
6389           SDValue Load =
6390               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6391           MemOpChains.push_back(Load.getValue(1));
6392           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6393           ArgOffset += PtrByteSize;
6394         } else {
6395           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6396           break;
6397         }
6398       }
6399       continue;
6400     }
6401 
6402     switch (Arg.getSimpleValueType().SimpleTy) {
6403     default: llvm_unreachable("Unexpected ValueType for argument!");
6404     case MVT::i1:
6405     case MVT::i32:
6406     case MVT::i64:
6407       if (GPR_idx != NumGPRs) {
6408         if (Arg.getValueType() == MVT::i1)
6409           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6410 
6411         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6412       } else {
6413         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6414                          isPPC64, isTailCall, false, MemOpChains,
6415                          TailCallArguments, dl);
6416       }
6417       ArgOffset += PtrByteSize;
6418       break;
6419     case MVT::f32:
6420     case MVT::f64:
6421       if (FPR_idx != NumFPRs) {
6422         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6423 
6424         if (isVarArg) {
6425           SDValue Store =
6426               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6427           MemOpChains.push_back(Store);
6428 
6429           // Float varargs are always shadowed in available integer registers
6430           if (GPR_idx != NumGPRs) {
6431             SDValue Load =
6432                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6433             MemOpChains.push_back(Load.getValue(1));
6434             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6435           }
6436           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6437             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6438             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6439             SDValue Load =
6440                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6441             MemOpChains.push_back(Load.getValue(1));
6442             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6443           }
6444         } else {
6445           // If we have any FPRs remaining, we may also have GPRs remaining.
6446           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6447           // GPRs.
6448           if (GPR_idx != NumGPRs)
6449             ++GPR_idx;
6450           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6451               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6452             ++GPR_idx;
6453         }
6454       } else
6455         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6456                          isPPC64, isTailCall, false, MemOpChains,
6457                          TailCallArguments, dl);
6458       if (isPPC64)
6459         ArgOffset += 8;
6460       else
6461         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6462       break;
6463     case MVT::v4f32:
6464     case MVT::v4i32:
6465     case MVT::v8i16:
6466     case MVT::v16i8:
6467       if (isVarArg) {
6468         // These go aligned on the stack, or in the corresponding R registers
6469         // when within range.  The Darwin PPC ABI doc claims they also go in
6470         // V registers; in fact gcc does this only for arguments that are
6471         // prototyped, not for those that match the ...  We do it for all
6472         // arguments, seems to work.
6473         while (ArgOffset % 16 !=0) {
6474           ArgOffset += PtrByteSize;
6475           if (GPR_idx != NumGPRs)
6476             GPR_idx++;
6477         }
6478         // We could elide this store in the case where the object fits
6479         // entirely in R registers.  Maybe later.
6480         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6481                              DAG.getConstant(ArgOffset, dl, PtrVT));
6482         SDValue Store =
6483             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6484         MemOpChains.push_back(Store);
6485         if (VR_idx != NumVRs) {
6486           SDValue Load =
6487               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6488           MemOpChains.push_back(Load.getValue(1));
6489           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6490         }
6491         ArgOffset += 16;
6492         for (unsigned i=0; i<16; i+=PtrByteSize) {
6493           if (GPR_idx == NumGPRs)
6494             break;
6495           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6496                                    DAG.getConstant(i, dl, PtrVT));
6497           SDValue Load =
6498               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6499           MemOpChains.push_back(Load.getValue(1));
6500           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6501         }
6502         break;
6503       }
6504 
6505       // Non-varargs Altivec params generally go in registers, but have
6506       // stack space allocated at the end.
6507       if (VR_idx != NumVRs) {
6508         // Doesn't have GPR space allocated.
6509         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6510       } else if (nAltivecParamsAtEnd==0) {
6511         // We are emitting Altivec params in order.
6512         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6513                          isPPC64, isTailCall, true, MemOpChains,
6514                          TailCallArguments, dl);
6515         ArgOffset += 16;
6516       }
6517       break;
6518     }
6519   }
6520   // If all Altivec parameters fit in registers, as they usually do,
6521   // they get stack space following the non-Altivec parameters.  We
6522   // don't track this here because nobody below needs it.
6523   // If there are more Altivec parameters than fit in registers emit
6524   // the stores here.
6525   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6526     unsigned j = 0;
6527     // Offset is aligned; skip 1st 12 params which go in V registers.
6528     ArgOffset = ((ArgOffset+15)/16)*16;
6529     ArgOffset += 12*16;
6530     for (unsigned i = 0; i != NumOps; ++i) {
6531       SDValue Arg = OutVals[i];
6532       EVT ArgType = Outs[i].VT;
6533       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6534           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6535         if (++j > NumVRs) {
6536           SDValue PtrOff;
6537           // We are emitting Altivec params in order.
6538           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6539                            isPPC64, isTailCall, true, MemOpChains,
6540                            TailCallArguments, dl);
6541           ArgOffset += 16;
6542         }
6543       }
6544     }
6545   }
6546 
6547   if (!MemOpChains.empty())
6548     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6549 
6550   // On Darwin, R12 must contain the address of an indirect callee.  This does
6551   // not mean the MTCTR instruction must use R12; it's easier to model this as
6552   // an extra parameter, so do that.
6553   if (!isTailCall &&
6554       !isFunctionGlobalAddress(Callee) &&
6555       !isa<ExternalSymbolSDNode>(Callee) &&
6556       !isBLACompatibleAddress(Callee, DAG))
6557     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6558                                                    PPC::R12), Callee));
6559 
6560   // Build a sequence of copy-to-reg nodes chained together with token chain
6561   // and flag operands which copy the outgoing args into the appropriate regs.
6562   SDValue InFlag;
6563   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6564     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6565                              RegsToPass[i].second, InFlag);
6566     InFlag = Chain.getValue(1);
6567   }
6568 
6569   if (isTailCall)
6570     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6571                     TailCallArguments);
6572 
6573   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6574                     /* unused except on PPC64 ELFv1 */ false, DAG,
6575                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6576                     NumBytes, Ins, InVals, CS);
6577 }
6578 
6579 
6580 SDValue PPCTargetLowering::LowerCall_AIX(
6581     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6582     bool isTailCall, bool isPatchPoint,
6583     const SmallVectorImpl<ISD::OutputArg> &Outs,
6584     const SmallVectorImpl<SDValue> &OutVals,
6585     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6586     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6587     ImmutableCallSite CS) const {
6588 
6589   assert((CallConv == CallingConv::C || CallConv == CallingConv::Fast) &&
6590          "Unimplemented calling convention!");
6591   if (isVarArg || isPatchPoint)
6592     report_fatal_error("This call type is unimplemented on AIX.");
6593 
6594   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6595   bool isPPC64 = PtrVT == MVT::i64;
6596   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6597   unsigned NumOps = Outs.size();
6598 
6599   if (NumOps != 0)
6600     report_fatal_error("Call lowering with parameters is not implemented "
6601                        "on AIX yet.");
6602 
6603   // Count how many bytes are to be pushed on the stack, including the linkage
6604   // area, parameter list area.
6605   // On XCOFF, we start with 24/48, which is reserved space for
6606   // [SP][CR][LR][2 x reserved][TOC].
6607   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6608 
6609   // The prolog code of the callee may store up to 8 GPR argument registers to
6610   // the stack, allowing va_start to index over them in memory if the callee
6611   // is variadic.
6612   // Because we cannot tell if this is needed on the caller side, we have to
6613   // conservatively assume that it is needed.  As such, make sure we have at
6614   // least enough stack space for the caller to store the 8 GPRs.
6615   unsigned NumBytes = LinkageSize + 8 * PtrByteSize;
6616 
6617   // Adjust the stack pointer for the new arguments...
6618   // These operations are automatically eliminated by the prolog/epilog
6619   // inserter pass.
6620   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6621   SDValue CallSeqStart = Chain;
6622 
6623   if (!isFunctionGlobalAddress(Callee) &&
6624       !isa<ExternalSymbolSDNode>(Callee))
6625     report_fatal_error("Handling of indirect call is unimplemented!");
6626 
6627   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6628   SDValue InFlag;
6629 
6630   if (isTailCall)
6631     report_fatal_error("Handling of tail call is unimplemented!");
6632   int SPDiff = 0;
6633 
6634   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6635                     /* unused except on PPC64 ELFv1 */ false, DAG,
6636                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6637                     NumBytes, Ins, InVals, CS);
6638 }
6639 
6640 bool
6641 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6642                                   MachineFunction &MF, bool isVarArg,
6643                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
6644                                   LLVMContext &Context) const {
6645   SmallVector<CCValAssign, 16> RVLocs;
6646   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6647   return CCInfo.CheckReturn(
6648       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6649                 ? RetCC_PPC_Cold
6650                 : RetCC_PPC);
6651 }
6652 
6653 SDValue
6654 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6655                                bool isVarArg,
6656                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6657                                const SmallVectorImpl<SDValue> &OutVals,
6658                                const SDLoc &dl, SelectionDAG &DAG) const {
6659   SmallVector<CCValAssign, 16> RVLocs;
6660   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6661                  *DAG.getContext());
6662   CCInfo.AnalyzeReturn(Outs,
6663                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6664                            ? RetCC_PPC_Cold
6665                            : RetCC_PPC);
6666 
6667   SDValue Flag;
6668   SmallVector<SDValue, 4> RetOps(1, Chain);
6669 
6670   // Copy the result values into the output registers.
6671   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6672     CCValAssign &VA = RVLocs[i];
6673     assert(VA.isRegLoc() && "Can only return in registers!");
6674 
6675     SDValue Arg = OutVals[i];
6676 
6677     switch (VA.getLocInfo()) {
6678     default: llvm_unreachable("Unknown loc info!");
6679     case CCValAssign::Full: break;
6680     case CCValAssign::AExt:
6681       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6682       break;
6683     case CCValAssign::ZExt:
6684       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6685       break;
6686     case CCValAssign::SExt:
6687       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6688       break;
6689     }
6690 
6691     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6692     Flag = Chain.getValue(1);
6693     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6694   }
6695 
6696   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6697   const MCPhysReg *I =
6698     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6699   if (I) {
6700     for (; *I; ++I) {
6701 
6702       if (PPC::G8RCRegClass.contains(*I))
6703         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6704       else if (PPC::F8RCRegClass.contains(*I))
6705         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6706       else if (PPC::CRRCRegClass.contains(*I))
6707         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6708       else if (PPC::VRRCRegClass.contains(*I))
6709         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6710       else
6711         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6712     }
6713   }
6714 
6715   RetOps[0] = Chain;  // Update chain.
6716 
6717   // Add the flag if we have it.
6718   if (Flag.getNode())
6719     RetOps.push_back(Flag);
6720 
6721   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6722 }
6723 
6724 SDValue
6725 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6726                                                 SelectionDAG &DAG) const {
6727   SDLoc dl(Op);
6728 
6729   // Get the correct type for integers.
6730   EVT IntVT = Op.getValueType();
6731 
6732   // Get the inputs.
6733   SDValue Chain = Op.getOperand(0);
6734   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6735   // Build a DYNAREAOFFSET node.
6736   SDValue Ops[2] = {Chain, FPSIdx};
6737   SDVTList VTs = DAG.getVTList(IntVT);
6738   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6739 }
6740 
6741 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6742                                              SelectionDAG &DAG) const {
6743   // When we pop the dynamic allocation we need to restore the SP link.
6744   SDLoc dl(Op);
6745 
6746   // Get the correct type for pointers.
6747   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6748 
6749   // Construct the stack pointer operand.
6750   bool isPPC64 = Subtarget.isPPC64();
6751   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6752   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6753 
6754   // Get the operands for the STACKRESTORE.
6755   SDValue Chain = Op.getOperand(0);
6756   SDValue SaveSP = Op.getOperand(1);
6757 
6758   // Load the old link SP.
6759   SDValue LoadLinkSP =
6760       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6761 
6762   // Restore the stack pointer.
6763   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6764 
6765   // Store the old link SP.
6766   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6767 }
6768 
6769 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6770   MachineFunction &MF = DAG.getMachineFunction();
6771   bool isPPC64 = Subtarget.isPPC64();
6772   EVT PtrVT = getPointerTy(MF.getDataLayout());
6773 
6774   // Get current frame pointer save index.  The users of this index will be
6775   // primarily DYNALLOC instructions.
6776   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6777   int RASI = FI->getReturnAddrSaveIndex();
6778 
6779   // If the frame pointer save index hasn't been defined yet.
6780   if (!RASI) {
6781     // Find out what the fix offset of the frame pointer save area.
6782     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6783     // Allocate the frame index for frame pointer save area.
6784     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6785     // Save the result.
6786     FI->setReturnAddrSaveIndex(RASI);
6787   }
6788   return DAG.getFrameIndex(RASI, PtrVT);
6789 }
6790 
6791 SDValue
6792 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6793   MachineFunction &MF = DAG.getMachineFunction();
6794   bool isPPC64 = Subtarget.isPPC64();
6795   EVT PtrVT = getPointerTy(MF.getDataLayout());
6796 
6797   // Get current frame pointer save index.  The users of this index will be
6798   // primarily DYNALLOC instructions.
6799   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6800   int FPSI = FI->getFramePointerSaveIndex();
6801 
6802   // If the frame pointer save index hasn't been defined yet.
6803   if (!FPSI) {
6804     // Find out what the fix offset of the frame pointer save area.
6805     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6806     // Allocate the frame index for frame pointer save area.
6807     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6808     // Save the result.
6809     FI->setFramePointerSaveIndex(FPSI);
6810   }
6811   return DAG.getFrameIndex(FPSI, PtrVT);
6812 }
6813 
6814 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6815                                                    SelectionDAG &DAG) const {
6816   // Get the inputs.
6817   SDValue Chain = Op.getOperand(0);
6818   SDValue Size  = Op.getOperand(1);
6819   SDLoc dl(Op);
6820 
6821   // Get the correct type for pointers.
6822   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6823   // Negate the size.
6824   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6825                                 DAG.getConstant(0, dl, PtrVT), Size);
6826   // Construct a node for the frame pointer save index.
6827   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6828   // Build a DYNALLOC node.
6829   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6830   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6831   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6832 }
6833 
6834 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6835                                                      SelectionDAG &DAG) const {
6836   MachineFunction &MF = DAG.getMachineFunction();
6837 
6838   bool isPPC64 = Subtarget.isPPC64();
6839   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6840 
6841   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6842   return DAG.getFrameIndex(FI, PtrVT);
6843 }
6844 
6845 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6846                                                SelectionDAG &DAG) const {
6847   SDLoc DL(Op);
6848   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6849                      DAG.getVTList(MVT::i32, MVT::Other),
6850                      Op.getOperand(0), Op.getOperand(1));
6851 }
6852 
6853 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6854                                                 SelectionDAG &DAG) const {
6855   SDLoc DL(Op);
6856   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6857                      Op.getOperand(0), Op.getOperand(1));
6858 }
6859 
6860 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6861   if (Op.getValueType().isVector())
6862     return LowerVectorLoad(Op, DAG);
6863 
6864   assert(Op.getValueType() == MVT::i1 &&
6865          "Custom lowering only for i1 loads");
6866 
6867   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6868 
6869   SDLoc dl(Op);
6870   LoadSDNode *LD = cast<LoadSDNode>(Op);
6871 
6872   SDValue Chain = LD->getChain();
6873   SDValue BasePtr = LD->getBasePtr();
6874   MachineMemOperand *MMO = LD->getMemOperand();
6875 
6876   SDValue NewLD =
6877       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6878                      BasePtr, MVT::i8, MMO);
6879   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6880 
6881   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6882   return DAG.getMergeValues(Ops, dl);
6883 }
6884 
6885 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6886   if (Op.getOperand(1).getValueType().isVector())
6887     return LowerVectorStore(Op, DAG);
6888 
6889   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6890          "Custom lowering only for i1 stores");
6891 
6892   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6893 
6894   SDLoc dl(Op);
6895   StoreSDNode *ST = cast<StoreSDNode>(Op);
6896 
6897   SDValue Chain = ST->getChain();
6898   SDValue BasePtr = ST->getBasePtr();
6899   SDValue Value = ST->getValue();
6900   MachineMemOperand *MMO = ST->getMemOperand();
6901 
6902   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6903                       Value);
6904   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6905 }
6906 
6907 // FIXME: Remove this once the ANDI glue bug is fixed:
6908 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6909   assert(Op.getValueType() == MVT::i1 &&
6910          "Custom lowering only for i1 results");
6911 
6912   SDLoc DL(Op);
6913   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6914                      Op.getOperand(0));
6915 }
6916 
6917 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
6918                                                SelectionDAG &DAG) const {
6919 
6920   // Implements a vector truncate that fits in a vector register as a shuffle.
6921   // We want to legalize vector truncates down to where the source fits in
6922   // a vector register (and target is therefore smaller than vector register
6923   // size).  At that point legalization will try to custom lower the sub-legal
6924   // result and get here - where we can contain the truncate as a single target
6925   // operation.
6926 
6927   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
6928   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
6929   //
6930   // We will implement it for big-endian ordering as this (where x denotes
6931   // undefined):
6932   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
6933   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
6934   //
6935   // The same operation in little-endian ordering will be:
6936   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
6937   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
6938 
6939   assert(Op.getValueType().isVector() && "Vector type expected.");
6940 
6941   SDLoc DL(Op);
6942   SDValue N1 = Op.getOperand(0);
6943   unsigned SrcSize = N1.getValueType().getSizeInBits();
6944   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
6945   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
6946 
6947   EVT TrgVT = Op.getValueType();
6948   unsigned TrgNumElts = TrgVT.getVectorNumElements();
6949   EVT EltVT = TrgVT.getVectorElementType();
6950   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
6951   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
6952 
6953   // First list the elements we want to keep.
6954   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
6955   SmallVector<int, 16> ShuffV;
6956   if (Subtarget.isLittleEndian())
6957     for (unsigned i = 0; i < TrgNumElts; ++i)
6958       ShuffV.push_back(i * SizeMult);
6959   else
6960     for (unsigned i = 1; i <= TrgNumElts; ++i)
6961       ShuffV.push_back(i * SizeMult - 1);
6962 
6963   // Populate the remaining elements with undefs.
6964   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
6965     // ShuffV.push_back(i + WideNumElts);
6966     ShuffV.push_back(WideNumElts + 1);
6967 
6968   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
6969   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
6970 }
6971 
6972 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6973 /// possible.
6974 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6975   // Not FP? Not a fsel.
6976   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6977       !Op.getOperand(2).getValueType().isFloatingPoint())
6978     return Op;
6979 
6980   // We might be able to do better than this under some circumstances, but in
6981   // general, fsel-based lowering of select is a finite-math-only optimization.
6982   // For more information, see section F.3 of the 2.06 ISA specification.
6983   if (!DAG.getTarget().Options.NoInfsFPMath ||
6984       !DAG.getTarget().Options.NoNaNsFPMath)
6985     return Op;
6986   // TODO: Propagate flags from the select rather than global settings.
6987   SDNodeFlags Flags;
6988   Flags.setNoInfs(true);
6989   Flags.setNoNaNs(true);
6990 
6991   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6992 
6993   EVT ResVT = Op.getValueType();
6994   EVT CmpVT = Op.getOperand(0).getValueType();
6995   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6996   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6997   SDLoc dl(Op);
6998 
6999   // If the RHS of the comparison is a 0.0, we don't need to do the
7000   // subtraction at all.
7001   SDValue Sel1;
7002   if (isFloatingPointZero(RHS))
7003     switch (CC) {
7004     default: break;       // SETUO etc aren't handled by fsel.
7005     case ISD::SETNE:
7006       std::swap(TV, FV);
7007       LLVM_FALLTHROUGH;
7008     case ISD::SETEQ:
7009       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7010         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7011       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7012       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7013         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7014       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7015                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7016     case ISD::SETULT:
7017     case ISD::SETLT:
7018       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7019       LLVM_FALLTHROUGH;
7020     case ISD::SETOGE:
7021     case ISD::SETGE:
7022       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7023         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7024       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7025     case ISD::SETUGT:
7026     case ISD::SETGT:
7027       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7028       LLVM_FALLTHROUGH;
7029     case ISD::SETOLE:
7030     case ISD::SETLE:
7031       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7032         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7033       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7034                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7035     }
7036 
7037   SDValue Cmp;
7038   switch (CC) {
7039   default: break;       // SETUO etc aren't handled by fsel.
7040   case ISD::SETNE:
7041     std::swap(TV, FV);
7042     LLVM_FALLTHROUGH;
7043   case ISD::SETEQ:
7044     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7045     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7046       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7047     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7048     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7049       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7050     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7051                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7052   case ISD::SETULT:
7053   case ISD::SETLT:
7054     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7055     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7056       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7057     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7058   case ISD::SETOGE:
7059   case ISD::SETGE:
7060     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7061     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7062       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7063     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7064   case ISD::SETUGT:
7065   case ISD::SETGT:
7066     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7067     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7068       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7069     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7070   case ISD::SETOLE:
7071   case ISD::SETLE:
7072     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7073     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7074       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7075     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7076   }
7077   return Op;
7078 }
7079 
7080 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7081                                                SelectionDAG &DAG,
7082                                                const SDLoc &dl) const {
7083   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7084   SDValue Src = Op.getOperand(0);
7085   if (Src.getValueType() == MVT::f32)
7086     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7087 
7088   SDValue Tmp;
7089   switch (Op.getSimpleValueType().SimpleTy) {
7090   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7091   case MVT::i32:
7092     Tmp = DAG.getNode(
7093         Op.getOpcode() == ISD::FP_TO_SINT
7094             ? PPCISD::FCTIWZ
7095             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7096         dl, MVT::f64, Src);
7097     break;
7098   case MVT::i64:
7099     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7100            "i64 FP_TO_UINT is supported only with FPCVT");
7101     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7102                                                         PPCISD::FCTIDUZ,
7103                       dl, MVT::f64, Src);
7104     break;
7105   }
7106 
7107   // Convert the FP value to an int value through memory.
7108   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7109     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
7110   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7111   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7112   MachinePointerInfo MPI =
7113       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7114 
7115   // Emit a store to the stack slot.
7116   SDValue Chain;
7117   if (i32Stack) {
7118     MachineFunction &MF = DAG.getMachineFunction();
7119     MachineMemOperand *MMO =
7120       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
7121     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
7122     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7123               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7124   } else
7125     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
7126 
7127   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7128   // add in a bias on big endian.
7129   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7130     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7131                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7132     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7133   }
7134 
7135   RLI.Chain = Chain;
7136   RLI.Ptr = FIPtr;
7137   RLI.MPI = MPI;
7138 }
7139 
7140 /// Custom lowers floating point to integer conversions to use
7141 /// the direct move instructions available in ISA 2.07 to avoid the
7142 /// need for load/store combinations.
7143 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7144                                                     SelectionDAG &DAG,
7145                                                     const SDLoc &dl) const {
7146   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7147   SDValue Src = Op.getOperand(0);
7148 
7149   if (Src.getValueType() == MVT::f32)
7150     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7151 
7152   SDValue Tmp;
7153   switch (Op.getSimpleValueType().SimpleTy) {
7154   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7155   case MVT::i32:
7156     Tmp = DAG.getNode(
7157         Op.getOpcode() == ISD::FP_TO_SINT
7158             ? PPCISD::FCTIWZ
7159             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7160         dl, MVT::f64, Src);
7161     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
7162     break;
7163   case MVT::i64:
7164     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7165            "i64 FP_TO_UINT is supported only with FPCVT");
7166     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7167                                                         PPCISD::FCTIDUZ,
7168                       dl, MVT::f64, Src);
7169     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
7170     break;
7171   }
7172   return Tmp;
7173 }
7174 
7175 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7176                                           const SDLoc &dl) const {
7177 
7178   // FP to INT conversions are legal for f128.
7179   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
7180     return Op;
7181 
7182   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7183   // PPC (the libcall is not available).
7184   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
7185     if (Op.getValueType() == MVT::i32) {
7186       if (Op.getOpcode() == ISD::FP_TO_SINT) {
7187         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7188                                  MVT::f64, Op.getOperand(0),
7189                                  DAG.getIntPtrConstant(0, dl));
7190         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7191                                  MVT::f64, Op.getOperand(0),
7192                                  DAG.getIntPtrConstant(1, dl));
7193 
7194         // Add the two halves of the long double in round-to-zero mode.
7195         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7196 
7197         // Now use a smaller FP_TO_SINT.
7198         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7199       }
7200       if (Op.getOpcode() == ISD::FP_TO_UINT) {
7201         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7202         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7203         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
7204         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7205         // FIXME: generated code sucks.
7206         // TODO: Are there fast-math-flags to propagate to this FSUB?
7207         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
7208                                    Op.getOperand(0), Tmp);
7209         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7210         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
7211                            DAG.getConstant(0x80000000, dl, MVT::i32));
7212         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
7213                                     Op.getOperand(0));
7214         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
7215                                ISD::SETGE);
7216       }
7217     }
7218 
7219     return SDValue();
7220   }
7221 
7222   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
7223     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
7224 
7225   ReuseLoadInfo RLI;
7226   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7227 
7228   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7229                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7230 }
7231 
7232 // We're trying to insert a regular store, S, and then a load, L. If the
7233 // incoming value, O, is a load, we might just be able to have our load use the
7234 // address used by O. However, we don't know if anything else will store to
7235 // that address before we can load from it. To prevent this situation, we need
7236 // to insert our load, L, into the chain as a peer of O. To do this, we give L
7237 // the same chain operand as O, we create a token factor from the chain results
7238 // of O and L, and we replace all uses of O's chain result with that token
7239 // factor (see spliceIntoChain below for this last part).
7240 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
7241                                             ReuseLoadInfo &RLI,
7242                                             SelectionDAG &DAG,
7243                                             ISD::LoadExtType ET) const {
7244   SDLoc dl(Op);
7245   if (ET == ISD::NON_EXTLOAD &&
7246       (Op.getOpcode() == ISD::FP_TO_UINT ||
7247        Op.getOpcode() == ISD::FP_TO_SINT) &&
7248       isOperationLegalOrCustom(Op.getOpcode(),
7249                                Op.getOperand(0).getValueType())) {
7250 
7251     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7252     return true;
7253   }
7254 
7255   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
7256   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
7257       LD->isNonTemporal())
7258     return false;
7259   if (LD->getMemoryVT() != MemVT)
7260     return false;
7261 
7262   RLI.Ptr = LD->getBasePtr();
7263   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
7264     assert(LD->getAddressingMode() == ISD::PRE_INC &&
7265            "Non-pre-inc AM on PPC?");
7266     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
7267                           LD->getOffset());
7268   }
7269 
7270   RLI.Chain = LD->getChain();
7271   RLI.MPI = LD->getPointerInfo();
7272   RLI.IsDereferenceable = LD->isDereferenceable();
7273   RLI.IsInvariant = LD->isInvariant();
7274   RLI.Alignment = LD->getAlignment();
7275   RLI.AAInfo = LD->getAAInfo();
7276   RLI.Ranges = LD->getRanges();
7277 
7278   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
7279   return true;
7280 }
7281 
7282 // Given the head of the old chain, ResChain, insert a token factor containing
7283 // it and NewResChain, and make users of ResChain now be users of that token
7284 // factor.
7285 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
7286 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
7287                                         SDValue NewResChain,
7288                                         SelectionDAG &DAG) const {
7289   if (!ResChain)
7290     return;
7291 
7292   SDLoc dl(NewResChain);
7293 
7294   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7295                            NewResChain, DAG.getUNDEF(MVT::Other));
7296   assert(TF.getNode() != NewResChain.getNode() &&
7297          "A new TF really is required here");
7298 
7299   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
7300   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
7301 }
7302 
7303 /// Analyze profitability of direct move
7304 /// prefer float load to int load plus direct move
7305 /// when there is no integer use of int load
7306 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
7307   SDNode *Origin = Op.getOperand(0).getNode();
7308   if (Origin->getOpcode() != ISD::LOAD)
7309     return true;
7310 
7311   // If there is no LXSIBZX/LXSIHZX, like Power8,
7312   // prefer direct move if the memory size is 1 or 2 bytes.
7313   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
7314   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
7315     return true;
7316 
7317   for (SDNode::use_iterator UI = Origin->use_begin(),
7318                             UE = Origin->use_end();
7319        UI != UE; ++UI) {
7320 
7321     // Only look at the users of the loaded value.
7322     if (UI.getUse().get().getResNo() != 0)
7323       continue;
7324 
7325     if (UI->getOpcode() != ISD::SINT_TO_FP &&
7326         UI->getOpcode() != ISD::UINT_TO_FP)
7327       return true;
7328   }
7329 
7330   return false;
7331 }
7332 
7333 /// Custom lowers integer to floating point conversions to use
7334 /// the direct move instructions available in ISA 2.07 to avoid the
7335 /// need for load/store combinations.
7336 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
7337                                                     SelectionDAG &DAG,
7338                                                     const SDLoc &dl) const {
7339   assert((Op.getValueType() == MVT::f32 ||
7340           Op.getValueType() == MVT::f64) &&
7341          "Invalid floating point type as target of conversion");
7342   assert(Subtarget.hasFPCVT() &&
7343          "Int to FP conversions with direct moves require FPCVT");
7344   SDValue FP;
7345   SDValue Src = Op.getOperand(0);
7346   bool SinglePrec = Op.getValueType() == MVT::f32;
7347   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
7348   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
7349   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
7350                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
7351 
7352   if (WordInt) {
7353     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
7354                      dl, MVT::f64, Src);
7355     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7356   }
7357   else {
7358     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
7359     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7360   }
7361 
7362   return FP;
7363 }
7364 
7365 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
7366 
7367   EVT VecVT = Vec.getValueType();
7368   assert(VecVT.isVector() && "Expected a vector type.");
7369   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
7370 
7371   EVT EltVT = VecVT.getVectorElementType();
7372   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7373   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7374 
7375   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
7376   SmallVector<SDValue, 16> Ops(NumConcat);
7377   Ops[0] = Vec;
7378   SDValue UndefVec = DAG.getUNDEF(VecVT);
7379   for (unsigned i = 1; i < NumConcat; ++i)
7380     Ops[i] = UndefVec;
7381 
7382   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
7383 }
7384 
7385 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
7386                                                 const SDLoc &dl) const {
7387 
7388   unsigned Opc = Op.getOpcode();
7389   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
7390          "Unexpected conversion type");
7391   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
7392          "Supports conversions to v2f64/v4f32 only.");
7393 
7394   bool SignedConv = Opc == ISD::SINT_TO_FP;
7395   bool FourEltRes = Op.getValueType() == MVT::v4f32;
7396 
7397   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
7398   EVT WideVT = Wide.getValueType();
7399   unsigned WideNumElts = WideVT.getVectorNumElements();
7400   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
7401 
7402   SmallVector<int, 16> ShuffV;
7403   for (unsigned i = 0; i < WideNumElts; ++i)
7404     ShuffV.push_back(i + WideNumElts);
7405 
7406   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
7407   int SaveElts = FourEltRes ? 4 : 2;
7408   if (Subtarget.isLittleEndian())
7409     for (int i = 0; i < SaveElts; i++)
7410       ShuffV[i * Stride] = i;
7411   else
7412     for (int i = 1; i <= SaveElts; i++)
7413       ShuffV[i * Stride - 1] = i - 1;
7414 
7415   SDValue ShuffleSrc2 =
7416       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
7417   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
7418   unsigned ExtendOp =
7419       SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST;
7420 
7421   SDValue Extend;
7422   if (!Subtarget.hasP9Altivec() && SignedConv) {
7423     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
7424     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
7425                          DAG.getValueType(Op.getOperand(0).getValueType()));
7426   } else
7427     Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange);
7428 
7429   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
7430 }
7431 
7432 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
7433                                           SelectionDAG &DAG) const {
7434   SDLoc dl(Op);
7435 
7436   EVT InVT = Op.getOperand(0).getValueType();
7437   EVT OutVT = Op.getValueType();
7438   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
7439       isOperationCustom(Op.getOpcode(), InVT))
7440     return LowerINT_TO_FPVector(Op, DAG, dl);
7441 
7442   // Conversions to f128 are legal.
7443   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
7444     return Op;
7445 
7446   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
7447     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
7448       return SDValue();
7449 
7450     SDValue Value = Op.getOperand(0);
7451     // The values are now known to be -1 (false) or 1 (true). To convert this
7452     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7453     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7454     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7455 
7456     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7457 
7458     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7459 
7460     if (Op.getValueType() != MVT::v4f64)
7461       Value = DAG.getNode(ISD::FP_ROUND, dl,
7462                           Op.getValueType(), Value,
7463                           DAG.getIntPtrConstant(1, dl));
7464     return Value;
7465   }
7466 
7467   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
7468   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
7469     return SDValue();
7470 
7471   if (Op.getOperand(0).getValueType() == MVT::i1)
7472     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
7473                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
7474                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
7475 
7476   // If we have direct moves, we can do all the conversion, skip the store/load
7477   // however, without FPCVT we can't do most conversions.
7478   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
7479       Subtarget.isPPC64() && Subtarget.hasFPCVT())
7480     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
7481 
7482   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
7483          "UINT_TO_FP is supported only with FPCVT");
7484 
7485   // If we have FCFIDS, then use it when converting to single-precision.
7486   // Otherwise, convert to double-precision and then round.
7487   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7488                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
7489                                                             : PPCISD::FCFIDS)
7490                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
7491                                                             : PPCISD::FCFID);
7492   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7493                   ? MVT::f32
7494                   : MVT::f64;
7495 
7496   if (Op.getOperand(0).getValueType() == MVT::i64) {
7497     SDValue SINT = Op.getOperand(0);
7498     // When converting to single-precision, we actually need to convert
7499     // to double-precision first and then round to single-precision.
7500     // To avoid double-rounding effects during that operation, we have
7501     // to prepare the input operand.  Bits that might be truncated when
7502     // converting to double-precision are replaced by a bit that won't
7503     // be lost at this stage, but is below the single-precision rounding
7504     // position.
7505     //
7506     // However, if -enable-unsafe-fp-math is in effect, accept double
7507     // rounding to avoid the extra overhead.
7508     if (Op.getValueType() == MVT::f32 &&
7509         !Subtarget.hasFPCVT() &&
7510         !DAG.getTarget().Options.UnsafeFPMath) {
7511 
7512       // Twiddle input to make sure the low 11 bits are zero.  (If this
7513       // is the case, we are guaranteed the value will fit into the 53 bit
7514       // mantissa of an IEEE double-precision value without rounding.)
7515       // If any of those low 11 bits were not zero originally, make sure
7516       // bit 12 (value 2048) is set instead, so that the final rounding
7517       // to single-precision gets the correct result.
7518       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7519                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
7520       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
7521                           Round, DAG.getConstant(2047, dl, MVT::i64));
7522       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
7523       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7524                           Round, DAG.getConstant(-2048, dl, MVT::i64));
7525 
7526       // However, we cannot use that value unconditionally: if the magnitude
7527       // of the input value is small, the bit-twiddling we did above might
7528       // end up visibly changing the output.  Fortunately, in that case, we
7529       // don't need to twiddle bits since the original input will convert
7530       // exactly to double-precision floating-point already.  Therefore,
7531       // construct a conditional to use the original value if the top 11
7532       // bits are all sign-bit copies, and use the rounded value computed
7533       // above otherwise.
7534       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
7535                                  SINT, DAG.getConstant(53, dl, MVT::i32));
7536       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
7537                          Cond, DAG.getConstant(1, dl, MVT::i64));
7538       Cond = DAG.getSetCC(dl, MVT::i32,
7539                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
7540 
7541       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
7542     }
7543 
7544     ReuseLoadInfo RLI;
7545     SDValue Bits;
7546 
7547     MachineFunction &MF = DAG.getMachineFunction();
7548     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
7549       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7550                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7551       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7552     } else if (Subtarget.hasLFIWAX() &&
7553                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
7554       MachineMemOperand *MMO =
7555         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7556                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7557       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7558       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
7559                                      DAG.getVTList(MVT::f64, MVT::Other),
7560                                      Ops, MVT::i32, MMO);
7561       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7562     } else if (Subtarget.hasFPCVT() &&
7563                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
7564       MachineMemOperand *MMO =
7565         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7566                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7567       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7568       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
7569                                      DAG.getVTList(MVT::f64, MVT::Other),
7570                                      Ops, MVT::i32, MMO);
7571       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7572     } else if (((Subtarget.hasLFIWAX() &&
7573                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
7574                 (Subtarget.hasFPCVT() &&
7575                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
7576                SINT.getOperand(0).getValueType() == MVT::i32) {
7577       MachineFrameInfo &MFI = MF.getFrameInfo();
7578       EVT PtrVT = getPointerTy(DAG.getDataLayout());
7579 
7580       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7581       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7582 
7583       SDValue Store =
7584           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
7585                        MachinePointerInfo::getFixedStack(
7586                            DAG.getMachineFunction(), FrameIdx));
7587 
7588       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7589              "Expected an i32 store");
7590 
7591       RLI.Ptr = FIdx;
7592       RLI.Chain = Store;
7593       RLI.MPI =
7594           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7595       RLI.Alignment = 4;
7596 
7597       MachineMemOperand *MMO =
7598         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7599                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7600       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7601       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
7602                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
7603                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
7604                                      Ops, MVT::i32, MMO);
7605     } else
7606       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
7607 
7608     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
7609 
7610     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7611       FP = DAG.getNode(ISD::FP_ROUND, dl,
7612                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
7613     return FP;
7614   }
7615 
7616   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
7617          "Unhandled INT_TO_FP type in custom expander!");
7618   // Since we only generate this in 64-bit mode, we can take advantage of
7619   // 64-bit registers.  In particular, sign extend the input value into the
7620   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
7621   // then lfd it and fcfid it.
7622   MachineFunction &MF = DAG.getMachineFunction();
7623   MachineFrameInfo &MFI = MF.getFrameInfo();
7624   EVT PtrVT = getPointerTy(MF.getDataLayout());
7625 
7626   SDValue Ld;
7627   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
7628     ReuseLoadInfo RLI;
7629     bool ReusingLoad;
7630     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
7631                                             DAG))) {
7632       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7633       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7634 
7635       SDValue Store =
7636           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7637                        MachinePointerInfo::getFixedStack(
7638                            DAG.getMachineFunction(), FrameIdx));
7639 
7640       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7641              "Expected an i32 store");
7642 
7643       RLI.Ptr = FIdx;
7644       RLI.Chain = Store;
7645       RLI.MPI =
7646           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7647       RLI.Alignment = 4;
7648     }
7649 
7650     MachineMemOperand *MMO =
7651       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7652                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7653     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7654     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
7655                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
7656                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
7657                                  Ops, MVT::i32, MMO);
7658     if (ReusingLoad)
7659       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
7660   } else {
7661     assert(Subtarget.isPPC64() &&
7662            "i32->FP without LFIWAX supported only on PPC64");
7663 
7664     int FrameIdx = MFI.CreateStackObject(8, 8, false);
7665     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7666 
7667     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
7668                                 Op.getOperand(0));
7669 
7670     // STD the extended value into the stack slot.
7671     SDValue Store = DAG.getStore(
7672         DAG.getEntryNode(), dl, Ext64, FIdx,
7673         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7674 
7675     // Load the value as a double.
7676     Ld = DAG.getLoad(
7677         MVT::f64, dl, Store, FIdx,
7678         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7679   }
7680 
7681   // FCFID it and return it.
7682   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
7683   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7684     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
7685                      DAG.getIntPtrConstant(0, dl));
7686   return FP;
7687 }
7688 
7689 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7690                                             SelectionDAG &DAG) const {
7691   SDLoc dl(Op);
7692   /*
7693    The rounding mode is in bits 30:31 of FPSR, and has the following
7694    settings:
7695      00 Round to nearest
7696      01 Round to 0
7697      10 Round to +inf
7698      11 Round to -inf
7699 
7700   FLT_ROUNDS, on the other hand, expects the following:
7701     -1 Undefined
7702      0 Round to 0
7703      1 Round to nearest
7704      2 Round to +inf
7705      3 Round to -inf
7706 
7707   To perform the conversion, we do:
7708     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7709   */
7710 
7711   MachineFunction &MF = DAG.getMachineFunction();
7712   EVT VT = Op.getValueType();
7713   EVT PtrVT = getPointerTy(MF.getDataLayout());
7714 
7715   // Save FP Control Word to register
7716   EVT NodeTys[] = {
7717     MVT::f64,    // return register
7718     MVT::Glue    // unused in this context
7719   };
7720   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7721 
7722   // Save FP register to stack slot
7723   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7724   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7725   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7726                                MachinePointerInfo());
7727 
7728   // Load FP Control Word from low 32 bits of stack slot.
7729   SDValue Four = DAG.getConstant(4, dl, PtrVT);
7730   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7731   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7732 
7733   // Transform as necessary
7734   SDValue CWD1 =
7735     DAG.getNode(ISD::AND, dl, MVT::i32,
7736                 CWD, DAG.getConstant(3, dl, MVT::i32));
7737   SDValue CWD2 =
7738     DAG.getNode(ISD::SRL, dl, MVT::i32,
7739                 DAG.getNode(ISD::AND, dl, MVT::i32,
7740                             DAG.getNode(ISD::XOR, dl, MVT::i32,
7741                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
7742                             DAG.getConstant(3, dl, MVT::i32)),
7743                 DAG.getConstant(1, dl, MVT::i32));
7744 
7745   SDValue RetVal =
7746     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7747 
7748   return DAG.getNode((VT.getSizeInBits() < 16 ?
7749                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7750 }
7751 
7752 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7753   EVT VT = Op.getValueType();
7754   unsigned BitWidth = VT.getSizeInBits();
7755   SDLoc dl(Op);
7756   assert(Op.getNumOperands() == 3 &&
7757          VT == Op.getOperand(1).getValueType() &&
7758          "Unexpected SHL!");
7759 
7760   // Expand into a bunch of logical ops.  Note that these ops
7761   // depend on the PPC behavior for oversized shift amounts.
7762   SDValue Lo = Op.getOperand(0);
7763   SDValue Hi = Op.getOperand(1);
7764   SDValue Amt = Op.getOperand(2);
7765   EVT AmtVT = Amt.getValueType();
7766 
7767   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7768                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7769   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7770   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7771   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7772   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7773                              DAG.getConstant(-BitWidth, dl, AmtVT));
7774   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7775   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7776   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7777   SDValue OutOps[] = { OutLo, OutHi };
7778   return DAG.getMergeValues(OutOps, dl);
7779 }
7780 
7781 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7782   EVT VT = Op.getValueType();
7783   SDLoc dl(Op);
7784   unsigned BitWidth = VT.getSizeInBits();
7785   assert(Op.getNumOperands() == 3 &&
7786          VT == Op.getOperand(1).getValueType() &&
7787          "Unexpected SRL!");
7788 
7789   // Expand into a bunch of logical ops.  Note that these ops
7790   // depend on the PPC behavior for oversized shift amounts.
7791   SDValue Lo = Op.getOperand(0);
7792   SDValue Hi = Op.getOperand(1);
7793   SDValue Amt = Op.getOperand(2);
7794   EVT AmtVT = Amt.getValueType();
7795 
7796   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7797                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7798   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7799   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7800   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7801   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7802                              DAG.getConstant(-BitWidth, dl, AmtVT));
7803   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7804   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7805   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7806   SDValue OutOps[] = { OutLo, OutHi };
7807   return DAG.getMergeValues(OutOps, dl);
7808 }
7809 
7810 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7811   SDLoc dl(Op);
7812   EVT VT = Op.getValueType();
7813   unsigned BitWidth = VT.getSizeInBits();
7814   assert(Op.getNumOperands() == 3 &&
7815          VT == Op.getOperand(1).getValueType() &&
7816          "Unexpected SRA!");
7817 
7818   // Expand into a bunch of logical ops, followed by a select_cc.
7819   SDValue Lo = Op.getOperand(0);
7820   SDValue Hi = Op.getOperand(1);
7821   SDValue Amt = Op.getOperand(2);
7822   EVT AmtVT = Amt.getValueType();
7823 
7824   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7825                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7826   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7827   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7828   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7829   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7830                              DAG.getConstant(-BitWidth, dl, AmtVT));
7831   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7832   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7833   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7834                                   Tmp4, Tmp6, ISD::SETLE);
7835   SDValue OutOps[] = { OutLo, OutHi };
7836   return DAG.getMergeValues(OutOps, dl);
7837 }
7838 
7839 //===----------------------------------------------------------------------===//
7840 // Vector related lowering.
7841 //
7842 
7843 /// BuildSplatI - Build a canonical splati of Val with an element size of
7844 /// SplatSize.  Cast the result to VT.
7845 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7846                            SelectionDAG &DAG, const SDLoc &dl) {
7847   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7848 
7849   static const MVT VTys[] = { // canonical VT to use for each size.
7850     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7851   };
7852 
7853   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7854 
7855   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7856   if (Val == -1)
7857     SplatSize = 1;
7858 
7859   EVT CanonicalVT = VTys[SplatSize-1];
7860 
7861   // Build a canonical splat for this value.
7862   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7863 }
7864 
7865 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7866 /// specified intrinsic ID.
7867 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7868                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
7869   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7870   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7871                      DAG.getConstant(IID, dl, MVT::i32), Op);
7872 }
7873 
7874 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7875 /// specified intrinsic ID.
7876 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7877                                 SelectionDAG &DAG, const SDLoc &dl,
7878                                 EVT DestVT = MVT::Other) {
7879   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7880   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7881                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7882 }
7883 
7884 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7885 /// specified intrinsic ID.
7886 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7887                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7888                                 EVT DestVT = MVT::Other) {
7889   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7890   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7891                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7892 }
7893 
7894 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7895 /// amount.  The result has the specified value type.
7896 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7897                            SelectionDAG &DAG, const SDLoc &dl) {
7898   // Force LHS/RHS to be the right type.
7899   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7900   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7901 
7902   int Ops[16];
7903   for (unsigned i = 0; i != 16; ++i)
7904     Ops[i] = i + Amt;
7905   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7906   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7907 }
7908 
7909 /// Do we have an efficient pattern in a .td file for this node?
7910 ///
7911 /// \param V - pointer to the BuildVectorSDNode being matched
7912 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
7913 ///
7914 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
7915 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
7916 /// the opposite is true (expansion is beneficial) are:
7917 /// - The node builds a vector out of integers that are not 32 or 64-bits
7918 /// - The node builds a vector out of constants
7919 /// - The node is a "load-and-splat"
7920 /// In all other cases, we will choose to keep the BUILD_VECTOR.
7921 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
7922                                             bool HasDirectMove,
7923                                             bool HasP8Vector) {
7924   EVT VecVT = V->getValueType(0);
7925   bool RightType = VecVT == MVT::v2f64 ||
7926     (HasP8Vector && VecVT == MVT::v4f32) ||
7927     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
7928   if (!RightType)
7929     return false;
7930 
7931   bool IsSplat = true;
7932   bool IsLoad = false;
7933   SDValue Op0 = V->getOperand(0);
7934 
7935   // This function is called in a block that confirms the node is not a constant
7936   // splat. So a constant BUILD_VECTOR here means the vector is built out of
7937   // different constants.
7938   if (V->isConstant())
7939     return false;
7940   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
7941     if (V->getOperand(i).isUndef())
7942       return false;
7943     // We want to expand nodes that represent load-and-splat even if the
7944     // loaded value is a floating point truncation or conversion to int.
7945     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
7946         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
7947          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7948         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
7949          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7950         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
7951          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
7952       IsLoad = true;
7953     // If the operands are different or the input is not a load and has more
7954     // uses than just this BV node, then it isn't a splat.
7955     if (V->getOperand(i) != Op0 ||
7956         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
7957       IsSplat = false;
7958   }
7959   return !(IsSplat && IsLoad);
7960 }
7961 
7962 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
7963 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
7964 
7965   SDLoc dl(Op);
7966   SDValue Op0 = Op->getOperand(0);
7967 
7968   if (!EnableQuadPrecision ||
7969       (Op.getValueType() != MVT::f128 ) ||
7970       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
7971       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
7972       (Op0.getOperand(1).getValueType() != MVT::i64))
7973     return SDValue();
7974 
7975   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
7976                      Op0.getOperand(1));
7977 }
7978 
7979 // If this is a case we can't handle, return null and let the default
7980 // expansion code take care of it.  If we CAN select this case, and if it
7981 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7982 // this case more efficiently than a constant pool load, lower it to the
7983 // sequence of ops that should be used.
7984 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7985                                              SelectionDAG &DAG) const {
7986   SDLoc dl(Op);
7987   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7988   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7989 
7990   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7991     // We first build an i32 vector, load it into a QPX register,
7992     // then convert it to a floating-point vector and compare it
7993     // to a zero vector to get the boolean result.
7994     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7995     int FrameIdx = MFI.CreateStackObject(16, 16, false);
7996     MachinePointerInfo PtrInfo =
7997         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7998     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7999     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8000 
8001     assert(BVN->getNumOperands() == 4 &&
8002       "BUILD_VECTOR for v4i1 does not have 4 operands");
8003 
8004     bool IsConst = true;
8005     for (unsigned i = 0; i < 4; ++i) {
8006       if (BVN->getOperand(i).isUndef()) continue;
8007       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
8008         IsConst = false;
8009         break;
8010       }
8011     }
8012 
8013     if (IsConst) {
8014       Constant *One =
8015         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
8016       Constant *NegOne =
8017         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
8018 
8019       Constant *CV[4];
8020       for (unsigned i = 0; i < 4; ++i) {
8021         if (BVN->getOperand(i).isUndef())
8022           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
8023         else if (isNullConstant(BVN->getOperand(i)))
8024           CV[i] = NegOne;
8025         else
8026           CV[i] = One;
8027       }
8028 
8029       Constant *CP = ConstantVector::get(CV);
8030       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
8031                                           16 /* alignment */);
8032 
8033       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
8034       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
8035       return DAG.getMemIntrinsicNode(
8036           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
8037           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
8038     }
8039 
8040     SmallVector<SDValue, 4> Stores;
8041     for (unsigned i = 0; i < 4; ++i) {
8042       if (BVN->getOperand(i).isUndef()) continue;
8043 
8044       unsigned Offset = 4*i;
8045       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8046       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8047 
8048       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
8049       if (StoreSize > 4) {
8050         Stores.push_back(
8051             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
8052                               PtrInfo.getWithOffset(Offset), MVT::i32));
8053       } else {
8054         SDValue StoreValue = BVN->getOperand(i);
8055         if (StoreSize < 4)
8056           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
8057 
8058         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
8059                                       PtrInfo.getWithOffset(Offset)));
8060       }
8061     }
8062 
8063     SDValue StoreChain;
8064     if (!Stores.empty())
8065       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8066     else
8067       StoreChain = DAG.getEntryNode();
8068 
8069     // Now load from v4i32 into the QPX register; this will extend it to
8070     // v4i64 but not yet convert it to a floating point. Nevertheless, this
8071     // is typed as v4f64 because the QPX register integer states are not
8072     // explicitly represented.
8073 
8074     SDValue Ops[] = {StoreChain,
8075                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
8076                      FIdx};
8077     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
8078 
8079     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
8080       dl, VTs, Ops, MVT::v4i32, PtrInfo);
8081     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8082       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
8083       LoadedVect);
8084 
8085     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
8086 
8087     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
8088   }
8089 
8090   // All other QPX vectors are handled by generic code.
8091   if (Subtarget.hasQPX())
8092     return SDValue();
8093 
8094   // Check if this is a splat of a constant value.
8095   APInt APSplatBits, APSplatUndef;
8096   unsigned SplatBitSize;
8097   bool HasAnyUndefs;
8098   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8099                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
8100       SplatBitSize > 32) {
8101     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
8102     // lowered to VSX instructions under certain conditions.
8103     // Without VSX, there is no pattern more efficient than expanding the node.
8104     if (Subtarget.hasVSX() &&
8105         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8106                                         Subtarget.hasP8Vector()))
8107       return Op;
8108     return SDValue();
8109   }
8110 
8111   unsigned SplatBits = APSplatBits.getZExtValue();
8112   unsigned SplatUndef = APSplatUndef.getZExtValue();
8113   unsigned SplatSize = SplatBitSize / 8;
8114 
8115   // First, handle single instruction cases.
8116 
8117   // All zeros?
8118   if (SplatBits == 0) {
8119     // Canonicalize all zero vectors to be v4i32.
8120     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8121       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8122       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8123     }
8124     return Op;
8125   }
8126 
8127   // We have XXSPLTIB for constant splats one byte wide
8128   if (Subtarget.hasP9Vector() && SplatSize == 1) {
8129     // This is a splat of 1-byte elements with some elements potentially undef.
8130     // Rather than trying to match undef in the SDAG patterns, ensure that all
8131     // elements are the same constant.
8132     if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
8133       SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
8134                                                        dl, MVT::i32));
8135       SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
8136       if (Op.getValueType() != MVT::v16i8)
8137         return DAG.getBitcast(Op.getValueType(), NewBV);
8138       return NewBV;
8139     }
8140 
8141     // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll
8142     // detect that constant splats like v8i16: 0xABAB are really just splats
8143     // of a 1-byte constant. In this case, we need to convert the node to a
8144     // splat of v16i8 and a bitcast.
8145     if (Op.getValueType() != MVT::v16i8)
8146       return DAG.getBitcast(Op.getValueType(),
8147                             DAG.getConstant(SplatBits, dl, MVT::v16i8));
8148 
8149     return Op;
8150   }
8151 
8152   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8153   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8154                     (32-SplatBitSize));
8155   if (SextVal >= -16 && SextVal <= 15)
8156     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
8157 
8158   // Two instruction sequences.
8159 
8160   // If this value is in the range [-32,30] and is even, use:
8161   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8162   // If this value is in the range [17,31] and is odd, use:
8163   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8164   // If this value is in the range [-31,-17] and is odd, use:
8165   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8166   // Note the last two are three-instruction sequences.
8167   if (SextVal >= -32 && SextVal <= 31) {
8168     // To avoid having these optimizations undone by constant folding,
8169     // we convert to a pseudo that will be expanded later into one of
8170     // the above forms.
8171     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8172     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8173               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8174     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8175     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8176     if (VT == Op.getValueType())
8177       return RetVal;
8178     else
8179       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8180   }
8181 
8182   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
8183   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
8184   // for fneg/fabs.
8185   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8186     // Make -1 and vspltisw -1:
8187     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
8188 
8189     // Make the VSLW intrinsic, computing 0x8000_0000.
8190     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
8191                                    OnesV, DAG, dl);
8192 
8193     // xor by OnesV to invert it.
8194     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
8195     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8196   }
8197 
8198   // Check to see if this is a wide variety of vsplti*, binop self cases.
8199   static const signed char SplatCsts[] = {
8200     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
8201     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
8202   };
8203 
8204   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
8205     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
8206     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
8207     int i = SplatCsts[idx];
8208 
8209     // Figure out what shift amount will be used by altivec if shifted by i in
8210     // this splat size.
8211     unsigned TypeShiftAmt = i & (SplatBitSize-1);
8212 
8213     // vsplti + shl self.
8214     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
8215       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8216       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8217         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
8218         Intrinsic::ppc_altivec_vslw
8219       };
8220       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8221       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8222     }
8223 
8224     // vsplti + srl self.
8225     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8226       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8227       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8228         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
8229         Intrinsic::ppc_altivec_vsrw
8230       };
8231       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8232       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8233     }
8234 
8235     // vsplti + sra self.
8236     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8237       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8238       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8239         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
8240         Intrinsic::ppc_altivec_vsraw
8241       };
8242       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8243       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8244     }
8245 
8246     // vsplti + rol self.
8247     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
8248                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
8249       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8250       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8251         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
8252         Intrinsic::ppc_altivec_vrlw
8253       };
8254       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8255       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8256     }
8257 
8258     // t = vsplti c, result = vsldoi t, t, 1
8259     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
8260       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8261       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
8262       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8263     }
8264     // t = vsplti c, result = vsldoi t, t, 2
8265     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
8266       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8267       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
8268       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8269     }
8270     // t = vsplti c, result = vsldoi t, t, 3
8271     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
8272       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8273       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
8274       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8275     }
8276   }
8277 
8278   return SDValue();
8279 }
8280 
8281 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8282 /// the specified operations to build the shuffle.
8283 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8284                                       SDValue RHS, SelectionDAG &DAG,
8285                                       const SDLoc &dl) {
8286   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8287   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8288   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8289 
8290   enum {
8291     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8292     OP_VMRGHW,
8293     OP_VMRGLW,
8294     OP_VSPLTISW0,
8295     OP_VSPLTISW1,
8296     OP_VSPLTISW2,
8297     OP_VSPLTISW3,
8298     OP_VSLDOI4,
8299     OP_VSLDOI8,
8300     OP_VSLDOI12
8301   };
8302 
8303   if (OpNum == OP_COPY) {
8304     if (LHSID == (1*9+2)*9+3) return LHS;
8305     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8306     return RHS;
8307   }
8308 
8309   SDValue OpLHS, OpRHS;
8310   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8311   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8312 
8313   int ShufIdxs[16];
8314   switch (OpNum) {
8315   default: llvm_unreachable("Unknown i32 permute!");
8316   case OP_VMRGHW:
8317     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
8318     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
8319     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
8320     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
8321     break;
8322   case OP_VMRGLW:
8323     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
8324     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
8325     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
8326     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
8327     break;
8328   case OP_VSPLTISW0:
8329     for (unsigned i = 0; i != 16; ++i)
8330       ShufIdxs[i] = (i&3)+0;
8331     break;
8332   case OP_VSPLTISW1:
8333     for (unsigned i = 0; i != 16; ++i)
8334       ShufIdxs[i] = (i&3)+4;
8335     break;
8336   case OP_VSPLTISW2:
8337     for (unsigned i = 0; i != 16; ++i)
8338       ShufIdxs[i] = (i&3)+8;
8339     break;
8340   case OP_VSPLTISW3:
8341     for (unsigned i = 0; i != 16; ++i)
8342       ShufIdxs[i] = (i&3)+12;
8343     break;
8344   case OP_VSLDOI4:
8345     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
8346   case OP_VSLDOI8:
8347     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
8348   case OP_VSLDOI12:
8349     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
8350   }
8351   EVT VT = OpLHS.getValueType();
8352   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
8353   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
8354   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
8355   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8356 }
8357 
8358 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
8359 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
8360 /// SDValue.
8361 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
8362                                            SelectionDAG &DAG) const {
8363   const unsigned BytesInVector = 16;
8364   bool IsLE = Subtarget.isLittleEndian();
8365   SDLoc dl(N);
8366   SDValue V1 = N->getOperand(0);
8367   SDValue V2 = N->getOperand(1);
8368   unsigned ShiftElts = 0, InsertAtByte = 0;
8369   bool Swap = false;
8370 
8371   // Shifts required to get the byte we want at element 7.
8372   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
8373                                    0, 15, 14, 13, 12, 11, 10, 9};
8374   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
8375                                 1, 2,  3,  4,  5,  6,  7,  8};
8376 
8377   ArrayRef<int> Mask = N->getMask();
8378   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
8379 
8380   // For each mask element, find out if we're just inserting something
8381   // from V2 into V1 or vice versa.
8382   // Possible permutations inserting an element from V2 into V1:
8383   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8384   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8385   //   ...
8386   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
8387   // Inserting from V1 into V2 will be similar, except mask range will be
8388   // [16,31].
8389 
8390   bool FoundCandidate = false;
8391   // If both vector operands for the shuffle are the same vector, the mask
8392   // will contain only elements from the first one and the second one will be
8393   // undef.
8394   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
8395   // Go through the mask of half-words to find an element that's being moved
8396   // from one vector to the other.
8397   for (unsigned i = 0; i < BytesInVector; ++i) {
8398     unsigned CurrentElement = Mask[i];
8399     // If 2nd operand is undefined, we should only look for element 7 in the
8400     // Mask.
8401     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
8402       continue;
8403 
8404     bool OtherElementsInOrder = true;
8405     // Examine the other elements in the Mask to see if they're in original
8406     // order.
8407     for (unsigned j = 0; j < BytesInVector; ++j) {
8408       if (j == i)
8409         continue;
8410       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
8411       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
8412       // in which we always assume we're always picking from the 1st operand.
8413       int MaskOffset =
8414           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
8415       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
8416         OtherElementsInOrder = false;
8417         break;
8418       }
8419     }
8420     // If other elements are in original order, we record the number of shifts
8421     // we need to get the element we want into element 7. Also record which byte
8422     // in the vector we should insert into.
8423     if (OtherElementsInOrder) {
8424       // If 2nd operand is undefined, we assume no shifts and no swapping.
8425       if (V2.isUndef()) {
8426         ShiftElts = 0;
8427         Swap = false;
8428       } else {
8429         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
8430         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
8431                          : BigEndianShifts[CurrentElement & 0xF];
8432         Swap = CurrentElement < BytesInVector;
8433       }
8434       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
8435       FoundCandidate = true;
8436       break;
8437     }
8438   }
8439 
8440   if (!FoundCandidate)
8441     return SDValue();
8442 
8443   // Candidate found, construct the proper SDAG sequence with VINSERTB,
8444   // optionally with VECSHL if shift is required.
8445   if (Swap)
8446     std::swap(V1, V2);
8447   if (V2.isUndef())
8448     V2 = V1;
8449   if (ShiftElts) {
8450     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8451                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8452     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
8453                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
8454   }
8455   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
8456                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
8457 }
8458 
8459 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
8460 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
8461 /// SDValue.
8462 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
8463                                            SelectionDAG &DAG) const {
8464   const unsigned NumHalfWords = 8;
8465   const unsigned BytesInVector = NumHalfWords * 2;
8466   // Check that the shuffle is on half-words.
8467   if (!isNByteElemShuffleMask(N, 2, 1))
8468     return SDValue();
8469 
8470   bool IsLE = Subtarget.isLittleEndian();
8471   SDLoc dl(N);
8472   SDValue V1 = N->getOperand(0);
8473   SDValue V2 = N->getOperand(1);
8474   unsigned ShiftElts = 0, InsertAtByte = 0;
8475   bool Swap = false;
8476 
8477   // Shifts required to get the half-word we want at element 3.
8478   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
8479   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
8480 
8481   uint32_t Mask = 0;
8482   uint32_t OriginalOrderLow = 0x1234567;
8483   uint32_t OriginalOrderHigh = 0x89ABCDEF;
8484   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
8485   // 32-bit space, only need 4-bit nibbles per element.
8486   for (unsigned i = 0; i < NumHalfWords; ++i) {
8487     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8488     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
8489   }
8490 
8491   // For each mask element, find out if we're just inserting something
8492   // from V2 into V1 or vice versa.  Possible permutations inserting an element
8493   // from V2 into V1:
8494   //   X, 1, 2, 3, 4, 5, 6, 7
8495   //   0, X, 2, 3, 4, 5, 6, 7
8496   //   0, 1, X, 3, 4, 5, 6, 7
8497   //   0, 1, 2, X, 4, 5, 6, 7
8498   //   0, 1, 2, 3, X, 5, 6, 7
8499   //   0, 1, 2, 3, 4, X, 6, 7
8500   //   0, 1, 2, 3, 4, 5, X, 7
8501   //   0, 1, 2, 3, 4, 5, 6, X
8502   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
8503 
8504   bool FoundCandidate = false;
8505   // Go through the mask of half-words to find an element that's being moved
8506   // from one vector to the other.
8507   for (unsigned i = 0; i < NumHalfWords; ++i) {
8508     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8509     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
8510     uint32_t MaskOtherElts = ~(0xF << MaskShift);
8511     uint32_t TargetOrder = 0x0;
8512 
8513     // If both vector operands for the shuffle are the same vector, the mask
8514     // will contain only elements from the first one and the second one will be
8515     // undef.
8516     if (V2.isUndef()) {
8517       ShiftElts = 0;
8518       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
8519       TargetOrder = OriginalOrderLow;
8520       Swap = false;
8521       // Skip if not the correct element or mask of other elements don't equal
8522       // to our expected order.
8523       if (MaskOneElt == VINSERTHSrcElem &&
8524           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8525         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8526         FoundCandidate = true;
8527         break;
8528       }
8529     } else { // If both operands are defined.
8530       // Target order is [8,15] if the current mask is between [0,7].
8531       TargetOrder =
8532           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
8533       // Skip if mask of other elements don't equal our expected order.
8534       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8535         // We only need the last 3 bits for the number of shifts.
8536         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
8537                          : BigEndianShifts[MaskOneElt & 0x7];
8538         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8539         Swap = MaskOneElt < NumHalfWords;
8540         FoundCandidate = true;
8541         break;
8542       }
8543     }
8544   }
8545 
8546   if (!FoundCandidate)
8547     return SDValue();
8548 
8549   // Candidate found, construct the proper SDAG sequence with VINSERTH,
8550   // optionally with VECSHL if shift is required.
8551   if (Swap)
8552     std::swap(V1, V2);
8553   if (V2.isUndef())
8554     V2 = V1;
8555   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8556   if (ShiftElts) {
8557     // Double ShiftElts because we're left shifting on v16i8 type.
8558     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8559                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
8560     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
8561     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8562                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8563     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8564   }
8565   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8566   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8567                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
8568   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8569 }
8570 
8571 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
8572 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
8573 /// return the code it can be lowered into.  Worst case, it can always be
8574 /// lowered into a vperm.
8575 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
8576                                                SelectionDAG &DAG) const {
8577   SDLoc dl(Op);
8578   SDValue V1 = Op.getOperand(0);
8579   SDValue V2 = Op.getOperand(1);
8580   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8581   EVT VT = Op.getValueType();
8582   bool isLittleEndian = Subtarget.isLittleEndian();
8583 
8584   unsigned ShiftElts, InsertAtByte;
8585   bool Swap = false;
8586   if (Subtarget.hasP9Vector() &&
8587       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
8588                            isLittleEndian)) {
8589     if (Swap)
8590       std::swap(V1, V2);
8591     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8592     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
8593     if (ShiftElts) {
8594       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
8595                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
8596       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
8597                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8598       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8599     }
8600     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
8601                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8602     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8603   }
8604 
8605   if (Subtarget.hasP9Altivec()) {
8606     SDValue NewISDNode;
8607     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
8608       return NewISDNode;
8609 
8610     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
8611       return NewISDNode;
8612   }
8613 
8614   if (Subtarget.hasVSX() &&
8615       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8616     if (Swap)
8617       std::swap(V1, V2);
8618     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8619     SDValue Conv2 =
8620         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
8621 
8622     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
8623                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8624     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
8625   }
8626 
8627   if (Subtarget.hasVSX() &&
8628     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8629     if (Swap)
8630       std::swap(V1, V2);
8631     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8632     SDValue Conv2 =
8633         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
8634 
8635     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
8636                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8637     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
8638   }
8639 
8640   if (Subtarget.hasP9Vector()) {
8641      if (PPC::isXXBRHShuffleMask(SVOp)) {
8642       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8643       SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv);
8644       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
8645     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
8646       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8647       SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv);
8648       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
8649     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
8650       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8651       SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv);
8652       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
8653     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
8654       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
8655       SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv);
8656       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
8657     }
8658   }
8659 
8660   if (Subtarget.hasVSX()) {
8661     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
8662       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
8663 
8664       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8665       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
8666                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
8667       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
8668     }
8669 
8670     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
8671     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
8672       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8673       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
8674       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
8675     }
8676   }
8677 
8678   if (Subtarget.hasQPX()) {
8679     if (VT.getVectorNumElements() != 4)
8680       return SDValue();
8681 
8682     if (V2.isUndef()) V2 = V1;
8683 
8684     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
8685     if (AlignIdx != -1) {
8686       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
8687                          DAG.getConstant(AlignIdx, dl, MVT::i32));
8688     } else if (SVOp->isSplat()) {
8689       int SplatIdx = SVOp->getSplatIndex();
8690       if (SplatIdx >= 4) {
8691         std::swap(V1, V2);
8692         SplatIdx -= 4;
8693       }
8694 
8695       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
8696                          DAG.getConstant(SplatIdx, dl, MVT::i32));
8697     }
8698 
8699     // Lower this into a qvgpci/qvfperm pair.
8700 
8701     // Compute the qvgpci literal
8702     unsigned idx = 0;
8703     for (unsigned i = 0; i < 4; ++i) {
8704       int m = SVOp->getMaskElt(i);
8705       unsigned mm = m >= 0 ? (unsigned) m : i;
8706       idx |= mm << (3-i)*3;
8707     }
8708 
8709     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
8710                              DAG.getConstant(idx, dl, MVT::i32));
8711     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
8712   }
8713 
8714   // Cases that are handled by instructions that take permute immediates
8715   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
8716   // selected by the instruction selector.
8717   if (V2.isUndef()) {
8718     if (PPC::isSplatShuffleMask(SVOp, 1) ||
8719         PPC::isSplatShuffleMask(SVOp, 2) ||
8720         PPC::isSplatShuffleMask(SVOp, 4) ||
8721         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
8722         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
8723         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
8724         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
8725         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
8726         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
8727         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
8728         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
8729         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
8730         (Subtarget.hasP8Altivec() && (
8731          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
8732          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
8733          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
8734       return Op;
8735     }
8736   }
8737 
8738   // Altivec has a variety of "shuffle immediates" that take two vector inputs
8739   // and produce a fixed permutation.  If any of these match, do not lower to
8740   // VPERM.
8741   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
8742   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8743       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8744       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
8745       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8746       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8747       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8748       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8749       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8750       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8751       (Subtarget.hasP8Altivec() && (
8752        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8753        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
8754        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
8755     return Op;
8756 
8757   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
8758   // perfect shuffle table to emit an optimal matching sequence.
8759   ArrayRef<int> PermMask = SVOp->getMask();
8760 
8761   unsigned PFIndexes[4];
8762   bool isFourElementShuffle = true;
8763   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
8764     unsigned EltNo = 8;   // Start out undef.
8765     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
8766       if (PermMask[i*4+j] < 0)
8767         continue;   // Undef, ignore it.
8768 
8769       unsigned ByteSource = PermMask[i*4+j];
8770       if ((ByteSource & 3) != j) {
8771         isFourElementShuffle = false;
8772         break;
8773       }
8774 
8775       if (EltNo == 8) {
8776         EltNo = ByteSource/4;
8777       } else if (EltNo != ByteSource/4) {
8778         isFourElementShuffle = false;
8779         break;
8780       }
8781     }
8782     PFIndexes[i] = EltNo;
8783   }
8784 
8785   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
8786   // perfect shuffle vector to determine if it is cost effective to do this as
8787   // discrete instructions, or whether we should use a vperm.
8788   // For now, we skip this for little endian until such time as we have a
8789   // little-endian perfect shuffle table.
8790   if (isFourElementShuffle && !isLittleEndian) {
8791     // Compute the index in the perfect shuffle table.
8792     unsigned PFTableIndex =
8793       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8794 
8795     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8796     unsigned Cost  = (PFEntry >> 30);
8797 
8798     // Determining when to avoid vperm is tricky.  Many things affect the cost
8799     // of vperm, particularly how many times the perm mask needs to be computed.
8800     // For example, if the perm mask can be hoisted out of a loop or is already
8801     // used (perhaps because there are multiple permutes with the same shuffle
8802     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
8803     // the loop requires an extra register.
8804     //
8805     // As a compromise, we only emit discrete instructions if the shuffle can be
8806     // generated in 3 or fewer operations.  When we have loop information
8807     // available, if this block is within a loop, we should avoid using vperm
8808     // for 3-operation perms and use a constant pool load instead.
8809     if (Cost < 3)
8810       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8811   }
8812 
8813   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
8814   // vector that will get spilled to the constant pool.
8815   if (V2.isUndef()) V2 = V1;
8816 
8817   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
8818   // that it is in input element units, not in bytes.  Convert now.
8819 
8820   // For little endian, the order of the input vectors is reversed, and
8821   // the permutation mask is complemented with respect to 31.  This is
8822   // necessary to produce proper semantics with the big-endian-biased vperm
8823   // instruction.
8824   EVT EltVT = V1.getValueType().getVectorElementType();
8825   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
8826 
8827   SmallVector<SDValue, 16> ResultMask;
8828   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
8829     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
8830 
8831     for (unsigned j = 0; j != BytesPerElement; ++j)
8832       if (isLittleEndian)
8833         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
8834                                              dl, MVT::i32));
8835       else
8836         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
8837                                              MVT::i32));
8838   }
8839 
8840   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
8841   if (isLittleEndian)
8842     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8843                        V2, V1, VPermMask);
8844   else
8845     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8846                        V1, V2, VPermMask);
8847 }
8848 
8849 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
8850 /// vector comparison.  If it is, return true and fill in Opc/isDot with
8851 /// information about the intrinsic.
8852 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
8853                                  bool &isDot, const PPCSubtarget &Subtarget) {
8854   unsigned IntrinsicID =
8855       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
8856   CompareOpc = -1;
8857   isDot = false;
8858   switch (IntrinsicID) {
8859   default:
8860     return false;
8861   // Comparison predicates.
8862   case Intrinsic::ppc_altivec_vcmpbfp_p:
8863     CompareOpc = 966;
8864     isDot = true;
8865     break;
8866   case Intrinsic::ppc_altivec_vcmpeqfp_p:
8867     CompareOpc = 198;
8868     isDot = true;
8869     break;
8870   case Intrinsic::ppc_altivec_vcmpequb_p:
8871     CompareOpc = 6;
8872     isDot = true;
8873     break;
8874   case Intrinsic::ppc_altivec_vcmpequh_p:
8875     CompareOpc = 70;
8876     isDot = true;
8877     break;
8878   case Intrinsic::ppc_altivec_vcmpequw_p:
8879     CompareOpc = 134;
8880     isDot = true;
8881     break;
8882   case Intrinsic::ppc_altivec_vcmpequd_p:
8883     if (Subtarget.hasP8Altivec()) {
8884       CompareOpc = 199;
8885       isDot = true;
8886     } else
8887       return false;
8888     break;
8889   case Intrinsic::ppc_altivec_vcmpneb_p:
8890   case Intrinsic::ppc_altivec_vcmpneh_p:
8891   case Intrinsic::ppc_altivec_vcmpnew_p:
8892   case Intrinsic::ppc_altivec_vcmpnezb_p:
8893   case Intrinsic::ppc_altivec_vcmpnezh_p:
8894   case Intrinsic::ppc_altivec_vcmpnezw_p:
8895     if (Subtarget.hasP9Altivec()) {
8896       switch (IntrinsicID) {
8897       default:
8898         llvm_unreachable("Unknown comparison intrinsic.");
8899       case Intrinsic::ppc_altivec_vcmpneb_p:
8900         CompareOpc = 7;
8901         break;
8902       case Intrinsic::ppc_altivec_vcmpneh_p:
8903         CompareOpc = 71;
8904         break;
8905       case Intrinsic::ppc_altivec_vcmpnew_p:
8906         CompareOpc = 135;
8907         break;
8908       case Intrinsic::ppc_altivec_vcmpnezb_p:
8909         CompareOpc = 263;
8910         break;
8911       case Intrinsic::ppc_altivec_vcmpnezh_p:
8912         CompareOpc = 327;
8913         break;
8914       case Intrinsic::ppc_altivec_vcmpnezw_p:
8915         CompareOpc = 391;
8916         break;
8917       }
8918       isDot = true;
8919     } else
8920       return false;
8921     break;
8922   case Intrinsic::ppc_altivec_vcmpgefp_p:
8923     CompareOpc = 454;
8924     isDot = true;
8925     break;
8926   case Intrinsic::ppc_altivec_vcmpgtfp_p:
8927     CompareOpc = 710;
8928     isDot = true;
8929     break;
8930   case Intrinsic::ppc_altivec_vcmpgtsb_p:
8931     CompareOpc = 774;
8932     isDot = true;
8933     break;
8934   case Intrinsic::ppc_altivec_vcmpgtsh_p:
8935     CompareOpc = 838;
8936     isDot = true;
8937     break;
8938   case Intrinsic::ppc_altivec_vcmpgtsw_p:
8939     CompareOpc = 902;
8940     isDot = true;
8941     break;
8942   case Intrinsic::ppc_altivec_vcmpgtsd_p:
8943     if (Subtarget.hasP8Altivec()) {
8944       CompareOpc = 967;
8945       isDot = true;
8946     } else
8947       return false;
8948     break;
8949   case Intrinsic::ppc_altivec_vcmpgtub_p:
8950     CompareOpc = 518;
8951     isDot = true;
8952     break;
8953   case Intrinsic::ppc_altivec_vcmpgtuh_p:
8954     CompareOpc = 582;
8955     isDot = true;
8956     break;
8957   case Intrinsic::ppc_altivec_vcmpgtuw_p:
8958     CompareOpc = 646;
8959     isDot = true;
8960     break;
8961   case Intrinsic::ppc_altivec_vcmpgtud_p:
8962     if (Subtarget.hasP8Altivec()) {
8963       CompareOpc = 711;
8964       isDot = true;
8965     } else
8966       return false;
8967     break;
8968 
8969   // VSX predicate comparisons use the same infrastructure
8970   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8971   case Intrinsic::ppc_vsx_xvcmpgedp_p:
8972   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8973   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8974   case Intrinsic::ppc_vsx_xvcmpgesp_p:
8975   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8976     if (Subtarget.hasVSX()) {
8977       switch (IntrinsicID) {
8978       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8979         CompareOpc = 99;
8980         break;
8981       case Intrinsic::ppc_vsx_xvcmpgedp_p:
8982         CompareOpc = 115;
8983         break;
8984       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8985         CompareOpc = 107;
8986         break;
8987       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8988         CompareOpc = 67;
8989         break;
8990       case Intrinsic::ppc_vsx_xvcmpgesp_p:
8991         CompareOpc = 83;
8992         break;
8993       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8994         CompareOpc = 75;
8995         break;
8996       }
8997       isDot = true;
8998     } else
8999       return false;
9000     break;
9001 
9002   // Normal Comparisons.
9003   case Intrinsic::ppc_altivec_vcmpbfp:
9004     CompareOpc = 966;
9005     break;
9006   case Intrinsic::ppc_altivec_vcmpeqfp:
9007     CompareOpc = 198;
9008     break;
9009   case Intrinsic::ppc_altivec_vcmpequb:
9010     CompareOpc = 6;
9011     break;
9012   case Intrinsic::ppc_altivec_vcmpequh:
9013     CompareOpc = 70;
9014     break;
9015   case Intrinsic::ppc_altivec_vcmpequw:
9016     CompareOpc = 134;
9017     break;
9018   case Intrinsic::ppc_altivec_vcmpequd:
9019     if (Subtarget.hasP8Altivec())
9020       CompareOpc = 199;
9021     else
9022       return false;
9023     break;
9024   case Intrinsic::ppc_altivec_vcmpneb:
9025   case Intrinsic::ppc_altivec_vcmpneh:
9026   case Intrinsic::ppc_altivec_vcmpnew:
9027   case Intrinsic::ppc_altivec_vcmpnezb:
9028   case Intrinsic::ppc_altivec_vcmpnezh:
9029   case Intrinsic::ppc_altivec_vcmpnezw:
9030     if (Subtarget.hasP9Altivec())
9031       switch (IntrinsicID) {
9032       default:
9033         llvm_unreachable("Unknown comparison intrinsic.");
9034       case Intrinsic::ppc_altivec_vcmpneb:
9035         CompareOpc = 7;
9036         break;
9037       case Intrinsic::ppc_altivec_vcmpneh:
9038         CompareOpc = 71;
9039         break;
9040       case Intrinsic::ppc_altivec_vcmpnew:
9041         CompareOpc = 135;
9042         break;
9043       case Intrinsic::ppc_altivec_vcmpnezb:
9044         CompareOpc = 263;
9045         break;
9046       case Intrinsic::ppc_altivec_vcmpnezh:
9047         CompareOpc = 327;
9048         break;
9049       case Intrinsic::ppc_altivec_vcmpnezw:
9050         CompareOpc = 391;
9051         break;
9052       }
9053     else
9054       return false;
9055     break;
9056   case Intrinsic::ppc_altivec_vcmpgefp:
9057     CompareOpc = 454;
9058     break;
9059   case Intrinsic::ppc_altivec_vcmpgtfp:
9060     CompareOpc = 710;
9061     break;
9062   case Intrinsic::ppc_altivec_vcmpgtsb:
9063     CompareOpc = 774;
9064     break;
9065   case Intrinsic::ppc_altivec_vcmpgtsh:
9066     CompareOpc = 838;
9067     break;
9068   case Intrinsic::ppc_altivec_vcmpgtsw:
9069     CompareOpc = 902;
9070     break;
9071   case Intrinsic::ppc_altivec_vcmpgtsd:
9072     if (Subtarget.hasP8Altivec())
9073       CompareOpc = 967;
9074     else
9075       return false;
9076     break;
9077   case Intrinsic::ppc_altivec_vcmpgtub:
9078     CompareOpc = 518;
9079     break;
9080   case Intrinsic::ppc_altivec_vcmpgtuh:
9081     CompareOpc = 582;
9082     break;
9083   case Intrinsic::ppc_altivec_vcmpgtuw:
9084     CompareOpc = 646;
9085     break;
9086   case Intrinsic::ppc_altivec_vcmpgtud:
9087     if (Subtarget.hasP8Altivec())
9088       CompareOpc = 711;
9089     else
9090       return false;
9091     break;
9092   }
9093   return true;
9094 }
9095 
9096 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
9097 /// lower, do it, otherwise return null.
9098 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
9099                                                    SelectionDAG &DAG) const {
9100   unsigned IntrinsicID =
9101     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9102 
9103   SDLoc dl(Op);
9104 
9105   if (IntrinsicID == Intrinsic::thread_pointer) {
9106     // Reads the thread pointer register, used for __builtin_thread_pointer.
9107     if (Subtarget.isPPC64())
9108       return DAG.getRegister(PPC::X13, MVT::i64);
9109     return DAG.getRegister(PPC::R2, MVT::i32);
9110   }
9111 
9112   // If this is a lowered altivec predicate compare, CompareOpc is set to the
9113   // opcode number of the comparison.
9114   int CompareOpc;
9115   bool isDot;
9116   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
9117     return SDValue();    // Don't custom lower most intrinsics.
9118 
9119   // If this is a non-dot comparison, make the VCMP node and we are done.
9120   if (!isDot) {
9121     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
9122                               Op.getOperand(1), Op.getOperand(2),
9123                               DAG.getConstant(CompareOpc, dl, MVT::i32));
9124     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
9125   }
9126 
9127   // Create the PPCISD altivec 'dot' comparison node.
9128   SDValue Ops[] = {
9129     Op.getOperand(2),  // LHS
9130     Op.getOperand(3),  // RHS
9131     DAG.getConstant(CompareOpc, dl, MVT::i32)
9132   };
9133   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
9134   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9135 
9136   // Now that we have the comparison, emit a copy from the CR to a GPR.
9137   // This is flagged to the above dot comparison.
9138   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
9139                                 DAG.getRegister(PPC::CR6, MVT::i32),
9140                                 CompNode.getValue(1));
9141 
9142   // Unpack the result based on how the target uses it.
9143   unsigned BitNo;   // Bit # of CR6.
9144   bool InvertBit;   // Invert result?
9145   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
9146   default:  // Can't happen, don't crash on invalid number though.
9147   case 0:   // Return the value of the EQ bit of CR6.
9148     BitNo = 0; InvertBit = false;
9149     break;
9150   case 1:   // Return the inverted value of the EQ bit of CR6.
9151     BitNo = 0; InvertBit = true;
9152     break;
9153   case 2:   // Return the value of the LT bit of CR6.
9154     BitNo = 2; InvertBit = false;
9155     break;
9156   case 3:   // Return the inverted value of the LT bit of CR6.
9157     BitNo = 2; InvertBit = true;
9158     break;
9159   }
9160 
9161   // Shift the bit into the low position.
9162   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
9163                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
9164   // Isolate the bit.
9165   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
9166                       DAG.getConstant(1, dl, MVT::i32));
9167 
9168   // If we are supposed to, toggle the bit.
9169   if (InvertBit)
9170     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
9171                         DAG.getConstant(1, dl, MVT::i32));
9172   return Flags;
9173 }
9174 
9175 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
9176                                                SelectionDAG &DAG) const {
9177   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
9178   // the beginning of the argument list.
9179   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
9180   SDLoc DL(Op);
9181   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
9182   case Intrinsic::ppc_cfence: {
9183     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
9184     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
9185     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
9186                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
9187                                                   Op.getOperand(ArgStart + 1)),
9188                                       Op.getOperand(0)),
9189                    0);
9190   }
9191   default:
9192     break;
9193   }
9194   return SDValue();
9195 }
9196 
9197 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
9198   // Check for a DIV with the same operands as this REM.
9199   for (auto UI : Op.getOperand(1)->uses()) {
9200     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
9201         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
9202       if (UI->getOperand(0) == Op.getOperand(0) &&
9203           UI->getOperand(1) == Op.getOperand(1))
9204         return SDValue();
9205   }
9206   return Op;
9207 }
9208 
9209 // Lower scalar BSWAP64 to xxbrd.
9210 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
9211   SDLoc dl(Op);
9212   // MTVSRDD
9213   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
9214                    Op.getOperand(0));
9215   // XXBRD
9216   Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op);
9217   // MFVSRD
9218   int VectorIndex = 0;
9219   if (Subtarget.isLittleEndian())
9220     VectorIndex = 1;
9221   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
9222                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
9223   return Op;
9224 }
9225 
9226 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
9227 // compared to a value that is atomically loaded (atomic loads zero-extend).
9228 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
9229                                                 SelectionDAG &DAG) const {
9230   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
9231          "Expecting an atomic compare-and-swap here.");
9232   SDLoc dl(Op);
9233   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
9234   EVT MemVT = AtomicNode->getMemoryVT();
9235   if (MemVT.getSizeInBits() >= 32)
9236     return Op;
9237 
9238   SDValue CmpOp = Op.getOperand(2);
9239   // If this is already correctly zero-extended, leave it alone.
9240   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
9241   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
9242     return Op;
9243 
9244   // Clear the high bits of the compare operand.
9245   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
9246   SDValue NewCmpOp =
9247     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
9248                 DAG.getConstant(MaskVal, dl, MVT::i32));
9249 
9250   // Replace the existing compare operand with the properly zero-extended one.
9251   SmallVector<SDValue, 4> Ops;
9252   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
9253     Ops.push_back(AtomicNode->getOperand(i));
9254   Ops[2] = NewCmpOp;
9255   MachineMemOperand *MMO = AtomicNode->getMemOperand();
9256   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
9257   auto NodeTy =
9258     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
9259   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
9260 }
9261 
9262 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
9263                                                  SelectionDAG &DAG) const {
9264   SDLoc dl(Op);
9265   // Create a stack slot that is 16-byte aligned.
9266   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9267   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9268   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9269   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9270 
9271   // Store the input value into Value#0 of the stack slot.
9272   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
9273                                MachinePointerInfo());
9274   // Load it out.
9275   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
9276 }
9277 
9278 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9279                                                   SelectionDAG &DAG) const {
9280   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
9281          "Should only be called for ISD::INSERT_VECTOR_ELT");
9282 
9283   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9284   // We have legal lowering for constant indices but not for variable ones.
9285   if (!C)
9286     return SDValue();
9287 
9288   EVT VT = Op.getValueType();
9289   SDLoc dl(Op);
9290   SDValue V1 = Op.getOperand(0);
9291   SDValue V2 = Op.getOperand(1);
9292   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
9293   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
9294     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
9295     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
9296     unsigned InsertAtElement = C->getZExtValue();
9297     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
9298     if (Subtarget.isLittleEndian()) {
9299       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
9300     }
9301     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
9302                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9303   }
9304   return Op;
9305 }
9306 
9307 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9308                                                    SelectionDAG &DAG) const {
9309   SDLoc dl(Op);
9310   SDNode *N = Op.getNode();
9311 
9312   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
9313          "Unknown extract_vector_elt type");
9314 
9315   SDValue Value = N->getOperand(0);
9316 
9317   // The first part of this is like the store lowering except that we don't
9318   // need to track the chain.
9319 
9320   // The values are now known to be -1 (false) or 1 (true). To convert this
9321   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9322   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9323   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9324 
9325   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9326   // understand how to form the extending load.
9327   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9328 
9329   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9330 
9331   // Now convert to an integer and store.
9332   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9333     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9334     Value);
9335 
9336   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9337   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9338   MachinePointerInfo PtrInfo =
9339       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9340   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9341   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9342 
9343   SDValue StoreChain = DAG.getEntryNode();
9344   SDValue Ops[] = {StoreChain,
9345                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9346                    Value, FIdx};
9347   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9348 
9349   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9350     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9351 
9352   // Extract the value requested.
9353   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9354   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9355   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9356 
9357   SDValue IntVal =
9358       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
9359 
9360   if (!Subtarget.useCRBits())
9361     return IntVal;
9362 
9363   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
9364 }
9365 
9366 /// Lowering for QPX v4i1 loads
9367 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
9368                                            SelectionDAG &DAG) const {
9369   SDLoc dl(Op);
9370   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
9371   SDValue LoadChain = LN->getChain();
9372   SDValue BasePtr = LN->getBasePtr();
9373 
9374   if (Op.getValueType() == MVT::v4f64 ||
9375       Op.getValueType() == MVT::v4f32) {
9376     EVT MemVT = LN->getMemoryVT();
9377     unsigned Alignment = LN->getAlignment();
9378 
9379     // If this load is properly aligned, then it is legal.
9380     if (Alignment >= MemVT.getStoreSize())
9381       return Op;
9382 
9383     EVT ScalarVT = Op.getValueType().getScalarType(),
9384         ScalarMemVT = MemVT.getScalarType();
9385     unsigned Stride = ScalarMemVT.getStoreSize();
9386 
9387     SDValue Vals[4], LoadChains[4];
9388     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9389       SDValue Load;
9390       if (ScalarVT != ScalarMemVT)
9391         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
9392                               BasePtr,
9393                               LN->getPointerInfo().getWithOffset(Idx * Stride),
9394                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9395                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
9396       else
9397         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
9398                            LN->getPointerInfo().getWithOffset(Idx * Stride),
9399                            MinAlign(Alignment, Idx * Stride),
9400                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
9401 
9402       if (Idx == 0 && LN->isIndexed()) {
9403         assert(LN->getAddressingMode() == ISD::PRE_INC &&
9404                "Unknown addressing mode on vector load");
9405         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
9406                                   LN->getAddressingMode());
9407       }
9408 
9409       Vals[Idx] = Load;
9410       LoadChains[Idx] = Load.getValue(1);
9411 
9412       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9413                             DAG.getConstant(Stride, dl,
9414                                             BasePtr.getValueType()));
9415     }
9416 
9417     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9418     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
9419 
9420     if (LN->isIndexed()) {
9421       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
9422       return DAG.getMergeValues(RetOps, dl);
9423     }
9424 
9425     SDValue RetOps[] = { Value, TF };
9426     return DAG.getMergeValues(RetOps, dl);
9427   }
9428 
9429   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
9430   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
9431 
9432   // To lower v4i1 from a byte array, we load the byte elements of the
9433   // vector and then reuse the BUILD_VECTOR logic.
9434 
9435   SDValue VectElmts[4], VectElmtChains[4];
9436   for (unsigned i = 0; i < 4; ++i) {
9437     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9438     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9439 
9440     VectElmts[i] = DAG.getExtLoad(
9441         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
9442         LN->getPointerInfo().getWithOffset(i), MVT::i8,
9443         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
9444     VectElmtChains[i] = VectElmts[i].getValue(1);
9445   }
9446 
9447   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
9448   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
9449 
9450   SDValue RVals[] = { Value, LoadChain };
9451   return DAG.getMergeValues(RVals, dl);
9452 }
9453 
9454 /// Lowering for QPX v4i1 stores
9455 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
9456                                             SelectionDAG &DAG) const {
9457   SDLoc dl(Op);
9458   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
9459   SDValue StoreChain = SN->getChain();
9460   SDValue BasePtr = SN->getBasePtr();
9461   SDValue Value = SN->getValue();
9462 
9463   if (Value.getValueType() == MVT::v4f64 ||
9464       Value.getValueType() == MVT::v4f32) {
9465     EVT MemVT = SN->getMemoryVT();
9466     unsigned Alignment = SN->getAlignment();
9467 
9468     // If this store is properly aligned, then it is legal.
9469     if (Alignment >= MemVT.getStoreSize())
9470       return Op;
9471 
9472     EVT ScalarVT = Value.getValueType().getScalarType(),
9473         ScalarMemVT = MemVT.getScalarType();
9474     unsigned Stride = ScalarMemVT.getStoreSize();
9475 
9476     SDValue Stores[4];
9477     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9478       SDValue Ex = DAG.getNode(
9479           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
9480           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
9481       SDValue Store;
9482       if (ScalarVT != ScalarMemVT)
9483         Store =
9484             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
9485                               SN->getPointerInfo().getWithOffset(Idx * Stride),
9486                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9487                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
9488       else
9489         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
9490                              SN->getPointerInfo().getWithOffset(Idx * Stride),
9491                              MinAlign(Alignment, Idx * Stride),
9492                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
9493 
9494       if (Idx == 0 && SN->isIndexed()) {
9495         assert(SN->getAddressingMode() == ISD::PRE_INC &&
9496                "Unknown addressing mode on vector store");
9497         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
9498                                     SN->getAddressingMode());
9499       }
9500 
9501       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9502                             DAG.getConstant(Stride, dl,
9503                                             BasePtr.getValueType()));
9504       Stores[Idx] = Store;
9505     }
9506 
9507     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9508 
9509     if (SN->isIndexed()) {
9510       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
9511       return DAG.getMergeValues(RetOps, dl);
9512     }
9513 
9514     return TF;
9515   }
9516 
9517   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
9518   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
9519 
9520   // The values are now known to be -1 (false) or 1 (true). To convert this
9521   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9522   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9523   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9524 
9525   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9526   // understand how to form the extending load.
9527   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9528 
9529   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9530 
9531   // Now convert to an integer and store.
9532   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9533     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9534     Value);
9535 
9536   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9537   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9538   MachinePointerInfo PtrInfo =
9539       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9540   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9541   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9542 
9543   SDValue Ops[] = {StoreChain,
9544                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9545                    Value, FIdx};
9546   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9547 
9548   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9549     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9550 
9551   // Move data into the byte array.
9552   SDValue Loads[4], LoadChains[4];
9553   for (unsigned i = 0; i < 4; ++i) {
9554     unsigned Offset = 4*i;
9555     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9556     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9557 
9558     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
9559                            PtrInfo.getWithOffset(Offset));
9560     LoadChains[i] = Loads[i].getValue(1);
9561   }
9562 
9563   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9564 
9565   SDValue Stores[4];
9566   for (unsigned i = 0; i < 4; ++i) {
9567     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9568     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9569 
9570     Stores[i] = DAG.getTruncStore(
9571         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
9572         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
9573         SN->getAAInfo());
9574   }
9575 
9576   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9577 
9578   return StoreChain;
9579 }
9580 
9581 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9582   SDLoc dl(Op);
9583   if (Op.getValueType() == MVT::v4i32) {
9584     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9585 
9586     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
9587     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
9588 
9589     SDValue RHSSwap =   // = vrlw RHS, 16
9590       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
9591 
9592     // Shrinkify inputs to v8i16.
9593     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
9594     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
9595     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
9596 
9597     // Low parts multiplied together, generating 32-bit results (we ignore the
9598     // top parts).
9599     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
9600                                         LHS, RHS, DAG, dl, MVT::v4i32);
9601 
9602     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
9603                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
9604     // Shift the high parts up 16 bits.
9605     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
9606                               Neg16, DAG, dl);
9607     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
9608   } else if (Op.getValueType() == MVT::v8i16) {
9609     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9610 
9611     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
9612 
9613     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
9614                             LHS, RHS, Zero, DAG, dl);
9615   } else if (Op.getValueType() == MVT::v16i8) {
9616     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9617     bool isLittleEndian = Subtarget.isLittleEndian();
9618 
9619     // Multiply the even 8-bit parts, producing 16-bit sums.
9620     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
9621                                            LHS, RHS, DAG, dl, MVT::v8i16);
9622     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
9623 
9624     // Multiply the odd 8-bit parts, producing 16-bit sums.
9625     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
9626                                           LHS, RHS, DAG, dl, MVT::v8i16);
9627     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
9628 
9629     // Merge the results together.  Because vmuleub and vmuloub are
9630     // instructions with a big-endian bias, we must reverse the
9631     // element numbering and reverse the meaning of "odd" and "even"
9632     // when generating little endian code.
9633     int Ops[16];
9634     for (unsigned i = 0; i != 8; ++i) {
9635       if (isLittleEndian) {
9636         Ops[i*2  ] = 2*i;
9637         Ops[i*2+1] = 2*i+16;
9638       } else {
9639         Ops[i*2  ] = 2*i+1;
9640         Ops[i*2+1] = 2*i+1+16;
9641       }
9642     }
9643     if (isLittleEndian)
9644       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
9645     else
9646       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
9647   } else {
9648     llvm_unreachable("Unknown mul to lower!");
9649   }
9650 }
9651 
9652 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
9653 
9654   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
9655 
9656   EVT VT = Op.getValueType();
9657   assert(VT.isVector() &&
9658          "Only set vector abs as custom, scalar abs shouldn't reach here!");
9659   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
9660           VT == MVT::v16i8) &&
9661          "Unexpected vector element type!");
9662   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
9663          "Current subtarget doesn't support smax v2i64!");
9664 
9665   // For vector abs, it can be lowered to:
9666   // abs x
9667   // ==>
9668   // y = -x
9669   // smax(x, y)
9670 
9671   SDLoc dl(Op);
9672   SDValue X = Op.getOperand(0);
9673   SDValue Zero = DAG.getConstant(0, dl, VT);
9674   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
9675 
9676   // SMAX patch https://reviews.llvm.org/D47332
9677   // hasn't landed yet, so use intrinsic first here.
9678   // TODO: Should use SMAX directly once SMAX patch landed
9679   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
9680   if (VT == MVT::v2i64)
9681     BifID = Intrinsic::ppc_altivec_vmaxsd;
9682   else if (VT == MVT::v8i16)
9683     BifID = Intrinsic::ppc_altivec_vmaxsh;
9684   else if (VT == MVT::v16i8)
9685     BifID = Intrinsic::ppc_altivec_vmaxsb;
9686 
9687   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
9688 }
9689 
9690 // Custom lowering for fpext vf32 to v2f64
9691 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
9692 
9693   assert(Op.getOpcode() == ISD::FP_EXTEND &&
9694          "Should only be called for ISD::FP_EXTEND");
9695 
9696   // We only want to custom lower an extend from v2f32 to v2f64.
9697   if (Op.getValueType() != MVT::v2f64 ||
9698       Op.getOperand(0).getValueType() != MVT::v2f32)
9699     return SDValue();
9700 
9701   SDLoc dl(Op);
9702   SDValue Op0 = Op.getOperand(0);
9703 
9704   switch (Op0.getOpcode()) {
9705   default:
9706     return SDValue();
9707   case ISD::FADD:
9708   case ISD::FMUL:
9709   case ISD::FSUB: {
9710     SDValue NewLoad[2];
9711     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
9712       // Ensure both input are loads.
9713       SDValue LdOp = Op0.getOperand(i);
9714       if (LdOp.getOpcode() != ISD::LOAD)
9715         return SDValue();
9716       // Generate new load node.
9717       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
9718       SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() };
9719       NewLoad[i] =
9720         DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl,
9721                                 DAG.getVTList(MVT::v4f32, MVT::Other),
9722                                 LoadOps, LD->getMemoryVT(),
9723                                 LD->getMemOperand());
9724     }
9725     SDValue NewOp = DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32,
9726                               NewLoad[0], NewLoad[1],
9727                               Op0.getNode()->getFlags());
9728     return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewOp);
9729   }
9730   case ISD::LOAD: {
9731     LoadSDNode *LD = cast<LoadSDNode>(Op0);
9732     SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() };
9733     SDValue NewLd =
9734       DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl,
9735                               DAG.getVTList(MVT::v4f32, MVT::Other),
9736                               LoadOps, LD->getMemoryVT(), LD->getMemOperand());
9737     return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewLd);
9738   }
9739   }
9740   llvm_unreachable("ERROR:Should return for all cases within swtich.");
9741 }
9742 
9743 /// LowerOperation - Provide custom lowering hooks for some operations.
9744 ///
9745 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9746   switch (Op.getOpcode()) {
9747   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
9748   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9749   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9750   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9751   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9752   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9753   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9754   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
9755   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
9756 
9757   // Variable argument lowering.
9758   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9759   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9760   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9761 
9762   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
9763   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9764   case ISD::GET_DYNAMIC_AREA_OFFSET:
9765     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
9766 
9767   // Exception handling lowering.
9768   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
9769   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
9770   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
9771 
9772   case ISD::LOAD:               return LowerLOAD(Op, DAG);
9773   case ISD::STORE:              return LowerSTORE(Op, DAG);
9774   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
9775   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
9776   case ISD::FP_TO_UINT:
9777   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
9778   case ISD::UINT_TO_FP:
9779   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
9780   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9781 
9782   // Lower 64-bit shifts.
9783   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
9784   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
9785   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
9786 
9787   // Vector-related lowering.
9788   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9789   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9790   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9791   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9792   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9793   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9794   case ISD::MUL:                return LowerMUL(Op, DAG);
9795   case ISD::ABS:                return LowerABS(Op, DAG);
9796   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
9797 
9798   // For counter-based loop handling.
9799   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
9800 
9801   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9802 
9803   // Frame & Return address.
9804   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9805   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9806 
9807   case ISD::INTRINSIC_VOID:
9808     return LowerINTRINSIC_VOID(Op, DAG);
9809   case ISD::SREM:
9810   case ISD::UREM:
9811     return LowerREM(Op, DAG);
9812   case ISD::BSWAP:
9813     return LowerBSWAP(Op, DAG);
9814   case ISD::ATOMIC_CMP_SWAP:
9815     return LowerATOMIC_CMP_SWAP(Op, DAG);
9816   }
9817 }
9818 
9819 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
9820                                            SmallVectorImpl<SDValue>&Results,
9821                                            SelectionDAG &DAG) const {
9822   SDLoc dl(N);
9823   switch (N->getOpcode()) {
9824   default:
9825     llvm_unreachable("Do not know how to custom type legalize this operation!");
9826   case ISD::READCYCLECOUNTER: {
9827     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9828     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
9829 
9830     Results.push_back(RTB);
9831     Results.push_back(RTB.getValue(1));
9832     Results.push_back(RTB.getValue(2));
9833     break;
9834   }
9835   case ISD::INTRINSIC_W_CHAIN: {
9836     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
9837         Intrinsic::ppc_is_decremented_ctr_nonzero)
9838       break;
9839 
9840     assert(N->getValueType(0) == MVT::i1 &&
9841            "Unexpected result type for CTR decrement intrinsic");
9842     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
9843                                  N->getValueType(0));
9844     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
9845     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
9846                                  N->getOperand(1));
9847 
9848     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
9849     Results.push_back(NewInt.getValue(1));
9850     break;
9851   }
9852   case ISD::VAARG: {
9853     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
9854       return;
9855 
9856     EVT VT = N->getValueType(0);
9857 
9858     if (VT == MVT::i64) {
9859       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
9860 
9861       Results.push_back(NewNode);
9862       Results.push_back(NewNode.getValue(1));
9863     }
9864     return;
9865   }
9866   case ISD::FP_TO_SINT:
9867   case ISD::FP_TO_UINT:
9868     // LowerFP_TO_INT() can only handle f32 and f64.
9869     if (N->getOperand(0).getValueType() == MVT::ppcf128)
9870       return;
9871     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
9872     return;
9873   case ISD::TRUNCATE: {
9874     EVT TrgVT = N->getValueType(0);
9875     if (TrgVT.isVector() &&
9876         isOperationCustom(N->getOpcode(), TrgVT) &&
9877         N->getOperand(0).getValueType().getSizeInBits() <= 128)
9878       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
9879     return;
9880   }
9881   case ISD::BITCAST:
9882     // Don't handle bitcast here.
9883     return;
9884   }
9885 }
9886 
9887 //===----------------------------------------------------------------------===//
9888 //  Other Lowering Code
9889 //===----------------------------------------------------------------------===//
9890 
9891 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
9892   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9893   Function *Func = Intrinsic::getDeclaration(M, Id);
9894   return Builder.CreateCall(Func, {});
9895 }
9896 
9897 // The mappings for emitLeading/TrailingFence is taken from
9898 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
9899 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
9900                                                  Instruction *Inst,
9901                                                  AtomicOrdering Ord) const {
9902   if (Ord == AtomicOrdering::SequentiallyConsistent)
9903     return callIntrinsic(Builder, Intrinsic::ppc_sync);
9904   if (isReleaseOrStronger(Ord))
9905     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
9906   return nullptr;
9907 }
9908 
9909 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
9910                                                   Instruction *Inst,
9911                                                   AtomicOrdering Ord) const {
9912   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
9913     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
9914     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
9915     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
9916     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
9917       return Builder.CreateCall(
9918           Intrinsic::getDeclaration(
9919               Builder.GetInsertBlock()->getParent()->getParent(),
9920               Intrinsic::ppc_cfence, {Inst->getType()}),
9921           {Inst});
9922     // FIXME: Can use isync for rmw operation.
9923     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
9924   }
9925   return nullptr;
9926 }
9927 
9928 MachineBasicBlock *
9929 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
9930                                     unsigned AtomicSize,
9931                                     unsigned BinOpcode,
9932                                     unsigned CmpOpcode,
9933                                     unsigned CmpPred) const {
9934   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
9935   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9936 
9937   auto LoadMnemonic = PPC::LDARX;
9938   auto StoreMnemonic = PPC::STDCX;
9939   switch (AtomicSize) {
9940   default:
9941     llvm_unreachable("Unexpected size of atomic entity");
9942   case 1:
9943     LoadMnemonic = PPC::LBARX;
9944     StoreMnemonic = PPC::STBCX;
9945     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
9946     break;
9947   case 2:
9948     LoadMnemonic = PPC::LHARX;
9949     StoreMnemonic = PPC::STHCX;
9950     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
9951     break;
9952   case 4:
9953     LoadMnemonic = PPC::LWARX;
9954     StoreMnemonic = PPC::STWCX;
9955     break;
9956   case 8:
9957     LoadMnemonic = PPC::LDARX;
9958     StoreMnemonic = PPC::STDCX;
9959     break;
9960   }
9961 
9962   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9963   MachineFunction *F = BB->getParent();
9964   MachineFunction::iterator It = ++BB->getIterator();
9965 
9966   unsigned dest = MI.getOperand(0).getReg();
9967   unsigned ptrA = MI.getOperand(1).getReg();
9968   unsigned ptrB = MI.getOperand(2).getReg();
9969   unsigned incr = MI.getOperand(3).getReg();
9970   DebugLoc dl = MI.getDebugLoc();
9971 
9972   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
9973   MachineBasicBlock *loop2MBB =
9974     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
9975   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9976   F->insert(It, loopMBB);
9977   if (CmpOpcode)
9978     F->insert(It, loop2MBB);
9979   F->insert(It, exitMBB);
9980   exitMBB->splice(exitMBB->begin(), BB,
9981                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9982   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9983 
9984   MachineRegisterInfo &RegInfo = F->getRegInfo();
9985   unsigned TmpReg = (!BinOpcode) ? incr :
9986     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
9987                                            : &PPC::GPRCRegClass);
9988 
9989   //  thisMBB:
9990   //   ...
9991   //   fallthrough --> loopMBB
9992   BB->addSuccessor(loopMBB);
9993 
9994   //  loopMBB:
9995   //   l[wd]arx dest, ptr
9996   //   add r0, dest, incr
9997   //   st[wd]cx. r0, ptr
9998   //   bne- loopMBB
9999   //   fallthrough --> exitMBB
10000 
10001   // For max/min...
10002   //  loopMBB:
10003   //   l[wd]arx dest, ptr
10004   //   cmpl?[wd] incr, dest
10005   //   bgt exitMBB
10006   //  loop2MBB:
10007   //   st[wd]cx. dest, ptr
10008   //   bne- loopMBB
10009   //   fallthrough --> exitMBB
10010 
10011   BB = loopMBB;
10012   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10013     .addReg(ptrA).addReg(ptrB);
10014   if (BinOpcode)
10015     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10016   if (CmpOpcode) {
10017     // Signed comparisons of byte or halfword values must be sign-extended.
10018     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10019       unsigned ExtReg =  RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10020       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10021               ExtReg).addReg(dest);
10022       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10023         .addReg(incr).addReg(ExtReg);
10024     } else
10025       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10026         .addReg(incr).addReg(dest);
10027 
10028     BuildMI(BB, dl, TII->get(PPC::BCC))
10029       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10030     BB->addSuccessor(loop2MBB);
10031     BB->addSuccessor(exitMBB);
10032     BB = loop2MBB;
10033   }
10034   BuildMI(BB, dl, TII->get(StoreMnemonic))
10035     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10036   BuildMI(BB, dl, TII->get(PPC::BCC))
10037     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10038   BB->addSuccessor(loopMBB);
10039   BB->addSuccessor(exitMBB);
10040 
10041   //  exitMBB:
10042   //   ...
10043   BB = exitMBB;
10044   return BB;
10045 }
10046 
10047 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10048     MachineInstr &MI, MachineBasicBlock *BB,
10049     bool is8bit, // operation
10050     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10051   // If we support part-word atomic mnemonics, just use them
10052   if (Subtarget.hasPartwordAtomics())
10053     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10054                             CmpPred);
10055 
10056   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10057   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10058   // In 64 bit mode we have to use 64 bits for addresses, even though the
10059   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10060   // registers without caring whether they're 32 or 64, but here we're
10061   // doing actual arithmetic on the addresses.
10062   bool is64bit = Subtarget.isPPC64();
10063   bool isLittleEndian = Subtarget.isLittleEndian();
10064   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10065 
10066   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10067   MachineFunction *F = BB->getParent();
10068   MachineFunction::iterator It = ++BB->getIterator();
10069 
10070   unsigned dest = MI.getOperand(0).getReg();
10071   unsigned ptrA = MI.getOperand(1).getReg();
10072   unsigned ptrB = MI.getOperand(2).getReg();
10073   unsigned incr = MI.getOperand(3).getReg();
10074   DebugLoc dl = MI.getDebugLoc();
10075 
10076   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10077   MachineBasicBlock *loop2MBB =
10078       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10079   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10080   F->insert(It, loopMBB);
10081   if (CmpOpcode)
10082     F->insert(It, loop2MBB);
10083   F->insert(It, exitMBB);
10084   exitMBB->splice(exitMBB->begin(), BB,
10085                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10086   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10087 
10088   MachineRegisterInfo &RegInfo = F->getRegInfo();
10089   const TargetRegisterClass *RC =
10090       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10091   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10092 
10093   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
10094   unsigned Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10095   unsigned ShiftReg =
10096       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10097   unsigned Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10098   unsigned MaskReg = RegInfo.createVirtualRegister(GPRC);
10099   unsigned Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10100   unsigned Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10101   unsigned Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10102   unsigned Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10103   unsigned Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10104   unsigned TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10105   unsigned Ptr1Reg;
10106   unsigned TmpReg =
10107       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10108 
10109   //  thisMBB:
10110   //   ...
10111   //   fallthrough --> loopMBB
10112   BB->addSuccessor(loopMBB);
10113 
10114   // The 4-byte load must be aligned, while a char or short may be
10115   // anywhere in the word.  Hence all this nasty bookkeeping code.
10116   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10117   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10118   //   xori shift, shift1, 24 [16]
10119   //   rlwinm ptr, ptr1, 0, 0, 29
10120   //   slw incr2, incr, shift
10121   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10122   //   slw mask, mask2, shift
10123   //  loopMBB:
10124   //   lwarx tmpDest, ptr
10125   //   add tmp, tmpDest, incr2
10126   //   andc tmp2, tmpDest, mask
10127   //   and tmp3, tmp, mask
10128   //   or tmp4, tmp3, tmp2
10129   //   stwcx. tmp4, ptr
10130   //   bne- loopMBB
10131   //   fallthrough --> exitMBB
10132   //   srw dest, tmpDest, shift
10133   if (ptrA != ZeroReg) {
10134     Ptr1Reg = RegInfo.createVirtualRegister(RC);
10135     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10136         .addReg(ptrA)
10137         .addReg(ptrB);
10138   } else {
10139     Ptr1Reg = ptrB;
10140   }
10141   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10142   // mode.
10143   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10144       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10145       .addImm(3)
10146       .addImm(27)
10147       .addImm(is8bit ? 28 : 27);
10148   if (!isLittleEndian)
10149     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10150         .addReg(Shift1Reg)
10151         .addImm(is8bit ? 24 : 16);
10152   if (is64bit)
10153     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10154         .addReg(Ptr1Reg)
10155         .addImm(0)
10156         .addImm(61);
10157   else
10158     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10159         .addReg(Ptr1Reg)
10160         .addImm(0)
10161         .addImm(0)
10162         .addImm(29);
10163   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
10164   if (is8bit)
10165     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10166   else {
10167     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10168     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10169         .addReg(Mask3Reg)
10170         .addImm(65535);
10171   }
10172   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10173       .addReg(Mask2Reg)
10174       .addReg(ShiftReg);
10175 
10176   BB = loopMBB;
10177   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10178       .addReg(ZeroReg)
10179       .addReg(PtrReg);
10180   if (BinOpcode)
10181     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
10182         .addReg(Incr2Reg)
10183         .addReg(TmpDestReg);
10184   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
10185       .addReg(TmpDestReg)
10186       .addReg(MaskReg);
10187   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
10188   if (CmpOpcode) {
10189     // For unsigned comparisons, we can directly compare the shifted values.
10190     // For signed comparisons we shift and sign extend.
10191     unsigned SReg = RegInfo.createVirtualRegister(GPRC);
10192     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
10193         .addReg(TmpDestReg)
10194         .addReg(MaskReg);
10195     unsigned ValueReg = SReg;
10196     unsigned CmpReg = Incr2Reg;
10197     if (CmpOpcode == PPC::CMPW) {
10198       ValueReg = RegInfo.createVirtualRegister(GPRC);
10199       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
10200           .addReg(SReg)
10201           .addReg(ShiftReg);
10202       unsigned ValueSReg = RegInfo.createVirtualRegister(GPRC);
10203       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
10204           .addReg(ValueReg);
10205       ValueReg = ValueSReg;
10206       CmpReg = incr;
10207     }
10208     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10209         .addReg(CmpReg)
10210         .addReg(ValueReg);
10211     BuildMI(BB, dl, TII->get(PPC::BCC))
10212         .addImm(CmpPred)
10213         .addReg(PPC::CR0)
10214         .addMBB(exitMBB);
10215     BB->addSuccessor(loop2MBB);
10216     BB->addSuccessor(exitMBB);
10217     BB = loop2MBB;
10218   }
10219   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
10220   BuildMI(BB, dl, TII->get(PPC::STWCX))
10221       .addReg(Tmp4Reg)
10222       .addReg(ZeroReg)
10223       .addReg(PtrReg);
10224   BuildMI(BB, dl, TII->get(PPC::BCC))
10225       .addImm(PPC::PRED_NE)
10226       .addReg(PPC::CR0)
10227       .addMBB(loopMBB);
10228   BB->addSuccessor(loopMBB);
10229   BB->addSuccessor(exitMBB);
10230 
10231   //  exitMBB:
10232   //   ...
10233   BB = exitMBB;
10234   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
10235       .addReg(TmpDestReg)
10236       .addReg(ShiftReg);
10237   return BB;
10238 }
10239 
10240 llvm::MachineBasicBlock *
10241 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
10242                                     MachineBasicBlock *MBB) const {
10243   DebugLoc DL = MI.getDebugLoc();
10244   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10245   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
10246 
10247   MachineFunction *MF = MBB->getParent();
10248   MachineRegisterInfo &MRI = MF->getRegInfo();
10249 
10250   const BasicBlock *BB = MBB->getBasicBlock();
10251   MachineFunction::iterator I = ++MBB->getIterator();
10252 
10253   unsigned DstReg = MI.getOperand(0).getReg();
10254   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
10255   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
10256   unsigned mainDstReg = MRI.createVirtualRegister(RC);
10257   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
10258 
10259   MVT PVT = getPointerTy(MF->getDataLayout());
10260   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10261          "Invalid Pointer Size!");
10262   // For v = setjmp(buf), we generate
10263   //
10264   // thisMBB:
10265   //  SjLjSetup mainMBB
10266   //  bl mainMBB
10267   //  v_restore = 1
10268   //  b sinkMBB
10269   //
10270   // mainMBB:
10271   //  buf[LabelOffset] = LR
10272   //  v_main = 0
10273   //
10274   // sinkMBB:
10275   //  v = phi(main, restore)
10276   //
10277 
10278   MachineBasicBlock *thisMBB = MBB;
10279   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
10280   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
10281   MF->insert(I, mainMBB);
10282   MF->insert(I, sinkMBB);
10283 
10284   MachineInstrBuilder MIB;
10285 
10286   // Transfer the remainder of BB and its successor edges to sinkMBB.
10287   sinkMBB->splice(sinkMBB->begin(), MBB,
10288                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10289   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
10290 
10291   // Note that the structure of the jmp_buf used here is not compatible
10292   // with that used by libc, and is not designed to be. Specifically, it
10293   // stores only those 'reserved' registers that LLVM does not otherwise
10294   // understand how to spill. Also, by convention, by the time this
10295   // intrinsic is called, Clang has already stored the frame address in the
10296   // first slot of the buffer and stack address in the third. Following the
10297   // X86 target code, we'll store the jump address in the second slot. We also
10298   // need to save the TOC pointer (R2) to handle jumps between shared
10299   // libraries, and that will be stored in the fourth slot. The thread
10300   // identifier (R13) is not affected.
10301 
10302   // thisMBB:
10303   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10304   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10305   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10306 
10307   // Prepare IP either in reg.
10308   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
10309   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
10310   unsigned BufReg = MI.getOperand(1).getReg();
10311 
10312   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
10313     setUsesTOCBasePtr(*MBB->getParent());
10314     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
10315               .addReg(PPC::X2)
10316               .addImm(TOCOffset)
10317               .addReg(BufReg)
10318               .cloneMemRefs(MI);
10319   }
10320 
10321   // Naked functions never have a base pointer, and so we use r1. For all
10322   // other functions, this decision must be delayed until during PEI.
10323   unsigned BaseReg;
10324   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
10325     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
10326   else
10327     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
10328 
10329   MIB = BuildMI(*thisMBB, MI, DL,
10330                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
10331             .addReg(BaseReg)
10332             .addImm(BPOffset)
10333             .addReg(BufReg)
10334             .cloneMemRefs(MI);
10335 
10336   // Setup
10337   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
10338   MIB.addRegMask(TRI->getNoPreservedMask());
10339 
10340   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
10341 
10342   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
10343           .addMBB(mainMBB);
10344   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
10345 
10346   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
10347   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
10348 
10349   // mainMBB:
10350   //  mainDstReg = 0
10351   MIB =
10352       BuildMI(mainMBB, DL,
10353               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
10354 
10355   // Store IP
10356   if (Subtarget.isPPC64()) {
10357     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
10358             .addReg(LabelReg)
10359             .addImm(LabelOffset)
10360             .addReg(BufReg);
10361   } else {
10362     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
10363             .addReg(LabelReg)
10364             .addImm(LabelOffset)
10365             .addReg(BufReg);
10366   }
10367   MIB.cloneMemRefs(MI);
10368 
10369   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
10370   mainMBB->addSuccessor(sinkMBB);
10371 
10372   // sinkMBB:
10373   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10374           TII->get(PPC::PHI), DstReg)
10375     .addReg(mainDstReg).addMBB(mainMBB)
10376     .addReg(restoreDstReg).addMBB(thisMBB);
10377 
10378   MI.eraseFromParent();
10379   return sinkMBB;
10380 }
10381 
10382 MachineBasicBlock *
10383 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
10384                                      MachineBasicBlock *MBB) const {
10385   DebugLoc DL = MI.getDebugLoc();
10386   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10387 
10388   MachineFunction *MF = MBB->getParent();
10389   MachineRegisterInfo &MRI = MF->getRegInfo();
10390 
10391   MVT PVT = getPointerTy(MF->getDataLayout());
10392   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10393          "Invalid Pointer Size!");
10394 
10395   const TargetRegisterClass *RC =
10396     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10397   unsigned Tmp = MRI.createVirtualRegister(RC);
10398   // Since FP is only updated here but NOT referenced, it's treated as GPR.
10399   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
10400   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
10401   unsigned BP =
10402       (PVT == MVT::i64)
10403           ? PPC::X30
10404           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
10405                                                               : PPC::R30);
10406 
10407   MachineInstrBuilder MIB;
10408 
10409   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10410   const int64_t SPOffset    = 2 * PVT.getStoreSize();
10411   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10412   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10413 
10414   unsigned BufReg = MI.getOperand(0).getReg();
10415 
10416   // Reload FP (the jumped-to function may not have had a
10417   // frame pointer, and if so, then its r31 will be restored
10418   // as necessary).
10419   if (PVT == MVT::i64) {
10420     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
10421             .addImm(0)
10422             .addReg(BufReg);
10423   } else {
10424     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
10425             .addImm(0)
10426             .addReg(BufReg);
10427   }
10428   MIB.cloneMemRefs(MI);
10429 
10430   // Reload IP
10431   if (PVT == MVT::i64) {
10432     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
10433             .addImm(LabelOffset)
10434             .addReg(BufReg);
10435   } else {
10436     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
10437             .addImm(LabelOffset)
10438             .addReg(BufReg);
10439   }
10440   MIB.cloneMemRefs(MI);
10441 
10442   // Reload SP
10443   if (PVT == MVT::i64) {
10444     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
10445             .addImm(SPOffset)
10446             .addReg(BufReg);
10447   } else {
10448     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
10449             .addImm(SPOffset)
10450             .addReg(BufReg);
10451   }
10452   MIB.cloneMemRefs(MI);
10453 
10454   // Reload BP
10455   if (PVT == MVT::i64) {
10456     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
10457             .addImm(BPOffset)
10458             .addReg(BufReg);
10459   } else {
10460     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
10461             .addImm(BPOffset)
10462             .addReg(BufReg);
10463   }
10464   MIB.cloneMemRefs(MI);
10465 
10466   // Reload TOC
10467   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
10468     setUsesTOCBasePtr(*MBB->getParent());
10469     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
10470               .addImm(TOCOffset)
10471               .addReg(BufReg)
10472               .cloneMemRefs(MI);
10473   }
10474 
10475   // Jump
10476   BuildMI(*MBB, MI, DL,
10477           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
10478   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
10479 
10480   MI.eraseFromParent();
10481   return MBB;
10482 }
10483 
10484 MachineBasicBlock *
10485 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10486                                                MachineBasicBlock *BB) const {
10487   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
10488       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10489     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
10490         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10491       // Call lowering should have added an r2 operand to indicate a dependence
10492       // on the TOC base pointer value. It can't however, because there is no
10493       // way to mark the dependence as implicit there, and so the stackmap code
10494       // will confuse it with a regular operand. Instead, add the dependence
10495       // here.
10496       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
10497     }
10498 
10499     return emitPatchPoint(MI, BB);
10500   }
10501 
10502   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
10503       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
10504     return emitEHSjLjSetJmp(MI, BB);
10505   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
10506              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
10507     return emitEHSjLjLongJmp(MI, BB);
10508   }
10509 
10510   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10511 
10512   // To "insert" these instructions we actually have to insert their
10513   // control-flow patterns.
10514   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10515   MachineFunction::iterator It = ++BB->getIterator();
10516 
10517   MachineFunction *F = BB->getParent();
10518 
10519   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10520       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
10521       MI.getOpcode() == PPC::SELECT_I8) {
10522     SmallVector<MachineOperand, 2> Cond;
10523     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10524         MI.getOpcode() == PPC::SELECT_CC_I8)
10525       Cond.push_back(MI.getOperand(4));
10526     else
10527       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
10528     Cond.push_back(MI.getOperand(1));
10529 
10530     DebugLoc dl = MI.getDebugLoc();
10531     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
10532                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
10533   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10534              MI.getOpcode() == PPC::SELECT_CC_I8 ||
10535              MI.getOpcode() == PPC::SELECT_CC_F4 ||
10536              MI.getOpcode() == PPC::SELECT_CC_F8 ||
10537              MI.getOpcode() == PPC::SELECT_CC_F16 ||
10538              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
10539              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
10540              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
10541              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
10542              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
10543              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
10544              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
10545              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
10546              MI.getOpcode() == PPC::SELECT_CC_SPE ||
10547              MI.getOpcode() == PPC::SELECT_I4 ||
10548              MI.getOpcode() == PPC::SELECT_I8 ||
10549              MI.getOpcode() == PPC::SELECT_F4 ||
10550              MI.getOpcode() == PPC::SELECT_F8 ||
10551              MI.getOpcode() == PPC::SELECT_F16 ||
10552              MI.getOpcode() == PPC::SELECT_QFRC ||
10553              MI.getOpcode() == PPC::SELECT_QSRC ||
10554              MI.getOpcode() == PPC::SELECT_QBRC ||
10555              MI.getOpcode() == PPC::SELECT_SPE ||
10556              MI.getOpcode() == PPC::SELECT_SPE4 ||
10557              MI.getOpcode() == PPC::SELECT_VRRC ||
10558              MI.getOpcode() == PPC::SELECT_VSFRC ||
10559              MI.getOpcode() == PPC::SELECT_VSSRC ||
10560              MI.getOpcode() == PPC::SELECT_VSRC) {
10561     // The incoming instruction knows the destination vreg to set, the
10562     // condition code register to branch on, the true/false values to
10563     // select between, and a branch opcode to use.
10564 
10565     //  thisMBB:
10566     //  ...
10567     //   TrueVal = ...
10568     //   cmpTY ccX, r1, r2
10569     //   bCC copy1MBB
10570     //   fallthrough --> copy0MBB
10571     MachineBasicBlock *thisMBB = BB;
10572     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10573     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10574     DebugLoc dl = MI.getDebugLoc();
10575     F->insert(It, copy0MBB);
10576     F->insert(It, sinkMBB);
10577 
10578     // Transfer the remainder of BB and its successor edges to sinkMBB.
10579     sinkMBB->splice(sinkMBB->begin(), BB,
10580                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10581     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10582 
10583     // Next, add the true and fallthrough blocks as its successors.
10584     BB->addSuccessor(copy0MBB);
10585     BB->addSuccessor(sinkMBB);
10586 
10587     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
10588         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
10589         MI.getOpcode() == PPC::SELECT_F16 ||
10590         MI.getOpcode() == PPC::SELECT_SPE4 ||
10591         MI.getOpcode() == PPC::SELECT_SPE ||
10592         MI.getOpcode() == PPC::SELECT_QFRC ||
10593         MI.getOpcode() == PPC::SELECT_QSRC ||
10594         MI.getOpcode() == PPC::SELECT_QBRC ||
10595         MI.getOpcode() == PPC::SELECT_VRRC ||
10596         MI.getOpcode() == PPC::SELECT_VSFRC ||
10597         MI.getOpcode() == PPC::SELECT_VSSRC ||
10598         MI.getOpcode() == PPC::SELECT_VSRC) {
10599       BuildMI(BB, dl, TII->get(PPC::BC))
10600           .addReg(MI.getOperand(1).getReg())
10601           .addMBB(sinkMBB);
10602     } else {
10603       unsigned SelectPred = MI.getOperand(4).getImm();
10604       BuildMI(BB, dl, TII->get(PPC::BCC))
10605           .addImm(SelectPred)
10606           .addReg(MI.getOperand(1).getReg())
10607           .addMBB(sinkMBB);
10608     }
10609 
10610     //  copy0MBB:
10611     //   %FalseValue = ...
10612     //   # fallthrough to sinkMBB
10613     BB = copy0MBB;
10614 
10615     // Update machine-CFG edges
10616     BB->addSuccessor(sinkMBB);
10617 
10618     //  sinkMBB:
10619     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10620     //  ...
10621     BB = sinkMBB;
10622     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
10623         .addReg(MI.getOperand(3).getReg())
10624         .addMBB(copy0MBB)
10625         .addReg(MI.getOperand(2).getReg())
10626         .addMBB(thisMBB);
10627   } else if (MI.getOpcode() == PPC::ReadTB) {
10628     // To read the 64-bit time-base register on a 32-bit target, we read the
10629     // two halves. Should the counter have wrapped while it was being read, we
10630     // need to try again.
10631     // ...
10632     // readLoop:
10633     // mfspr Rx,TBU # load from TBU
10634     // mfspr Ry,TB  # load from TB
10635     // mfspr Rz,TBU # load from TBU
10636     // cmpw crX,Rx,Rz # check if 'old'='new'
10637     // bne readLoop   # branch if they're not equal
10638     // ...
10639 
10640     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
10641     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10642     DebugLoc dl = MI.getDebugLoc();
10643     F->insert(It, readMBB);
10644     F->insert(It, sinkMBB);
10645 
10646     // Transfer the remainder of BB and its successor edges to sinkMBB.
10647     sinkMBB->splice(sinkMBB->begin(), BB,
10648                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10649     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10650 
10651     BB->addSuccessor(readMBB);
10652     BB = readMBB;
10653 
10654     MachineRegisterInfo &RegInfo = F->getRegInfo();
10655     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10656     unsigned LoReg = MI.getOperand(0).getReg();
10657     unsigned HiReg = MI.getOperand(1).getReg();
10658 
10659     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
10660     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
10661     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
10662 
10663     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10664 
10665     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
10666         .addReg(HiReg)
10667         .addReg(ReadAgainReg);
10668     BuildMI(BB, dl, TII->get(PPC::BCC))
10669         .addImm(PPC::PRED_NE)
10670         .addReg(CmpReg)
10671         .addMBB(readMBB);
10672 
10673     BB->addSuccessor(readMBB);
10674     BB->addSuccessor(sinkMBB);
10675   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
10676     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
10677   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
10678     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
10679   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
10680     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
10681   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
10682     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
10683 
10684   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
10685     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
10686   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
10687     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
10688   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
10689     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
10690   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
10691     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
10692 
10693   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
10694     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
10695   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
10696     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
10697   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
10698     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
10699   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
10700     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
10701 
10702   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
10703     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
10704   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
10705     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
10706   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
10707     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
10708   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
10709     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
10710 
10711   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
10712     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
10713   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
10714     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
10715   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
10716     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
10717   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
10718     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
10719 
10720   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
10721     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
10722   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
10723     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
10724   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
10725     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
10726   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
10727     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
10728 
10729   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
10730     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
10731   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
10732     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
10733   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
10734     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
10735   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
10736     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
10737 
10738   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
10739     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
10740   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
10741     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
10742   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
10743     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
10744   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
10745     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
10746 
10747   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
10748     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
10749   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
10750     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
10751   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
10752     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
10753   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
10754     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
10755 
10756   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
10757     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
10758   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
10759     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
10760   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
10761     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
10762   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
10763     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
10764 
10765   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
10766     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
10767   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
10768     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
10769   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
10770     BB = EmitAtomicBinary(MI, BB, 4, 0);
10771   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
10772     BB = EmitAtomicBinary(MI, BB, 8, 0);
10773   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
10774            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
10775            (Subtarget.hasPartwordAtomics() &&
10776             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
10777            (Subtarget.hasPartwordAtomics() &&
10778             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
10779     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
10780 
10781     auto LoadMnemonic = PPC::LDARX;
10782     auto StoreMnemonic = PPC::STDCX;
10783     switch (MI.getOpcode()) {
10784     default:
10785       llvm_unreachable("Compare and swap of unknown size");
10786     case PPC::ATOMIC_CMP_SWAP_I8:
10787       LoadMnemonic = PPC::LBARX;
10788       StoreMnemonic = PPC::STBCX;
10789       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10790       break;
10791     case PPC::ATOMIC_CMP_SWAP_I16:
10792       LoadMnemonic = PPC::LHARX;
10793       StoreMnemonic = PPC::STHCX;
10794       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10795       break;
10796     case PPC::ATOMIC_CMP_SWAP_I32:
10797       LoadMnemonic = PPC::LWARX;
10798       StoreMnemonic = PPC::STWCX;
10799       break;
10800     case PPC::ATOMIC_CMP_SWAP_I64:
10801       LoadMnemonic = PPC::LDARX;
10802       StoreMnemonic = PPC::STDCX;
10803       break;
10804     }
10805     unsigned dest = MI.getOperand(0).getReg();
10806     unsigned ptrA = MI.getOperand(1).getReg();
10807     unsigned ptrB = MI.getOperand(2).getReg();
10808     unsigned oldval = MI.getOperand(3).getReg();
10809     unsigned newval = MI.getOperand(4).getReg();
10810     DebugLoc dl = MI.getDebugLoc();
10811 
10812     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10813     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10814     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10815     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10816     F->insert(It, loop1MBB);
10817     F->insert(It, loop2MBB);
10818     F->insert(It, midMBB);
10819     F->insert(It, exitMBB);
10820     exitMBB->splice(exitMBB->begin(), BB,
10821                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10822     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10823 
10824     //  thisMBB:
10825     //   ...
10826     //   fallthrough --> loopMBB
10827     BB->addSuccessor(loop1MBB);
10828 
10829     // loop1MBB:
10830     //   l[bhwd]arx dest, ptr
10831     //   cmp[wd] dest, oldval
10832     //   bne- midMBB
10833     // loop2MBB:
10834     //   st[bhwd]cx. newval, ptr
10835     //   bne- loopMBB
10836     //   b exitBB
10837     // midMBB:
10838     //   st[bhwd]cx. dest, ptr
10839     // exitBB:
10840     BB = loop1MBB;
10841     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
10842     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
10843         .addReg(oldval)
10844         .addReg(dest);
10845     BuildMI(BB, dl, TII->get(PPC::BCC))
10846         .addImm(PPC::PRED_NE)
10847         .addReg(PPC::CR0)
10848         .addMBB(midMBB);
10849     BB->addSuccessor(loop2MBB);
10850     BB->addSuccessor(midMBB);
10851 
10852     BB = loop2MBB;
10853     BuildMI(BB, dl, TII->get(StoreMnemonic))
10854         .addReg(newval)
10855         .addReg(ptrA)
10856         .addReg(ptrB);
10857     BuildMI(BB, dl, TII->get(PPC::BCC))
10858         .addImm(PPC::PRED_NE)
10859         .addReg(PPC::CR0)
10860         .addMBB(loop1MBB);
10861     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
10862     BB->addSuccessor(loop1MBB);
10863     BB->addSuccessor(exitMBB);
10864 
10865     BB = midMBB;
10866     BuildMI(BB, dl, TII->get(StoreMnemonic))
10867         .addReg(dest)
10868         .addReg(ptrA)
10869         .addReg(ptrB);
10870     BB->addSuccessor(exitMBB);
10871 
10872     //  exitMBB:
10873     //   ...
10874     BB = exitMBB;
10875   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
10876              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
10877     // We must use 64-bit registers for addresses when targeting 64-bit,
10878     // since we're actually doing arithmetic on them.  Other registers
10879     // can be 32-bit.
10880     bool is64bit = Subtarget.isPPC64();
10881     bool isLittleEndian = Subtarget.isLittleEndian();
10882     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
10883 
10884     unsigned dest = MI.getOperand(0).getReg();
10885     unsigned ptrA = MI.getOperand(1).getReg();
10886     unsigned ptrB = MI.getOperand(2).getReg();
10887     unsigned oldval = MI.getOperand(3).getReg();
10888     unsigned newval = MI.getOperand(4).getReg();
10889     DebugLoc dl = MI.getDebugLoc();
10890 
10891     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10892     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10893     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10894     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10895     F->insert(It, loop1MBB);
10896     F->insert(It, loop2MBB);
10897     F->insert(It, midMBB);
10898     F->insert(It, exitMBB);
10899     exitMBB->splice(exitMBB->begin(), BB,
10900                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10901     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10902 
10903     MachineRegisterInfo &RegInfo = F->getRegInfo();
10904     const TargetRegisterClass *RC =
10905         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10906     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10907 
10908     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
10909     unsigned Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10910     unsigned ShiftReg =
10911         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10912     unsigned NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
10913     unsigned NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
10914     unsigned OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
10915     unsigned OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
10916     unsigned MaskReg = RegInfo.createVirtualRegister(GPRC);
10917     unsigned Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10918     unsigned Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10919     unsigned Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10920     unsigned Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10921     unsigned TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10922     unsigned Ptr1Reg;
10923     unsigned TmpReg = RegInfo.createVirtualRegister(GPRC);
10924     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10925     //  thisMBB:
10926     //   ...
10927     //   fallthrough --> loopMBB
10928     BB->addSuccessor(loop1MBB);
10929 
10930     // The 4-byte load must be aligned, while a char or short may be
10931     // anywhere in the word.  Hence all this nasty bookkeeping code.
10932     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10933     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10934     //   xori shift, shift1, 24 [16]
10935     //   rlwinm ptr, ptr1, 0, 0, 29
10936     //   slw newval2, newval, shift
10937     //   slw oldval2, oldval,shift
10938     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10939     //   slw mask, mask2, shift
10940     //   and newval3, newval2, mask
10941     //   and oldval3, oldval2, mask
10942     // loop1MBB:
10943     //   lwarx tmpDest, ptr
10944     //   and tmp, tmpDest, mask
10945     //   cmpw tmp, oldval3
10946     //   bne- midMBB
10947     // loop2MBB:
10948     //   andc tmp2, tmpDest, mask
10949     //   or tmp4, tmp2, newval3
10950     //   stwcx. tmp4, ptr
10951     //   bne- loop1MBB
10952     //   b exitBB
10953     // midMBB:
10954     //   stwcx. tmpDest, ptr
10955     // exitBB:
10956     //   srw dest, tmpDest, shift
10957     if (ptrA != ZeroReg) {
10958       Ptr1Reg = RegInfo.createVirtualRegister(RC);
10959       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10960           .addReg(ptrA)
10961           .addReg(ptrB);
10962     } else {
10963       Ptr1Reg = ptrB;
10964     }
10965 
10966     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10967     // mode.
10968     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10969         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10970         .addImm(3)
10971         .addImm(27)
10972         .addImm(is8bit ? 28 : 27);
10973     if (!isLittleEndian)
10974       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10975           .addReg(Shift1Reg)
10976           .addImm(is8bit ? 24 : 16);
10977     if (is64bit)
10978       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10979           .addReg(Ptr1Reg)
10980           .addImm(0)
10981           .addImm(61);
10982     else
10983       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10984           .addReg(Ptr1Reg)
10985           .addImm(0)
10986           .addImm(0)
10987           .addImm(29);
10988     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
10989         .addReg(newval)
10990         .addReg(ShiftReg);
10991     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
10992         .addReg(oldval)
10993         .addReg(ShiftReg);
10994     if (is8bit)
10995       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10996     else {
10997       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10998       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10999           .addReg(Mask3Reg)
11000           .addImm(65535);
11001     }
11002     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11003         .addReg(Mask2Reg)
11004         .addReg(ShiftReg);
11005     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
11006         .addReg(NewVal2Reg)
11007         .addReg(MaskReg);
11008     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
11009         .addReg(OldVal2Reg)
11010         .addReg(MaskReg);
11011 
11012     BB = loop1MBB;
11013     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11014         .addReg(ZeroReg)
11015         .addReg(PtrReg);
11016     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
11017         .addReg(TmpDestReg)
11018         .addReg(MaskReg);
11019     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
11020         .addReg(TmpReg)
11021         .addReg(OldVal3Reg);
11022     BuildMI(BB, dl, TII->get(PPC::BCC))
11023         .addImm(PPC::PRED_NE)
11024         .addReg(PPC::CR0)
11025         .addMBB(midMBB);
11026     BB->addSuccessor(loop2MBB);
11027     BB->addSuccessor(midMBB);
11028 
11029     BB = loop2MBB;
11030     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11031         .addReg(TmpDestReg)
11032         .addReg(MaskReg);
11033     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
11034         .addReg(Tmp2Reg)
11035         .addReg(NewVal3Reg);
11036     BuildMI(BB, dl, TII->get(PPC::STWCX))
11037         .addReg(Tmp4Reg)
11038         .addReg(ZeroReg)
11039         .addReg(PtrReg);
11040     BuildMI(BB, dl, TII->get(PPC::BCC))
11041         .addImm(PPC::PRED_NE)
11042         .addReg(PPC::CR0)
11043         .addMBB(loop1MBB);
11044     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11045     BB->addSuccessor(loop1MBB);
11046     BB->addSuccessor(exitMBB);
11047 
11048     BB = midMBB;
11049     BuildMI(BB, dl, TII->get(PPC::STWCX))
11050         .addReg(TmpDestReg)
11051         .addReg(ZeroReg)
11052         .addReg(PtrReg);
11053     BB->addSuccessor(exitMBB);
11054 
11055     //  exitMBB:
11056     //   ...
11057     BB = exitMBB;
11058     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11059         .addReg(TmpReg)
11060         .addReg(ShiftReg);
11061   } else if (MI.getOpcode() == PPC::FADDrtz) {
11062     // This pseudo performs an FADD with rounding mode temporarily forced
11063     // to round-to-zero.  We emit this via custom inserter since the FPSCR
11064     // is not modeled at the SelectionDAG level.
11065     unsigned Dest = MI.getOperand(0).getReg();
11066     unsigned Src1 = MI.getOperand(1).getReg();
11067     unsigned Src2 = MI.getOperand(2).getReg();
11068     DebugLoc dl = MI.getDebugLoc();
11069 
11070     MachineRegisterInfo &RegInfo = F->getRegInfo();
11071     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11072 
11073     // Save FPSCR value.
11074     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
11075 
11076     // Set rounding mode to round-to-zero.
11077     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
11078     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
11079 
11080     // Perform addition.
11081     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
11082 
11083     // Restore FPSCR value.
11084     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
11085   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11086              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
11087              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11088              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
11089     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11090                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
11091                           ? PPC::ANDIo8
11092                           : PPC::ANDIo;
11093     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11094                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
11095 
11096     MachineRegisterInfo &RegInfo = F->getRegInfo();
11097     unsigned Dest = RegInfo.createVirtualRegister(
11098         Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
11099 
11100     DebugLoc dl = MI.getDebugLoc();
11101     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
11102         .addReg(MI.getOperand(1).getReg())
11103         .addImm(1);
11104     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
11105             MI.getOperand(0).getReg())
11106         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
11107   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
11108     DebugLoc Dl = MI.getDebugLoc();
11109     MachineRegisterInfo &RegInfo = F->getRegInfo();
11110     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11111     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
11112     return BB;
11113   } else if (MI.getOpcode() == PPC::SETRNDi) {
11114     DebugLoc dl = MI.getDebugLoc();
11115     unsigned OldFPSCRReg = MI.getOperand(0).getReg();
11116 
11117     // Save FPSCR value.
11118     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11119 
11120     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
11121     // the following settings:
11122     //   00 Round to nearest
11123     //   01 Round to 0
11124     //   10 Round to +inf
11125     //   11 Round to -inf
11126 
11127     // When the operand is immediate, using the two least significant bits of
11128     // the immediate to set the bits 62:63 of FPSCR.
11129     unsigned Mode = MI.getOperand(1).getImm();
11130     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
11131       .addImm(31);
11132 
11133     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
11134       .addImm(30);
11135   } else if (MI.getOpcode() == PPC::SETRND) {
11136     DebugLoc dl = MI.getDebugLoc();
11137 
11138     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
11139     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
11140     // If the target doesn't have DirectMove, we should use stack to do the
11141     // conversion, because the target doesn't have the instructions like mtvsrd
11142     // or mfvsrd to do this conversion directly.
11143     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
11144       if (Subtarget.hasDirectMove()) {
11145         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
11146           .addReg(SrcReg);
11147       } else {
11148         // Use stack to do the register copy.
11149         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
11150         MachineRegisterInfo &RegInfo = F->getRegInfo();
11151         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
11152         if (RC == &PPC::F8RCRegClass) {
11153           // Copy register from F8RCRegClass to G8RCRegclass.
11154           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
11155                  "Unsupported RegClass.");
11156 
11157           StoreOp = PPC::STFD;
11158           LoadOp = PPC::LD;
11159         } else {
11160           // Copy register from G8RCRegClass to F8RCRegclass.
11161           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
11162                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
11163                  "Unsupported RegClass.");
11164         }
11165 
11166         MachineFrameInfo &MFI = F->getFrameInfo();
11167         int FrameIdx = MFI.CreateStackObject(8, 8, false);
11168 
11169         MachineMemOperand *MMOStore = F->getMachineMemOperand(
11170           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11171           MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
11172           MFI.getObjectAlignment(FrameIdx));
11173 
11174         // Store the SrcReg into the stack.
11175         BuildMI(*BB, MI, dl, TII->get(StoreOp))
11176           .addReg(SrcReg)
11177           .addImm(0)
11178           .addFrameIndex(FrameIdx)
11179           .addMemOperand(MMOStore);
11180 
11181         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
11182           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11183           MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
11184           MFI.getObjectAlignment(FrameIdx));
11185 
11186         // Load from the stack where SrcReg is stored, and save to DestReg,
11187         // so we have done the RegClass conversion from RegClass::SrcReg to
11188         // RegClass::DestReg.
11189         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
11190           .addImm(0)
11191           .addFrameIndex(FrameIdx)
11192           .addMemOperand(MMOLoad);
11193       }
11194     };
11195 
11196     unsigned OldFPSCRReg = MI.getOperand(0).getReg();
11197 
11198     // Save FPSCR value.
11199     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11200 
11201     // When the operand is gprc register, use two least significant bits of the
11202     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
11203     //
11204     // copy OldFPSCRTmpReg, OldFPSCRReg
11205     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
11206     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
11207     // copy NewFPSCRReg, NewFPSCRTmpReg
11208     // mtfsf 255, NewFPSCRReg
11209     MachineOperand SrcOp = MI.getOperand(1);
11210     MachineRegisterInfo &RegInfo = F->getRegInfo();
11211     unsigned OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11212 
11213     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
11214 
11215     unsigned ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11216     unsigned ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11217 
11218     // The first operand of INSERT_SUBREG should be a register which has
11219     // subregisters, we only care about its RegClass, so we should use an
11220     // IMPLICIT_DEF register.
11221     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
11222     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
11223       .addReg(ImDefReg)
11224       .add(SrcOp)
11225       .addImm(1);
11226 
11227     unsigned NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11228     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
11229       .addReg(OldFPSCRTmpReg)
11230       .addReg(ExtSrcReg)
11231       .addImm(0)
11232       .addImm(62);
11233 
11234     unsigned NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11235     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
11236 
11237     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
11238     // bits of FPSCR.
11239     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
11240       .addImm(255)
11241       .addReg(NewFPSCRReg)
11242       .addImm(0)
11243       .addImm(0);
11244   } else {
11245     llvm_unreachable("Unexpected instr type to insert");
11246   }
11247 
11248   MI.eraseFromParent(); // The pseudo instruction is gone now.
11249   return BB;
11250 }
11251 
11252 //===----------------------------------------------------------------------===//
11253 // Target Optimization Hooks
11254 //===----------------------------------------------------------------------===//
11255 
11256 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
11257   // For the estimates, convergence is quadratic, so we essentially double the
11258   // number of digits correct after every iteration. For both FRE and FRSQRTE,
11259   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
11260   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
11261   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
11262   if (VT.getScalarType() == MVT::f64)
11263     RefinementSteps++;
11264   return RefinementSteps;
11265 }
11266 
11267 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
11268                                            int Enabled, int &RefinementSteps,
11269                                            bool &UseOneConstNR,
11270                                            bool Reciprocal) const {
11271   EVT VT = Operand.getValueType();
11272   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
11273       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
11274       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11275       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11276       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11277       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11278     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11279       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11280 
11281     // The Newton-Raphson computation with a single constant does not provide
11282     // enough accuracy on some CPUs.
11283     UseOneConstNR = !Subtarget.needsTwoConstNR();
11284     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
11285   }
11286   return SDValue();
11287 }
11288 
11289 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
11290                                             int Enabled,
11291                                             int &RefinementSteps) const {
11292   EVT VT = Operand.getValueType();
11293   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
11294       (VT == MVT::f64 && Subtarget.hasFRE()) ||
11295       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11296       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11297       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11298       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11299     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11300       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11301     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
11302   }
11303   return SDValue();
11304 }
11305 
11306 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
11307   // Note: This functionality is used only when unsafe-fp-math is enabled, and
11308   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
11309   // enabled for division), this functionality is redundant with the default
11310   // combiner logic (once the division -> reciprocal/multiply transformation
11311   // has taken place). As a result, this matters more for older cores than for
11312   // newer ones.
11313 
11314   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11315   // reciprocal if there are two or more FDIVs (for embedded cores with only
11316   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
11317   switch (Subtarget.getDarwinDirective()) {
11318   default:
11319     return 3;
11320   case PPC::DIR_440:
11321   case PPC::DIR_A2:
11322   case PPC::DIR_E500:
11323   case PPC::DIR_E500mc:
11324   case PPC::DIR_E5500:
11325     return 2;
11326   }
11327 }
11328 
11329 // isConsecutiveLSLoc needs to work even if all adds have not yet been
11330 // collapsed, and so we need to look through chains of them.
11331 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
11332                                      int64_t& Offset, SelectionDAG &DAG) {
11333   if (DAG.isBaseWithConstantOffset(Loc)) {
11334     Base = Loc.getOperand(0);
11335     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
11336 
11337     // The base might itself be a base plus an offset, and if so, accumulate
11338     // that as well.
11339     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
11340   }
11341 }
11342 
11343 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
11344                             unsigned Bytes, int Dist,
11345                             SelectionDAG &DAG) {
11346   if (VT.getSizeInBits() / 8 != Bytes)
11347     return false;
11348 
11349   SDValue BaseLoc = Base->getBasePtr();
11350   if (Loc.getOpcode() == ISD::FrameIndex) {
11351     if (BaseLoc.getOpcode() != ISD::FrameIndex)
11352       return false;
11353     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
11354     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
11355     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
11356     int FS  = MFI.getObjectSize(FI);
11357     int BFS = MFI.getObjectSize(BFI);
11358     if (FS != BFS || FS != (int)Bytes) return false;
11359     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
11360   }
11361 
11362   SDValue Base1 = Loc, Base2 = BaseLoc;
11363   int64_t Offset1 = 0, Offset2 = 0;
11364   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
11365   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
11366   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
11367     return true;
11368 
11369   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11370   const GlobalValue *GV1 = nullptr;
11371   const GlobalValue *GV2 = nullptr;
11372   Offset1 = 0;
11373   Offset2 = 0;
11374   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
11375   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
11376   if (isGA1 && isGA2 && GV1 == GV2)
11377     return Offset1 == (Offset2 + Dist*Bytes);
11378   return false;
11379 }
11380 
11381 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
11382 // not enforce equality of the chain operands.
11383 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
11384                             unsigned Bytes, int Dist,
11385                             SelectionDAG &DAG) {
11386   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
11387     EVT VT = LS->getMemoryVT();
11388     SDValue Loc = LS->getBasePtr();
11389     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
11390   }
11391 
11392   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
11393     EVT VT;
11394     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11395     default: return false;
11396     case Intrinsic::ppc_qpx_qvlfd:
11397     case Intrinsic::ppc_qpx_qvlfda:
11398       VT = MVT::v4f64;
11399       break;
11400     case Intrinsic::ppc_qpx_qvlfs:
11401     case Intrinsic::ppc_qpx_qvlfsa:
11402       VT = MVT::v4f32;
11403       break;
11404     case Intrinsic::ppc_qpx_qvlfcd:
11405     case Intrinsic::ppc_qpx_qvlfcda:
11406       VT = MVT::v2f64;
11407       break;
11408     case Intrinsic::ppc_qpx_qvlfcs:
11409     case Intrinsic::ppc_qpx_qvlfcsa:
11410       VT = MVT::v2f32;
11411       break;
11412     case Intrinsic::ppc_qpx_qvlfiwa:
11413     case Intrinsic::ppc_qpx_qvlfiwz:
11414     case Intrinsic::ppc_altivec_lvx:
11415     case Intrinsic::ppc_altivec_lvxl:
11416     case Intrinsic::ppc_vsx_lxvw4x:
11417     case Intrinsic::ppc_vsx_lxvw4x_be:
11418       VT = MVT::v4i32;
11419       break;
11420     case Intrinsic::ppc_vsx_lxvd2x:
11421     case Intrinsic::ppc_vsx_lxvd2x_be:
11422       VT = MVT::v2f64;
11423       break;
11424     case Intrinsic::ppc_altivec_lvebx:
11425       VT = MVT::i8;
11426       break;
11427     case Intrinsic::ppc_altivec_lvehx:
11428       VT = MVT::i16;
11429       break;
11430     case Intrinsic::ppc_altivec_lvewx:
11431       VT = MVT::i32;
11432       break;
11433     }
11434 
11435     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
11436   }
11437 
11438   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
11439     EVT VT;
11440     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11441     default: return false;
11442     case Intrinsic::ppc_qpx_qvstfd:
11443     case Intrinsic::ppc_qpx_qvstfda:
11444       VT = MVT::v4f64;
11445       break;
11446     case Intrinsic::ppc_qpx_qvstfs:
11447     case Intrinsic::ppc_qpx_qvstfsa:
11448       VT = MVT::v4f32;
11449       break;
11450     case Intrinsic::ppc_qpx_qvstfcd:
11451     case Intrinsic::ppc_qpx_qvstfcda:
11452       VT = MVT::v2f64;
11453       break;
11454     case Intrinsic::ppc_qpx_qvstfcs:
11455     case Intrinsic::ppc_qpx_qvstfcsa:
11456       VT = MVT::v2f32;
11457       break;
11458     case Intrinsic::ppc_qpx_qvstfiw:
11459     case Intrinsic::ppc_qpx_qvstfiwa:
11460     case Intrinsic::ppc_altivec_stvx:
11461     case Intrinsic::ppc_altivec_stvxl:
11462     case Intrinsic::ppc_vsx_stxvw4x:
11463       VT = MVT::v4i32;
11464       break;
11465     case Intrinsic::ppc_vsx_stxvd2x:
11466       VT = MVT::v2f64;
11467       break;
11468     case Intrinsic::ppc_vsx_stxvw4x_be:
11469       VT = MVT::v4i32;
11470       break;
11471     case Intrinsic::ppc_vsx_stxvd2x_be:
11472       VT = MVT::v2f64;
11473       break;
11474     case Intrinsic::ppc_altivec_stvebx:
11475       VT = MVT::i8;
11476       break;
11477     case Intrinsic::ppc_altivec_stvehx:
11478       VT = MVT::i16;
11479       break;
11480     case Intrinsic::ppc_altivec_stvewx:
11481       VT = MVT::i32;
11482       break;
11483     }
11484 
11485     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
11486   }
11487 
11488   return false;
11489 }
11490 
11491 // Return true is there is a nearyby consecutive load to the one provided
11492 // (regardless of alignment). We search up and down the chain, looking though
11493 // token factors and other loads (but nothing else). As a result, a true result
11494 // indicates that it is safe to create a new consecutive load adjacent to the
11495 // load provided.
11496 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
11497   SDValue Chain = LD->getChain();
11498   EVT VT = LD->getMemoryVT();
11499 
11500   SmallSet<SDNode *, 16> LoadRoots;
11501   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
11502   SmallSet<SDNode *, 16> Visited;
11503 
11504   // First, search up the chain, branching to follow all token-factor operands.
11505   // If we find a consecutive load, then we're done, otherwise, record all
11506   // nodes just above the top-level loads and token factors.
11507   while (!Queue.empty()) {
11508     SDNode *ChainNext = Queue.pop_back_val();
11509     if (!Visited.insert(ChainNext).second)
11510       continue;
11511 
11512     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
11513       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
11514         return true;
11515 
11516       if (!Visited.count(ChainLD->getChain().getNode()))
11517         Queue.push_back(ChainLD->getChain().getNode());
11518     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
11519       for (const SDUse &O : ChainNext->ops())
11520         if (!Visited.count(O.getNode()))
11521           Queue.push_back(O.getNode());
11522     } else
11523       LoadRoots.insert(ChainNext);
11524   }
11525 
11526   // Second, search down the chain, starting from the top-level nodes recorded
11527   // in the first phase. These top-level nodes are the nodes just above all
11528   // loads and token factors. Starting with their uses, recursively look though
11529   // all loads (just the chain uses) and token factors to find a consecutive
11530   // load.
11531   Visited.clear();
11532   Queue.clear();
11533 
11534   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
11535        IE = LoadRoots.end(); I != IE; ++I) {
11536     Queue.push_back(*I);
11537 
11538     while (!Queue.empty()) {
11539       SDNode *LoadRoot = Queue.pop_back_val();
11540       if (!Visited.insert(LoadRoot).second)
11541         continue;
11542 
11543       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
11544         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
11545           return true;
11546 
11547       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
11548            UE = LoadRoot->use_end(); UI != UE; ++UI)
11549         if (((isa<MemSDNode>(*UI) &&
11550             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
11551             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
11552           Queue.push_back(*UI);
11553     }
11554   }
11555 
11556   return false;
11557 }
11558 
11559 /// This function is called when we have proved that a SETCC node can be replaced
11560 /// by subtraction (and other supporting instructions) so that the result of
11561 /// comparison is kept in a GPR instead of CR. This function is purely for
11562 /// codegen purposes and has some flags to guide the codegen process.
11563 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
11564                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
11565   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
11566 
11567   // Zero extend the operands to the largest legal integer. Originally, they
11568   // must be of a strictly smaller size.
11569   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
11570                          DAG.getConstant(Size, DL, MVT::i32));
11571   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
11572                          DAG.getConstant(Size, DL, MVT::i32));
11573 
11574   // Swap if needed. Depends on the condition code.
11575   if (Swap)
11576     std::swap(Op0, Op1);
11577 
11578   // Subtract extended integers.
11579   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
11580 
11581   // Move the sign bit to the least significant position and zero out the rest.
11582   // Now the least significant bit carries the result of original comparison.
11583   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
11584                              DAG.getConstant(Size - 1, DL, MVT::i32));
11585   auto Final = Shifted;
11586 
11587   // Complement the result if needed. Based on the condition code.
11588   if (Complement)
11589     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
11590                         DAG.getConstant(1, DL, MVT::i64));
11591 
11592   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
11593 }
11594 
11595 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
11596                                                   DAGCombinerInfo &DCI) const {
11597   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
11598 
11599   SelectionDAG &DAG = DCI.DAG;
11600   SDLoc DL(N);
11601 
11602   // Size of integers being compared has a critical role in the following
11603   // analysis, so we prefer to do this when all types are legal.
11604   if (!DCI.isAfterLegalizeDAG())
11605     return SDValue();
11606 
11607   // If all users of SETCC extend its value to a legal integer type
11608   // then we replace SETCC with a subtraction
11609   for (SDNode::use_iterator UI = N->use_begin(),
11610        UE = N->use_end(); UI != UE; ++UI) {
11611     if (UI->getOpcode() != ISD::ZERO_EXTEND)
11612       return SDValue();
11613   }
11614 
11615   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
11616   auto OpSize = N->getOperand(0).getValueSizeInBits();
11617 
11618   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
11619 
11620   if (OpSize < Size) {
11621     switch (CC) {
11622     default: break;
11623     case ISD::SETULT:
11624       return generateEquivalentSub(N, Size, false, false, DL, DAG);
11625     case ISD::SETULE:
11626       return generateEquivalentSub(N, Size, true, true, DL, DAG);
11627     case ISD::SETUGT:
11628       return generateEquivalentSub(N, Size, false, true, DL, DAG);
11629     case ISD::SETUGE:
11630       return generateEquivalentSub(N, Size, true, false, DL, DAG);
11631     }
11632   }
11633 
11634   return SDValue();
11635 }
11636 
11637 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
11638                                                   DAGCombinerInfo &DCI) const {
11639   SelectionDAG &DAG = DCI.DAG;
11640   SDLoc dl(N);
11641 
11642   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
11643   // If we're tracking CR bits, we need to be careful that we don't have:
11644   //   trunc(binary-ops(zext(x), zext(y)))
11645   // or
11646   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
11647   // such that we're unnecessarily moving things into GPRs when it would be
11648   // better to keep them in CR bits.
11649 
11650   // Note that trunc here can be an actual i1 trunc, or can be the effective
11651   // truncation that comes from a setcc or select_cc.
11652   if (N->getOpcode() == ISD::TRUNCATE &&
11653       N->getValueType(0) != MVT::i1)
11654     return SDValue();
11655 
11656   if (N->getOperand(0).getValueType() != MVT::i32 &&
11657       N->getOperand(0).getValueType() != MVT::i64)
11658     return SDValue();
11659 
11660   if (N->getOpcode() == ISD::SETCC ||
11661       N->getOpcode() == ISD::SELECT_CC) {
11662     // If we're looking at a comparison, then we need to make sure that the
11663     // high bits (all except for the first) don't matter the result.
11664     ISD::CondCode CC =
11665       cast<CondCodeSDNode>(N->getOperand(
11666         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
11667     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
11668 
11669     if (ISD::isSignedIntSetCC(CC)) {
11670       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
11671           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
11672         return SDValue();
11673     } else if (ISD::isUnsignedIntSetCC(CC)) {
11674       if (!DAG.MaskedValueIsZero(N->getOperand(0),
11675                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
11676           !DAG.MaskedValueIsZero(N->getOperand(1),
11677                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
11678         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
11679                                              : SDValue());
11680     } else {
11681       // This is neither a signed nor an unsigned comparison, just make sure
11682       // that the high bits are equal.
11683       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
11684       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
11685 
11686       // We don't really care about what is known about the first bit (if
11687       // anything), so clear it in all masks prior to comparing them.
11688       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
11689       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
11690 
11691       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
11692         return SDValue();
11693     }
11694   }
11695 
11696   // We now know that the higher-order bits are irrelevant, we just need to
11697   // make sure that all of the intermediate operations are bit operations, and
11698   // all inputs are extensions.
11699   if (N->getOperand(0).getOpcode() != ISD::AND &&
11700       N->getOperand(0).getOpcode() != ISD::OR  &&
11701       N->getOperand(0).getOpcode() != ISD::XOR &&
11702       N->getOperand(0).getOpcode() != ISD::SELECT &&
11703       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
11704       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
11705       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
11706       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
11707       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
11708     return SDValue();
11709 
11710   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
11711       N->getOperand(1).getOpcode() != ISD::AND &&
11712       N->getOperand(1).getOpcode() != ISD::OR  &&
11713       N->getOperand(1).getOpcode() != ISD::XOR &&
11714       N->getOperand(1).getOpcode() != ISD::SELECT &&
11715       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
11716       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
11717       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
11718       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
11719       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
11720     return SDValue();
11721 
11722   SmallVector<SDValue, 4> Inputs;
11723   SmallVector<SDValue, 8> BinOps, PromOps;
11724   SmallPtrSet<SDNode *, 16> Visited;
11725 
11726   for (unsigned i = 0; i < 2; ++i) {
11727     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11728           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11729           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11730           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11731         isa<ConstantSDNode>(N->getOperand(i)))
11732       Inputs.push_back(N->getOperand(i));
11733     else
11734       BinOps.push_back(N->getOperand(i));
11735 
11736     if (N->getOpcode() == ISD::TRUNCATE)
11737       break;
11738   }
11739 
11740   // Visit all inputs, collect all binary operations (and, or, xor and
11741   // select) that are all fed by extensions.
11742   while (!BinOps.empty()) {
11743     SDValue BinOp = BinOps.back();
11744     BinOps.pop_back();
11745 
11746     if (!Visited.insert(BinOp.getNode()).second)
11747       continue;
11748 
11749     PromOps.push_back(BinOp);
11750 
11751     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11752       // The condition of the select is not promoted.
11753       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11754         continue;
11755       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11756         continue;
11757 
11758       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11759             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11760             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11761            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11762           isa<ConstantSDNode>(BinOp.getOperand(i))) {
11763         Inputs.push_back(BinOp.getOperand(i));
11764       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11765                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
11766                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11767                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11768                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
11769                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11770                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11771                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11772                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
11773         BinOps.push_back(BinOp.getOperand(i));
11774       } else {
11775         // We have an input that is not an extension or another binary
11776         // operation; we'll abort this transformation.
11777         return SDValue();
11778       }
11779     }
11780   }
11781 
11782   // Make sure that this is a self-contained cluster of operations (which
11783   // is not quite the same thing as saying that everything has only one
11784   // use).
11785   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11786     if (isa<ConstantSDNode>(Inputs[i]))
11787       continue;
11788 
11789     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
11790                               UE = Inputs[i].getNode()->use_end();
11791          UI != UE; ++UI) {
11792       SDNode *User = *UI;
11793       if (User != N && !Visited.count(User))
11794         return SDValue();
11795 
11796       // Make sure that we're not going to promote the non-output-value
11797       // operand(s) or SELECT or SELECT_CC.
11798       // FIXME: Although we could sometimes handle this, and it does occur in
11799       // practice that one of the condition inputs to the select is also one of
11800       // the outputs, we currently can't deal with this.
11801       if (User->getOpcode() == ISD::SELECT) {
11802         if (User->getOperand(0) == Inputs[i])
11803           return SDValue();
11804       } else if (User->getOpcode() == ISD::SELECT_CC) {
11805         if (User->getOperand(0) == Inputs[i] ||
11806             User->getOperand(1) == Inputs[i])
11807           return SDValue();
11808       }
11809     }
11810   }
11811 
11812   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
11813     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
11814                               UE = PromOps[i].getNode()->use_end();
11815          UI != UE; ++UI) {
11816       SDNode *User = *UI;
11817       if (User != N && !Visited.count(User))
11818         return SDValue();
11819 
11820       // Make sure that we're not going to promote the non-output-value
11821       // operand(s) or SELECT or SELECT_CC.
11822       // FIXME: Although we could sometimes handle this, and it does occur in
11823       // practice that one of the condition inputs to the select is also one of
11824       // the outputs, we currently can't deal with this.
11825       if (User->getOpcode() == ISD::SELECT) {
11826         if (User->getOperand(0) == PromOps[i])
11827           return SDValue();
11828       } else if (User->getOpcode() == ISD::SELECT_CC) {
11829         if (User->getOperand(0) == PromOps[i] ||
11830             User->getOperand(1) == PromOps[i])
11831           return SDValue();
11832       }
11833     }
11834   }
11835 
11836   // Replace all inputs with the extension operand.
11837   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11838     // Constants may have users outside the cluster of to-be-promoted nodes,
11839     // and so we need to replace those as we do the promotions.
11840     if (isa<ConstantSDNode>(Inputs[i]))
11841       continue;
11842     else
11843       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
11844   }
11845 
11846   std::list<HandleSDNode> PromOpHandles;
11847   for (auto &PromOp : PromOps)
11848     PromOpHandles.emplace_back(PromOp);
11849 
11850   // Replace all operations (these are all the same, but have a different
11851   // (i1) return type). DAG.getNode will validate that the types of
11852   // a binary operator match, so go through the list in reverse so that
11853   // we've likely promoted both operands first. Any intermediate truncations or
11854   // extensions disappear.
11855   while (!PromOpHandles.empty()) {
11856     SDValue PromOp = PromOpHandles.back().getValue();
11857     PromOpHandles.pop_back();
11858 
11859     if (PromOp.getOpcode() == ISD::TRUNCATE ||
11860         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
11861         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
11862         PromOp.getOpcode() == ISD::ANY_EXTEND) {
11863       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
11864           PromOp.getOperand(0).getValueType() != MVT::i1) {
11865         // The operand is not yet ready (see comment below).
11866         PromOpHandles.emplace_front(PromOp);
11867         continue;
11868       }
11869 
11870       SDValue RepValue = PromOp.getOperand(0);
11871       if (isa<ConstantSDNode>(RepValue))
11872         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
11873 
11874       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
11875       continue;
11876     }
11877 
11878     unsigned C;
11879     switch (PromOp.getOpcode()) {
11880     default:             C = 0; break;
11881     case ISD::SELECT:    C = 1; break;
11882     case ISD::SELECT_CC: C = 2; break;
11883     }
11884 
11885     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
11886          PromOp.getOperand(C).getValueType() != MVT::i1) ||
11887         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
11888          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
11889       // The to-be-promoted operands of this node have not yet been
11890       // promoted (this should be rare because we're going through the
11891       // list backward, but if one of the operands has several users in
11892       // this cluster of to-be-promoted nodes, it is possible).
11893       PromOpHandles.emplace_front(PromOp);
11894       continue;
11895     }
11896 
11897     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
11898                                 PromOp.getNode()->op_end());
11899 
11900     // If there are any constant inputs, make sure they're replaced now.
11901     for (unsigned i = 0; i < 2; ++i)
11902       if (isa<ConstantSDNode>(Ops[C+i]))
11903         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
11904 
11905     DAG.ReplaceAllUsesOfValueWith(PromOp,
11906       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
11907   }
11908 
11909   // Now we're left with the initial truncation itself.
11910   if (N->getOpcode() == ISD::TRUNCATE)
11911     return N->getOperand(0);
11912 
11913   // Otherwise, this is a comparison. The operands to be compared have just
11914   // changed type (to i1), but everything else is the same.
11915   return SDValue(N, 0);
11916 }
11917 
11918 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
11919                                                   DAGCombinerInfo &DCI) const {
11920   SelectionDAG &DAG = DCI.DAG;
11921   SDLoc dl(N);
11922 
11923   // If we're tracking CR bits, we need to be careful that we don't have:
11924   //   zext(binary-ops(trunc(x), trunc(y)))
11925   // or
11926   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
11927   // such that we're unnecessarily moving things into CR bits that can more
11928   // efficiently stay in GPRs. Note that if we're not certain that the high
11929   // bits are set as required by the final extension, we still may need to do
11930   // some masking to get the proper behavior.
11931 
11932   // This same functionality is important on PPC64 when dealing with
11933   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
11934   // the return values of functions. Because it is so similar, it is handled
11935   // here as well.
11936 
11937   if (N->getValueType(0) != MVT::i32 &&
11938       N->getValueType(0) != MVT::i64)
11939     return SDValue();
11940 
11941   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
11942         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
11943     return SDValue();
11944 
11945   if (N->getOperand(0).getOpcode() != ISD::AND &&
11946       N->getOperand(0).getOpcode() != ISD::OR  &&
11947       N->getOperand(0).getOpcode() != ISD::XOR &&
11948       N->getOperand(0).getOpcode() != ISD::SELECT &&
11949       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
11950     return SDValue();
11951 
11952   SmallVector<SDValue, 4> Inputs;
11953   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
11954   SmallPtrSet<SDNode *, 16> Visited;
11955 
11956   // Visit all inputs, collect all binary operations (and, or, xor and
11957   // select) that are all fed by truncations.
11958   while (!BinOps.empty()) {
11959     SDValue BinOp = BinOps.back();
11960     BinOps.pop_back();
11961 
11962     if (!Visited.insert(BinOp.getNode()).second)
11963       continue;
11964 
11965     PromOps.push_back(BinOp);
11966 
11967     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11968       // The condition of the select is not promoted.
11969       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11970         continue;
11971       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11972         continue;
11973 
11974       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11975           isa<ConstantSDNode>(BinOp.getOperand(i))) {
11976         Inputs.push_back(BinOp.getOperand(i));
11977       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11978                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
11979                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11980                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11981                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
11982         BinOps.push_back(BinOp.getOperand(i));
11983       } else {
11984         // We have an input that is not a truncation or another binary
11985         // operation; we'll abort this transformation.
11986         return SDValue();
11987       }
11988     }
11989   }
11990 
11991   // The operands of a select that must be truncated when the select is
11992   // promoted because the operand is actually part of the to-be-promoted set.
11993   DenseMap<SDNode *, EVT> SelectTruncOp[2];
11994 
11995   // Make sure that this is a self-contained cluster of operations (which
11996   // is not quite the same thing as saying that everything has only one
11997   // use).
11998   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11999     if (isa<ConstantSDNode>(Inputs[i]))
12000       continue;
12001 
12002     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12003                               UE = Inputs[i].getNode()->use_end();
12004          UI != UE; ++UI) {
12005       SDNode *User = *UI;
12006       if (User != N && !Visited.count(User))
12007         return SDValue();
12008 
12009       // If we're going to promote the non-output-value operand(s) or SELECT or
12010       // SELECT_CC, record them for truncation.
12011       if (User->getOpcode() == ISD::SELECT) {
12012         if (User->getOperand(0) == Inputs[i])
12013           SelectTruncOp[0].insert(std::make_pair(User,
12014                                     User->getOperand(0).getValueType()));
12015       } else if (User->getOpcode() == ISD::SELECT_CC) {
12016         if (User->getOperand(0) == Inputs[i])
12017           SelectTruncOp[0].insert(std::make_pair(User,
12018                                     User->getOperand(0).getValueType()));
12019         if (User->getOperand(1) == Inputs[i])
12020           SelectTruncOp[1].insert(std::make_pair(User,
12021                                     User->getOperand(1).getValueType()));
12022       }
12023     }
12024   }
12025 
12026   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12027     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12028                               UE = PromOps[i].getNode()->use_end();
12029          UI != UE; ++UI) {
12030       SDNode *User = *UI;
12031       if (User != N && !Visited.count(User))
12032         return SDValue();
12033 
12034       // If we're going to promote the non-output-value operand(s) or SELECT or
12035       // SELECT_CC, record them for truncation.
12036       if (User->getOpcode() == ISD::SELECT) {
12037         if (User->getOperand(0) == PromOps[i])
12038           SelectTruncOp[0].insert(std::make_pair(User,
12039                                     User->getOperand(0).getValueType()));
12040       } else if (User->getOpcode() == ISD::SELECT_CC) {
12041         if (User->getOperand(0) == PromOps[i])
12042           SelectTruncOp[0].insert(std::make_pair(User,
12043                                     User->getOperand(0).getValueType()));
12044         if (User->getOperand(1) == PromOps[i])
12045           SelectTruncOp[1].insert(std::make_pair(User,
12046                                     User->getOperand(1).getValueType()));
12047       }
12048     }
12049   }
12050 
12051   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
12052   bool ReallyNeedsExt = false;
12053   if (N->getOpcode() != ISD::ANY_EXTEND) {
12054     // If all of the inputs are not already sign/zero extended, then
12055     // we'll still need to do that at the end.
12056     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12057       if (isa<ConstantSDNode>(Inputs[i]))
12058         continue;
12059 
12060       unsigned OpBits =
12061         Inputs[i].getOperand(0).getValueSizeInBits();
12062       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
12063 
12064       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
12065            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
12066                                   APInt::getHighBitsSet(OpBits,
12067                                                         OpBits-PromBits))) ||
12068           (N->getOpcode() == ISD::SIGN_EXTEND &&
12069            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
12070              (OpBits-(PromBits-1)))) {
12071         ReallyNeedsExt = true;
12072         break;
12073       }
12074     }
12075   }
12076 
12077   // Replace all inputs, either with the truncation operand, or a
12078   // truncation or extension to the final output type.
12079   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12080     // Constant inputs need to be replaced with the to-be-promoted nodes that
12081     // use them because they might have users outside of the cluster of
12082     // promoted nodes.
12083     if (isa<ConstantSDNode>(Inputs[i]))
12084       continue;
12085 
12086     SDValue InSrc = Inputs[i].getOperand(0);
12087     if (Inputs[i].getValueType() == N->getValueType(0))
12088       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
12089     else if (N->getOpcode() == ISD::SIGN_EXTEND)
12090       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12091         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
12092     else if (N->getOpcode() == ISD::ZERO_EXTEND)
12093       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12094         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
12095     else
12096       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12097         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
12098   }
12099 
12100   std::list<HandleSDNode> PromOpHandles;
12101   for (auto &PromOp : PromOps)
12102     PromOpHandles.emplace_back(PromOp);
12103 
12104   // Replace all operations (these are all the same, but have a different
12105   // (promoted) return type). DAG.getNode will validate that the types of
12106   // a binary operator match, so go through the list in reverse so that
12107   // we've likely promoted both operands first.
12108   while (!PromOpHandles.empty()) {
12109     SDValue PromOp = PromOpHandles.back().getValue();
12110     PromOpHandles.pop_back();
12111 
12112     unsigned C;
12113     switch (PromOp.getOpcode()) {
12114     default:             C = 0; break;
12115     case ISD::SELECT:    C = 1; break;
12116     case ISD::SELECT_CC: C = 2; break;
12117     }
12118 
12119     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12120          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
12121         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12122          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
12123       // The to-be-promoted operands of this node have not yet been
12124       // promoted (this should be rare because we're going through the
12125       // list backward, but if one of the operands has several users in
12126       // this cluster of to-be-promoted nodes, it is possible).
12127       PromOpHandles.emplace_front(PromOp);
12128       continue;
12129     }
12130 
12131     // For SELECT and SELECT_CC nodes, we do a similar check for any
12132     // to-be-promoted comparison inputs.
12133     if (PromOp.getOpcode() == ISD::SELECT ||
12134         PromOp.getOpcode() == ISD::SELECT_CC) {
12135       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
12136            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
12137           (SelectTruncOp[1].count(PromOp.getNode()) &&
12138            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
12139         PromOpHandles.emplace_front(PromOp);
12140         continue;
12141       }
12142     }
12143 
12144     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12145                                 PromOp.getNode()->op_end());
12146 
12147     // If this node has constant inputs, then they'll need to be promoted here.
12148     for (unsigned i = 0; i < 2; ++i) {
12149       if (!isa<ConstantSDNode>(Ops[C+i]))
12150         continue;
12151       if (Ops[C+i].getValueType() == N->getValueType(0))
12152         continue;
12153 
12154       if (N->getOpcode() == ISD::SIGN_EXTEND)
12155         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12156       else if (N->getOpcode() == ISD::ZERO_EXTEND)
12157         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12158       else
12159         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12160     }
12161 
12162     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
12163     // truncate them again to the original value type.
12164     if (PromOp.getOpcode() == ISD::SELECT ||
12165         PromOp.getOpcode() == ISD::SELECT_CC) {
12166       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
12167       if (SI0 != SelectTruncOp[0].end())
12168         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
12169       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
12170       if (SI1 != SelectTruncOp[1].end())
12171         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
12172     }
12173 
12174     DAG.ReplaceAllUsesOfValueWith(PromOp,
12175       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
12176   }
12177 
12178   // Now we're left with the initial extension itself.
12179   if (!ReallyNeedsExt)
12180     return N->getOperand(0);
12181 
12182   // To zero extend, just mask off everything except for the first bit (in the
12183   // i1 case).
12184   if (N->getOpcode() == ISD::ZERO_EXTEND)
12185     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
12186                        DAG.getConstant(APInt::getLowBitsSet(
12187                                          N->getValueSizeInBits(0), PromBits),
12188                                        dl, N->getValueType(0)));
12189 
12190   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
12191          "Invalid extension type");
12192   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
12193   SDValue ShiftCst =
12194       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
12195   return DAG.getNode(
12196       ISD::SRA, dl, N->getValueType(0),
12197       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
12198       ShiftCst);
12199 }
12200 
12201 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
12202                                         DAGCombinerInfo &DCI) const {
12203   assert(N->getOpcode() == ISD::SETCC &&
12204          "Should be called with a SETCC node");
12205 
12206   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12207   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
12208     SDValue LHS = N->getOperand(0);
12209     SDValue RHS = N->getOperand(1);
12210 
12211     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
12212     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
12213         LHS.hasOneUse())
12214       std::swap(LHS, RHS);
12215 
12216     // x == 0-y --> x+y == 0
12217     // x != 0-y --> x+y != 0
12218     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
12219         RHS.hasOneUse()) {
12220       SDLoc DL(N);
12221       SelectionDAG &DAG = DCI.DAG;
12222       EVT VT = N->getValueType(0);
12223       EVT OpVT = LHS.getValueType();
12224       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
12225       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
12226     }
12227   }
12228 
12229   return DAGCombineTruncBoolExt(N, DCI);
12230 }
12231 
12232 // Is this an extending load from an f32 to an f64?
12233 static bool isFPExtLoad(SDValue Op) {
12234   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
12235     return LD->getExtensionType() == ISD::EXTLOAD &&
12236       Op.getValueType() == MVT::f64;
12237   return false;
12238 }
12239 
12240 /// Reduces the number of fp-to-int conversion when building a vector.
12241 ///
12242 /// If this vector is built out of floating to integer conversions,
12243 /// transform it to a vector built out of floating point values followed by a
12244 /// single floating to integer conversion of the vector.
12245 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
12246 /// becomes (fptosi (build_vector ($A, $B, ...)))
12247 SDValue PPCTargetLowering::
12248 combineElementTruncationToVectorTruncation(SDNode *N,
12249                                            DAGCombinerInfo &DCI) const {
12250   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12251          "Should be called with a BUILD_VECTOR node");
12252 
12253   SelectionDAG &DAG = DCI.DAG;
12254   SDLoc dl(N);
12255 
12256   SDValue FirstInput = N->getOperand(0);
12257   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
12258          "The input operand must be an fp-to-int conversion.");
12259 
12260   // This combine happens after legalization so the fp_to_[su]i nodes are
12261   // already converted to PPCSISD nodes.
12262   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
12263   if (FirstConversion == PPCISD::FCTIDZ ||
12264       FirstConversion == PPCISD::FCTIDUZ ||
12265       FirstConversion == PPCISD::FCTIWZ ||
12266       FirstConversion == PPCISD::FCTIWUZ) {
12267     bool IsSplat = true;
12268     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
12269       FirstConversion == PPCISD::FCTIWUZ;
12270     EVT SrcVT = FirstInput.getOperand(0).getValueType();
12271     SmallVector<SDValue, 4> Ops;
12272     EVT TargetVT = N->getValueType(0);
12273     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12274       SDValue NextOp = N->getOperand(i);
12275       if (NextOp.getOpcode() != PPCISD::MFVSR)
12276         return SDValue();
12277       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
12278       if (NextConversion != FirstConversion)
12279         return SDValue();
12280       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
12281       // This is not valid if the input was originally double precision. It is
12282       // also not profitable to do unless this is an extending load in which
12283       // case doing this combine will allow us to combine consecutive loads.
12284       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
12285         return SDValue();
12286       if (N->getOperand(i) != FirstInput)
12287         IsSplat = false;
12288     }
12289 
12290     // If this is a splat, we leave it as-is since there will be only a single
12291     // fp-to-int conversion followed by a splat of the integer. This is better
12292     // for 32-bit and smaller ints and neutral for 64-bit ints.
12293     if (IsSplat)
12294       return SDValue();
12295 
12296     // Now that we know we have the right type of node, get its operands
12297     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12298       SDValue In = N->getOperand(i).getOperand(0);
12299       if (Is32Bit) {
12300         // For 32-bit values, we need to add an FP_ROUND node (if we made it
12301         // here, we know that all inputs are extending loads so this is safe).
12302         if (In.isUndef())
12303           Ops.push_back(DAG.getUNDEF(SrcVT));
12304         else {
12305           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
12306                                       MVT::f32, In.getOperand(0),
12307                                       DAG.getIntPtrConstant(1, dl));
12308           Ops.push_back(Trunc);
12309         }
12310       } else
12311         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
12312     }
12313 
12314     unsigned Opcode;
12315     if (FirstConversion == PPCISD::FCTIDZ ||
12316         FirstConversion == PPCISD::FCTIWZ)
12317       Opcode = ISD::FP_TO_SINT;
12318     else
12319       Opcode = ISD::FP_TO_UINT;
12320 
12321     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
12322     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
12323     return DAG.getNode(Opcode, dl, TargetVT, BV);
12324   }
12325   return SDValue();
12326 }
12327 
12328 /// Reduce the number of loads when building a vector.
12329 ///
12330 /// Building a vector out of multiple loads can be converted to a load
12331 /// of the vector type if the loads are consecutive. If the loads are
12332 /// consecutive but in descending order, a shuffle is added at the end
12333 /// to reorder the vector.
12334 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
12335   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12336          "Should be called with a BUILD_VECTOR node");
12337 
12338   SDLoc dl(N);
12339 
12340   // Return early for non byte-sized type, as they can't be consecutive.
12341   if (!N->getValueType(0).getVectorElementType().isByteSized())
12342     return SDValue();
12343 
12344   bool InputsAreConsecutiveLoads = true;
12345   bool InputsAreReverseConsecutive = true;
12346   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
12347   SDValue FirstInput = N->getOperand(0);
12348   bool IsRoundOfExtLoad = false;
12349 
12350   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
12351       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
12352     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
12353     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
12354   }
12355   // Not a build vector of (possibly fp_rounded) loads.
12356   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
12357       N->getNumOperands() == 1)
12358     return SDValue();
12359 
12360   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
12361     // If any inputs are fp_round(extload), they all must be.
12362     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
12363       return SDValue();
12364 
12365     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
12366       N->getOperand(i);
12367     if (NextInput.getOpcode() != ISD::LOAD)
12368       return SDValue();
12369 
12370     SDValue PreviousInput =
12371       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
12372     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
12373     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
12374 
12375     // If any inputs are fp_round(extload), they all must be.
12376     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
12377       return SDValue();
12378 
12379     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
12380       InputsAreConsecutiveLoads = false;
12381     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
12382       InputsAreReverseConsecutive = false;
12383 
12384     // Exit early if the loads are neither consecutive nor reverse consecutive.
12385     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
12386       return SDValue();
12387   }
12388 
12389   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
12390          "The loads cannot be both consecutive and reverse consecutive.");
12391 
12392   SDValue FirstLoadOp =
12393     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
12394   SDValue LastLoadOp =
12395     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
12396                        N->getOperand(N->getNumOperands()-1);
12397 
12398   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
12399   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
12400   if (InputsAreConsecutiveLoads) {
12401     assert(LD1 && "Input needs to be a LoadSDNode.");
12402     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
12403                        LD1->getBasePtr(), LD1->getPointerInfo(),
12404                        LD1->getAlignment());
12405   }
12406   if (InputsAreReverseConsecutive) {
12407     assert(LDL && "Input needs to be a LoadSDNode.");
12408     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
12409                                LDL->getBasePtr(), LDL->getPointerInfo(),
12410                                LDL->getAlignment());
12411     SmallVector<int, 16> Ops;
12412     for (int i = N->getNumOperands() - 1; i >= 0; i--)
12413       Ops.push_back(i);
12414 
12415     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
12416                                 DAG.getUNDEF(N->getValueType(0)), Ops);
12417   }
12418   return SDValue();
12419 }
12420 
12421 // This function adds the required vector_shuffle needed to get
12422 // the elements of the vector extract in the correct position
12423 // as specified by the CorrectElems encoding.
12424 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
12425                                       SDValue Input, uint64_t Elems,
12426                                       uint64_t CorrectElems) {
12427   SDLoc dl(N);
12428 
12429   unsigned NumElems = Input.getValueType().getVectorNumElements();
12430   SmallVector<int, 16> ShuffleMask(NumElems, -1);
12431 
12432   // Knowing the element indices being extracted from the original
12433   // vector and the order in which they're being inserted, just put
12434   // them at element indices required for the instruction.
12435   for (unsigned i = 0; i < N->getNumOperands(); i++) {
12436     if (DAG.getDataLayout().isLittleEndian())
12437       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
12438     else
12439       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
12440     CorrectElems = CorrectElems >> 8;
12441     Elems = Elems >> 8;
12442   }
12443 
12444   SDValue Shuffle =
12445       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
12446                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
12447 
12448   EVT Ty = N->getValueType(0);
12449   SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
12450   return BV;
12451 }
12452 
12453 // Look for build vector patterns where input operands come from sign
12454 // extended vector_extract elements of specific indices. If the correct indices
12455 // aren't used, add a vector shuffle to fix up the indices and create a new
12456 // PPCISD:SExtVElems node which selects the vector sign extend instructions
12457 // during instruction selection.
12458 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
12459   // This array encodes the indices that the vector sign extend instructions
12460   // extract from when extending from one type to another for both BE and LE.
12461   // The right nibble of each byte corresponds to the LE incides.
12462   // and the left nibble of each byte corresponds to the BE incides.
12463   // For example: 0x3074B8FC  byte->word
12464   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
12465   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
12466   // For example: 0x000070F8  byte->double word
12467   // For LE: the allowed indices are: 0x0,0x8
12468   // For BE: the allowed indices are: 0x7,0xF
12469   uint64_t TargetElems[] = {
12470       0x3074B8FC, // b->w
12471       0x000070F8, // b->d
12472       0x10325476, // h->w
12473       0x00003074, // h->d
12474       0x00001032, // w->d
12475   };
12476 
12477   uint64_t Elems = 0;
12478   int Index;
12479   SDValue Input;
12480 
12481   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
12482     if (!Op)
12483       return false;
12484     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
12485         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
12486       return false;
12487 
12488     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
12489     // of the right width.
12490     SDValue Extract = Op.getOperand(0);
12491     if (Extract.getOpcode() == ISD::ANY_EXTEND)
12492       Extract = Extract.getOperand(0);
12493     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12494       return false;
12495 
12496     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
12497     if (!ExtOp)
12498       return false;
12499 
12500     Index = ExtOp->getZExtValue();
12501     if (Input && Input != Extract.getOperand(0))
12502       return false;
12503 
12504     if (!Input)
12505       Input = Extract.getOperand(0);
12506 
12507     Elems = Elems << 8;
12508     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
12509     Elems |= Index;
12510 
12511     return true;
12512   };
12513 
12514   // If the build vector operands aren't sign extended vector extracts,
12515   // of the same input vector, then return.
12516   for (unsigned i = 0; i < N->getNumOperands(); i++) {
12517     if (!isSExtOfVecExtract(N->getOperand(i))) {
12518       return SDValue();
12519     }
12520   }
12521 
12522   // If the vector extract indicies are not correct, add the appropriate
12523   // vector_shuffle.
12524   int TgtElemArrayIdx;
12525   int InputSize = Input.getValueType().getScalarSizeInBits();
12526   int OutputSize = N->getValueType(0).getScalarSizeInBits();
12527   if (InputSize + OutputSize == 40)
12528     TgtElemArrayIdx = 0;
12529   else if (InputSize + OutputSize == 72)
12530     TgtElemArrayIdx = 1;
12531   else if (InputSize + OutputSize == 48)
12532     TgtElemArrayIdx = 2;
12533   else if (InputSize + OutputSize == 80)
12534     TgtElemArrayIdx = 3;
12535   else if (InputSize + OutputSize == 96)
12536     TgtElemArrayIdx = 4;
12537   else
12538     return SDValue();
12539 
12540   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
12541   CorrectElems = DAG.getDataLayout().isLittleEndian()
12542                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
12543                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
12544   if (Elems != CorrectElems) {
12545     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
12546   }
12547 
12548   // Regular lowering will catch cases where a shuffle is not needed.
12549   return SDValue();
12550 }
12551 
12552 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
12553                                                  DAGCombinerInfo &DCI) const {
12554   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12555          "Should be called with a BUILD_VECTOR node");
12556 
12557   SelectionDAG &DAG = DCI.DAG;
12558   SDLoc dl(N);
12559 
12560   if (!Subtarget.hasVSX())
12561     return SDValue();
12562 
12563   // The target independent DAG combiner will leave a build_vector of
12564   // float-to-int conversions intact. We can generate MUCH better code for
12565   // a float-to-int conversion of a vector of floats.
12566   SDValue FirstInput = N->getOperand(0);
12567   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
12568     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
12569     if (Reduced)
12570       return Reduced;
12571   }
12572 
12573   // If we're building a vector out of consecutive loads, just load that
12574   // vector type.
12575   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
12576   if (Reduced)
12577     return Reduced;
12578 
12579   // If we're building a vector out of extended elements from another vector
12580   // we have P9 vector integer extend instructions. The code assumes legal
12581   // input types (i.e. it can't handle things like v4i16) so do not run before
12582   // legalization.
12583   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
12584     Reduced = combineBVOfVecSExt(N, DAG);
12585     if (Reduced)
12586       return Reduced;
12587   }
12588 
12589 
12590   if (N->getValueType(0) != MVT::v2f64)
12591     return SDValue();
12592 
12593   // Looking for:
12594   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
12595   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
12596       FirstInput.getOpcode() != ISD::UINT_TO_FP)
12597     return SDValue();
12598   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
12599       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
12600     return SDValue();
12601   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
12602     return SDValue();
12603 
12604   SDValue Ext1 = FirstInput.getOperand(0);
12605   SDValue Ext2 = N->getOperand(1).getOperand(0);
12606   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12607      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12608     return SDValue();
12609 
12610   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
12611   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
12612   if (!Ext1Op || !Ext2Op)
12613     return SDValue();
12614   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
12615       Ext1.getOperand(0) != Ext2.getOperand(0))
12616     return SDValue();
12617 
12618   int FirstElem = Ext1Op->getZExtValue();
12619   int SecondElem = Ext2Op->getZExtValue();
12620   int SubvecIdx;
12621   if (FirstElem == 0 && SecondElem == 1)
12622     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
12623   else if (FirstElem == 2 && SecondElem == 3)
12624     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
12625   else
12626     return SDValue();
12627 
12628   SDValue SrcVec = Ext1.getOperand(0);
12629   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
12630     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
12631   return DAG.getNode(NodeType, dl, MVT::v2f64,
12632                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
12633 }
12634 
12635 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
12636                                               DAGCombinerInfo &DCI) const {
12637   assert((N->getOpcode() == ISD::SINT_TO_FP ||
12638           N->getOpcode() == ISD::UINT_TO_FP) &&
12639          "Need an int -> FP conversion node here");
12640 
12641   if (useSoftFloat() || !Subtarget.has64BitSupport())
12642     return SDValue();
12643 
12644   SelectionDAG &DAG = DCI.DAG;
12645   SDLoc dl(N);
12646   SDValue Op(N, 0);
12647 
12648   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
12649   // from the hardware.
12650   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
12651     return SDValue();
12652   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
12653       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
12654     return SDValue();
12655 
12656   SDValue FirstOperand(Op.getOperand(0));
12657   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
12658     (FirstOperand.getValueType() == MVT::i8 ||
12659      FirstOperand.getValueType() == MVT::i16);
12660   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
12661     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
12662     bool DstDouble = Op.getValueType() == MVT::f64;
12663     unsigned ConvOp = Signed ?
12664       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
12665       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
12666     SDValue WidthConst =
12667       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
12668                             dl, false);
12669     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
12670     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
12671     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
12672                                          DAG.getVTList(MVT::f64, MVT::Other),
12673                                          Ops, MVT::i8, LDN->getMemOperand());
12674 
12675     // For signed conversion, we need to sign-extend the value in the VSR
12676     if (Signed) {
12677       SDValue ExtOps[] = { Ld, WidthConst };
12678       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
12679       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
12680     } else
12681       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
12682   }
12683 
12684 
12685   // For i32 intermediate values, unfortunately, the conversion functions
12686   // leave the upper 32 bits of the value are undefined. Within the set of
12687   // scalar instructions, we have no method for zero- or sign-extending the
12688   // value. Thus, we cannot handle i32 intermediate values here.
12689   if (Op.getOperand(0).getValueType() == MVT::i32)
12690     return SDValue();
12691 
12692   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
12693          "UINT_TO_FP is supported only with FPCVT");
12694 
12695   // If we have FCFIDS, then use it when converting to single-precision.
12696   // Otherwise, convert to double-precision and then round.
12697   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
12698                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
12699                                                             : PPCISD::FCFIDS)
12700                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
12701                                                             : PPCISD::FCFID);
12702   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
12703                   ? MVT::f32
12704                   : MVT::f64;
12705 
12706   // If we're converting from a float, to an int, and back to a float again,
12707   // then we don't need the store/load pair at all.
12708   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
12709        Subtarget.hasFPCVT()) ||
12710       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
12711     SDValue Src = Op.getOperand(0).getOperand(0);
12712     if (Src.getValueType() == MVT::f32) {
12713       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
12714       DCI.AddToWorklist(Src.getNode());
12715     } else if (Src.getValueType() != MVT::f64) {
12716       // Make sure that we don't pick up a ppc_fp128 source value.
12717       return SDValue();
12718     }
12719 
12720     unsigned FCTOp =
12721       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
12722                                                         PPCISD::FCTIDUZ;
12723 
12724     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
12725     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
12726 
12727     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
12728       FP = DAG.getNode(ISD::FP_ROUND, dl,
12729                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
12730       DCI.AddToWorklist(FP.getNode());
12731     }
12732 
12733     return FP;
12734   }
12735 
12736   return SDValue();
12737 }
12738 
12739 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
12740 // builtins) into loads with swaps.
12741 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
12742                                               DAGCombinerInfo &DCI) const {
12743   SelectionDAG &DAG = DCI.DAG;
12744   SDLoc dl(N);
12745   SDValue Chain;
12746   SDValue Base;
12747   MachineMemOperand *MMO;
12748 
12749   switch (N->getOpcode()) {
12750   default:
12751     llvm_unreachable("Unexpected opcode for little endian VSX load");
12752   case ISD::LOAD: {
12753     LoadSDNode *LD = cast<LoadSDNode>(N);
12754     Chain = LD->getChain();
12755     Base = LD->getBasePtr();
12756     MMO = LD->getMemOperand();
12757     // If the MMO suggests this isn't a load of a full vector, leave
12758     // things alone.  For a built-in, we have to make the change for
12759     // correctness, so if there is a size problem that will be a bug.
12760     if (MMO->getSize() < 16)
12761       return SDValue();
12762     break;
12763   }
12764   case ISD::INTRINSIC_W_CHAIN: {
12765     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
12766     Chain = Intrin->getChain();
12767     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
12768     // us what we want. Get operand 2 instead.
12769     Base = Intrin->getOperand(2);
12770     MMO = Intrin->getMemOperand();
12771     break;
12772   }
12773   }
12774 
12775   MVT VecTy = N->getValueType(0).getSimpleVT();
12776 
12777   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
12778   // aligned and the type is a vector with elements up to 4 bytes
12779   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
12780       && VecTy.getScalarSizeInBits() <= 32 ) {
12781     return SDValue();
12782   }
12783 
12784   SDValue LoadOps[] = { Chain, Base };
12785   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
12786                                          DAG.getVTList(MVT::v2f64, MVT::Other),
12787                                          LoadOps, MVT::v2f64, MMO);
12788 
12789   DCI.AddToWorklist(Load.getNode());
12790   Chain = Load.getValue(1);
12791   SDValue Swap = DAG.getNode(
12792       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
12793   DCI.AddToWorklist(Swap.getNode());
12794 
12795   // Add a bitcast if the resulting load type doesn't match v2f64.
12796   if (VecTy != MVT::v2f64) {
12797     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
12798     DCI.AddToWorklist(N.getNode());
12799     // Package {bitcast value, swap's chain} to match Load's shape.
12800     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
12801                        N, Swap.getValue(1));
12802   }
12803 
12804   return Swap;
12805 }
12806 
12807 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
12808 // builtins) into stores with swaps.
12809 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
12810                                                DAGCombinerInfo &DCI) const {
12811   SelectionDAG &DAG = DCI.DAG;
12812   SDLoc dl(N);
12813   SDValue Chain;
12814   SDValue Base;
12815   unsigned SrcOpnd;
12816   MachineMemOperand *MMO;
12817 
12818   switch (N->getOpcode()) {
12819   default:
12820     llvm_unreachable("Unexpected opcode for little endian VSX store");
12821   case ISD::STORE: {
12822     StoreSDNode *ST = cast<StoreSDNode>(N);
12823     Chain = ST->getChain();
12824     Base = ST->getBasePtr();
12825     MMO = ST->getMemOperand();
12826     SrcOpnd = 1;
12827     // If the MMO suggests this isn't a store of a full vector, leave
12828     // things alone.  For a built-in, we have to make the change for
12829     // correctness, so if there is a size problem that will be a bug.
12830     if (MMO->getSize() < 16)
12831       return SDValue();
12832     break;
12833   }
12834   case ISD::INTRINSIC_VOID: {
12835     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
12836     Chain = Intrin->getChain();
12837     // Intrin->getBasePtr() oddly does not get what we want.
12838     Base = Intrin->getOperand(3);
12839     MMO = Intrin->getMemOperand();
12840     SrcOpnd = 2;
12841     break;
12842   }
12843   }
12844 
12845   SDValue Src = N->getOperand(SrcOpnd);
12846   MVT VecTy = Src.getValueType().getSimpleVT();
12847 
12848   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
12849   // aligned and the type is a vector with elements up to 4 bytes
12850   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
12851       && VecTy.getScalarSizeInBits() <= 32 ) {
12852     return SDValue();
12853   }
12854 
12855   // All stores are done as v2f64 and possible bit cast.
12856   if (VecTy != MVT::v2f64) {
12857     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
12858     DCI.AddToWorklist(Src.getNode());
12859   }
12860 
12861   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
12862                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
12863   DCI.AddToWorklist(Swap.getNode());
12864   Chain = Swap.getValue(1);
12865   SDValue StoreOps[] = { Chain, Swap, Base };
12866   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
12867                                           DAG.getVTList(MVT::Other),
12868                                           StoreOps, VecTy, MMO);
12869   DCI.AddToWorklist(Store.getNode());
12870   return Store;
12871 }
12872 
12873 // Handle DAG combine for STORE (FP_TO_INT F).
12874 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
12875                                                DAGCombinerInfo &DCI) const {
12876 
12877   SelectionDAG &DAG = DCI.DAG;
12878   SDLoc dl(N);
12879   unsigned Opcode = N->getOperand(1).getOpcode();
12880 
12881   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
12882          && "Not a FP_TO_INT Instruction!");
12883 
12884   SDValue Val = N->getOperand(1).getOperand(0);
12885   EVT Op1VT = N->getOperand(1).getValueType();
12886   EVT ResVT = Val.getValueType();
12887 
12888   // Floating point types smaller than 32 bits are not legal on Power.
12889   if (ResVT.getScalarSizeInBits() < 32)
12890     return SDValue();
12891 
12892   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
12893   bool ValidTypeForStoreFltAsInt =
12894         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
12895          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
12896 
12897   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() ||
12898       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
12899     return SDValue();
12900 
12901   // Extend f32 values to f64
12902   if (ResVT.getScalarSizeInBits() == 32) {
12903     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
12904     DCI.AddToWorklist(Val.getNode());
12905   }
12906 
12907   // Set signed or unsigned conversion opcode.
12908   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
12909                           PPCISD::FP_TO_SINT_IN_VSR :
12910                           PPCISD::FP_TO_UINT_IN_VSR;
12911 
12912   Val = DAG.getNode(ConvOpcode,
12913                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
12914   DCI.AddToWorklist(Val.getNode());
12915 
12916   // Set number of bytes being converted.
12917   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
12918   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
12919                     DAG.getIntPtrConstant(ByteSize, dl, false),
12920                     DAG.getValueType(Op1VT) };
12921 
12922   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
12923           DAG.getVTList(MVT::Other), Ops,
12924           cast<StoreSDNode>(N)->getMemoryVT(),
12925           cast<StoreSDNode>(N)->getMemOperand());
12926 
12927   DCI.AddToWorklist(Val.getNode());
12928   return Val;
12929 }
12930 
12931 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
12932                                              DAGCombinerInfo &DCI) const {
12933   SelectionDAG &DAG = DCI.DAG;
12934   SDLoc dl(N);
12935   switch (N->getOpcode()) {
12936   default: break;
12937   case ISD::ADD:
12938     return combineADD(N, DCI);
12939   case ISD::SHL:
12940     return combineSHL(N, DCI);
12941   case ISD::SRA:
12942     return combineSRA(N, DCI);
12943   case ISD::SRL:
12944     return combineSRL(N, DCI);
12945   case ISD::MUL:
12946     return combineMUL(N, DCI);
12947   case PPCISD::SHL:
12948     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
12949         return N->getOperand(0);
12950     break;
12951   case PPCISD::SRL:
12952     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
12953         return N->getOperand(0);
12954     break;
12955   case PPCISD::SRA:
12956     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
12957       if (C->isNullValue() ||   //  0 >>s V -> 0.
12958           C->isAllOnesValue())    // -1 >>s V -> -1.
12959         return N->getOperand(0);
12960     }
12961     break;
12962   case ISD::SIGN_EXTEND:
12963   case ISD::ZERO_EXTEND:
12964   case ISD::ANY_EXTEND:
12965     return DAGCombineExtBoolTrunc(N, DCI);
12966   case ISD::TRUNCATE:
12967     return combineTRUNCATE(N, DCI);
12968   case ISD::SETCC:
12969     if (SDValue CSCC = combineSetCC(N, DCI))
12970       return CSCC;
12971     LLVM_FALLTHROUGH;
12972   case ISD::SELECT_CC:
12973     return DAGCombineTruncBoolExt(N, DCI);
12974   case ISD::SINT_TO_FP:
12975   case ISD::UINT_TO_FP:
12976     return combineFPToIntToFP(N, DCI);
12977   case ISD::STORE: {
12978 
12979     EVT Op1VT = N->getOperand(1).getValueType();
12980     unsigned Opcode = N->getOperand(1).getOpcode();
12981 
12982     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
12983       SDValue Val= combineStoreFPToInt(N, DCI);
12984       if (Val)
12985         return Val;
12986     }
12987 
12988     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
12989     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
12990         N->getOperand(1).getNode()->hasOneUse() &&
12991         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
12992          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
12993 
12994       // STBRX can only handle simple types and it makes no sense to store less
12995       // two bytes in byte-reversed order.
12996       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
12997       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
12998         break;
12999 
13000       SDValue BSwapOp = N->getOperand(1).getOperand(0);
13001       // Do an any-extend to 32-bits if this is a half-word input.
13002       if (BSwapOp.getValueType() == MVT::i16)
13003         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
13004 
13005       // If the type of BSWAP operand is wider than stored memory width
13006       // it need to be shifted to the right side before STBRX.
13007       if (Op1VT.bitsGT(mVT)) {
13008         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
13009         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
13010                               DAG.getConstant(Shift, dl, MVT::i32));
13011         // Need to truncate if this is a bswap of i64 stored as i32/i16.
13012         if (Op1VT == MVT::i64)
13013           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
13014       }
13015 
13016       SDValue Ops[] = {
13017         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
13018       };
13019       return
13020         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
13021                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
13022                                 cast<StoreSDNode>(N)->getMemOperand());
13023     }
13024 
13025     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
13026     // So it can increase the chance of CSE constant construction.
13027     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
13028         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
13029       // Need to sign-extended to 64-bits to handle negative values.
13030       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
13031       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
13032                                     MemVT.getSizeInBits());
13033       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
13034 
13035       // DAG.getTruncStore() can't be used here because it doesn't accept
13036       // the general (base + offset) addressing mode.
13037       // So we use UpdateNodeOperands and setTruncatingStore instead.
13038       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
13039                              N->getOperand(3));
13040       cast<StoreSDNode>(N)->setTruncatingStore(true);
13041       return SDValue(N, 0);
13042     }
13043 
13044     // For little endian, VSX stores require generating xxswapd/lxvd2x.
13045     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13046     if (Op1VT.isSimple()) {
13047       MVT StoreVT = Op1VT.getSimpleVT();
13048       if (Subtarget.needsSwapsForVSXMemOps() &&
13049           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
13050            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
13051         return expandVSXStoreForLE(N, DCI);
13052     }
13053     break;
13054   }
13055   case ISD::LOAD: {
13056     LoadSDNode *LD = cast<LoadSDNode>(N);
13057     EVT VT = LD->getValueType(0);
13058 
13059     // For little endian, VSX loads require generating lxvd2x/xxswapd.
13060     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
13061     if (VT.isSimple()) {
13062       MVT LoadVT = VT.getSimpleVT();
13063       if (Subtarget.needsSwapsForVSXMemOps() &&
13064           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
13065            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
13066         return expandVSXLoadForLE(N, DCI);
13067     }
13068 
13069     // We sometimes end up with a 64-bit integer load, from which we extract
13070     // two single-precision floating-point numbers. This happens with
13071     // std::complex<float>, and other similar structures, because of the way we
13072     // canonicalize structure copies. However, if we lack direct moves,
13073     // then the final bitcasts from the extracted integer values to the
13074     // floating-point numbers turn into store/load pairs. Even with direct moves,
13075     // just loading the two floating-point numbers is likely better.
13076     auto ReplaceTwoFloatLoad = [&]() {
13077       if (VT != MVT::i64)
13078         return false;
13079 
13080       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
13081           LD->isVolatile())
13082         return false;
13083 
13084       //  We're looking for a sequence like this:
13085       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
13086       //      t16: i64 = srl t13, Constant:i32<32>
13087       //    t17: i32 = truncate t16
13088       //  t18: f32 = bitcast t17
13089       //    t19: i32 = truncate t13
13090       //  t20: f32 = bitcast t19
13091 
13092       if (!LD->hasNUsesOfValue(2, 0))
13093         return false;
13094 
13095       auto UI = LD->use_begin();
13096       while (UI.getUse().getResNo() != 0) ++UI;
13097       SDNode *Trunc = *UI++;
13098       while (UI.getUse().getResNo() != 0) ++UI;
13099       SDNode *RightShift = *UI;
13100       if (Trunc->getOpcode() != ISD::TRUNCATE)
13101         std::swap(Trunc, RightShift);
13102 
13103       if (Trunc->getOpcode() != ISD::TRUNCATE ||
13104           Trunc->getValueType(0) != MVT::i32 ||
13105           !Trunc->hasOneUse())
13106         return false;
13107       if (RightShift->getOpcode() != ISD::SRL ||
13108           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
13109           RightShift->getConstantOperandVal(1) != 32 ||
13110           !RightShift->hasOneUse())
13111         return false;
13112 
13113       SDNode *Trunc2 = *RightShift->use_begin();
13114       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
13115           Trunc2->getValueType(0) != MVT::i32 ||
13116           !Trunc2->hasOneUse())
13117         return false;
13118 
13119       SDNode *Bitcast = *Trunc->use_begin();
13120       SDNode *Bitcast2 = *Trunc2->use_begin();
13121 
13122       if (Bitcast->getOpcode() != ISD::BITCAST ||
13123           Bitcast->getValueType(0) != MVT::f32)
13124         return false;
13125       if (Bitcast2->getOpcode() != ISD::BITCAST ||
13126           Bitcast2->getValueType(0) != MVT::f32)
13127         return false;
13128 
13129       if (Subtarget.isLittleEndian())
13130         std::swap(Bitcast, Bitcast2);
13131 
13132       // Bitcast has the second float (in memory-layout order) and Bitcast2
13133       // has the first one.
13134 
13135       SDValue BasePtr = LD->getBasePtr();
13136       if (LD->isIndexed()) {
13137         assert(LD->getAddressingMode() == ISD::PRE_INC &&
13138                "Non-pre-inc AM on PPC?");
13139         BasePtr =
13140           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
13141                       LD->getOffset());
13142       }
13143 
13144       auto MMOFlags =
13145           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
13146       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
13147                                       LD->getPointerInfo(), LD->getAlignment(),
13148                                       MMOFlags, LD->getAAInfo());
13149       SDValue AddPtr =
13150         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
13151                     BasePtr, DAG.getIntPtrConstant(4, dl));
13152       SDValue FloatLoad2 = DAG.getLoad(
13153           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
13154           LD->getPointerInfo().getWithOffset(4),
13155           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
13156 
13157       if (LD->isIndexed()) {
13158         // Note that DAGCombine should re-form any pre-increment load(s) from
13159         // what is produced here if that makes sense.
13160         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
13161       }
13162 
13163       DCI.CombineTo(Bitcast2, FloatLoad);
13164       DCI.CombineTo(Bitcast, FloatLoad2);
13165 
13166       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
13167                                     SDValue(FloatLoad2.getNode(), 1));
13168       return true;
13169     };
13170 
13171     if (ReplaceTwoFloatLoad())
13172       return SDValue(N, 0);
13173 
13174     EVT MemVT = LD->getMemoryVT();
13175     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
13176     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
13177     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
13178     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
13179     if (LD->isUnindexed() && VT.isVector() &&
13180         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
13181           // P8 and later hardware should just use LOAD.
13182           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
13183                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
13184          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
13185           LD->getAlignment() >= ScalarABIAlignment)) &&
13186         LD->getAlignment() < ABIAlignment) {
13187       // This is a type-legal unaligned Altivec or QPX load.
13188       SDValue Chain = LD->getChain();
13189       SDValue Ptr = LD->getBasePtr();
13190       bool isLittleEndian = Subtarget.isLittleEndian();
13191 
13192       // This implements the loading of unaligned vectors as described in
13193       // the venerable Apple Velocity Engine overview. Specifically:
13194       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
13195       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
13196       //
13197       // The general idea is to expand a sequence of one or more unaligned
13198       // loads into an alignment-based permutation-control instruction (lvsl
13199       // or lvsr), a series of regular vector loads (which always truncate
13200       // their input address to an aligned address), and a series of
13201       // permutations.  The results of these permutations are the requested
13202       // loaded values.  The trick is that the last "extra" load is not taken
13203       // from the address you might suspect (sizeof(vector) bytes after the
13204       // last requested load), but rather sizeof(vector) - 1 bytes after the
13205       // last requested vector. The point of this is to avoid a page fault if
13206       // the base address happened to be aligned. This works because if the
13207       // base address is aligned, then adding less than a full vector length
13208       // will cause the last vector in the sequence to be (re)loaded.
13209       // Otherwise, the next vector will be fetched as you might suspect was
13210       // necessary.
13211 
13212       // We might be able to reuse the permutation generation from
13213       // a different base address offset from this one by an aligned amount.
13214       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
13215       // optimization later.
13216       Intrinsic::ID Intr, IntrLD, IntrPerm;
13217       MVT PermCntlTy, PermTy, LDTy;
13218       if (Subtarget.hasAltivec()) {
13219         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
13220                                  Intrinsic::ppc_altivec_lvsl;
13221         IntrLD = Intrinsic::ppc_altivec_lvx;
13222         IntrPerm = Intrinsic::ppc_altivec_vperm;
13223         PermCntlTy = MVT::v16i8;
13224         PermTy = MVT::v4i32;
13225         LDTy = MVT::v4i32;
13226       } else {
13227         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
13228                                        Intrinsic::ppc_qpx_qvlpcls;
13229         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
13230                                        Intrinsic::ppc_qpx_qvlfs;
13231         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
13232         PermCntlTy = MVT::v4f64;
13233         PermTy = MVT::v4f64;
13234         LDTy = MemVT.getSimpleVT();
13235       }
13236 
13237       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
13238 
13239       // Create the new MMO for the new base load. It is like the original MMO,
13240       // but represents an area in memory almost twice the vector size centered
13241       // on the original address. If the address is unaligned, we might start
13242       // reading up to (sizeof(vector)-1) bytes below the address of the
13243       // original unaligned load.
13244       MachineFunction &MF = DAG.getMachineFunction();
13245       MachineMemOperand *BaseMMO =
13246         MF.getMachineMemOperand(LD->getMemOperand(),
13247                                 -(long)MemVT.getStoreSize()+1,
13248                                 2*MemVT.getStoreSize()-1);
13249 
13250       // Create the new base load.
13251       SDValue LDXIntID =
13252           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
13253       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
13254       SDValue BaseLoad =
13255         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13256                                 DAG.getVTList(PermTy, MVT::Other),
13257                                 BaseLoadOps, LDTy, BaseMMO);
13258 
13259       // Note that the value of IncOffset (which is provided to the next
13260       // load's pointer info offset value, and thus used to calculate the
13261       // alignment), and the value of IncValue (which is actually used to
13262       // increment the pointer value) are different! This is because we
13263       // require the next load to appear to be aligned, even though it
13264       // is actually offset from the base pointer by a lesser amount.
13265       int IncOffset = VT.getSizeInBits() / 8;
13266       int IncValue = IncOffset;
13267 
13268       // Walk (both up and down) the chain looking for another load at the real
13269       // (aligned) offset (the alignment of the other load does not matter in
13270       // this case). If found, then do not use the offset reduction trick, as
13271       // that will prevent the loads from being later combined (as they would
13272       // otherwise be duplicates).
13273       if (!findConsecutiveLoad(LD, DAG))
13274         --IncValue;
13275 
13276       SDValue Increment =
13277           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
13278       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13279 
13280       MachineMemOperand *ExtraMMO =
13281         MF.getMachineMemOperand(LD->getMemOperand(),
13282                                 1, 2*MemVT.getStoreSize()-1);
13283       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
13284       SDValue ExtraLoad =
13285         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13286                                 DAG.getVTList(PermTy, MVT::Other),
13287                                 ExtraLoadOps, LDTy, ExtraMMO);
13288 
13289       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
13290         BaseLoad.getValue(1), ExtraLoad.getValue(1));
13291 
13292       // Because vperm has a big-endian bias, we must reverse the order
13293       // of the input vectors and complement the permute control vector
13294       // when generating little endian code.  We have already handled the
13295       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
13296       // and ExtraLoad here.
13297       SDValue Perm;
13298       if (isLittleEndian)
13299         Perm = BuildIntrinsicOp(IntrPerm,
13300                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
13301       else
13302         Perm = BuildIntrinsicOp(IntrPerm,
13303                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
13304 
13305       if (VT != PermTy)
13306         Perm = Subtarget.hasAltivec() ?
13307                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
13308                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
13309                                DAG.getTargetConstant(1, dl, MVT::i64));
13310                                // second argument is 1 because this rounding
13311                                // is always exact.
13312 
13313       // The output of the permutation is our loaded result, the TokenFactor is
13314       // our new chain.
13315       DCI.CombineTo(N, Perm, TF);
13316       return SDValue(N, 0);
13317     }
13318     }
13319     break;
13320     case ISD::INTRINSIC_WO_CHAIN: {
13321       bool isLittleEndian = Subtarget.isLittleEndian();
13322       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13323       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
13324                                            : Intrinsic::ppc_altivec_lvsl);
13325       if ((IID == Intr ||
13326            IID == Intrinsic::ppc_qpx_qvlpcld  ||
13327            IID == Intrinsic::ppc_qpx_qvlpcls) &&
13328         N->getOperand(1)->getOpcode() == ISD::ADD) {
13329         SDValue Add = N->getOperand(1);
13330 
13331         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
13332                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
13333 
13334         if (DAG.MaskedValueIsZero(Add->getOperand(1),
13335                                   APInt::getAllOnesValue(Bits /* alignment */)
13336                                       .zext(Add.getScalarValueSizeInBits()))) {
13337           SDNode *BasePtr = Add->getOperand(0).getNode();
13338           for (SDNode::use_iterator UI = BasePtr->use_begin(),
13339                                     UE = BasePtr->use_end();
13340                UI != UE; ++UI) {
13341             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13342                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
13343               // We've found another LVSL/LVSR, and this address is an aligned
13344               // multiple of that one. The results will be the same, so use the
13345               // one we've just found instead.
13346 
13347               return SDValue(*UI, 0);
13348             }
13349           }
13350         }
13351 
13352         if (isa<ConstantSDNode>(Add->getOperand(1))) {
13353           SDNode *BasePtr = Add->getOperand(0).getNode();
13354           for (SDNode::use_iterator UI = BasePtr->use_begin(),
13355                UE = BasePtr->use_end(); UI != UE; ++UI) {
13356             if (UI->getOpcode() == ISD::ADD &&
13357                 isa<ConstantSDNode>(UI->getOperand(1)) &&
13358                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
13359                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
13360                 (1ULL << Bits) == 0) {
13361               SDNode *OtherAdd = *UI;
13362               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
13363                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
13364                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13365                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
13366                   return SDValue(*VI, 0);
13367                 }
13368               }
13369             }
13370           }
13371         }
13372       }
13373 
13374       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
13375       // Expose the vabsduw/h/b opportunity for down stream
13376       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
13377           (IID == Intrinsic::ppc_altivec_vmaxsw ||
13378            IID == Intrinsic::ppc_altivec_vmaxsh ||
13379            IID == Intrinsic::ppc_altivec_vmaxsb)) {
13380         SDValue V1 = N->getOperand(1);
13381         SDValue V2 = N->getOperand(2);
13382         if ((V1.getSimpleValueType() == MVT::v4i32 ||
13383              V1.getSimpleValueType() == MVT::v8i16 ||
13384              V1.getSimpleValueType() == MVT::v16i8) &&
13385             V1.getSimpleValueType() == V2.getSimpleValueType()) {
13386           // (0-a, a)
13387           if (V1.getOpcode() == ISD::SUB &&
13388               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
13389               V1.getOperand(1) == V2) {
13390             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
13391           }
13392           // (a, 0-a)
13393           if (V2.getOpcode() == ISD::SUB &&
13394               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
13395               V2.getOperand(1) == V1) {
13396             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
13397           }
13398           // (x-y, y-x)
13399           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
13400               V1.getOperand(0) == V2.getOperand(1) &&
13401               V1.getOperand(1) == V2.getOperand(0)) {
13402             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
13403           }
13404         }
13405       }
13406     }
13407 
13408     break;
13409   case ISD::INTRINSIC_W_CHAIN:
13410     // For little endian, VSX loads require generating lxvd2x/xxswapd.
13411     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
13412     if (Subtarget.needsSwapsForVSXMemOps()) {
13413       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13414       default:
13415         break;
13416       case Intrinsic::ppc_vsx_lxvw4x:
13417       case Intrinsic::ppc_vsx_lxvd2x:
13418         return expandVSXLoadForLE(N, DCI);
13419       }
13420     }
13421     break;
13422   case ISD::INTRINSIC_VOID:
13423     // For little endian, VSX stores require generating xxswapd/stxvd2x.
13424     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13425     if (Subtarget.needsSwapsForVSXMemOps()) {
13426       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13427       default:
13428         break;
13429       case Intrinsic::ppc_vsx_stxvw4x:
13430       case Intrinsic::ppc_vsx_stxvd2x:
13431         return expandVSXStoreForLE(N, DCI);
13432       }
13433     }
13434     break;
13435   case ISD::BSWAP:
13436     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
13437     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
13438         N->getOperand(0).hasOneUse() &&
13439         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
13440          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
13441           N->getValueType(0) == MVT::i64))) {
13442       SDValue Load = N->getOperand(0);
13443       LoadSDNode *LD = cast<LoadSDNode>(Load);
13444       // Create the byte-swapping load.
13445       SDValue Ops[] = {
13446         LD->getChain(),    // Chain
13447         LD->getBasePtr(),  // Ptr
13448         DAG.getValueType(N->getValueType(0)) // VT
13449       };
13450       SDValue BSLoad =
13451         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
13452                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
13453                                               MVT::i64 : MVT::i32, MVT::Other),
13454                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
13455 
13456       // If this is an i16 load, insert the truncate.
13457       SDValue ResVal = BSLoad;
13458       if (N->getValueType(0) == MVT::i16)
13459         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
13460 
13461       // First, combine the bswap away.  This makes the value produced by the
13462       // load dead.
13463       DCI.CombineTo(N, ResVal);
13464 
13465       // Next, combine the load away, we give it a bogus result value but a real
13466       // chain result.  The result value is dead because the bswap is dead.
13467       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
13468 
13469       // Return N so it doesn't get rechecked!
13470       return SDValue(N, 0);
13471     }
13472     break;
13473   case PPCISD::VCMP:
13474     // If a VCMPo node already exists with exactly the same operands as this
13475     // node, use its result instead of this node (VCMPo computes both a CR6 and
13476     // a normal output).
13477     //
13478     if (!N->getOperand(0).hasOneUse() &&
13479         !N->getOperand(1).hasOneUse() &&
13480         !N->getOperand(2).hasOneUse()) {
13481 
13482       // Scan all of the users of the LHS, looking for VCMPo's that match.
13483       SDNode *VCMPoNode = nullptr;
13484 
13485       SDNode *LHSN = N->getOperand(0).getNode();
13486       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
13487            UI != E; ++UI)
13488         if (UI->getOpcode() == PPCISD::VCMPo &&
13489             UI->getOperand(1) == N->getOperand(1) &&
13490             UI->getOperand(2) == N->getOperand(2) &&
13491             UI->getOperand(0) == N->getOperand(0)) {
13492           VCMPoNode = *UI;
13493           break;
13494         }
13495 
13496       // If there is no VCMPo node, or if the flag value has a single use, don't
13497       // transform this.
13498       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
13499         break;
13500 
13501       // Look at the (necessarily single) use of the flag value.  If it has a
13502       // chain, this transformation is more complex.  Note that multiple things
13503       // could use the value result, which we should ignore.
13504       SDNode *FlagUser = nullptr;
13505       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
13506            FlagUser == nullptr; ++UI) {
13507         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
13508         SDNode *User = *UI;
13509         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
13510           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
13511             FlagUser = User;
13512             break;
13513           }
13514         }
13515       }
13516 
13517       // If the user is a MFOCRF instruction, we know this is safe.
13518       // Otherwise we give up for right now.
13519       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
13520         return SDValue(VCMPoNode, 0);
13521     }
13522     break;
13523   case ISD::BRCOND: {
13524     SDValue Cond = N->getOperand(1);
13525     SDValue Target = N->getOperand(2);
13526 
13527     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13528         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
13529           Intrinsic::ppc_is_decremented_ctr_nonzero) {
13530 
13531       // We now need to make the intrinsic dead (it cannot be instruction
13532       // selected).
13533       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
13534       assert(Cond.getNode()->hasOneUse() &&
13535              "Counter decrement has more than one use");
13536 
13537       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
13538                          N->getOperand(0), Target);
13539     }
13540   }
13541   break;
13542   case ISD::BR_CC: {
13543     // If this is a branch on an altivec predicate comparison, lower this so
13544     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
13545     // lowering is done pre-legalize, because the legalizer lowers the predicate
13546     // compare down to code that is difficult to reassemble.
13547     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
13548     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
13549 
13550     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
13551     // value. If so, pass-through the AND to get to the intrinsic.
13552     if (LHS.getOpcode() == ISD::AND &&
13553         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13554         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
13555           Intrinsic::ppc_is_decremented_ctr_nonzero &&
13556         isa<ConstantSDNode>(LHS.getOperand(1)) &&
13557         !isNullConstant(LHS.getOperand(1)))
13558       LHS = LHS.getOperand(0);
13559 
13560     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13561         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
13562           Intrinsic::ppc_is_decremented_ctr_nonzero &&
13563         isa<ConstantSDNode>(RHS)) {
13564       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
13565              "Counter decrement comparison is not EQ or NE");
13566 
13567       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
13568       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
13569                     (CC == ISD::SETNE && !Val);
13570 
13571       // We now need to make the intrinsic dead (it cannot be instruction
13572       // selected).
13573       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
13574       assert(LHS.getNode()->hasOneUse() &&
13575              "Counter decrement has more than one use");
13576 
13577       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
13578                          N->getOperand(0), N->getOperand(4));
13579     }
13580 
13581     int CompareOpc;
13582     bool isDot;
13583 
13584     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13585         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
13586         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
13587       assert(isDot && "Can't compare against a vector result!");
13588 
13589       // If this is a comparison against something other than 0/1, then we know
13590       // that the condition is never/always true.
13591       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
13592       if (Val != 0 && Val != 1) {
13593         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
13594           return N->getOperand(0);
13595         // Always !=, turn it into an unconditional branch.
13596         return DAG.getNode(ISD::BR, dl, MVT::Other,
13597                            N->getOperand(0), N->getOperand(4));
13598       }
13599 
13600       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
13601 
13602       // Create the PPCISD altivec 'dot' comparison node.
13603       SDValue Ops[] = {
13604         LHS.getOperand(2),  // LHS of compare
13605         LHS.getOperand(3),  // RHS of compare
13606         DAG.getConstant(CompareOpc, dl, MVT::i32)
13607       };
13608       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
13609       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
13610 
13611       // Unpack the result based on how the target uses it.
13612       PPC::Predicate CompOpc;
13613       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
13614       default:  // Can't happen, don't crash on invalid number though.
13615       case 0:   // Branch on the value of the EQ bit of CR6.
13616         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
13617         break;
13618       case 1:   // Branch on the inverted value of the EQ bit of CR6.
13619         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
13620         break;
13621       case 2:   // Branch on the value of the LT bit of CR6.
13622         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
13623         break;
13624       case 3:   // Branch on the inverted value of the LT bit of CR6.
13625         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
13626         break;
13627       }
13628 
13629       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
13630                          DAG.getConstant(CompOpc, dl, MVT::i32),
13631                          DAG.getRegister(PPC::CR6, MVT::i32),
13632                          N->getOperand(4), CompNode.getValue(1));
13633     }
13634     break;
13635   }
13636   case ISD::BUILD_VECTOR:
13637     return DAGCombineBuildVector(N, DCI);
13638   case ISD::ABS:
13639     return combineABS(N, DCI);
13640   case ISD::VSELECT:
13641     return combineVSelect(N, DCI);
13642   }
13643 
13644   return SDValue();
13645 }
13646 
13647 SDValue
13648 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
13649                                  SelectionDAG &DAG,
13650                                  SmallVectorImpl<SDNode *> &Created) const {
13651   // fold (sdiv X, pow2)
13652   EVT VT = N->getValueType(0);
13653   if (VT == MVT::i64 && !Subtarget.isPPC64())
13654     return SDValue();
13655   if ((VT != MVT::i32 && VT != MVT::i64) ||
13656       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
13657     return SDValue();
13658 
13659   SDLoc DL(N);
13660   SDValue N0 = N->getOperand(0);
13661 
13662   bool IsNegPow2 = (-Divisor).isPowerOf2();
13663   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
13664   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
13665 
13666   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
13667   Created.push_back(Op.getNode());
13668 
13669   if (IsNegPow2) {
13670     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
13671     Created.push_back(Op.getNode());
13672   }
13673 
13674   return Op;
13675 }
13676 
13677 //===----------------------------------------------------------------------===//
13678 // Inline Assembly Support
13679 //===----------------------------------------------------------------------===//
13680 
13681 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
13682                                                       KnownBits &Known,
13683                                                       const APInt &DemandedElts,
13684                                                       const SelectionDAG &DAG,
13685                                                       unsigned Depth) const {
13686   Known.resetAll();
13687   switch (Op.getOpcode()) {
13688   default: break;
13689   case PPCISD::LBRX: {
13690     // lhbrx is known to have the top bits cleared out.
13691     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
13692       Known.Zero = 0xFFFF0000;
13693     break;
13694   }
13695   case ISD::INTRINSIC_WO_CHAIN: {
13696     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
13697     default: break;
13698     case Intrinsic::ppc_altivec_vcmpbfp_p:
13699     case Intrinsic::ppc_altivec_vcmpeqfp_p:
13700     case Intrinsic::ppc_altivec_vcmpequb_p:
13701     case Intrinsic::ppc_altivec_vcmpequh_p:
13702     case Intrinsic::ppc_altivec_vcmpequw_p:
13703     case Intrinsic::ppc_altivec_vcmpequd_p:
13704     case Intrinsic::ppc_altivec_vcmpgefp_p:
13705     case Intrinsic::ppc_altivec_vcmpgtfp_p:
13706     case Intrinsic::ppc_altivec_vcmpgtsb_p:
13707     case Intrinsic::ppc_altivec_vcmpgtsh_p:
13708     case Intrinsic::ppc_altivec_vcmpgtsw_p:
13709     case Intrinsic::ppc_altivec_vcmpgtsd_p:
13710     case Intrinsic::ppc_altivec_vcmpgtub_p:
13711     case Intrinsic::ppc_altivec_vcmpgtuh_p:
13712     case Intrinsic::ppc_altivec_vcmpgtuw_p:
13713     case Intrinsic::ppc_altivec_vcmpgtud_p:
13714       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
13715       break;
13716     }
13717   }
13718   }
13719 }
13720 
13721 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
13722   switch (Subtarget.getDarwinDirective()) {
13723   default: break;
13724   case PPC::DIR_970:
13725   case PPC::DIR_PWR4:
13726   case PPC::DIR_PWR5:
13727   case PPC::DIR_PWR5X:
13728   case PPC::DIR_PWR6:
13729   case PPC::DIR_PWR6X:
13730   case PPC::DIR_PWR7:
13731   case PPC::DIR_PWR8:
13732   case PPC::DIR_PWR9: {
13733     if (!ML)
13734       break;
13735 
13736     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
13737 
13738     // For small loops (between 5 and 8 instructions), align to a 32-byte
13739     // boundary so that the entire loop fits in one instruction-cache line.
13740     uint64_t LoopSize = 0;
13741     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
13742       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
13743         LoopSize += TII->getInstSizeInBytes(*J);
13744         if (LoopSize > 32)
13745           break;
13746       }
13747 
13748     if (LoopSize > 16 && LoopSize <= 32)
13749       return 5;
13750 
13751     break;
13752   }
13753   }
13754 
13755   return TargetLowering::getPrefLoopAlignment(ML);
13756 }
13757 
13758 /// getConstraintType - Given a constraint, return the type of
13759 /// constraint it is for this target.
13760 PPCTargetLowering::ConstraintType
13761 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
13762   if (Constraint.size() == 1) {
13763     switch (Constraint[0]) {
13764     default: break;
13765     case 'b':
13766     case 'r':
13767     case 'f':
13768     case 'd':
13769     case 'v':
13770     case 'y':
13771       return C_RegisterClass;
13772     case 'Z':
13773       // FIXME: While Z does indicate a memory constraint, it specifically
13774       // indicates an r+r address (used in conjunction with the 'y' modifier
13775       // in the replacement string). Currently, we're forcing the base
13776       // register to be r0 in the asm printer (which is interpreted as zero)
13777       // and forming the complete address in the second register. This is
13778       // suboptimal.
13779       return C_Memory;
13780     }
13781   } else if (Constraint == "wc") { // individual CR bits.
13782     return C_RegisterClass;
13783   } else if (Constraint == "wa" || Constraint == "wd" ||
13784              Constraint == "wf" || Constraint == "ws" ||
13785              Constraint == "wi") {
13786     return C_RegisterClass; // VSX registers.
13787   }
13788   return TargetLowering::getConstraintType(Constraint);
13789 }
13790 
13791 /// Examine constraint type and operand type and determine a weight value.
13792 /// This object must already have been set up with the operand type
13793 /// and the current alternative constraint selected.
13794 TargetLowering::ConstraintWeight
13795 PPCTargetLowering::getSingleConstraintMatchWeight(
13796     AsmOperandInfo &info, const char *constraint) const {
13797   ConstraintWeight weight = CW_Invalid;
13798   Value *CallOperandVal = info.CallOperandVal;
13799     // If we don't have a value, we can't do a match,
13800     // but allow it at the lowest weight.
13801   if (!CallOperandVal)
13802     return CW_Default;
13803   Type *type = CallOperandVal->getType();
13804 
13805   // Look at the constraint type.
13806   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
13807     return CW_Register; // an individual CR bit.
13808   else if ((StringRef(constraint) == "wa" ||
13809             StringRef(constraint) == "wd" ||
13810             StringRef(constraint) == "wf") &&
13811            type->isVectorTy())
13812     return CW_Register;
13813   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
13814     return CW_Register;
13815   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
13816     return CW_Register; // just hold 64-bit integers data.
13817 
13818   switch (*constraint) {
13819   default:
13820     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13821     break;
13822   case 'b':
13823     if (type->isIntegerTy())
13824       weight = CW_Register;
13825     break;
13826   case 'f':
13827     if (type->isFloatTy())
13828       weight = CW_Register;
13829     break;
13830   case 'd':
13831     if (type->isDoubleTy())
13832       weight = CW_Register;
13833     break;
13834   case 'v':
13835     if (type->isVectorTy())
13836       weight = CW_Register;
13837     break;
13838   case 'y':
13839     weight = CW_Register;
13840     break;
13841   case 'Z':
13842     weight = CW_Memory;
13843     break;
13844   }
13845   return weight;
13846 }
13847 
13848 std::pair<unsigned, const TargetRegisterClass *>
13849 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
13850                                                 StringRef Constraint,
13851                                                 MVT VT) const {
13852   if (Constraint.size() == 1) {
13853     // GCC RS6000 Constraint Letters
13854     switch (Constraint[0]) {
13855     case 'b':   // R1-R31
13856       if (VT == MVT::i64 && Subtarget.isPPC64())
13857         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
13858       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
13859     case 'r':   // R0-R31
13860       if (VT == MVT::i64 && Subtarget.isPPC64())
13861         return std::make_pair(0U, &PPC::G8RCRegClass);
13862       return std::make_pair(0U, &PPC::GPRCRegClass);
13863     // 'd' and 'f' constraints are both defined to be "the floating point
13864     // registers", where one is for 32-bit and the other for 64-bit. We don't
13865     // really care overly much here so just give them all the same reg classes.
13866     case 'd':
13867     case 'f':
13868       if (Subtarget.hasSPE()) {
13869         if (VT == MVT::f32 || VT == MVT::i32)
13870           return std::make_pair(0U, &PPC::SPE4RCRegClass);
13871         if (VT == MVT::f64 || VT == MVT::i64)
13872           return std::make_pair(0U, &PPC::SPERCRegClass);
13873       } else {
13874         if (VT == MVT::f32 || VT == MVT::i32)
13875           return std::make_pair(0U, &PPC::F4RCRegClass);
13876         if (VT == MVT::f64 || VT == MVT::i64)
13877           return std::make_pair(0U, &PPC::F8RCRegClass);
13878         if (VT == MVT::v4f64 && Subtarget.hasQPX())
13879           return std::make_pair(0U, &PPC::QFRCRegClass);
13880         if (VT == MVT::v4f32 && Subtarget.hasQPX())
13881           return std::make_pair(0U, &PPC::QSRCRegClass);
13882       }
13883       break;
13884     case 'v':
13885       if (VT == MVT::v4f64 && Subtarget.hasQPX())
13886         return std::make_pair(0U, &PPC::QFRCRegClass);
13887       if (VT == MVT::v4f32 && Subtarget.hasQPX())
13888         return std::make_pair(0U, &PPC::QSRCRegClass);
13889       if (Subtarget.hasAltivec())
13890         return std::make_pair(0U, &PPC::VRRCRegClass);
13891       break;
13892     case 'y':   // crrc
13893       return std::make_pair(0U, &PPC::CRRCRegClass);
13894     }
13895   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
13896     // An individual CR bit.
13897     return std::make_pair(0U, &PPC::CRBITRCRegClass);
13898   } else if ((Constraint == "wa" || Constraint == "wd" ||
13899              Constraint == "wf" || Constraint == "wi") &&
13900              Subtarget.hasVSX()) {
13901     return std::make_pair(0U, &PPC::VSRCRegClass);
13902   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
13903     if (VT == MVT::f32 && Subtarget.hasP8Vector())
13904       return std::make_pair(0U, &PPC::VSSRCRegClass);
13905     else
13906       return std::make_pair(0U, &PPC::VSFRCRegClass);
13907   }
13908 
13909   std::pair<unsigned, const TargetRegisterClass *> R =
13910       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
13911 
13912   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
13913   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
13914   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
13915   // register.
13916   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
13917   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
13918   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
13919       PPC::GPRCRegClass.contains(R.first))
13920     return std::make_pair(TRI->getMatchingSuperReg(R.first,
13921                             PPC::sub_32, &PPC::G8RCRegClass),
13922                           &PPC::G8RCRegClass);
13923 
13924   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
13925   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
13926     R.first = PPC::CR0;
13927     R.second = &PPC::CRRCRegClass;
13928   }
13929 
13930   return R;
13931 }
13932 
13933 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13934 /// vector.  If it is invalid, don't add anything to Ops.
13935 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13936                                                      std::string &Constraint,
13937                                                      std::vector<SDValue>&Ops,
13938                                                      SelectionDAG &DAG) const {
13939   SDValue Result;
13940 
13941   // Only support length 1 constraints.
13942   if (Constraint.length() > 1) return;
13943 
13944   char Letter = Constraint[0];
13945   switch (Letter) {
13946   default: break;
13947   case 'I':
13948   case 'J':
13949   case 'K':
13950   case 'L':
13951   case 'M':
13952   case 'N':
13953   case 'O':
13954   case 'P': {
13955     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
13956     if (!CST) return; // Must be an immediate to match.
13957     SDLoc dl(Op);
13958     int64_t Value = CST->getSExtValue();
13959     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
13960                          // numbers are printed as such.
13961     switch (Letter) {
13962     default: llvm_unreachable("Unknown constraint letter!");
13963     case 'I':  // "I" is a signed 16-bit constant.
13964       if (isInt<16>(Value))
13965         Result = DAG.getTargetConstant(Value, dl, TCVT);
13966       break;
13967     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
13968       if (isShiftedUInt<16, 16>(Value))
13969         Result = DAG.getTargetConstant(Value, dl, TCVT);
13970       break;
13971     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
13972       if (isShiftedInt<16, 16>(Value))
13973         Result = DAG.getTargetConstant(Value, dl, TCVT);
13974       break;
13975     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
13976       if (isUInt<16>(Value))
13977         Result = DAG.getTargetConstant(Value, dl, TCVT);
13978       break;
13979     case 'M':  // "M" is a constant that is greater than 31.
13980       if (Value > 31)
13981         Result = DAG.getTargetConstant(Value, dl, TCVT);
13982       break;
13983     case 'N':  // "N" is a positive constant that is an exact power of two.
13984       if (Value > 0 && isPowerOf2_64(Value))
13985         Result = DAG.getTargetConstant(Value, dl, TCVT);
13986       break;
13987     case 'O':  // "O" is the constant zero.
13988       if (Value == 0)
13989         Result = DAG.getTargetConstant(Value, dl, TCVT);
13990       break;
13991     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
13992       if (isInt<16>(-Value))
13993         Result = DAG.getTargetConstant(Value, dl, TCVT);
13994       break;
13995     }
13996     break;
13997   }
13998   }
13999 
14000   if (Result.getNode()) {
14001     Ops.push_back(Result);
14002     return;
14003   }
14004 
14005   // Handle standard constraint letters.
14006   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14007 }
14008 
14009 // isLegalAddressingMode - Return true if the addressing mode represented
14010 // by AM is legal for this target, for a load/store of the specified type.
14011 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14012                                               const AddrMode &AM, Type *Ty,
14013                                               unsigned AS, Instruction *I) const {
14014   // PPC does not allow r+i addressing modes for vectors!
14015   if (Ty->isVectorTy() && AM.BaseOffs != 0)
14016     return false;
14017 
14018   // PPC allows a sign-extended 16-bit immediate field.
14019   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
14020     return false;
14021 
14022   // No global is ever allowed as a base.
14023   if (AM.BaseGV)
14024     return false;
14025 
14026   // PPC only support r+r,
14027   switch (AM.Scale) {
14028   case 0:  // "r+i" or just "i", depending on HasBaseReg.
14029     break;
14030   case 1:
14031     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
14032       return false;
14033     // Otherwise we have r+r or r+i.
14034     break;
14035   case 2:
14036     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
14037       return false;
14038     // Allow 2*r as r+r.
14039     break;
14040   default:
14041     // No other scales are supported.
14042     return false;
14043   }
14044 
14045   return true;
14046 }
14047 
14048 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
14049                                            SelectionDAG &DAG) const {
14050   MachineFunction &MF = DAG.getMachineFunction();
14051   MachineFrameInfo &MFI = MF.getFrameInfo();
14052   MFI.setReturnAddressIsTaken(true);
14053 
14054   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14055     return SDValue();
14056 
14057   SDLoc dl(Op);
14058   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14059 
14060   // Make sure the function does not optimize away the store of the RA to
14061   // the stack.
14062   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
14063   FuncInfo->setLRStoreRequired();
14064   bool isPPC64 = Subtarget.isPPC64();
14065   auto PtrVT = getPointerTy(MF.getDataLayout());
14066 
14067   if (Depth > 0) {
14068     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14069     SDValue Offset =
14070         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
14071                         isPPC64 ? MVT::i64 : MVT::i32);
14072     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14073                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
14074                        MachinePointerInfo());
14075   }
14076 
14077   // Just load the return address off the stack.
14078   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
14079   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
14080                      MachinePointerInfo());
14081 }
14082 
14083 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
14084                                           SelectionDAG &DAG) const {
14085   SDLoc dl(Op);
14086   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14087 
14088   MachineFunction &MF = DAG.getMachineFunction();
14089   MachineFrameInfo &MFI = MF.getFrameInfo();
14090   MFI.setFrameAddressIsTaken(true);
14091 
14092   EVT PtrVT = getPointerTy(MF.getDataLayout());
14093   bool isPPC64 = PtrVT == MVT::i64;
14094 
14095   // Naked functions never have a frame pointer, and so we use r1. For all
14096   // other functions, this decision must be delayed until during PEI.
14097   unsigned FrameReg;
14098   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
14099     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
14100   else
14101     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
14102 
14103   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
14104                                          PtrVT);
14105   while (Depth--)
14106     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
14107                             FrameAddr, MachinePointerInfo());
14108   return FrameAddr;
14109 }
14110 
14111 // FIXME? Maybe this could be a TableGen attribute on some registers and
14112 // this table could be generated automatically from RegInfo.
14113 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
14114                                               SelectionDAG &DAG) const {
14115   bool isPPC64 = Subtarget.isPPC64();
14116   bool isDarwinABI = Subtarget.isDarwinABI();
14117 
14118   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
14119       (!isPPC64 && VT != MVT::i32))
14120     report_fatal_error("Invalid register global variable type");
14121 
14122   bool is64Bit = isPPC64 && VT == MVT::i64;
14123   unsigned Reg = StringSwitch<unsigned>(RegName)
14124                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
14125                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
14126                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
14127                                   (is64Bit ? PPC::X13 : PPC::R13))
14128                    .Default(0);
14129 
14130   if (Reg)
14131     return Reg;
14132   report_fatal_error("Invalid register name global variable");
14133 }
14134 
14135 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
14136   // 32-bit SVR4 ABI access everything as got-indirect.
14137   if (Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
14138     return true;
14139 
14140   CodeModel::Model CModel = getTargetMachine().getCodeModel();
14141   // If it is small or large code model, module locals are accessed
14142   // indirectly by loading their address from .toc/.got. The difference
14143   // is that for large code model we have ADDISTocHa + LDtocL and for
14144   // small code model we simply have LDtoc.
14145   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
14146     return true;
14147 
14148   // JumpTable and BlockAddress are accessed as got-indirect.
14149   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
14150     return true;
14151 
14152   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
14153     const GlobalValue *GV = G->getGlobal();
14154     unsigned char GVFlags = Subtarget.classifyGlobalReference(GV);
14155     // The NLP flag indicates that a global access has to use an
14156     // extra indirection.
14157     if (GVFlags & PPCII::MO_NLP_FLAG)
14158       return true;
14159   }
14160 
14161   return false;
14162 }
14163 
14164 bool
14165 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14166   // The PowerPC target isn't yet aware of offsets.
14167   return false;
14168 }
14169 
14170 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14171                                            const CallInst &I,
14172                                            MachineFunction &MF,
14173                                            unsigned Intrinsic) const {
14174   switch (Intrinsic) {
14175   case Intrinsic::ppc_qpx_qvlfd:
14176   case Intrinsic::ppc_qpx_qvlfs:
14177   case Intrinsic::ppc_qpx_qvlfcd:
14178   case Intrinsic::ppc_qpx_qvlfcs:
14179   case Intrinsic::ppc_qpx_qvlfiwa:
14180   case Intrinsic::ppc_qpx_qvlfiwz:
14181   case Intrinsic::ppc_altivec_lvx:
14182   case Intrinsic::ppc_altivec_lvxl:
14183   case Intrinsic::ppc_altivec_lvebx:
14184   case Intrinsic::ppc_altivec_lvehx:
14185   case Intrinsic::ppc_altivec_lvewx:
14186   case Intrinsic::ppc_vsx_lxvd2x:
14187   case Intrinsic::ppc_vsx_lxvw4x: {
14188     EVT VT;
14189     switch (Intrinsic) {
14190     case Intrinsic::ppc_altivec_lvebx:
14191       VT = MVT::i8;
14192       break;
14193     case Intrinsic::ppc_altivec_lvehx:
14194       VT = MVT::i16;
14195       break;
14196     case Intrinsic::ppc_altivec_lvewx:
14197       VT = MVT::i32;
14198       break;
14199     case Intrinsic::ppc_vsx_lxvd2x:
14200       VT = MVT::v2f64;
14201       break;
14202     case Intrinsic::ppc_qpx_qvlfd:
14203       VT = MVT::v4f64;
14204       break;
14205     case Intrinsic::ppc_qpx_qvlfs:
14206       VT = MVT::v4f32;
14207       break;
14208     case Intrinsic::ppc_qpx_qvlfcd:
14209       VT = MVT::v2f64;
14210       break;
14211     case Intrinsic::ppc_qpx_qvlfcs:
14212       VT = MVT::v2f32;
14213       break;
14214     default:
14215       VT = MVT::v4i32;
14216       break;
14217     }
14218 
14219     Info.opc = ISD::INTRINSIC_W_CHAIN;
14220     Info.memVT = VT;
14221     Info.ptrVal = I.getArgOperand(0);
14222     Info.offset = -VT.getStoreSize()+1;
14223     Info.size = 2*VT.getStoreSize()-1;
14224     Info.align = 1;
14225     Info.flags = MachineMemOperand::MOLoad;
14226     return true;
14227   }
14228   case Intrinsic::ppc_qpx_qvlfda:
14229   case Intrinsic::ppc_qpx_qvlfsa:
14230   case Intrinsic::ppc_qpx_qvlfcda:
14231   case Intrinsic::ppc_qpx_qvlfcsa:
14232   case Intrinsic::ppc_qpx_qvlfiwaa:
14233   case Intrinsic::ppc_qpx_qvlfiwza: {
14234     EVT VT;
14235     switch (Intrinsic) {
14236     case Intrinsic::ppc_qpx_qvlfda:
14237       VT = MVT::v4f64;
14238       break;
14239     case Intrinsic::ppc_qpx_qvlfsa:
14240       VT = MVT::v4f32;
14241       break;
14242     case Intrinsic::ppc_qpx_qvlfcda:
14243       VT = MVT::v2f64;
14244       break;
14245     case Intrinsic::ppc_qpx_qvlfcsa:
14246       VT = MVT::v2f32;
14247       break;
14248     default:
14249       VT = MVT::v4i32;
14250       break;
14251     }
14252 
14253     Info.opc = ISD::INTRINSIC_W_CHAIN;
14254     Info.memVT = VT;
14255     Info.ptrVal = I.getArgOperand(0);
14256     Info.offset = 0;
14257     Info.size = VT.getStoreSize();
14258     Info.align = 1;
14259     Info.flags = MachineMemOperand::MOLoad;
14260     return true;
14261   }
14262   case Intrinsic::ppc_qpx_qvstfd:
14263   case Intrinsic::ppc_qpx_qvstfs:
14264   case Intrinsic::ppc_qpx_qvstfcd:
14265   case Intrinsic::ppc_qpx_qvstfcs:
14266   case Intrinsic::ppc_qpx_qvstfiw:
14267   case Intrinsic::ppc_altivec_stvx:
14268   case Intrinsic::ppc_altivec_stvxl:
14269   case Intrinsic::ppc_altivec_stvebx:
14270   case Intrinsic::ppc_altivec_stvehx:
14271   case Intrinsic::ppc_altivec_stvewx:
14272   case Intrinsic::ppc_vsx_stxvd2x:
14273   case Intrinsic::ppc_vsx_stxvw4x: {
14274     EVT VT;
14275     switch (Intrinsic) {
14276     case Intrinsic::ppc_altivec_stvebx:
14277       VT = MVT::i8;
14278       break;
14279     case Intrinsic::ppc_altivec_stvehx:
14280       VT = MVT::i16;
14281       break;
14282     case Intrinsic::ppc_altivec_stvewx:
14283       VT = MVT::i32;
14284       break;
14285     case Intrinsic::ppc_vsx_stxvd2x:
14286       VT = MVT::v2f64;
14287       break;
14288     case Intrinsic::ppc_qpx_qvstfd:
14289       VT = MVT::v4f64;
14290       break;
14291     case Intrinsic::ppc_qpx_qvstfs:
14292       VT = MVT::v4f32;
14293       break;
14294     case Intrinsic::ppc_qpx_qvstfcd:
14295       VT = MVT::v2f64;
14296       break;
14297     case Intrinsic::ppc_qpx_qvstfcs:
14298       VT = MVT::v2f32;
14299       break;
14300     default:
14301       VT = MVT::v4i32;
14302       break;
14303     }
14304 
14305     Info.opc = ISD::INTRINSIC_VOID;
14306     Info.memVT = VT;
14307     Info.ptrVal = I.getArgOperand(1);
14308     Info.offset = -VT.getStoreSize()+1;
14309     Info.size = 2*VT.getStoreSize()-1;
14310     Info.align = 1;
14311     Info.flags = MachineMemOperand::MOStore;
14312     return true;
14313   }
14314   case Intrinsic::ppc_qpx_qvstfda:
14315   case Intrinsic::ppc_qpx_qvstfsa:
14316   case Intrinsic::ppc_qpx_qvstfcda:
14317   case Intrinsic::ppc_qpx_qvstfcsa:
14318   case Intrinsic::ppc_qpx_qvstfiwa: {
14319     EVT VT;
14320     switch (Intrinsic) {
14321     case Intrinsic::ppc_qpx_qvstfda:
14322       VT = MVT::v4f64;
14323       break;
14324     case Intrinsic::ppc_qpx_qvstfsa:
14325       VT = MVT::v4f32;
14326       break;
14327     case Intrinsic::ppc_qpx_qvstfcda:
14328       VT = MVT::v2f64;
14329       break;
14330     case Intrinsic::ppc_qpx_qvstfcsa:
14331       VT = MVT::v2f32;
14332       break;
14333     default:
14334       VT = MVT::v4i32;
14335       break;
14336     }
14337 
14338     Info.opc = ISD::INTRINSIC_VOID;
14339     Info.memVT = VT;
14340     Info.ptrVal = I.getArgOperand(1);
14341     Info.offset = 0;
14342     Info.size = VT.getStoreSize();
14343     Info.align = 1;
14344     Info.flags = MachineMemOperand::MOStore;
14345     return true;
14346   }
14347   default:
14348     break;
14349   }
14350 
14351   return false;
14352 }
14353 
14354 /// getOptimalMemOpType - Returns the target specific optimal type for load
14355 /// and store operations as a result of memset, memcpy, and memmove
14356 /// lowering. If DstAlign is zero that means it's safe to destination
14357 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
14358 /// means there isn't a need to check it against alignment requirement,
14359 /// probably because the source does not need to be loaded. If 'IsMemset' is
14360 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
14361 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
14362 /// source is constant so it does not need to be loaded.
14363 /// It returns EVT::Other if the type should be determined using generic
14364 /// target-independent logic.
14365 EVT PPCTargetLowering::getOptimalMemOpType(
14366     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
14367     bool ZeroMemset, bool MemcpyStrSrc,
14368     const AttributeList &FuncAttributes) const {
14369   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
14370     // When expanding a memset, require at least two QPX instructions to cover
14371     // the cost of loading the value to be stored from the constant pool.
14372     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
14373        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
14374         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
14375       return MVT::v4f64;
14376     }
14377 
14378     // We should use Altivec/VSX loads and stores when available. For unaligned
14379     // addresses, unaligned VSX loads are only fast starting with the P8.
14380     if (Subtarget.hasAltivec() && Size >= 16 &&
14381         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
14382          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
14383       return MVT::v4i32;
14384   }
14385 
14386   if (Subtarget.isPPC64()) {
14387     return MVT::i64;
14388   }
14389 
14390   return MVT::i32;
14391 }
14392 
14393 /// Returns true if it is beneficial to convert a load of a constant
14394 /// to just the constant itself.
14395 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
14396                                                           Type *Ty) const {
14397   assert(Ty->isIntegerTy());
14398 
14399   unsigned BitSize = Ty->getPrimitiveSizeInBits();
14400   return !(BitSize == 0 || BitSize > 64);
14401 }
14402 
14403 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14404   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14405     return false;
14406   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14407   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14408   return NumBits1 == 64 && NumBits2 == 32;
14409 }
14410 
14411 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14412   if (!VT1.isInteger() || !VT2.isInteger())
14413     return false;
14414   unsigned NumBits1 = VT1.getSizeInBits();
14415   unsigned NumBits2 = VT2.getSizeInBits();
14416   return NumBits1 == 64 && NumBits2 == 32;
14417 }
14418 
14419 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14420   // Generally speaking, zexts are not free, but they are free when they can be
14421   // folded with other operations.
14422   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
14423     EVT MemVT = LD->getMemoryVT();
14424     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
14425          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
14426         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
14427          LD->getExtensionType() == ISD::ZEXTLOAD))
14428       return true;
14429   }
14430 
14431   // FIXME: Add other cases...
14432   //  - 32-bit shifts with a zext to i64
14433   //  - zext after ctlz, bswap, etc.
14434   //  - zext after and by a constant mask
14435 
14436   return TargetLowering::isZExtFree(Val, VT2);
14437 }
14438 
14439 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
14440   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
14441          "invalid fpext types");
14442   // Extending to float128 is not free.
14443   if (DestVT == MVT::f128)
14444     return false;
14445   return true;
14446 }
14447 
14448 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14449   return isInt<16>(Imm) || isUInt<16>(Imm);
14450 }
14451 
14452 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
14453   return isInt<16>(Imm) || isUInt<16>(Imm);
14454 }
14455 
14456 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
14457                                                        unsigned,
14458                                                        unsigned,
14459                                                        bool *Fast) const {
14460   if (DisablePPCUnaligned)
14461     return false;
14462 
14463   // PowerPC supports unaligned memory access for simple non-vector types.
14464   // Although accessing unaligned addresses is not as efficient as accessing
14465   // aligned addresses, it is generally more efficient than manual expansion,
14466   // and generally only traps for software emulation when crossing page
14467   // boundaries.
14468 
14469   if (!VT.isSimple())
14470     return false;
14471 
14472   if (VT.getSimpleVT().isVector()) {
14473     if (Subtarget.hasVSX()) {
14474       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
14475           VT != MVT::v4f32 && VT != MVT::v4i32)
14476         return false;
14477     } else {
14478       return false;
14479     }
14480   }
14481 
14482   if (VT == MVT::ppcf128)
14483     return false;
14484 
14485   if (Fast)
14486     *Fast = true;
14487 
14488   return true;
14489 }
14490 
14491 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14492   VT = VT.getScalarType();
14493 
14494   if (!VT.isSimple())
14495     return false;
14496 
14497   switch (VT.getSimpleVT().SimpleTy) {
14498   case MVT::f32:
14499   case MVT::f64:
14500     return true;
14501   case MVT::f128:
14502     return (EnableQuadPrecision && Subtarget.hasP9Vector());
14503   default:
14504     break;
14505   }
14506 
14507   return false;
14508 }
14509 
14510 const MCPhysReg *
14511 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
14512   // LR is a callee-save register, but we must treat it as clobbered by any call
14513   // site. Hence we include LR in the scratch registers, which are in turn added
14514   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
14515   // to CTR, which is used by any indirect call.
14516   static const MCPhysReg ScratchRegs[] = {
14517     PPC::X12, PPC::LR8, PPC::CTR8, 0
14518   };
14519 
14520   return ScratchRegs;
14521 }
14522 
14523 unsigned PPCTargetLowering::getExceptionPointerRegister(
14524     const Constant *PersonalityFn) const {
14525   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
14526 }
14527 
14528 unsigned PPCTargetLowering::getExceptionSelectorRegister(
14529     const Constant *PersonalityFn) const {
14530   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
14531 }
14532 
14533 bool
14534 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
14535                      EVT VT , unsigned DefinedValues) const {
14536   if (VT == MVT::v2i64)
14537     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
14538 
14539   if (Subtarget.hasVSX() || Subtarget.hasQPX())
14540     return true;
14541 
14542   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
14543 }
14544 
14545 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
14546   if (DisableILPPref || Subtarget.enableMachineScheduler())
14547     return TargetLowering::getSchedulingPreference(N);
14548 
14549   return Sched::ILP;
14550 }
14551 
14552 // Create a fast isel object.
14553 FastISel *
14554 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
14555                                   const TargetLibraryInfo *LibInfo) const {
14556   return PPC::createFastISel(FuncInfo, LibInfo);
14557 }
14558 
14559 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14560   if (Subtarget.isDarwinABI()) return;
14561   if (!Subtarget.isPPC64()) return;
14562 
14563   // Update IsSplitCSR in PPCFunctionInfo
14564   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
14565   PFI->setIsSplitCSR(true);
14566 }
14567 
14568 void PPCTargetLowering::insertCopiesSplitCSR(
14569   MachineBasicBlock *Entry,
14570   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14571   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
14572   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14573   if (!IStart)
14574     return;
14575 
14576   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
14577   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14578   MachineBasicBlock::iterator MBBI = Entry->begin();
14579   for (const MCPhysReg *I = IStart; *I; ++I) {
14580     const TargetRegisterClass *RC = nullptr;
14581     if (PPC::G8RCRegClass.contains(*I))
14582       RC = &PPC::G8RCRegClass;
14583     else if (PPC::F8RCRegClass.contains(*I))
14584       RC = &PPC::F8RCRegClass;
14585     else if (PPC::CRRCRegClass.contains(*I))
14586       RC = &PPC::CRRCRegClass;
14587     else if (PPC::VRRCRegClass.contains(*I))
14588       RC = &PPC::VRRCRegClass;
14589     else
14590       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14591 
14592     unsigned NewVR = MRI->createVirtualRegister(RC);
14593     // Create copy from CSR to a virtual register.
14594     // FIXME: this currently does not emit CFI pseudo-instructions, it works
14595     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14596     // nounwind. If we want to generalize this later, we may need to emit
14597     // CFI pseudo-instructions.
14598     assert(Entry->getParent()->getFunction().hasFnAttribute(
14599              Attribute::NoUnwind) &&
14600            "Function should be nounwind in insertCopiesSplitCSR!");
14601     Entry->addLiveIn(*I);
14602     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14603       .addReg(*I);
14604 
14605     // Insert the copy-back instructions right before the terminator.
14606     for (auto *Exit : Exits)
14607       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14608               TII->get(TargetOpcode::COPY), *I)
14609         .addReg(NewVR);
14610   }
14611 }
14612 
14613 // Override to enable LOAD_STACK_GUARD lowering on Linux.
14614 bool PPCTargetLowering::useLoadStackGuardNode() const {
14615   if (!Subtarget.isTargetLinux())
14616     return TargetLowering::useLoadStackGuardNode();
14617   return true;
14618 }
14619 
14620 // Override to disable global variable loading on Linux.
14621 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
14622   if (!Subtarget.isTargetLinux())
14623     return TargetLowering::insertSSPDeclarations(M);
14624 }
14625 
14626 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
14627                                      bool ForCodeSize) const {
14628   if (!VT.isSimple() || !Subtarget.hasVSX())
14629     return false;
14630 
14631   switch(VT.getSimpleVT().SimpleTy) {
14632   default:
14633     // For FP types that are currently not supported by PPC backend, return
14634     // false. Examples: f16, f80.
14635     return false;
14636   case MVT::f32:
14637   case MVT::f64:
14638   case MVT::ppcf128:
14639     return Imm.isPosZero();
14640   }
14641 }
14642 
14643 // For vector shift operation op, fold
14644 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
14645 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
14646                                   SelectionDAG &DAG) {
14647   SDValue N0 = N->getOperand(0);
14648   SDValue N1 = N->getOperand(1);
14649   EVT VT = N0.getValueType();
14650   unsigned OpSizeInBits = VT.getScalarSizeInBits();
14651   unsigned Opcode = N->getOpcode();
14652   unsigned TargetOpcode;
14653 
14654   switch (Opcode) {
14655   default:
14656     llvm_unreachable("Unexpected shift operation");
14657   case ISD::SHL:
14658     TargetOpcode = PPCISD::SHL;
14659     break;
14660   case ISD::SRL:
14661     TargetOpcode = PPCISD::SRL;
14662     break;
14663   case ISD::SRA:
14664     TargetOpcode = PPCISD::SRA;
14665     break;
14666   }
14667 
14668   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
14669       N1->getOpcode() == ISD::AND)
14670     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
14671       if (Mask->getZExtValue() == OpSizeInBits - 1)
14672         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
14673 
14674   return SDValue();
14675 }
14676 
14677 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
14678   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14679     return Value;
14680 
14681   SDValue N0 = N->getOperand(0);
14682   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
14683   if (!Subtarget.isISA3_0() ||
14684       N0.getOpcode() != ISD::SIGN_EXTEND ||
14685       N0.getOperand(0).getValueType() != MVT::i32 ||
14686       CN1 == nullptr || N->getValueType(0) != MVT::i64)
14687     return SDValue();
14688 
14689   // We can't save an operation here if the value is already extended, and
14690   // the existing shift is easier to combine.
14691   SDValue ExtsSrc = N0.getOperand(0);
14692   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
14693       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
14694     return SDValue();
14695 
14696   SDLoc DL(N0);
14697   SDValue ShiftBy = SDValue(CN1, 0);
14698   // We want the shift amount to be i32 on the extswli, but the shift could
14699   // have an i64.
14700   if (ShiftBy.getValueType() == MVT::i64)
14701     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
14702 
14703   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
14704                          ShiftBy);
14705 }
14706 
14707 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
14708   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14709     return Value;
14710 
14711   return SDValue();
14712 }
14713 
14714 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
14715   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14716     return Value;
14717 
14718   return SDValue();
14719 }
14720 
14721 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
14722 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
14723 // When C is zero, the equation (addi Z, -C) can be simplified to Z
14724 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
14725 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
14726                                  const PPCSubtarget &Subtarget) {
14727   if (!Subtarget.isPPC64())
14728     return SDValue();
14729 
14730   SDValue LHS = N->getOperand(0);
14731   SDValue RHS = N->getOperand(1);
14732 
14733   auto isZextOfCompareWithConstant = [](SDValue Op) {
14734     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
14735         Op.getValueType() != MVT::i64)
14736       return false;
14737 
14738     SDValue Cmp = Op.getOperand(0);
14739     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
14740         Cmp.getOperand(0).getValueType() != MVT::i64)
14741       return false;
14742 
14743     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
14744       int64_t NegConstant = 0 - Constant->getSExtValue();
14745       // Due to the limitations of the addi instruction,
14746       // -C is required to be [-32768, 32767].
14747       return isInt<16>(NegConstant);
14748     }
14749 
14750     return false;
14751   };
14752 
14753   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
14754   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
14755 
14756   // If there is a pattern, canonicalize a zext operand to the RHS.
14757   if (LHSHasPattern && !RHSHasPattern)
14758     std::swap(LHS, RHS);
14759   else if (!LHSHasPattern && !RHSHasPattern)
14760     return SDValue();
14761 
14762   SDLoc DL(N);
14763   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
14764   SDValue Cmp = RHS.getOperand(0);
14765   SDValue Z = Cmp.getOperand(0);
14766   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
14767 
14768   assert(Constant && "Constant Should not be a null pointer.");
14769   int64_t NegConstant = 0 - Constant->getSExtValue();
14770 
14771   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
14772   default: break;
14773   case ISD::SETNE: {
14774     //                                 when C == 0
14775     //                             --> addze X, (addic Z, -1).carry
14776     //                            /
14777     // add X, (zext(setne Z, C))--
14778     //                            \    when -32768 <= -C <= 32767 && C != 0
14779     //                             --> addze X, (addic (addi Z, -C), -1).carry
14780     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
14781                               DAG.getConstant(NegConstant, DL, MVT::i64));
14782     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
14783     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
14784                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
14785     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
14786                        SDValue(Addc.getNode(), 1));
14787     }
14788   case ISD::SETEQ: {
14789     //                                 when C == 0
14790     //                             --> addze X, (subfic Z, 0).carry
14791     //                            /
14792     // add X, (zext(sete  Z, C))--
14793     //                            \    when -32768 <= -C <= 32767 && C != 0
14794     //                             --> addze X, (subfic (addi Z, -C), 0).carry
14795     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
14796                               DAG.getConstant(NegConstant, DL, MVT::i64));
14797     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
14798     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
14799                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
14800     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
14801                        SDValue(Subc.getNode(), 1));
14802     }
14803   }
14804 
14805   return SDValue();
14806 }
14807 
14808 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
14809   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
14810     return Value;
14811 
14812   return SDValue();
14813 }
14814 
14815 // Detect TRUNCATE operations on bitcasts of float128 values.
14816 // What we are looking for here is the situtation where we extract a subset
14817 // of bits from a 128 bit float.
14818 // This can be of two forms:
14819 // 1) BITCAST of f128 feeding TRUNCATE
14820 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
14821 // The reason this is required is because we do not have a legal i128 type
14822 // and so we want to prevent having to store the f128 and then reload part
14823 // of it.
14824 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
14825                                            DAGCombinerInfo &DCI) const {
14826   // If we are using CRBits then try that first.
14827   if (Subtarget.useCRBits()) {
14828     // Check if CRBits did anything and return that if it did.
14829     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
14830       return CRTruncValue;
14831   }
14832 
14833   SDLoc dl(N);
14834   SDValue Op0 = N->getOperand(0);
14835 
14836   // Looking for a truncate of i128 to i64.
14837   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
14838     return SDValue();
14839 
14840   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
14841 
14842   // SRL feeding TRUNCATE.
14843   if (Op0.getOpcode() == ISD::SRL) {
14844     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
14845     // The right shift has to be by 64 bits.
14846     if (!ConstNode || ConstNode->getZExtValue() != 64)
14847       return SDValue();
14848 
14849     // Switch the element number to extract.
14850     EltToExtract = EltToExtract ? 0 : 1;
14851     // Update Op0 past the SRL.
14852     Op0 = Op0.getOperand(0);
14853   }
14854 
14855   // BITCAST feeding a TRUNCATE possibly via SRL.
14856   if (Op0.getOpcode() == ISD::BITCAST &&
14857       Op0.getValueType() == MVT::i128 &&
14858       Op0.getOperand(0).getValueType() == MVT::f128) {
14859     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
14860     return DCI.DAG.getNode(
14861         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
14862         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
14863   }
14864   return SDValue();
14865 }
14866 
14867 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
14868   SelectionDAG &DAG = DCI.DAG;
14869 
14870   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
14871   if (!ConstOpOrElement)
14872     return SDValue();
14873 
14874   // An imul is usually smaller than the alternative sequence for legal type.
14875   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
14876       isOperationLegal(ISD::MUL, N->getValueType(0)))
14877     return SDValue();
14878 
14879   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
14880     switch (this->Subtarget.getDarwinDirective()) {
14881     default:
14882       // TODO: enhance the condition for subtarget before pwr8
14883       return false;
14884     case PPC::DIR_PWR8:
14885       //  type        mul     add    shl
14886       // scalar        4       1      1
14887       // vector        7       2      2
14888       return true;
14889     case PPC::DIR_PWR9:
14890       //  type        mul     add    shl
14891       // scalar        5       2      2
14892       // vector        7       2      2
14893 
14894       // The cycle RATIO of related operations are showed as a table above.
14895       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
14896       // scalar and vector type. For 2 instrs patterns, add/sub + shl
14897       // are 4, it is always profitable; but for 3 instrs patterns
14898       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
14899       // So we should only do it for vector type.
14900       return IsAddOne && IsNeg ? VT.isVector() : true;
14901     }
14902   };
14903 
14904   EVT VT = N->getValueType(0);
14905   SDLoc DL(N);
14906 
14907   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
14908   bool IsNeg = MulAmt.isNegative();
14909   APInt MulAmtAbs = MulAmt.abs();
14910 
14911   if ((MulAmtAbs - 1).isPowerOf2()) {
14912     // (mul x, 2^N + 1) => (add (shl x, N), x)
14913     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
14914 
14915     if (!IsProfitable(IsNeg, true, VT))
14916       return SDValue();
14917 
14918     SDValue Op0 = N->getOperand(0);
14919     SDValue Op1 =
14920         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14921                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
14922     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
14923 
14924     if (!IsNeg)
14925       return Res;
14926 
14927     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
14928   } else if ((MulAmtAbs + 1).isPowerOf2()) {
14929     // (mul x, 2^N - 1) => (sub (shl x, N), x)
14930     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
14931 
14932     if (!IsProfitable(IsNeg, false, VT))
14933       return SDValue();
14934 
14935     SDValue Op0 = N->getOperand(0);
14936     SDValue Op1 =
14937         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14938                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
14939 
14940     if (!IsNeg)
14941       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
14942     else
14943       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
14944 
14945   } else {
14946     return SDValue();
14947   }
14948 }
14949 
14950 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
14951   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
14952   if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64())
14953     return false;
14954 
14955   // If not a tail call then no need to proceed.
14956   if (!CI->isTailCall())
14957     return false;
14958 
14959   // If tail calls are disabled for the caller then we are done.
14960   const Function *Caller = CI->getParent()->getParent();
14961   auto Attr = Caller->getFnAttribute("disable-tail-calls");
14962   if (Attr.getValueAsString() == "true")
14963     return false;
14964 
14965   // If sibling calls have been disabled and tail-calls aren't guaranteed
14966   // there is no reason to duplicate.
14967   auto &TM = getTargetMachine();
14968   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
14969     return false;
14970 
14971   // Can't tail call a function called indirectly, or if it has variadic args.
14972   const Function *Callee = CI->getCalledFunction();
14973   if (!Callee || Callee->isVarArg())
14974     return false;
14975 
14976   // Make sure the callee and caller calling conventions are eligible for tco.
14977   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
14978                                            CI->getCallingConv()))
14979       return false;
14980 
14981   // If the function is local then we have a good chance at tail-calling it
14982   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
14983 }
14984 
14985 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
14986   if (!Subtarget.hasVSX())
14987     return false;
14988   if (Subtarget.hasP9Vector() && VT == MVT::f128)
14989     return true;
14990   return VT == MVT::f32 || VT == MVT::f64 ||
14991     VT == MVT::v4f32 || VT == MVT::v2f64;
14992 }
14993 
14994 bool PPCTargetLowering::
14995 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
14996   const Value *Mask = AndI.getOperand(1);
14997   // If the mask is suitable for andi. or andis. we should sink the and.
14998   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
14999     // Can't handle constants wider than 64-bits.
15000     if (CI->getBitWidth() > 64)
15001       return false;
15002     int64_t ConstVal = CI->getZExtValue();
15003     return isUInt<16>(ConstVal) ||
15004       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
15005   }
15006 
15007   // For non-constant masks, we can always use the record-form and.
15008   return true;
15009 }
15010 
15011 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
15012 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
15013 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
15014 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
15015 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
15016 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
15017   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
15018   assert(Subtarget.hasP9Altivec() &&
15019          "Only combine this when P9 altivec supported!");
15020   EVT VT = N->getValueType(0);
15021   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15022     return SDValue();
15023 
15024   SelectionDAG &DAG = DCI.DAG;
15025   SDLoc dl(N);
15026   if (N->getOperand(0).getOpcode() == ISD::SUB) {
15027     // Even for signed integers, if it's known to be positive (as signed
15028     // integer) due to zero-extended inputs.
15029     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
15030     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
15031     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
15032          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
15033         (SubOpcd1 == ISD::ZERO_EXTEND ||
15034          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
15035       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15036                          N->getOperand(0)->getOperand(0),
15037                          N->getOperand(0)->getOperand(1),
15038                          DAG.getTargetConstant(0, dl, MVT::i32));
15039     }
15040 
15041     // For type v4i32, it can be optimized with xvnegsp + vabsduw
15042     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
15043         N->getOperand(0).hasOneUse()) {
15044       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15045                          N->getOperand(0)->getOperand(0),
15046                          N->getOperand(0)->getOperand(1),
15047                          DAG.getTargetConstant(1, dl, MVT::i32));
15048     }
15049   }
15050 
15051   return SDValue();
15052 }
15053 
15054 // For type v4i32/v8ii16/v16i8, transform
15055 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
15056 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
15057 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
15058 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
15059 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
15060                                           DAGCombinerInfo &DCI) const {
15061   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
15062   assert(Subtarget.hasP9Altivec() &&
15063          "Only combine this when P9 altivec supported!");
15064 
15065   SelectionDAG &DAG = DCI.DAG;
15066   SDLoc dl(N);
15067   SDValue Cond = N->getOperand(0);
15068   SDValue TrueOpnd = N->getOperand(1);
15069   SDValue FalseOpnd = N->getOperand(2);
15070   EVT VT = N->getOperand(1).getValueType();
15071 
15072   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
15073       FalseOpnd.getOpcode() != ISD::SUB)
15074     return SDValue();
15075 
15076   // ABSD only available for type v4i32/v8i16/v16i8
15077   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15078     return SDValue();
15079 
15080   // At least to save one more dependent computation
15081   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
15082     return SDValue();
15083 
15084   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15085 
15086   // Can only handle unsigned comparison here
15087   switch (CC) {
15088   default:
15089     return SDValue();
15090   case ISD::SETUGT:
15091   case ISD::SETUGE:
15092     break;
15093   case ISD::SETULT:
15094   case ISD::SETULE:
15095     std::swap(TrueOpnd, FalseOpnd);
15096     break;
15097   }
15098 
15099   SDValue CmpOpnd1 = Cond.getOperand(0);
15100   SDValue CmpOpnd2 = Cond.getOperand(1);
15101 
15102   // SETCC CmpOpnd1 CmpOpnd2 cond
15103   // TrueOpnd = CmpOpnd1 - CmpOpnd2
15104   // FalseOpnd = CmpOpnd2 - CmpOpnd1
15105   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
15106       TrueOpnd.getOperand(1) == CmpOpnd2 &&
15107       FalseOpnd.getOperand(0) == CmpOpnd2 &&
15108       FalseOpnd.getOperand(1) == CmpOpnd1) {
15109     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
15110                        CmpOpnd1, CmpOpnd2,
15111                        DAG.getTargetConstant(0, dl, MVT::i32));
15112   }
15113 
15114   return SDValue();
15115 }
15116