xref: /freebsd/contrib/llvm-project/llvm/lib/Target/PowerPC/PPCISelLowering.cpp (revision 8bcb0991864975618c09697b1aca10683346d9f0)
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/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/RuntimeLibcalls.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetLowering.h"
55 #include "llvm/CodeGen/TargetRegisterInfo.h"
56 #include "llvm/CodeGen/ValueTypes.h"
57 #include "llvm/IR/CallSite.h"
58 #include "llvm/IR/CallingConv.h"
59 #include "llvm/IR/Constant.h"
60 #include "llvm/IR/Constants.h"
61 #include "llvm/IR/DataLayout.h"
62 #include "llvm/IR/DebugLoc.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/GlobalValue.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/Intrinsics.h"
69 #include "llvm/IR/Module.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/Value.h"
73 #include "llvm/MC/MCContext.h"
74 #include "llvm/MC/MCExpr.h"
75 #include "llvm/MC/MCRegisterInfo.h"
76 #include "llvm/MC/MCSymbolXCOFF.h"
77 #include "llvm/Support/AtomicOrdering.h"
78 #include "llvm/Support/BranchProbability.h"
79 #include "llvm/Support/Casting.h"
80 #include "llvm/Support/CodeGen.h"
81 #include "llvm/Support/CommandLine.h"
82 #include "llvm/Support/Compiler.h"
83 #include "llvm/Support/Debug.h"
84 #include "llvm/Support/ErrorHandling.h"
85 #include "llvm/Support/Format.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MachineValueType.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/raw_ostream.h"
90 #include "llvm/Target/TargetMachine.h"
91 #include "llvm/Target/TargetOptions.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <list>
97 #include <utility>
98 #include <vector>
99 
100 using namespace llvm;
101 
102 #define DEBUG_TYPE "ppc-lowering"
103 
104 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
105 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
106 
107 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
108 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
109 
110 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
111 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
112 
113 static cl::opt<bool> DisableSCO("disable-ppc-sco",
114 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
115 
116 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
117 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
118 
119 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
120 cl::desc("enable quad precision float support on ppc"), cl::Hidden);
121 
122 STATISTIC(NumTailCalls, "Number of tail calls");
123 STATISTIC(NumSiblingCalls, "Number of sibling calls");
124 
125 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
126 
127 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
128 
129 // FIXME: Remove this once the bug has been fixed!
130 extern cl::opt<bool> ANDIGlueBug;
131 
132 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
133                                      const PPCSubtarget &STI)
134     : TargetLowering(TM), Subtarget(STI) {
135   // Use _setjmp/_longjmp instead of setjmp/longjmp.
136   setUseUnderscoreSetJmp(true);
137   setUseUnderscoreLongJmp(true);
138 
139   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
140   // arguments are at least 4/8 bytes aligned.
141   bool isPPC64 = Subtarget.isPPC64();
142   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
143 
144   // Set up the register classes.
145   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
146   if (!useSoftFloat()) {
147     if (hasSPE()) {
148       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
149       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
150     } else {
151       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
152       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
153     }
154   }
155 
156   // Match BITREVERSE to customized fast code sequence in the td file.
157   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
158   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
159 
160   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
161   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
162 
163   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
164   for (MVT VT : MVT::integer_valuetypes()) {
165     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
166     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
167   }
168 
169   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
170 
171   // PowerPC has pre-inc load and store's.
172   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
173   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
174   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
175   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
176   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
177   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
178   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
179   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
180   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
181   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
182   if (!Subtarget.hasSPE()) {
183     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
184     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
185     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
186     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
187   }
188 
189   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
190   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
191   for (MVT VT : ScalarIntVTs) {
192     setOperationAction(ISD::ADDC, VT, Legal);
193     setOperationAction(ISD::ADDE, VT, Legal);
194     setOperationAction(ISD::SUBC, VT, Legal);
195     setOperationAction(ISD::SUBE, VT, Legal);
196   }
197 
198   if (Subtarget.useCRBits()) {
199     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
200 
201     if (isPPC64 || Subtarget.hasFPCVT()) {
202       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
203       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
204                          isPPC64 ? MVT::i64 : MVT::i32);
205       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
206       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
207                         isPPC64 ? MVT::i64 : MVT::i32);
208     } else {
209       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
210       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
211     }
212 
213     // PowerPC does not support direct load/store of condition registers.
214     setOperationAction(ISD::LOAD, MVT::i1, Custom);
215     setOperationAction(ISD::STORE, MVT::i1, Custom);
216 
217     // FIXME: Remove this once the ANDI glue bug is fixed:
218     if (ANDIGlueBug)
219       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
220 
221     for (MVT VT : MVT::integer_valuetypes()) {
222       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
223       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
224       setTruncStoreAction(VT, MVT::i1, Expand);
225     }
226 
227     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
228   }
229 
230   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
231   // PPC (the libcall is not available).
232   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
233   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
234 
235   // We do not currently implement these libm ops for PowerPC.
236   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
237   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
238   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
239   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
240   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
241   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
242 
243   // PowerPC has no SREM/UREM instructions unless we are on P9
244   // On P9 we may use a hardware instruction to compute the remainder.
245   // The instructions are not legalized directly because in the cases where the
246   // result of both the remainder and the division is required it is more
247   // efficient to compute the remainder from the result of the division rather
248   // than use the remainder instruction.
249   if (Subtarget.isISA3_0()) {
250     setOperationAction(ISD::SREM, MVT::i32, Custom);
251     setOperationAction(ISD::UREM, MVT::i32, Custom);
252     setOperationAction(ISD::SREM, MVT::i64, Custom);
253     setOperationAction(ISD::UREM, MVT::i64, Custom);
254   } else {
255     setOperationAction(ISD::SREM, MVT::i32, Expand);
256     setOperationAction(ISD::UREM, MVT::i32, Expand);
257     setOperationAction(ISD::SREM, MVT::i64, Expand);
258     setOperationAction(ISD::UREM, MVT::i64, Expand);
259   }
260 
261   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
262   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
263   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
264   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
265   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
266   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
267   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
268   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
269   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
270 
271   // We don't support sin/cos/sqrt/fmod/pow
272   setOperationAction(ISD::FSIN , MVT::f64, Expand);
273   setOperationAction(ISD::FCOS , MVT::f64, Expand);
274   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
275   setOperationAction(ISD::FREM , MVT::f64, Expand);
276   setOperationAction(ISD::FPOW , MVT::f64, Expand);
277   setOperationAction(ISD::FSIN , MVT::f32, Expand);
278   setOperationAction(ISD::FCOS , MVT::f32, Expand);
279   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
280   setOperationAction(ISD::FREM , MVT::f32, Expand);
281   setOperationAction(ISD::FPOW , MVT::f32, Expand);
282   if (Subtarget.hasSPE()) {
283     setOperationAction(ISD::FMA  , MVT::f64, Expand);
284     setOperationAction(ISD::FMA  , MVT::f32, Expand);
285   } else {
286     setOperationAction(ISD::FMA  , MVT::f64, Legal);
287     setOperationAction(ISD::FMA  , MVT::f32, Legal);
288   }
289 
290   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
291 
292   // If we're enabling GP optimizations, use hardware square root
293   if (!Subtarget.hasFSQRT() &&
294       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
295         Subtarget.hasFRE()))
296     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
297 
298   if (!Subtarget.hasFSQRT() &&
299       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
300         Subtarget.hasFRES()))
301     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
302 
303   if (Subtarget.hasFCPSGN()) {
304     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
305     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
306   } else {
307     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
308     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
309   }
310 
311   if (Subtarget.hasFPRND()) {
312     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
313     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
314     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
315     setOperationAction(ISD::FROUND, MVT::f64, Legal);
316 
317     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
318     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
319     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
320     setOperationAction(ISD::FROUND, MVT::f32, Legal);
321   }
322 
323   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
324   // to speed up scalar BSWAP64.
325   // CTPOP or CTTZ were introduced in P8/P9 respectively
326   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
327   if (Subtarget.hasP9Vector())
328     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
329   else
330     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
331   if (Subtarget.isISA3_0()) {
332     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
333     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
334   } else {
335     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
336     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
337   }
338 
339   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
340     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
341     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
342   } else {
343     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
344     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
345   }
346 
347   // PowerPC does not have ROTR
348   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
349   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
350 
351   if (!Subtarget.useCRBits()) {
352     // PowerPC does not have Select
353     setOperationAction(ISD::SELECT, MVT::i32, Expand);
354     setOperationAction(ISD::SELECT, MVT::i64, Expand);
355     setOperationAction(ISD::SELECT, MVT::f32, Expand);
356     setOperationAction(ISD::SELECT, MVT::f64, Expand);
357   }
358 
359   // PowerPC wants to turn select_cc of FP into fsel when possible.
360   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
361   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
362 
363   // PowerPC wants to optimize integer setcc a bit
364   if (!Subtarget.useCRBits())
365     setOperationAction(ISD::SETCC, MVT::i32, Custom);
366 
367   // PowerPC does not have BRCOND which requires SetCC
368   if (!Subtarget.useCRBits())
369     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
370 
371   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
372 
373   if (Subtarget.hasSPE()) {
374     // SPE has built-in conversions
375     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
376     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
377     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
378   } else {
379     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
380     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
381 
382     // PowerPC does not have [U|S]INT_TO_FP
383     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
384     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
385   }
386 
387   if (Subtarget.hasDirectMove() && isPPC64) {
388     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
389     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
390     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
391     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
392   } else {
393     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
394     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
395     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
396     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
397   }
398 
399   // We cannot sextinreg(i1).  Expand to shifts.
400   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
401 
402   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
403   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
404   // support continuation, user-level threading, and etc.. As a result, no
405   // other SjLj exception interfaces are implemented and please don't build
406   // your own exception handling based on them.
407   // LLVM/Clang supports zero-cost DWARF exception handling.
408   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
409   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
410 
411   // We want to legalize GlobalAddress and ConstantPool nodes into the
412   // appropriate instructions to materialize the address.
413   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
414   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
415   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
416   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
417   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
418   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
419   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
420   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
421   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
422   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
423 
424   // TRAP is legal.
425   setOperationAction(ISD::TRAP, MVT::Other, Legal);
426 
427   // TRAMPOLINE is custom lowered.
428   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
429   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
430 
431   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
432   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
433 
434   if (Subtarget.is64BitELFABI()) {
435     // VAARG always uses double-word chunks, so promote anything smaller.
436     setOperationAction(ISD::VAARG, MVT::i1, Promote);
437     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
438     setOperationAction(ISD::VAARG, MVT::i8, Promote);
439     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
440     setOperationAction(ISD::VAARG, MVT::i16, Promote);
441     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
442     setOperationAction(ISD::VAARG, MVT::i32, Promote);
443     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
444     setOperationAction(ISD::VAARG, MVT::Other, Expand);
445   } else if (Subtarget.is32BitELFABI()) {
446     // VAARG is custom lowered with the 32-bit SVR4 ABI.
447     setOperationAction(ISD::VAARG, MVT::Other, Custom);
448     setOperationAction(ISD::VAARG, MVT::i64, Custom);
449   } else
450     setOperationAction(ISD::VAARG, MVT::Other, Expand);
451 
452   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
453   if (Subtarget.is32BitELFABI())
454     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
455   else
456     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
457 
458   // Use the default implementation.
459   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
460   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
461   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
462   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
463   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
464   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
465   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
466   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
467   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
468 
469   // We want to custom lower some of our intrinsics.
470   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
471 
472   // To handle counter-based loop conditions.
473   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
474 
475   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
476   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
477   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
478   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
479 
480   // Comparisons that require checking two conditions.
481   if (Subtarget.hasSPE()) {
482     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
483     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
484     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
485     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
486   }
487   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
488   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
489   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
490   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
491   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
492   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
493   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
494   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
495   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
496   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
497   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
498   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
499 
500   if (Subtarget.has64BitSupport()) {
501     // They also have instructions for converting between i64 and fp.
502     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
503     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
504     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
505     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
506     // This is just the low 32 bits of a (signed) fp->i64 conversion.
507     // We cannot do this with Promote because i64 is not a legal type.
508     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
509 
510     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
511       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
512   } else {
513     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
514     if (Subtarget.hasSPE())
515       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
516     else
517       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
518   }
519 
520   // With the instructions enabled under FPCVT, we can do everything.
521   if (Subtarget.hasFPCVT()) {
522     if (Subtarget.has64BitSupport()) {
523       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
524       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
525       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
526       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
527     }
528 
529     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
530     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
531     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
532     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
533   }
534 
535   if (Subtarget.use64BitRegs()) {
536     // 64-bit PowerPC implementations can support i64 types directly
537     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
538     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
539     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
540     // 64-bit PowerPC wants to expand i128 shifts itself.
541     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
542     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
543     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
544   } else {
545     // 32-bit PowerPC wants to expand i64 shifts itself.
546     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
547     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
548     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
549   }
550 
551   if (Subtarget.hasAltivec()) {
552     // First set operation action for all vector types to expand. Then we
553     // will selectively turn on ones that can be effectively codegen'd.
554     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
555       // add/sub are legal for all supported vector VT's.
556       setOperationAction(ISD::ADD, VT, Legal);
557       setOperationAction(ISD::SUB, VT, Legal);
558 
559       // For v2i64, these are only valid with P8Vector. This is corrected after
560       // the loop.
561       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
562         setOperationAction(ISD::SMAX, VT, Legal);
563         setOperationAction(ISD::SMIN, VT, Legal);
564         setOperationAction(ISD::UMAX, VT, Legal);
565         setOperationAction(ISD::UMIN, VT, Legal);
566       }
567       else {
568         setOperationAction(ISD::SMAX, VT, Expand);
569         setOperationAction(ISD::SMIN, VT, Expand);
570         setOperationAction(ISD::UMAX, VT, Expand);
571         setOperationAction(ISD::UMIN, VT, Expand);
572       }
573 
574       if (Subtarget.hasVSX()) {
575         setOperationAction(ISD::FMAXNUM, VT, Legal);
576         setOperationAction(ISD::FMINNUM, VT, Legal);
577       }
578 
579       // Vector instructions introduced in P8
580       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
581         setOperationAction(ISD::CTPOP, VT, Legal);
582         setOperationAction(ISD::CTLZ, VT, Legal);
583       }
584       else {
585         setOperationAction(ISD::CTPOP, VT, Expand);
586         setOperationAction(ISD::CTLZ, VT, Expand);
587       }
588 
589       // Vector instructions introduced in P9
590       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
591         setOperationAction(ISD::CTTZ, VT, Legal);
592       else
593         setOperationAction(ISD::CTTZ, VT, Expand);
594 
595       // We promote all shuffles to v16i8.
596       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
597       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
598 
599       // We promote all non-typed operations to v4i32.
600       setOperationAction(ISD::AND   , VT, Promote);
601       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
602       setOperationAction(ISD::OR    , VT, Promote);
603       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
604       setOperationAction(ISD::XOR   , VT, Promote);
605       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
606       setOperationAction(ISD::LOAD  , VT, Promote);
607       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
608       setOperationAction(ISD::SELECT, VT, Promote);
609       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
610       setOperationAction(ISD::VSELECT, VT, Legal);
611       setOperationAction(ISD::SELECT_CC, VT, Promote);
612       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
613       setOperationAction(ISD::STORE, VT, Promote);
614       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
615 
616       // No other operations are legal.
617       setOperationAction(ISD::MUL , VT, Expand);
618       setOperationAction(ISD::SDIV, VT, Expand);
619       setOperationAction(ISD::SREM, VT, Expand);
620       setOperationAction(ISD::UDIV, VT, Expand);
621       setOperationAction(ISD::UREM, VT, Expand);
622       setOperationAction(ISD::FDIV, VT, Expand);
623       setOperationAction(ISD::FREM, VT, Expand);
624       setOperationAction(ISD::FNEG, VT, Expand);
625       setOperationAction(ISD::FSQRT, VT, Expand);
626       setOperationAction(ISD::FLOG, VT, Expand);
627       setOperationAction(ISD::FLOG10, VT, Expand);
628       setOperationAction(ISD::FLOG2, VT, Expand);
629       setOperationAction(ISD::FEXP, VT, Expand);
630       setOperationAction(ISD::FEXP2, VT, Expand);
631       setOperationAction(ISD::FSIN, VT, Expand);
632       setOperationAction(ISD::FCOS, VT, Expand);
633       setOperationAction(ISD::FABS, VT, Expand);
634       setOperationAction(ISD::FFLOOR, VT, Expand);
635       setOperationAction(ISD::FCEIL,  VT, Expand);
636       setOperationAction(ISD::FTRUNC, VT, Expand);
637       setOperationAction(ISD::FRINT,  VT, Expand);
638       setOperationAction(ISD::FNEARBYINT, VT, Expand);
639       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
640       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
641       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
642       setOperationAction(ISD::MULHU, VT, Expand);
643       setOperationAction(ISD::MULHS, VT, Expand);
644       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
645       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
646       setOperationAction(ISD::UDIVREM, VT, Expand);
647       setOperationAction(ISD::SDIVREM, VT, Expand);
648       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
649       setOperationAction(ISD::FPOW, VT, Expand);
650       setOperationAction(ISD::BSWAP, VT, Expand);
651       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
652       setOperationAction(ISD::ROTL, VT, Expand);
653       setOperationAction(ISD::ROTR, VT, Expand);
654 
655       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
656         setTruncStoreAction(VT, InnerVT, Expand);
657         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
658         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
659         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
660       }
661     }
662     if (!Subtarget.hasP8Vector()) {
663       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
664       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
665       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
666       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
667     }
668 
669     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
670       setOperationAction(ISD::ABS, VT, Custom);
671 
672     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
673     // with merges, splats, etc.
674     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
675 
676     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
677     // are cheap, so handle them before they get expanded to scalar.
678     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
679     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
680     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
681     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
682     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
683 
684     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
685     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
686     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
687     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
688     setOperationAction(ISD::SELECT, MVT::v4i32,
689                        Subtarget.useCRBits() ? Legal : Expand);
690     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
691     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
692     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
693     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
694     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
695     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
696     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
697     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
698     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
699 
700     // Without hasP8Altivec set, v2i64 SMAX isn't available.
701     // But ABS custom lowering requires SMAX support.
702     if (!Subtarget.hasP8Altivec())
703       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
704 
705     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
706     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
707     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
708     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
709 
710     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
711     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
712 
713     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
714       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
715       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
716     }
717 
718     if (Subtarget.hasP8Altivec())
719       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
720     else
721       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
722 
723     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
724     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
725 
726     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
727     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
728 
729     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
730     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
731     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
732     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
733 
734     // Altivec does not contain unordered floating-point compare instructions
735     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
736     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
737     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
738     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
739 
740     if (Subtarget.hasVSX()) {
741       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
742       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
743       if (Subtarget.hasP8Vector()) {
744         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
745         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
746       }
747       if (Subtarget.hasDirectMove() && isPPC64) {
748         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
749         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
750         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
751         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
752         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
753         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
754         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
755         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
756       }
757       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
758 
759       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
760       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
761       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
762       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
763       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
764 
765       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
766 
767       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
768       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
769 
770       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
771       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
772 
773       // Share the Altivec comparison restrictions.
774       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
775       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
776       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
777       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
778 
779       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
780       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
781 
782       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
783 
784       if (Subtarget.hasP8Vector())
785         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
786 
787       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
788 
789       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
790       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
791       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
792 
793       if (Subtarget.hasP8Altivec()) {
794         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
795         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
796         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
797 
798         // 128 bit shifts can be accomplished via 3 instructions for SHL and
799         // SRL, but not for SRA because of the instructions available:
800         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
801         // doing
802         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
803         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
804         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
805 
806         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
807       }
808       else {
809         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
810         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
811         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
812 
813         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
814 
815         // VSX v2i64 only supports non-arithmetic operations.
816         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
817         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
818       }
819 
820       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
821       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
822       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
823       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
824 
825       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
826 
827       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
828       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
829       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
830       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
831 
832       // Custom handling for partial vectors of integers converted to
833       // floating point. We already have optimal handling for v2i32 through
834       // the DAG combine, so those aren't necessary.
835       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
836       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
837       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
838       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
839       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
840       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
841       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
842       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
843 
844       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
845       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
846       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
847       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
848       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
849       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
850 
851       if (Subtarget.hasDirectMove())
852         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
853       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
854 
855       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
856     }
857 
858     if (Subtarget.hasP8Altivec()) {
859       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
860       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
861     }
862 
863     if (Subtarget.hasP9Vector()) {
864       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
865       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
866 
867       // 128 bit shifts can be accomplished via 3 instructions for SHL and
868       // SRL, but not for SRA because of the instructions available:
869       // VS{RL} and VS{RL}O.
870       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
871       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
872       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
873 
874       if (EnableQuadPrecision) {
875         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
876         setOperationAction(ISD::FADD, MVT::f128, Legal);
877         setOperationAction(ISD::FSUB, MVT::f128, Legal);
878         setOperationAction(ISD::FDIV, MVT::f128, Legal);
879         setOperationAction(ISD::FMUL, MVT::f128, Legal);
880         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
881         // No extending loads to f128 on PPC.
882         for (MVT FPT : MVT::fp_valuetypes())
883           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
884         setOperationAction(ISD::FMA, MVT::f128, Legal);
885         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
886         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
887         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
888         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
889         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
890         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
891 
892         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
893         setOperationAction(ISD::FRINT, MVT::f128, Legal);
894         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
895         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
896         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
897         setOperationAction(ISD::FROUND, MVT::f128, Legal);
898 
899         setOperationAction(ISD::SELECT, MVT::f128, Expand);
900         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
901         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
902         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
903         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
904         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
905         // No implementation for these ops for PowerPC.
906         setOperationAction(ISD::FSIN , MVT::f128, Expand);
907         setOperationAction(ISD::FCOS , MVT::f128, Expand);
908         setOperationAction(ISD::FPOW, MVT::f128, Expand);
909         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
910         setOperationAction(ISD::FREM, MVT::f128, Expand);
911       }
912       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
913 
914     }
915 
916     if (Subtarget.hasP9Altivec()) {
917       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
918       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
919     }
920   }
921 
922   if (Subtarget.hasQPX()) {
923     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
924     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
925     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
926     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
927 
928     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
929     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
930 
931     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
932     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
933 
934     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
935     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
936 
937     if (!Subtarget.useCRBits())
938       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
939     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
940 
941     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
942     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
943     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
944     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
945     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
946     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
947     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
948 
949     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
950     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
951 
952     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
953     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
954 
955     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
956     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
957     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
958     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
959     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
960     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
961     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
962     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
963     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
964     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
965 
966     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
967     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
968 
969     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
970     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
971 
972     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
973 
974     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
975     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
976     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
977     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
978 
979     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
980     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
981 
982     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
983     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
984 
985     if (!Subtarget.useCRBits())
986       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
987     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
988 
989     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
990     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
991     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
992     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
993     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
994     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
995     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
996 
997     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
998     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
999 
1000     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
1001     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
1002     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
1003     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
1004     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
1005     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
1006     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
1007     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
1008     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
1009     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1010 
1011     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1012     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1013 
1014     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1015     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1016 
1017     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1018 
1019     setOperationAction(ISD::AND , MVT::v4i1, Legal);
1020     setOperationAction(ISD::OR , MVT::v4i1, Legal);
1021     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1022 
1023     if (!Subtarget.useCRBits())
1024       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1025     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1026 
1027     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
1028     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1029 
1030     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1031     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1032     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1033     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1034     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1035     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1036     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1037 
1038     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1039     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1040 
1041     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1042 
1043     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1044     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1045     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1046     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1047 
1048     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1049     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1050     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1051     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1052 
1053     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1054     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1055 
1056     // These need to set FE_INEXACT, and so cannot be vectorized here.
1057     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1058     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1059 
1060     if (TM.Options.UnsafeFPMath) {
1061       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1062       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1063 
1064       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1065       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1066     } else {
1067       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1068       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1069 
1070       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1071       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1072     }
1073   }
1074 
1075   if (Subtarget.has64BitSupport())
1076     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1077 
1078   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1079 
1080   if (!isPPC64) {
1081     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1082     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1083   }
1084 
1085   setBooleanContents(ZeroOrOneBooleanContent);
1086 
1087   if (Subtarget.hasAltivec()) {
1088     // Altivec instructions set fields to all zeros or all ones.
1089     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1090   }
1091 
1092   if (!isPPC64) {
1093     // These libcalls are not available in 32-bit.
1094     setLibcallName(RTLIB::SHL_I128, nullptr);
1095     setLibcallName(RTLIB::SRL_I128, nullptr);
1096     setLibcallName(RTLIB::SRA_I128, nullptr);
1097   }
1098 
1099   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1100 
1101   // We have target-specific dag combine patterns for the following nodes:
1102   setTargetDAGCombine(ISD::ADD);
1103   setTargetDAGCombine(ISD::SHL);
1104   setTargetDAGCombine(ISD::SRA);
1105   setTargetDAGCombine(ISD::SRL);
1106   setTargetDAGCombine(ISD::MUL);
1107   setTargetDAGCombine(ISD::SINT_TO_FP);
1108   setTargetDAGCombine(ISD::BUILD_VECTOR);
1109   if (Subtarget.hasFPCVT())
1110     setTargetDAGCombine(ISD::UINT_TO_FP);
1111   setTargetDAGCombine(ISD::LOAD);
1112   setTargetDAGCombine(ISD::STORE);
1113   setTargetDAGCombine(ISD::BR_CC);
1114   if (Subtarget.useCRBits())
1115     setTargetDAGCombine(ISD::BRCOND);
1116   setTargetDAGCombine(ISD::BSWAP);
1117   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1118   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1119   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1120 
1121   setTargetDAGCombine(ISD::SIGN_EXTEND);
1122   setTargetDAGCombine(ISD::ZERO_EXTEND);
1123   setTargetDAGCombine(ISD::ANY_EXTEND);
1124 
1125   setTargetDAGCombine(ISD::TRUNCATE);
1126   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1127 
1128 
1129   if (Subtarget.useCRBits()) {
1130     setTargetDAGCombine(ISD::TRUNCATE);
1131     setTargetDAGCombine(ISD::SETCC);
1132     setTargetDAGCombine(ISD::SELECT_CC);
1133   }
1134 
1135   // Use reciprocal estimates.
1136   if (TM.Options.UnsafeFPMath) {
1137     setTargetDAGCombine(ISD::FDIV);
1138     setTargetDAGCombine(ISD::FSQRT);
1139   }
1140 
1141   if (Subtarget.hasP9Altivec()) {
1142     setTargetDAGCombine(ISD::ABS);
1143     setTargetDAGCombine(ISD::VSELECT);
1144   }
1145 
1146   // Darwin long double math library functions have $LDBL128 appended.
1147   if (Subtarget.isDarwin()) {
1148     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1149     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1150     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1151     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1152     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1153     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1154     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1155     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1156     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1157     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1158   }
1159 
1160   if (EnableQuadPrecision) {
1161     setLibcallName(RTLIB::LOG_F128, "logf128");
1162     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1163     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1164     setLibcallName(RTLIB::EXP_F128, "expf128");
1165     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1166     setLibcallName(RTLIB::SIN_F128, "sinf128");
1167     setLibcallName(RTLIB::COS_F128, "cosf128");
1168     setLibcallName(RTLIB::POW_F128, "powf128");
1169     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1170     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1171     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1172     setLibcallName(RTLIB::REM_F128, "fmodf128");
1173   }
1174 
1175   // With 32 condition bits, we don't need to sink (and duplicate) compares
1176   // aggressively in CodeGenPrep.
1177   if (Subtarget.useCRBits()) {
1178     setHasMultipleConditionRegisters();
1179     setJumpIsExpensive();
1180   }
1181 
1182   setMinFunctionAlignment(Align(4));
1183   if (Subtarget.isDarwin())
1184     setPrefFunctionAlignment(Align(16));
1185 
1186   switch (Subtarget.getDarwinDirective()) {
1187   default: break;
1188   case PPC::DIR_970:
1189   case PPC::DIR_A2:
1190   case PPC::DIR_E500:
1191   case PPC::DIR_E500mc:
1192   case PPC::DIR_E5500:
1193   case PPC::DIR_PWR4:
1194   case PPC::DIR_PWR5:
1195   case PPC::DIR_PWR5X:
1196   case PPC::DIR_PWR6:
1197   case PPC::DIR_PWR6X:
1198   case PPC::DIR_PWR7:
1199   case PPC::DIR_PWR8:
1200   case PPC::DIR_PWR9:
1201     setPrefLoopAlignment(Align(16));
1202     setPrefFunctionAlignment(Align(16));
1203     break;
1204   }
1205 
1206   if (Subtarget.enableMachineScheduler())
1207     setSchedulingPreference(Sched::Source);
1208   else
1209     setSchedulingPreference(Sched::Hybrid);
1210 
1211   computeRegisterProperties(STI.getRegisterInfo());
1212 
1213   // The Freescale cores do better with aggressive inlining of memcpy and
1214   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1215   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1216       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1217     MaxStoresPerMemset = 32;
1218     MaxStoresPerMemsetOptSize = 16;
1219     MaxStoresPerMemcpy = 32;
1220     MaxStoresPerMemcpyOptSize = 8;
1221     MaxStoresPerMemmove = 32;
1222     MaxStoresPerMemmoveOptSize = 8;
1223   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1224     // The A2 also benefits from (very) aggressive inlining of memcpy and
1225     // friends. The overhead of a the function call, even when warm, can be
1226     // over one hundred cycles.
1227     MaxStoresPerMemset = 128;
1228     MaxStoresPerMemcpy = 128;
1229     MaxStoresPerMemmove = 128;
1230     MaxLoadsPerMemcmp = 128;
1231   } else {
1232     MaxLoadsPerMemcmp = 8;
1233     MaxLoadsPerMemcmpOptSize = 4;
1234   }
1235 }
1236 
1237 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1238 /// the desired ByVal argument alignment.
1239 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1240                              unsigned MaxMaxAlign) {
1241   if (MaxAlign == MaxMaxAlign)
1242     return;
1243   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1244     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1245       MaxAlign = 32;
1246     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1247       MaxAlign = 16;
1248   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1249     unsigned EltAlign = 0;
1250     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1251     if (EltAlign > MaxAlign)
1252       MaxAlign = EltAlign;
1253   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1254     for (auto *EltTy : STy->elements()) {
1255       unsigned EltAlign = 0;
1256       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1257       if (EltAlign > MaxAlign)
1258         MaxAlign = EltAlign;
1259       if (MaxAlign == MaxMaxAlign)
1260         break;
1261     }
1262   }
1263 }
1264 
1265 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1266 /// function arguments in the caller parameter area.
1267 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1268                                                   const DataLayout &DL) const {
1269   // Darwin passes everything on 4 byte boundary.
1270   if (Subtarget.isDarwin())
1271     return 4;
1272 
1273   // 16byte and wider vectors are passed on 16byte boundary.
1274   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1275   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1276   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1277     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1278   return Align;
1279 }
1280 
1281 bool PPCTargetLowering::useSoftFloat() const {
1282   return Subtarget.useSoftFloat();
1283 }
1284 
1285 bool PPCTargetLowering::hasSPE() const {
1286   return Subtarget.hasSPE();
1287 }
1288 
1289 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1290   return VT.isScalarInteger();
1291 }
1292 
1293 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1294   switch ((PPCISD::NodeType)Opcode) {
1295   case PPCISD::FIRST_NUMBER:    break;
1296   case PPCISD::FSEL:            return "PPCISD::FSEL";
1297   case PPCISD::FCFID:           return "PPCISD::FCFID";
1298   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1299   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1300   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1301   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1302   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1303   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1304   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1305   case PPCISD::FP_TO_UINT_IN_VSR:
1306                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1307   case PPCISD::FP_TO_SINT_IN_VSR:
1308                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1309   case PPCISD::FRE:             return "PPCISD::FRE";
1310   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1311   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1312   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1313   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1314   case PPCISD::VPERM:           return "PPCISD::VPERM";
1315   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1316   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1317   case PPCISD::XXREVERSE:       return "PPCISD::XXREVERSE";
1318   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1319   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1320   case PPCISD::CMPB:            return "PPCISD::CMPB";
1321   case PPCISD::Hi:              return "PPCISD::Hi";
1322   case PPCISD::Lo:              return "PPCISD::Lo";
1323   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1324   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1325   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1326   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1327   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1328   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1329   case PPCISD::SRL:             return "PPCISD::SRL";
1330   case PPCISD::SRA:             return "PPCISD::SRA";
1331   case PPCISD::SHL:             return "PPCISD::SHL";
1332   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1333   case PPCISD::CALL:            return "PPCISD::CALL";
1334   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1335   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1336   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1337   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1338   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1339   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1340   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1341   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1342   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1343   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1344   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1345   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1346   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1347   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1348   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1349   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1350   case PPCISD::VCMP:            return "PPCISD::VCMP";
1351   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1352   case PPCISD::LBRX:            return "PPCISD::LBRX";
1353   case PPCISD::STBRX:           return "PPCISD::STBRX";
1354   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1355   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1356   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1357   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1358   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1359   case PPCISD::SExtVElems:      return "PPCISD::SExtVElems";
1360   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1361   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1362   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1363   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1364   case PPCISD::ST_VSR_SCAL_INT:
1365                                 return "PPCISD::ST_VSR_SCAL_INT";
1366   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1367   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1368   case PPCISD::BDZ:             return "PPCISD::BDZ";
1369   case PPCISD::MFFS:            return "PPCISD::MFFS";
1370   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1371   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1372   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1373   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1374   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1375   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1376   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1377   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1378   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1379   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1380   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1381   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1382   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1383   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1384   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1385   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1386   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1387   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1388   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1389   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1390   case PPCISD::SC:              return "PPCISD::SC";
1391   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1392   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1393   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1394   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1395   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1396   case PPCISD::VABSD:           return "PPCISD::VABSD";
1397   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1398   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1399   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1400   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1401   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1402   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1403   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1404   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1405   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1406   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1407   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1408   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1409   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1410   }
1411   return nullptr;
1412 }
1413 
1414 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1415                                           EVT VT) const {
1416   if (!VT.isVector())
1417     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1418 
1419   if (Subtarget.hasQPX())
1420     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1421 
1422   return VT.changeVectorElementTypeToInteger();
1423 }
1424 
1425 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1426   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1427   return true;
1428 }
1429 
1430 //===----------------------------------------------------------------------===//
1431 // Node matching predicates, for use by the tblgen matching code.
1432 //===----------------------------------------------------------------------===//
1433 
1434 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1435 static bool isFloatingPointZero(SDValue Op) {
1436   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1437     return CFP->getValueAPF().isZero();
1438   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1439     // Maybe this has already been legalized into the constant pool?
1440     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1441       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1442         return CFP->getValueAPF().isZero();
1443   }
1444   return false;
1445 }
1446 
1447 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1448 /// true if Op is undef or if it matches the specified value.
1449 static bool isConstantOrUndef(int Op, int Val) {
1450   return Op < 0 || Op == Val;
1451 }
1452 
1453 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1454 /// VPKUHUM instruction.
1455 /// The ShuffleKind distinguishes between big-endian operations with
1456 /// two different inputs (0), either-endian operations with two identical
1457 /// inputs (1), and little-endian operations with two different inputs (2).
1458 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1459 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1460                                SelectionDAG &DAG) {
1461   bool IsLE = DAG.getDataLayout().isLittleEndian();
1462   if (ShuffleKind == 0) {
1463     if (IsLE)
1464       return false;
1465     for (unsigned i = 0; i != 16; ++i)
1466       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1467         return false;
1468   } else if (ShuffleKind == 2) {
1469     if (!IsLE)
1470       return false;
1471     for (unsigned i = 0; i != 16; ++i)
1472       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1473         return false;
1474   } else if (ShuffleKind == 1) {
1475     unsigned j = IsLE ? 0 : 1;
1476     for (unsigned i = 0; i != 8; ++i)
1477       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1478           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1479         return false;
1480   }
1481   return true;
1482 }
1483 
1484 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1485 /// VPKUWUM instruction.
1486 /// The ShuffleKind distinguishes between big-endian operations with
1487 /// two different inputs (0), either-endian operations with two identical
1488 /// inputs (1), and little-endian operations with two different inputs (2).
1489 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1490 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1491                                SelectionDAG &DAG) {
1492   bool IsLE = DAG.getDataLayout().isLittleEndian();
1493   if (ShuffleKind == 0) {
1494     if (IsLE)
1495       return false;
1496     for (unsigned i = 0; i != 16; i += 2)
1497       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1498           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1499         return false;
1500   } else if (ShuffleKind == 2) {
1501     if (!IsLE)
1502       return false;
1503     for (unsigned i = 0; i != 16; i += 2)
1504       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1505           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1506         return false;
1507   } else if (ShuffleKind == 1) {
1508     unsigned j = IsLE ? 0 : 2;
1509     for (unsigned i = 0; i != 8; i += 2)
1510       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1511           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1512           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1513           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1514         return false;
1515   }
1516   return true;
1517 }
1518 
1519 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1520 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1521 /// current subtarget.
1522 ///
1523 /// The ShuffleKind distinguishes between big-endian operations with
1524 /// two different inputs (0), either-endian operations with two identical
1525 /// inputs (1), and little-endian operations with two different inputs (2).
1526 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1527 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1528                                SelectionDAG &DAG) {
1529   const PPCSubtarget& Subtarget =
1530       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1531   if (!Subtarget.hasP8Vector())
1532     return false;
1533 
1534   bool IsLE = DAG.getDataLayout().isLittleEndian();
1535   if (ShuffleKind == 0) {
1536     if (IsLE)
1537       return false;
1538     for (unsigned i = 0; i != 16; i += 4)
1539       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1540           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1541           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1542           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1543         return false;
1544   } else if (ShuffleKind == 2) {
1545     if (!IsLE)
1546       return false;
1547     for (unsigned i = 0; i != 16; i += 4)
1548       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1549           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1550           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1551           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1552         return false;
1553   } else if (ShuffleKind == 1) {
1554     unsigned j = IsLE ? 0 : 4;
1555     for (unsigned i = 0; i != 8; i += 4)
1556       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1557           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1558           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1559           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1560           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1561           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1562           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1563           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1564         return false;
1565   }
1566   return true;
1567 }
1568 
1569 /// isVMerge - Common function, used to match vmrg* shuffles.
1570 ///
1571 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1572                      unsigned LHSStart, unsigned RHSStart) {
1573   if (N->getValueType(0) != MVT::v16i8)
1574     return false;
1575   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1576          "Unsupported merge size!");
1577 
1578   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1579     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1580       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1581                              LHSStart+j+i*UnitSize) ||
1582           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1583                              RHSStart+j+i*UnitSize))
1584         return false;
1585     }
1586   return true;
1587 }
1588 
1589 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1590 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1591 /// The ShuffleKind distinguishes between big-endian merges with two
1592 /// different inputs (0), either-endian merges with two identical inputs (1),
1593 /// and little-endian merges with two different inputs (2).  For the latter,
1594 /// the input operands are swapped (see PPCInstrAltivec.td).
1595 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1596                              unsigned ShuffleKind, SelectionDAG &DAG) {
1597   if (DAG.getDataLayout().isLittleEndian()) {
1598     if (ShuffleKind == 1) // unary
1599       return isVMerge(N, UnitSize, 0, 0);
1600     else if (ShuffleKind == 2) // swapped
1601       return isVMerge(N, UnitSize, 0, 16);
1602     else
1603       return false;
1604   } else {
1605     if (ShuffleKind == 1) // unary
1606       return isVMerge(N, UnitSize, 8, 8);
1607     else if (ShuffleKind == 0) // normal
1608       return isVMerge(N, UnitSize, 8, 24);
1609     else
1610       return false;
1611   }
1612 }
1613 
1614 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1615 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1616 /// The ShuffleKind distinguishes between big-endian merges with two
1617 /// different inputs (0), either-endian merges with two identical inputs (1),
1618 /// and little-endian merges with two different inputs (2).  For the latter,
1619 /// the input operands are swapped (see PPCInstrAltivec.td).
1620 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1621                              unsigned ShuffleKind, SelectionDAG &DAG) {
1622   if (DAG.getDataLayout().isLittleEndian()) {
1623     if (ShuffleKind == 1) // unary
1624       return isVMerge(N, UnitSize, 8, 8);
1625     else if (ShuffleKind == 2) // swapped
1626       return isVMerge(N, UnitSize, 8, 24);
1627     else
1628       return false;
1629   } else {
1630     if (ShuffleKind == 1) // unary
1631       return isVMerge(N, UnitSize, 0, 0);
1632     else if (ShuffleKind == 0) // normal
1633       return isVMerge(N, UnitSize, 0, 16);
1634     else
1635       return false;
1636   }
1637 }
1638 
1639 /**
1640  * Common function used to match vmrgew and vmrgow shuffles
1641  *
1642  * The indexOffset determines whether to look for even or odd words in
1643  * the shuffle mask. This is based on the of the endianness of the target
1644  * machine.
1645  *   - Little Endian:
1646  *     - Use offset of 0 to check for odd elements
1647  *     - Use offset of 4 to check for even elements
1648  *   - Big Endian:
1649  *     - Use offset of 0 to check for even elements
1650  *     - Use offset of 4 to check for odd elements
1651  * A detailed description of the vector element ordering for little endian and
1652  * big endian can be found at
1653  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1654  * Targeting your applications - what little endian and big endian IBM XL C/C++
1655  * compiler differences mean to you
1656  *
1657  * The mask to the shuffle vector instruction specifies the indices of the
1658  * elements from the two input vectors to place in the result. The elements are
1659  * numbered in array-access order, starting with the first vector. These vectors
1660  * are always of type v16i8, thus each vector will contain 16 elements of size
1661  * 8. More info on the shuffle vector can be found in the
1662  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1663  * Language Reference.
1664  *
1665  * The RHSStartValue indicates whether the same input vectors are used (unary)
1666  * or two different input vectors are used, based on the following:
1667  *   - If the instruction uses the same vector for both inputs, the range of the
1668  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1669  *     be 0.
1670  *   - If the instruction has two different vectors then the range of the
1671  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1672  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1673  *     to 31 specify elements in the second vector).
1674  *
1675  * \param[in] N The shuffle vector SD Node to analyze
1676  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1677  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1678  * vector to the shuffle_vector instruction
1679  * \return true iff this shuffle vector represents an even or odd word merge
1680  */
1681 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1682                      unsigned RHSStartValue) {
1683   if (N->getValueType(0) != MVT::v16i8)
1684     return false;
1685 
1686   for (unsigned i = 0; i < 2; ++i)
1687     for (unsigned j = 0; j < 4; ++j)
1688       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1689                              i*RHSStartValue+j+IndexOffset) ||
1690           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1691                              i*RHSStartValue+j+IndexOffset+8))
1692         return false;
1693   return true;
1694 }
1695 
1696 /**
1697  * Determine if the specified shuffle mask is suitable for the vmrgew or
1698  * vmrgow instructions.
1699  *
1700  * \param[in] N The shuffle vector SD Node to analyze
1701  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1702  * \param[in] ShuffleKind Identify the type of merge:
1703  *   - 0 = big-endian merge with two different inputs;
1704  *   - 1 = either-endian merge with two identical inputs;
1705  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1706  *     little-endian merges).
1707  * \param[in] DAG The current SelectionDAG
1708  * \return true iff this shuffle mask
1709  */
1710 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1711                               unsigned ShuffleKind, SelectionDAG &DAG) {
1712   if (DAG.getDataLayout().isLittleEndian()) {
1713     unsigned indexOffset = CheckEven ? 4 : 0;
1714     if (ShuffleKind == 1) // Unary
1715       return isVMerge(N, indexOffset, 0);
1716     else if (ShuffleKind == 2) // swapped
1717       return isVMerge(N, indexOffset, 16);
1718     else
1719       return false;
1720   }
1721   else {
1722     unsigned indexOffset = CheckEven ? 0 : 4;
1723     if (ShuffleKind == 1) // Unary
1724       return isVMerge(N, indexOffset, 0);
1725     else if (ShuffleKind == 0) // Normal
1726       return isVMerge(N, indexOffset, 16);
1727     else
1728       return false;
1729   }
1730   return false;
1731 }
1732 
1733 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1734 /// amount, otherwise return -1.
1735 /// The ShuffleKind distinguishes between big-endian operations with two
1736 /// different inputs (0), either-endian operations with two identical inputs
1737 /// (1), and little-endian operations with two different inputs (2).  For the
1738 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1739 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1740                              SelectionDAG &DAG) {
1741   if (N->getValueType(0) != MVT::v16i8)
1742     return -1;
1743 
1744   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1745 
1746   // Find the first non-undef value in the shuffle mask.
1747   unsigned i;
1748   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1749     /*search*/;
1750 
1751   if (i == 16) return -1;  // all undef.
1752 
1753   // Otherwise, check to see if the rest of the elements are consecutively
1754   // numbered from this value.
1755   unsigned ShiftAmt = SVOp->getMaskElt(i);
1756   if (ShiftAmt < i) return -1;
1757 
1758   ShiftAmt -= i;
1759   bool isLE = DAG.getDataLayout().isLittleEndian();
1760 
1761   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1762     // Check the rest of the elements to see if they are consecutive.
1763     for (++i; i != 16; ++i)
1764       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1765         return -1;
1766   } else if (ShuffleKind == 1) {
1767     // Check the rest of the elements to see if they are consecutive.
1768     for (++i; i != 16; ++i)
1769       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1770         return -1;
1771   } else
1772     return -1;
1773 
1774   if (isLE)
1775     ShiftAmt = 16 - ShiftAmt;
1776 
1777   return ShiftAmt;
1778 }
1779 
1780 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1781 /// specifies a splat of a single element that is suitable for input to
1782 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1783 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1784   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1785          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1786 
1787   // The consecutive indices need to specify an element, not part of two
1788   // different elements.  So abandon ship early if this isn't the case.
1789   if (N->getMaskElt(0) % EltSize != 0)
1790     return false;
1791 
1792   // This is a splat operation if each element of the permute is the same, and
1793   // if the value doesn't reference the second vector.
1794   unsigned ElementBase = N->getMaskElt(0);
1795 
1796   // FIXME: Handle UNDEF elements too!
1797   if (ElementBase >= 16)
1798     return false;
1799 
1800   // Check that the indices are consecutive, in the case of a multi-byte element
1801   // splatted with a v16i8 mask.
1802   for (unsigned i = 1; i != EltSize; ++i)
1803     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1804       return false;
1805 
1806   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1807     if (N->getMaskElt(i) < 0) continue;
1808     for (unsigned j = 0; j != EltSize; ++j)
1809       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1810         return false;
1811   }
1812   return true;
1813 }
1814 
1815 /// Check that the mask is shuffling N byte elements. Within each N byte
1816 /// element of the mask, the indices could be either in increasing or
1817 /// decreasing order as long as they are consecutive.
1818 /// \param[in] N the shuffle vector SD Node to analyze
1819 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1820 /// Word/DoubleWord/QuadWord).
1821 /// \param[in] StepLen the delta indices number among the N byte element, if
1822 /// the mask is in increasing/decreasing order then it is 1/-1.
1823 /// \return true iff the mask is shuffling N byte elements.
1824 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1825                                    int StepLen) {
1826   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1827          "Unexpected element width.");
1828   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1829 
1830   unsigned NumOfElem = 16 / Width;
1831   unsigned MaskVal[16]; //  Width is never greater than 16
1832   for (unsigned i = 0; i < NumOfElem; ++i) {
1833     MaskVal[0] = N->getMaskElt(i * Width);
1834     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1835       return false;
1836     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1837       return false;
1838     }
1839 
1840     for (unsigned int j = 1; j < Width; ++j) {
1841       MaskVal[j] = N->getMaskElt(i * Width + j);
1842       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1843         return false;
1844       }
1845     }
1846   }
1847 
1848   return true;
1849 }
1850 
1851 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1852                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1853   if (!isNByteElemShuffleMask(N, 4, 1))
1854     return false;
1855 
1856   // Now we look at mask elements 0,4,8,12
1857   unsigned M0 = N->getMaskElt(0) / 4;
1858   unsigned M1 = N->getMaskElt(4) / 4;
1859   unsigned M2 = N->getMaskElt(8) / 4;
1860   unsigned M3 = N->getMaskElt(12) / 4;
1861   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1862   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1863 
1864   // Below, let H and L be arbitrary elements of the shuffle mask
1865   // where H is in the range [4,7] and L is in the range [0,3].
1866   // H, 1, 2, 3 or L, 5, 6, 7
1867   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1868       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1869     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1870     InsertAtByte = IsLE ? 12 : 0;
1871     Swap = M0 < 4;
1872     return true;
1873   }
1874   // 0, H, 2, 3 or 4, L, 6, 7
1875   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1876       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1877     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1878     InsertAtByte = IsLE ? 8 : 4;
1879     Swap = M1 < 4;
1880     return true;
1881   }
1882   // 0, 1, H, 3 or 4, 5, L, 7
1883   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1884       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1885     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1886     InsertAtByte = IsLE ? 4 : 8;
1887     Swap = M2 < 4;
1888     return true;
1889   }
1890   // 0, 1, 2, H or 4, 5, 6, L
1891   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1892       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1893     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1894     InsertAtByte = IsLE ? 0 : 12;
1895     Swap = M3 < 4;
1896     return true;
1897   }
1898 
1899   // If both vector operands for the shuffle are the same vector, the mask will
1900   // contain only elements from the first one and the second one will be undef.
1901   if (N->getOperand(1).isUndef()) {
1902     ShiftElts = 0;
1903     Swap = true;
1904     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1905     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1906       InsertAtByte = IsLE ? 12 : 0;
1907       return true;
1908     }
1909     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1910       InsertAtByte = IsLE ? 8 : 4;
1911       return true;
1912     }
1913     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1914       InsertAtByte = IsLE ? 4 : 8;
1915       return true;
1916     }
1917     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1918       InsertAtByte = IsLE ? 0 : 12;
1919       return true;
1920     }
1921   }
1922 
1923   return false;
1924 }
1925 
1926 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1927                                bool &Swap, bool IsLE) {
1928   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1929   // Ensure each byte index of the word is consecutive.
1930   if (!isNByteElemShuffleMask(N, 4, 1))
1931     return false;
1932 
1933   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1934   unsigned M0 = N->getMaskElt(0) / 4;
1935   unsigned M1 = N->getMaskElt(4) / 4;
1936   unsigned M2 = N->getMaskElt(8) / 4;
1937   unsigned M3 = N->getMaskElt(12) / 4;
1938 
1939   // If both vector operands for the shuffle are the same vector, the mask will
1940   // contain only elements from the first one and the second one will be undef.
1941   if (N->getOperand(1).isUndef()) {
1942     assert(M0 < 4 && "Indexing into an undef vector?");
1943     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1944       return false;
1945 
1946     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1947     Swap = false;
1948     return true;
1949   }
1950 
1951   // Ensure each word index of the ShuffleVector Mask is consecutive.
1952   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1953     return false;
1954 
1955   if (IsLE) {
1956     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1957       // Input vectors don't need to be swapped if the leading element
1958       // of the result is one of the 3 left elements of the second vector
1959       // (or if there is no shift to be done at all).
1960       Swap = false;
1961       ShiftElts = (8 - M0) % 8;
1962     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1963       // Input vectors need to be swapped if the leading element
1964       // of the result is one of the 3 left elements of the first vector
1965       // (or if we're shifting by 4 - thereby simply swapping the vectors).
1966       Swap = true;
1967       ShiftElts = (4 - M0) % 4;
1968     }
1969 
1970     return true;
1971   } else {                                          // BE
1972     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
1973       // Input vectors don't need to be swapped if the leading element
1974       // of the result is one of the 4 elements of the first vector.
1975       Swap = false;
1976       ShiftElts = M0;
1977     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
1978       // Input vectors need to be swapped if the leading element
1979       // of the result is one of the 4 elements of the right vector.
1980       Swap = true;
1981       ShiftElts = M0 - 4;
1982     }
1983 
1984     return true;
1985   }
1986 }
1987 
1988 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
1989   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1990 
1991   if (!isNByteElemShuffleMask(N, Width, -1))
1992     return false;
1993 
1994   for (int i = 0; i < 16; i += Width)
1995     if (N->getMaskElt(i) != i + Width - 1)
1996       return false;
1997 
1998   return true;
1999 }
2000 
2001 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2002   return isXXBRShuffleMaskHelper(N, 2);
2003 }
2004 
2005 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2006   return isXXBRShuffleMaskHelper(N, 4);
2007 }
2008 
2009 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2010   return isXXBRShuffleMaskHelper(N, 8);
2011 }
2012 
2013 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2014   return isXXBRShuffleMaskHelper(N, 16);
2015 }
2016 
2017 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2018 /// if the inputs to the instruction should be swapped and set \p DM to the
2019 /// value for the immediate.
2020 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2021 /// AND element 0 of the result comes from the first input (LE) or second input
2022 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2023 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2024 /// mask.
2025 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2026                                bool &Swap, bool IsLE) {
2027   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2028 
2029   // Ensure each byte index of the double word is consecutive.
2030   if (!isNByteElemShuffleMask(N, 8, 1))
2031     return false;
2032 
2033   unsigned M0 = N->getMaskElt(0) / 8;
2034   unsigned M1 = N->getMaskElt(8) / 8;
2035   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2036 
2037   // If both vector operands for the shuffle are the same vector, the mask will
2038   // contain only elements from the first one and the second one will be undef.
2039   if (N->getOperand(1).isUndef()) {
2040     if ((M0 | M1) < 2) {
2041       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2042       Swap = false;
2043       return true;
2044     } else
2045       return false;
2046   }
2047 
2048   if (IsLE) {
2049     if (M0 > 1 && M1 < 2) {
2050       Swap = false;
2051     } else if (M0 < 2 && M1 > 1) {
2052       M0 = (M0 + 2) % 4;
2053       M1 = (M1 + 2) % 4;
2054       Swap = true;
2055     } else
2056       return false;
2057 
2058     // Note: if control flow comes here that means Swap is already set above
2059     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2060     return true;
2061   } else { // BE
2062     if (M0 < 2 && M1 > 1) {
2063       Swap = false;
2064     } else if (M0 > 1 && M1 < 2) {
2065       M0 = (M0 + 2) % 4;
2066       M1 = (M1 + 2) % 4;
2067       Swap = true;
2068     } else
2069       return false;
2070 
2071     // Note: if control flow comes here that means Swap is already set above
2072     DM = (M0 << 1) + (M1 & 1);
2073     return true;
2074   }
2075 }
2076 
2077 
2078 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2079 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2080 /// elements are counted from the left of the vector register).
2081 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2082                                          SelectionDAG &DAG) {
2083   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2084   assert(isSplatShuffleMask(SVOp, EltSize));
2085   if (DAG.getDataLayout().isLittleEndian())
2086     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2087   else
2088     return SVOp->getMaskElt(0) / EltSize;
2089 }
2090 
2091 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2092 /// by using a vspltis[bhw] instruction of the specified element size, return
2093 /// the constant being splatted.  The ByteSize field indicates the number of
2094 /// bytes of each element [124] -> [bhw].
2095 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2096   SDValue OpVal(nullptr, 0);
2097 
2098   // If ByteSize of the splat is bigger than the element size of the
2099   // build_vector, then we have a case where we are checking for a splat where
2100   // multiple elements of the buildvector are folded together into a single
2101   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2102   unsigned EltSize = 16/N->getNumOperands();
2103   if (EltSize < ByteSize) {
2104     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2105     SDValue UniquedVals[4];
2106     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2107 
2108     // See if all of the elements in the buildvector agree across.
2109     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2110       if (N->getOperand(i).isUndef()) continue;
2111       // If the element isn't a constant, bail fully out.
2112       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2113 
2114       if (!UniquedVals[i&(Multiple-1)].getNode())
2115         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2116       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2117         return SDValue();  // no match.
2118     }
2119 
2120     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2121     // either constant or undef values that are identical for each chunk.  See
2122     // if these chunks can form into a larger vspltis*.
2123 
2124     // Check to see if all of the leading entries are either 0 or -1.  If
2125     // neither, then this won't fit into the immediate field.
2126     bool LeadingZero = true;
2127     bool LeadingOnes = true;
2128     for (unsigned i = 0; i != Multiple-1; ++i) {
2129       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2130 
2131       LeadingZero &= isNullConstant(UniquedVals[i]);
2132       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2133     }
2134     // Finally, check the least significant entry.
2135     if (LeadingZero) {
2136       if (!UniquedVals[Multiple-1].getNode())
2137         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2138       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2139       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2140         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2141     }
2142     if (LeadingOnes) {
2143       if (!UniquedVals[Multiple-1].getNode())
2144         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2145       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2146       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2147         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2148     }
2149 
2150     return SDValue();
2151   }
2152 
2153   // Check to see if this buildvec has a single non-undef value in its elements.
2154   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2155     if (N->getOperand(i).isUndef()) continue;
2156     if (!OpVal.getNode())
2157       OpVal = N->getOperand(i);
2158     else if (OpVal != N->getOperand(i))
2159       return SDValue();
2160   }
2161 
2162   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2163 
2164   unsigned ValSizeInBytes = EltSize;
2165   uint64_t Value = 0;
2166   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2167     Value = CN->getZExtValue();
2168   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2169     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2170     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2171   }
2172 
2173   // If the splat value is larger than the element value, then we can never do
2174   // this splat.  The only case that we could fit the replicated bits into our
2175   // immediate field for would be zero, and we prefer to use vxor for it.
2176   if (ValSizeInBytes < ByteSize) return SDValue();
2177 
2178   // If the element value is larger than the splat value, check if it consists
2179   // of a repeated bit pattern of size ByteSize.
2180   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2181     return SDValue();
2182 
2183   // Properly sign extend the value.
2184   int MaskVal = SignExtend32(Value, ByteSize * 8);
2185 
2186   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2187   if (MaskVal == 0) return SDValue();
2188 
2189   // Finally, if this value fits in a 5 bit sext field, return it
2190   if (SignExtend32<5>(MaskVal) == MaskVal)
2191     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2192   return SDValue();
2193 }
2194 
2195 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2196 /// amount, otherwise return -1.
2197 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2198   EVT VT = N->getValueType(0);
2199   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2200     return -1;
2201 
2202   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2203 
2204   // Find the first non-undef value in the shuffle mask.
2205   unsigned i;
2206   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2207     /*search*/;
2208 
2209   if (i == 4) return -1;  // all undef.
2210 
2211   // Otherwise, check to see if the rest of the elements are consecutively
2212   // numbered from this value.
2213   unsigned ShiftAmt = SVOp->getMaskElt(i);
2214   if (ShiftAmt < i) return -1;
2215   ShiftAmt -= i;
2216 
2217   // Check the rest of the elements to see if they are consecutive.
2218   for (++i; i != 4; ++i)
2219     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2220       return -1;
2221 
2222   return ShiftAmt;
2223 }
2224 
2225 //===----------------------------------------------------------------------===//
2226 //  Addressing Mode Selection
2227 //===----------------------------------------------------------------------===//
2228 
2229 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2230 /// or 64-bit immediate, and if the value can be accurately represented as a
2231 /// sign extension from a 16-bit value.  If so, this returns true and the
2232 /// immediate.
2233 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2234   if (!isa<ConstantSDNode>(N))
2235     return false;
2236 
2237   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2238   if (N->getValueType(0) == MVT::i32)
2239     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2240   else
2241     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2242 }
2243 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2244   return isIntS16Immediate(Op.getNode(), Imm);
2245 }
2246 
2247 
2248 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2249 /// be represented as an indexed [r+r] operation.
2250 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2251                                                SDValue &Index,
2252                                                SelectionDAG &DAG) const {
2253   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2254       UI != E; ++UI) {
2255     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2256       if (Memop->getMemoryVT() == MVT::f64) {
2257           Base = N.getOperand(0);
2258           Index = N.getOperand(1);
2259           return true;
2260       }
2261     }
2262   }
2263   return false;
2264 }
2265 
2266 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2267 /// can be represented as an indexed [r+r] operation.  Returns false if it
2268 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2269 /// non-zero and N can be represented by a base register plus a signed 16-bit
2270 /// displacement, make a more precise judgement by checking (displacement % \p
2271 /// EncodingAlignment).
2272 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2273                                             SDValue &Index, SelectionDAG &DAG,
2274                                             unsigned EncodingAlignment) const {
2275   int16_t imm = 0;
2276   if (N.getOpcode() == ISD::ADD) {
2277     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2278     // SPE load/store can only handle 8-bit offsets.
2279     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2280         return true;
2281     if (isIntS16Immediate(N.getOperand(1), imm) &&
2282         (!EncodingAlignment || !(imm % EncodingAlignment)))
2283       return false; // r+i
2284     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2285       return false;    // r+i
2286 
2287     Base = N.getOperand(0);
2288     Index = N.getOperand(1);
2289     return true;
2290   } else if (N.getOpcode() == ISD::OR) {
2291     if (isIntS16Immediate(N.getOperand(1), imm) &&
2292         (!EncodingAlignment || !(imm % EncodingAlignment)))
2293       return false; // r+i can fold it if we can.
2294 
2295     // If this is an or of disjoint bitfields, we can codegen this as an add
2296     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2297     // disjoint.
2298     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2299 
2300     if (LHSKnown.Zero.getBoolValue()) {
2301       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2302       // If all of the bits are known zero on the LHS or RHS, the add won't
2303       // carry.
2304       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2305         Base = N.getOperand(0);
2306         Index = N.getOperand(1);
2307         return true;
2308       }
2309     }
2310   }
2311 
2312   return false;
2313 }
2314 
2315 // If we happen to be doing an i64 load or store into a stack slot that has
2316 // less than a 4-byte alignment, then the frame-index elimination may need to
2317 // use an indexed load or store instruction (because the offset may not be a
2318 // multiple of 4). The extra register needed to hold the offset comes from the
2319 // register scavenger, and it is possible that the scavenger will need to use
2320 // an emergency spill slot. As a result, we need to make sure that a spill slot
2321 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2322 // stack slot.
2323 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2324   // FIXME: This does not handle the LWA case.
2325   if (VT != MVT::i64)
2326     return;
2327 
2328   // NOTE: We'll exclude negative FIs here, which come from argument
2329   // lowering, because there are no known test cases triggering this problem
2330   // using packed structures (or similar). We can remove this exclusion if
2331   // we find such a test case. The reason why this is so test-case driven is
2332   // because this entire 'fixup' is only to prevent crashes (from the
2333   // register scavenger) on not-really-valid inputs. For example, if we have:
2334   //   %a = alloca i1
2335   //   %b = bitcast i1* %a to i64*
2336   //   store i64* a, i64 b
2337   // then the store should really be marked as 'align 1', but is not. If it
2338   // were marked as 'align 1' then the indexed form would have been
2339   // instruction-selected initially, and the problem this 'fixup' is preventing
2340   // won't happen regardless.
2341   if (FrameIdx < 0)
2342     return;
2343 
2344   MachineFunction &MF = DAG.getMachineFunction();
2345   MachineFrameInfo &MFI = MF.getFrameInfo();
2346 
2347   unsigned Align = MFI.getObjectAlignment(FrameIdx);
2348   if (Align >= 4)
2349     return;
2350 
2351   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2352   FuncInfo->setHasNonRISpills();
2353 }
2354 
2355 /// Returns true if the address N can be represented by a base register plus
2356 /// a signed 16-bit displacement [r+imm], and if it is not better
2357 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2358 /// displacements that are multiples of that value.
2359 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2360                                             SDValue &Base,
2361                                             SelectionDAG &DAG,
2362                                             unsigned EncodingAlignment) const {
2363   // FIXME dl should come from parent load or store, not from address
2364   SDLoc dl(N);
2365   // If this can be more profitably realized as r+r, fail.
2366   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2367     return false;
2368 
2369   if (N.getOpcode() == ISD::ADD) {
2370     int16_t imm = 0;
2371     if (isIntS16Immediate(N.getOperand(1), imm) &&
2372         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2373       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2374       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2375         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2376         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2377       } else {
2378         Base = N.getOperand(0);
2379       }
2380       return true; // [r+i]
2381     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2382       // Match LOAD (ADD (X, Lo(G))).
2383       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2384              && "Cannot handle constant offsets yet!");
2385       Disp = N.getOperand(1).getOperand(0);  // The global address.
2386       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2387              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2388              Disp.getOpcode() == ISD::TargetConstantPool ||
2389              Disp.getOpcode() == ISD::TargetJumpTable);
2390       Base = N.getOperand(0);
2391       return true;  // [&g+r]
2392     }
2393   } else if (N.getOpcode() == ISD::OR) {
2394     int16_t imm = 0;
2395     if (isIntS16Immediate(N.getOperand(1), imm) &&
2396         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2397       // If this is an or of disjoint bitfields, we can codegen this as an add
2398       // (for better address arithmetic) if the LHS and RHS of the OR are
2399       // provably disjoint.
2400       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2401 
2402       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2403         // If all of the bits are known zero on the LHS or RHS, the add won't
2404         // carry.
2405         if (FrameIndexSDNode *FI =
2406               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2407           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2408           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2409         } else {
2410           Base = N.getOperand(0);
2411         }
2412         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2413         return true;
2414       }
2415     }
2416   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2417     // Loading from a constant address.
2418 
2419     // If this address fits entirely in a 16-bit sext immediate field, codegen
2420     // this as "d, 0"
2421     int16_t Imm;
2422     if (isIntS16Immediate(CN, Imm) &&
2423         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2424       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2425       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2426                              CN->getValueType(0));
2427       return true;
2428     }
2429 
2430     // Handle 32-bit sext immediates with LIS + addr mode.
2431     if ((CN->getValueType(0) == MVT::i32 ||
2432          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2433         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2434       int Addr = (int)CN->getZExtValue();
2435 
2436       // Otherwise, break this down into an LIS + disp.
2437       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2438 
2439       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2440                                    MVT::i32);
2441       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2442       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2443       return true;
2444     }
2445   }
2446 
2447   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2448   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2449     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2450     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2451   } else
2452     Base = N;
2453   return true;      // [r+0]
2454 }
2455 
2456 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2457 /// represented as an indexed [r+r] operation.
2458 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2459                                                 SDValue &Index,
2460                                                 SelectionDAG &DAG) const {
2461   // Check to see if we can easily represent this as an [r+r] address.  This
2462   // will fail if it thinks that the address is more profitably represented as
2463   // reg+imm, e.g. where imm = 0.
2464   if (SelectAddressRegReg(N, Base, Index, DAG))
2465     return true;
2466 
2467   // If the address is the result of an add, we will utilize the fact that the
2468   // address calculation includes an implicit add.  However, we can reduce
2469   // register pressure if we do not materialize a constant just for use as the
2470   // index register.  We only get rid of the add if it is not an add of a
2471   // value and a 16-bit signed constant and both have a single use.
2472   int16_t imm = 0;
2473   if (N.getOpcode() == ISD::ADD &&
2474       (!isIntS16Immediate(N.getOperand(1), imm) ||
2475        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2476     Base = N.getOperand(0);
2477     Index = N.getOperand(1);
2478     return true;
2479   }
2480 
2481   // Otherwise, do it the hard way, using R0 as the base register.
2482   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2483                          N.getValueType());
2484   Index = N;
2485   return true;
2486 }
2487 
2488 /// Returns true if we should use a direct load into vector instruction
2489 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2490 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2491 
2492   // If there are any other uses other than scalar to vector, then we should
2493   // keep it as a scalar load -> direct move pattern to prevent multiple
2494   // loads.
2495   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2496   if (!LD)
2497     return false;
2498 
2499   EVT MemVT = LD->getMemoryVT();
2500   if (!MemVT.isSimple())
2501     return false;
2502   switch(MemVT.getSimpleVT().SimpleTy) {
2503   case MVT::i64:
2504     break;
2505   case MVT::i32:
2506     if (!ST.hasP8Vector())
2507       return false;
2508     break;
2509   case MVT::i16:
2510   case MVT::i8:
2511     if (!ST.hasP9Vector())
2512       return false;
2513     break;
2514   default:
2515     return false;
2516   }
2517 
2518   SDValue LoadedVal(N, 0);
2519   if (!LoadedVal.hasOneUse())
2520     return false;
2521 
2522   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2523        UI != UE; ++UI)
2524     if (UI.getUse().get().getResNo() == 0 &&
2525         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2526       return false;
2527 
2528   return true;
2529 }
2530 
2531 /// getPreIndexedAddressParts - returns true by value, base pointer and
2532 /// offset pointer and addressing mode by reference if the node's address
2533 /// can be legally represented as pre-indexed load / store address.
2534 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2535                                                   SDValue &Offset,
2536                                                   ISD::MemIndexedMode &AM,
2537                                                   SelectionDAG &DAG) const {
2538   if (DisablePPCPreinc) return false;
2539 
2540   bool isLoad = true;
2541   SDValue Ptr;
2542   EVT VT;
2543   unsigned Alignment;
2544   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2545     Ptr = LD->getBasePtr();
2546     VT = LD->getMemoryVT();
2547     Alignment = LD->getAlignment();
2548   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2549     Ptr = ST->getBasePtr();
2550     VT  = ST->getMemoryVT();
2551     Alignment = ST->getAlignment();
2552     isLoad = false;
2553   } else
2554     return false;
2555 
2556   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2557   // instructions because we can fold these into a more efficient instruction
2558   // instead, (such as LXSD).
2559   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2560     return false;
2561   }
2562 
2563   // PowerPC doesn't have preinc load/store instructions for vectors (except
2564   // for QPX, which does have preinc r+r forms).
2565   if (VT.isVector()) {
2566     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2567       return false;
2568     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2569       AM = ISD::PRE_INC;
2570       return true;
2571     }
2572   }
2573 
2574   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2575     // Common code will reject creating a pre-inc form if the base pointer
2576     // is a frame index, or if N is a store and the base pointer is either
2577     // the same as or a predecessor of the value being stored.  Check for
2578     // those situations here, and try with swapped Base/Offset instead.
2579     bool Swap = false;
2580 
2581     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2582       Swap = true;
2583     else if (!isLoad) {
2584       SDValue Val = cast<StoreSDNode>(N)->getValue();
2585       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2586         Swap = true;
2587     }
2588 
2589     if (Swap)
2590       std::swap(Base, Offset);
2591 
2592     AM = ISD::PRE_INC;
2593     return true;
2594   }
2595 
2596   // LDU/STU can only handle immediates that are a multiple of 4.
2597   if (VT != MVT::i64) {
2598     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2599       return false;
2600   } else {
2601     // LDU/STU need an address with at least 4-byte alignment.
2602     if (Alignment < 4)
2603       return false;
2604 
2605     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2606       return false;
2607   }
2608 
2609   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2610     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2611     // sext i32 to i64 when addr mode is r+i.
2612     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2613         LD->getExtensionType() == ISD::SEXTLOAD &&
2614         isa<ConstantSDNode>(Offset))
2615       return false;
2616   }
2617 
2618   AM = ISD::PRE_INC;
2619   return true;
2620 }
2621 
2622 //===----------------------------------------------------------------------===//
2623 //  LowerOperation implementation
2624 //===----------------------------------------------------------------------===//
2625 
2626 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2627 /// and LoOpFlags to the target MO flags.
2628 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2629                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2630                                const GlobalValue *GV = nullptr) {
2631   HiOpFlags = PPCII::MO_HA;
2632   LoOpFlags = PPCII::MO_LO;
2633 
2634   // Don't use the pic base if not in PIC relocation model.
2635   if (IsPIC) {
2636     HiOpFlags |= PPCII::MO_PIC_FLAG;
2637     LoOpFlags |= PPCII::MO_PIC_FLAG;
2638   }
2639 
2640   // If this is a reference to a global value that requires a non-lazy-ptr, make
2641   // sure that instruction lowering adds it.
2642   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2643     HiOpFlags |= PPCII::MO_NLP_FLAG;
2644     LoOpFlags |= PPCII::MO_NLP_FLAG;
2645 
2646     if (GV->hasHiddenVisibility()) {
2647       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2648       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2649     }
2650   }
2651 }
2652 
2653 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2654                              SelectionDAG &DAG) {
2655   SDLoc DL(HiPart);
2656   EVT PtrVT = HiPart.getValueType();
2657   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2658 
2659   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2660   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2661 
2662   // With PIC, the first instruction is actually "GR+hi(&G)".
2663   if (isPIC)
2664     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2665                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2666 
2667   // Generate non-pic code that has direct accesses to the constant pool.
2668   // The address of the global is just (hi(&g)+lo(&g)).
2669   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2670 }
2671 
2672 static void setUsesTOCBasePtr(MachineFunction &MF) {
2673   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2674   FuncInfo->setUsesTOCBasePtr();
2675 }
2676 
2677 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2678   setUsesTOCBasePtr(DAG.getMachineFunction());
2679 }
2680 
2681 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2682                                        SDValue GA) const {
2683   const bool Is64Bit = Subtarget.isPPC64();
2684   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2685   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2686                         : Subtarget.isAIXABI()
2687                               ? DAG.getRegister(PPC::R2, VT)
2688                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2689   SDValue Ops[] = { GA, Reg };
2690   return DAG.getMemIntrinsicNode(
2691       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2692       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2693       MachineMemOperand::MOLoad);
2694 }
2695 
2696 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2697                                              SelectionDAG &DAG) const {
2698   EVT PtrVT = Op.getValueType();
2699   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2700   const Constant *C = CP->getConstVal();
2701 
2702   // 64-bit SVR4 ABI code is always position-independent.
2703   // The actual address of the GlobalValue is stored in the TOC.
2704   if (Subtarget.is64BitELFABI()) {
2705     setUsesTOCBasePtr(DAG);
2706     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2707     return getTOCEntry(DAG, SDLoc(CP), GA);
2708   }
2709 
2710   unsigned MOHiFlag, MOLoFlag;
2711   bool IsPIC = isPositionIndependent();
2712   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2713 
2714   if (IsPIC && Subtarget.isSVR4ABI()) {
2715     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2716                                            PPCII::MO_PIC_FLAG);
2717     return getTOCEntry(DAG, SDLoc(CP), GA);
2718   }
2719 
2720   SDValue CPIHi =
2721     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2722   SDValue CPILo =
2723     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2724   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2725 }
2726 
2727 // For 64-bit PowerPC, prefer the more compact relative encodings.
2728 // This trades 32 bits per jump table entry for one or two instructions
2729 // on the jump site.
2730 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2731   if (isJumpTableRelative())
2732     return MachineJumpTableInfo::EK_LabelDifference32;
2733 
2734   return TargetLowering::getJumpTableEncoding();
2735 }
2736 
2737 bool PPCTargetLowering::isJumpTableRelative() const {
2738   if (Subtarget.isPPC64())
2739     return true;
2740   return TargetLowering::isJumpTableRelative();
2741 }
2742 
2743 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2744                                                     SelectionDAG &DAG) const {
2745   if (!Subtarget.isPPC64())
2746     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2747 
2748   switch (getTargetMachine().getCodeModel()) {
2749   case CodeModel::Small:
2750   case CodeModel::Medium:
2751     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2752   default:
2753     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2754                        getPointerTy(DAG.getDataLayout()));
2755   }
2756 }
2757 
2758 const MCExpr *
2759 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2760                                                 unsigned JTI,
2761                                                 MCContext &Ctx) const {
2762   if (!Subtarget.isPPC64())
2763     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2764 
2765   switch (getTargetMachine().getCodeModel()) {
2766   case CodeModel::Small:
2767   case CodeModel::Medium:
2768     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2769   default:
2770     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2771   }
2772 }
2773 
2774 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2775   EVT PtrVT = Op.getValueType();
2776   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2777 
2778   // 64-bit SVR4 ABI code is always position-independent.
2779   // The actual address of the GlobalValue is stored in the TOC.
2780   if (Subtarget.is64BitELFABI()) {
2781     setUsesTOCBasePtr(DAG);
2782     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2783     return getTOCEntry(DAG, SDLoc(JT), GA);
2784   }
2785 
2786   unsigned MOHiFlag, MOLoFlag;
2787   bool IsPIC = isPositionIndependent();
2788   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2789 
2790   if (IsPIC && Subtarget.isSVR4ABI()) {
2791     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2792                                         PPCII::MO_PIC_FLAG);
2793     return getTOCEntry(DAG, SDLoc(GA), GA);
2794   }
2795 
2796   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2797   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2798   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2799 }
2800 
2801 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2802                                              SelectionDAG &DAG) const {
2803   EVT PtrVT = Op.getValueType();
2804   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2805   const BlockAddress *BA = BASDN->getBlockAddress();
2806 
2807   // 64-bit SVR4 ABI code is always position-independent.
2808   // The actual BlockAddress is stored in the TOC.
2809   if (Subtarget.is64BitELFABI()) {
2810     setUsesTOCBasePtr(DAG);
2811     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2812     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2813   }
2814 
2815   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2816   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2817     return getTOCEntry(
2818         DAG, SDLoc(BASDN),
2819         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2820 
2821   unsigned MOHiFlag, MOLoFlag;
2822   bool IsPIC = isPositionIndependent();
2823   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2824   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2825   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2826   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2827 }
2828 
2829 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2830                                               SelectionDAG &DAG) const {
2831   // FIXME: TLS addresses currently use medium model code sequences,
2832   // which is the most useful form.  Eventually support for small and
2833   // large models could be added if users need it, at the cost of
2834   // additional complexity.
2835   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2836   if (DAG.getTarget().useEmulatedTLS())
2837     return LowerToTLSEmulatedModel(GA, DAG);
2838 
2839   SDLoc dl(GA);
2840   const GlobalValue *GV = GA->getGlobal();
2841   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2842   bool is64bit = Subtarget.isPPC64();
2843   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2844   PICLevel::Level picLevel = M->getPICLevel();
2845 
2846   const TargetMachine &TM = getTargetMachine();
2847   TLSModel::Model Model = TM.getTLSModel(GV);
2848 
2849   if (Model == TLSModel::LocalExec) {
2850     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2851                                                PPCII::MO_TPREL_HA);
2852     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2853                                                PPCII::MO_TPREL_LO);
2854     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2855                              : DAG.getRegister(PPC::R2, MVT::i32);
2856 
2857     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2858     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2859   }
2860 
2861   if (Model == TLSModel::InitialExec) {
2862     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2863     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2864                                                 PPCII::MO_TLS);
2865     SDValue GOTPtr;
2866     if (is64bit) {
2867       setUsesTOCBasePtr(DAG);
2868       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2869       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2870                            PtrVT, GOTReg, TGA);
2871     } else {
2872       if (!TM.isPositionIndependent())
2873         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2874       else if (picLevel == PICLevel::SmallPIC)
2875         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2876       else
2877         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2878     }
2879     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2880                                    PtrVT, TGA, GOTPtr);
2881     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2882   }
2883 
2884   if (Model == TLSModel::GeneralDynamic) {
2885     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2886     SDValue GOTPtr;
2887     if (is64bit) {
2888       setUsesTOCBasePtr(DAG);
2889       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2890       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2891                                    GOTReg, TGA);
2892     } else {
2893       if (picLevel == PICLevel::SmallPIC)
2894         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2895       else
2896         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2897     }
2898     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2899                        GOTPtr, TGA, TGA);
2900   }
2901 
2902   if (Model == TLSModel::LocalDynamic) {
2903     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2904     SDValue GOTPtr;
2905     if (is64bit) {
2906       setUsesTOCBasePtr(DAG);
2907       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2908       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2909                            GOTReg, TGA);
2910     } else {
2911       if (picLevel == PICLevel::SmallPIC)
2912         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2913       else
2914         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2915     }
2916     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2917                                   PtrVT, GOTPtr, TGA, TGA);
2918     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2919                                       PtrVT, TLSAddr, TGA);
2920     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2921   }
2922 
2923   llvm_unreachable("Unknown TLS model!");
2924 }
2925 
2926 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2927                                               SelectionDAG &DAG) const {
2928   EVT PtrVT = Op.getValueType();
2929   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2930   SDLoc DL(GSDN);
2931   const GlobalValue *GV = GSDN->getGlobal();
2932 
2933   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
2934   // The actual address of the GlobalValue is stored in the TOC.
2935   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2936     setUsesTOCBasePtr(DAG);
2937     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2938     return getTOCEntry(DAG, DL, GA);
2939   }
2940 
2941   unsigned MOHiFlag, MOLoFlag;
2942   bool IsPIC = isPositionIndependent();
2943   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2944 
2945   if (IsPIC && Subtarget.isSVR4ABI()) {
2946     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2947                                             GSDN->getOffset(),
2948                                             PPCII::MO_PIC_FLAG);
2949     return getTOCEntry(DAG, DL, GA);
2950   }
2951 
2952   SDValue GAHi =
2953     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2954   SDValue GALo =
2955     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2956 
2957   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2958 
2959   // If the global reference is actually to a non-lazy-pointer, we have to do an
2960   // extra load to get the address of the global.
2961   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2962     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2963   return Ptr;
2964 }
2965 
2966 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2967   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2968   SDLoc dl(Op);
2969 
2970   if (Op.getValueType() == MVT::v2i64) {
2971     // When the operands themselves are v2i64 values, we need to do something
2972     // special because VSX has no underlying comparison operations for these.
2973     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2974       // Equality can be handled by casting to the legal type for Altivec
2975       // comparisons, everything else needs to be expanded.
2976       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2977         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2978                  DAG.getSetCC(dl, MVT::v4i32,
2979                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2980                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2981                    CC));
2982       }
2983 
2984       return SDValue();
2985     }
2986 
2987     // We handle most of these in the usual way.
2988     return Op;
2989   }
2990 
2991   // If we're comparing for equality to zero, expose the fact that this is
2992   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2993   // fold the new nodes.
2994   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2995     return V;
2996 
2997   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2998     // Leave comparisons against 0 and -1 alone for now, since they're usually
2999     // optimized.  FIXME: revisit this when we can custom lower all setcc
3000     // optimizations.
3001     if (C->isAllOnesValue() || C->isNullValue())
3002       return SDValue();
3003   }
3004 
3005   // If we have an integer seteq/setne, turn it into a compare against zero
3006   // by xor'ing the rhs with the lhs, which is faster than setting a
3007   // condition register, reading it back out, and masking the correct bit.  The
3008   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3009   // the result to other bit-twiddling opportunities.
3010   EVT LHSVT = Op.getOperand(0).getValueType();
3011   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3012     EVT VT = Op.getValueType();
3013     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3014                                 Op.getOperand(1));
3015     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3016   }
3017   return SDValue();
3018 }
3019 
3020 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3021   SDNode *Node = Op.getNode();
3022   EVT VT = Node->getValueType(0);
3023   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3024   SDValue InChain = Node->getOperand(0);
3025   SDValue VAListPtr = Node->getOperand(1);
3026   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3027   SDLoc dl(Node);
3028 
3029   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3030 
3031   // gpr_index
3032   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3033                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3034   InChain = GprIndex.getValue(1);
3035 
3036   if (VT == MVT::i64) {
3037     // Check if GprIndex is even
3038     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3039                                  DAG.getConstant(1, dl, MVT::i32));
3040     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3041                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3042     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3043                                           DAG.getConstant(1, dl, MVT::i32));
3044     // Align GprIndex to be even if it isn't
3045     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3046                            GprIndex);
3047   }
3048 
3049   // fpr index is 1 byte after gpr
3050   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3051                                DAG.getConstant(1, dl, MVT::i32));
3052 
3053   // fpr
3054   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3055                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3056   InChain = FprIndex.getValue(1);
3057 
3058   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3059                                        DAG.getConstant(8, dl, MVT::i32));
3060 
3061   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3062                                         DAG.getConstant(4, dl, MVT::i32));
3063 
3064   // areas
3065   SDValue OverflowArea =
3066       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3067   InChain = OverflowArea.getValue(1);
3068 
3069   SDValue RegSaveArea =
3070       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3071   InChain = RegSaveArea.getValue(1);
3072 
3073   // select overflow_area if index > 8
3074   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3075                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3076 
3077   // adjustment constant gpr_index * 4/8
3078   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3079                                     VT.isInteger() ? GprIndex : FprIndex,
3080                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3081                                                     MVT::i32));
3082 
3083   // OurReg = RegSaveArea + RegConstant
3084   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3085                                RegConstant);
3086 
3087   // Floating types are 32 bytes into RegSaveArea
3088   if (VT.isFloatingPoint())
3089     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3090                          DAG.getConstant(32, dl, MVT::i32));
3091 
3092   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3093   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3094                                    VT.isInteger() ? GprIndex : FprIndex,
3095                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3096                                                    MVT::i32));
3097 
3098   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3099                               VT.isInteger() ? VAListPtr : FprPtr,
3100                               MachinePointerInfo(SV), MVT::i8);
3101 
3102   // determine if we should load from reg_save_area or overflow_area
3103   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3104 
3105   // increase overflow_area by 4/8 if gpr/fpr > 8
3106   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3107                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3108                                           dl, MVT::i32));
3109 
3110   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3111                              OverflowAreaPlusN);
3112 
3113   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3114                               MachinePointerInfo(), MVT::i32);
3115 
3116   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3117 }
3118 
3119 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3120   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3121 
3122   // We have to copy the entire va_list struct:
3123   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3124   return DAG.getMemcpy(Op.getOperand(0), Op,
3125                        Op.getOperand(1), Op.getOperand(2),
3126                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
3127                        false, MachinePointerInfo(), MachinePointerInfo());
3128 }
3129 
3130 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3131                                                   SelectionDAG &DAG) const {
3132   return Op.getOperand(0);
3133 }
3134 
3135 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3136                                                 SelectionDAG &DAG) const {
3137   SDValue Chain = Op.getOperand(0);
3138   SDValue Trmp = Op.getOperand(1); // trampoline
3139   SDValue FPtr = Op.getOperand(2); // nested function
3140   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3141   SDLoc dl(Op);
3142 
3143   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3144   bool isPPC64 = (PtrVT == MVT::i64);
3145   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3146 
3147   TargetLowering::ArgListTy Args;
3148   TargetLowering::ArgListEntry Entry;
3149 
3150   Entry.Ty = IntPtrTy;
3151   Entry.Node = Trmp; Args.push_back(Entry);
3152 
3153   // TrampSize == (isPPC64 ? 48 : 40);
3154   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3155                                isPPC64 ? MVT::i64 : MVT::i32);
3156   Args.push_back(Entry);
3157 
3158   Entry.Node = FPtr; Args.push_back(Entry);
3159   Entry.Node = Nest; Args.push_back(Entry);
3160 
3161   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3162   TargetLowering::CallLoweringInfo CLI(DAG);
3163   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3164       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3165       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3166 
3167   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3168   return CallResult.second;
3169 }
3170 
3171 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3172   MachineFunction &MF = DAG.getMachineFunction();
3173   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3174   EVT PtrVT = getPointerTy(MF.getDataLayout());
3175 
3176   SDLoc dl(Op);
3177 
3178   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
3179     // vastart just stores the address of the VarArgsFrameIndex slot into the
3180     // memory location argument.
3181     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3182     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3183     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3184                         MachinePointerInfo(SV));
3185   }
3186 
3187   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3188   // We suppose the given va_list is already allocated.
3189   //
3190   // typedef struct {
3191   //  char gpr;     /* index into the array of 8 GPRs
3192   //                 * stored in the register save area
3193   //                 * gpr=0 corresponds to r3,
3194   //                 * gpr=1 to r4, etc.
3195   //                 */
3196   //  char fpr;     /* index into the array of 8 FPRs
3197   //                 * stored in the register save area
3198   //                 * fpr=0 corresponds to f1,
3199   //                 * fpr=1 to f2, etc.
3200   //                 */
3201   //  char *overflow_arg_area;
3202   //                /* location on stack that holds
3203   //                 * the next overflow argument
3204   //                 */
3205   //  char *reg_save_area;
3206   //               /* where r3:r10 and f1:f8 (if saved)
3207   //                * are stored
3208   //                */
3209   // } va_list[1];
3210 
3211   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3212   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3213   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3214                                             PtrVT);
3215   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3216                                  PtrVT);
3217 
3218   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3219   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3220 
3221   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3222   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3223 
3224   uint64_t FPROffset = 1;
3225   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3226 
3227   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3228 
3229   // Store first byte : number of int regs
3230   SDValue firstStore =
3231       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3232                         MachinePointerInfo(SV), MVT::i8);
3233   uint64_t nextOffset = FPROffset;
3234   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3235                                   ConstFPROffset);
3236 
3237   // Store second byte : number of float regs
3238   SDValue secondStore =
3239       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3240                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3241   nextOffset += StackOffset;
3242   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3243 
3244   // Store second word : arguments given on stack
3245   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3246                                     MachinePointerInfo(SV, nextOffset));
3247   nextOffset += FrameOffset;
3248   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3249 
3250   // Store third word : arguments given in registers
3251   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3252                       MachinePointerInfo(SV, nextOffset));
3253 }
3254 
3255 /// FPR - The set of FP registers that should be allocated for arguments
3256 /// on Darwin and AIX.
3257 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3258                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3259                                 PPC::F11, PPC::F12, PPC::F13};
3260 
3261 /// QFPR - The set of QPX registers that should be allocated for arguments.
3262 static const MCPhysReg QFPR[] = {
3263     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3264     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3265 
3266 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3267 /// the stack.
3268 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3269                                        unsigned PtrByteSize) {
3270   unsigned ArgSize = ArgVT.getStoreSize();
3271   if (Flags.isByVal())
3272     ArgSize = Flags.getByValSize();
3273 
3274   // Round up to multiples of the pointer size, except for array members,
3275   // which are always packed.
3276   if (!Flags.isInConsecutiveRegs())
3277     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3278 
3279   return ArgSize;
3280 }
3281 
3282 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3283 /// on the stack.
3284 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3285                                             ISD::ArgFlagsTy Flags,
3286                                             unsigned PtrByteSize) {
3287   unsigned Align = PtrByteSize;
3288 
3289   // Altivec parameters are padded to a 16 byte boundary.
3290   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3291       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3292       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3293       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3294     Align = 16;
3295   // QPX vector types stored in double-precision are padded to a 32 byte
3296   // boundary.
3297   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3298     Align = 32;
3299 
3300   // ByVal parameters are aligned as requested.
3301   if (Flags.isByVal()) {
3302     unsigned BVAlign = Flags.getByValAlign();
3303     if (BVAlign > PtrByteSize) {
3304       if (BVAlign % PtrByteSize != 0)
3305           llvm_unreachable(
3306             "ByVal alignment is not a multiple of the pointer size");
3307 
3308       Align = BVAlign;
3309     }
3310   }
3311 
3312   // Array members are always packed to their original alignment.
3313   if (Flags.isInConsecutiveRegs()) {
3314     // If the array member was split into multiple registers, the first
3315     // needs to be aligned to the size of the full type.  (Except for
3316     // ppcf128, which is only aligned as its f64 components.)
3317     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3318       Align = OrigVT.getStoreSize();
3319     else
3320       Align = ArgVT.getStoreSize();
3321   }
3322 
3323   return Align;
3324 }
3325 
3326 /// CalculateStackSlotUsed - Return whether this argument will use its
3327 /// stack slot (instead of being passed in registers).  ArgOffset,
3328 /// AvailableFPRs, and AvailableVRs must hold the current argument
3329 /// position, and will be updated to account for this argument.
3330 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3331                                    ISD::ArgFlagsTy Flags,
3332                                    unsigned PtrByteSize,
3333                                    unsigned LinkageSize,
3334                                    unsigned ParamAreaSize,
3335                                    unsigned &ArgOffset,
3336                                    unsigned &AvailableFPRs,
3337                                    unsigned &AvailableVRs, bool HasQPX) {
3338   bool UseMemory = false;
3339 
3340   // Respect alignment of argument on the stack.
3341   unsigned Align =
3342     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3343   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3344   // If there's no space left in the argument save area, we must
3345   // use memory (this check also catches zero-sized arguments).
3346   if (ArgOffset >= LinkageSize + ParamAreaSize)
3347     UseMemory = true;
3348 
3349   // Allocate argument on the stack.
3350   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3351   if (Flags.isInConsecutiveRegsLast())
3352     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3353   // If we overran the argument save area, we must use memory
3354   // (this check catches arguments passed partially in memory)
3355   if (ArgOffset > LinkageSize + ParamAreaSize)
3356     UseMemory = true;
3357 
3358   // However, if the argument is actually passed in an FPR or a VR,
3359   // we don't use memory after all.
3360   if (!Flags.isByVal()) {
3361     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3362         // QPX registers overlap with the scalar FP registers.
3363         (HasQPX && (ArgVT == MVT::v4f32 ||
3364                     ArgVT == MVT::v4f64 ||
3365                     ArgVT == MVT::v4i1)))
3366       if (AvailableFPRs > 0) {
3367         --AvailableFPRs;
3368         return false;
3369       }
3370     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3371         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3372         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3373         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3374       if (AvailableVRs > 0) {
3375         --AvailableVRs;
3376         return false;
3377       }
3378   }
3379 
3380   return UseMemory;
3381 }
3382 
3383 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3384 /// ensure minimum alignment required for target.
3385 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3386                                      unsigned NumBytes) {
3387   unsigned TargetAlign = Lowering->getStackAlignment();
3388   unsigned AlignMask = TargetAlign - 1;
3389   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3390   return NumBytes;
3391 }
3392 
3393 SDValue PPCTargetLowering::LowerFormalArguments(
3394     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3395     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3396     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3397   if (Subtarget.is64BitELFABI())
3398     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3399                                        InVals);
3400   else if (Subtarget.is32BitELFABI())
3401     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3402                                        InVals);
3403 
3404   // FIXME: We are using this for both AIX and Darwin. We should add appropriate
3405   // AIX testing, and rename it appropriately.
3406   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3407                                      InVals);
3408 }
3409 
3410 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3411     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3412     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3413     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3414 
3415   // 32-bit SVR4 ABI Stack Frame Layout:
3416   //              +-----------------------------------+
3417   //        +-->  |            Back chain             |
3418   //        |     +-----------------------------------+
3419   //        |     | Floating-point register save area |
3420   //        |     +-----------------------------------+
3421   //        |     |    General register save area     |
3422   //        |     +-----------------------------------+
3423   //        |     |          CR save word             |
3424   //        |     +-----------------------------------+
3425   //        |     |         VRSAVE save word          |
3426   //        |     +-----------------------------------+
3427   //        |     |         Alignment padding         |
3428   //        |     +-----------------------------------+
3429   //        |     |     Vector register save area     |
3430   //        |     +-----------------------------------+
3431   //        |     |       Local variable space        |
3432   //        |     +-----------------------------------+
3433   //        |     |        Parameter list area        |
3434   //        |     +-----------------------------------+
3435   //        |     |           LR save word            |
3436   //        |     +-----------------------------------+
3437   // SP-->  +---  |            Back chain             |
3438   //              +-----------------------------------+
3439   //
3440   // Specifications:
3441   //   System V Application Binary Interface PowerPC Processor Supplement
3442   //   AltiVec Technology Programming Interface Manual
3443 
3444   MachineFunction &MF = DAG.getMachineFunction();
3445   MachineFrameInfo &MFI = MF.getFrameInfo();
3446   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3447 
3448   EVT PtrVT = getPointerTy(MF.getDataLayout());
3449   // Potential tail calls could cause overwriting of argument stack slots.
3450   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3451                        (CallConv == CallingConv::Fast));
3452   unsigned PtrByteSize = 4;
3453 
3454   // Assign locations to all of the incoming arguments.
3455   SmallVector<CCValAssign, 16> ArgLocs;
3456   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3457                  *DAG.getContext());
3458 
3459   // Reserve space for the linkage area on the stack.
3460   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3461   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3462   if (useSoftFloat())
3463     CCInfo.PreAnalyzeFormalArguments(Ins);
3464 
3465   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3466   CCInfo.clearWasPPCF128();
3467 
3468   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3469     CCValAssign &VA = ArgLocs[i];
3470 
3471     // Arguments stored in registers.
3472     if (VA.isRegLoc()) {
3473       const TargetRegisterClass *RC;
3474       EVT ValVT = VA.getValVT();
3475 
3476       switch (ValVT.getSimpleVT().SimpleTy) {
3477         default:
3478           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3479         case MVT::i1:
3480         case MVT::i32:
3481           RC = &PPC::GPRCRegClass;
3482           break;
3483         case MVT::f32:
3484           if (Subtarget.hasP8Vector())
3485             RC = &PPC::VSSRCRegClass;
3486           else if (Subtarget.hasSPE())
3487             RC = &PPC::GPRCRegClass;
3488           else
3489             RC = &PPC::F4RCRegClass;
3490           break;
3491         case MVT::f64:
3492           if (Subtarget.hasVSX())
3493             RC = &PPC::VSFRCRegClass;
3494           else if (Subtarget.hasSPE())
3495             // SPE passes doubles in GPR pairs.
3496             RC = &PPC::GPRCRegClass;
3497           else
3498             RC = &PPC::F8RCRegClass;
3499           break;
3500         case MVT::v16i8:
3501         case MVT::v8i16:
3502         case MVT::v4i32:
3503           RC = &PPC::VRRCRegClass;
3504           break;
3505         case MVT::v4f32:
3506           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3507           break;
3508         case MVT::v2f64:
3509         case MVT::v2i64:
3510           RC = &PPC::VRRCRegClass;
3511           break;
3512         case MVT::v4f64:
3513           RC = &PPC::QFRCRegClass;
3514           break;
3515         case MVT::v4i1:
3516           RC = &PPC::QBRCRegClass;
3517           break;
3518       }
3519 
3520       SDValue ArgValue;
3521       // Transform the arguments stored in physical registers into
3522       // virtual ones.
3523       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3524         assert(i + 1 < e && "No second half of double precision argument");
3525         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3526         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3527         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3528         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3529         if (!Subtarget.isLittleEndian())
3530           std::swap (ArgValueLo, ArgValueHi);
3531         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3532                                ArgValueHi);
3533       } else {
3534         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3535         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3536                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3537         if (ValVT == MVT::i1)
3538           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3539       }
3540 
3541       InVals.push_back(ArgValue);
3542     } else {
3543       // Argument stored in memory.
3544       assert(VA.isMemLoc());
3545 
3546       // Get the extended size of the argument type in stack
3547       unsigned ArgSize = VA.getLocVT().getStoreSize();
3548       // Get the actual size of the argument type
3549       unsigned ObjSize = VA.getValVT().getStoreSize();
3550       unsigned ArgOffset = VA.getLocMemOffset();
3551       // Stack objects in PPC32 are right justified.
3552       ArgOffset += ArgSize - ObjSize;
3553       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3554 
3555       // Create load nodes to retrieve arguments from the stack.
3556       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3557       InVals.push_back(
3558           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3559     }
3560   }
3561 
3562   // Assign locations to all of the incoming aggregate by value arguments.
3563   // Aggregates passed by value are stored in the local variable space of the
3564   // caller's stack frame, right above the parameter list area.
3565   SmallVector<CCValAssign, 16> ByValArgLocs;
3566   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3567                       ByValArgLocs, *DAG.getContext());
3568 
3569   // Reserve stack space for the allocations in CCInfo.
3570   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3571 
3572   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3573 
3574   // Area that is at least reserved in the caller of this function.
3575   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3576   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3577 
3578   // Set the size that is at least reserved in caller of this function.  Tail
3579   // call optimized function's reserved stack space needs to be aligned so that
3580   // taking the difference between two stack areas will result in an aligned
3581   // stack.
3582   MinReservedArea =
3583       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3584   FuncInfo->setMinReservedArea(MinReservedArea);
3585 
3586   SmallVector<SDValue, 8> MemOps;
3587 
3588   // If the function takes variable number of arguments, make a frame index for
3589   // the start of the first vararg value... for expansion of llvm.va_start.
3590   if (isVarArg) {
3591     static const MCPhysReg GPArgRegs[] = {
3592       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3593       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3594     };
3595     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3596 
3597     static const MCPhysReg FPArgRegs[] = {
3598       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3599       PPC::F8
3600     };
3601     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3602 
3603     if (useSoftFloat() || hasSPE())
3604        NumFPArgRegs = 0;
3605 
3606     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3607     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3608 
3609     // Make room for NumGPArgRegs and NumFPArgRegs.
3610     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3611                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3612 
3613     FuncInfo->setVarArgsStackOffset(
3614       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3615                             CCInfo.getNextStackOffset(), true));
3616 
3617     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3618     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3619 
3620     // The fixed integer arguments of a variadic function are stored to the
3621     // VarArgsFrameIndex on the stack so that they may be loaded by
3622     // dereferencing the result of va_next.
3623     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3624       // Get an existing live-in vreg, or add a new one.
3625       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3626       if (!VReg)
3627         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3628 
3629       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3630       SDValue Store =
3631           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3632       MemOps.push_back(Store);
3633       // Increment the address by four for the next argument to store
3634       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3635       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3636     }
3637 
3638     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3639     // is set.
3640     // The double arguments are stored to the VarArgsFrameIndex
3641     // on the stack.
3642     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3643       // Get an existing live-in vreg, or add a new one.
3644       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3645       if (!VReg)
3646         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3647 
3648       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3649       SDValue Store =
3650           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3651       MemOps.push_back(Store);
3652       // Increment the address by eight for the next argument to store
3653       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3654                                          PtrVT);
3655       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3656     }
3657   }
3658 
3659   if (!MemOps.empty())
3660     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3661 
3662   return Chain;
3663 }
3664 
3665 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3666 // value to MVT::i64 and then truncate to the correct register size.
3667 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3668                                              EVT ObjectVT, SelectionDAG &DAG,
3669                                              SDValue ArgVal,
3670                                              const SDLoc &dl) const {
3671   if (Flags.isSExt())
3672     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3673                          DAG.getValueType(ObjectVT));
3674   else if (Flags.isZExt())
3675     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3676                          DAG.getValueType(ObjectVT));
3677 
3678   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3679 }
3680 
3681 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3682     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3683     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3684     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3685   // TODO: add description of PPC stack frame format, or at least some docs.
3686   //
3687   bool isELFv2ABI = Subtarget.isELFv2ABI();
3688   bool isLittleEndian = Subtarget.isLittleEndian();
3689   MachineFunction &MF = DAG.getMachineFunction();
3690   MachineFrameInfo &MFI = MF.getFrameInfo();
3691   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3692 
3693   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3694          "fastcc not supported on varargs functions");
3695 
3696   EVT PtrVT = getPointerTy(MF.getDataLayout());
3697   // Potential tail calls could cause overwriting of argument stack slots.
3698   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3699                        (CallConv == CallingConv::Fast));
3700   unsigned PtrByteSize = 8;
3701   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3702 
3703   static const MCPhysReg GPR[] = {
3704     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3705     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3706   };
3707   static const MCPhysReg VR[] = {
3708     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3709     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3710   };
3711 
3712   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3713   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3714   const unsigned Num_VR_Regs  = array_lengthof(VR);
3715   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3716 
3717   // Do a first pass over the arguments to determine whether the ABI
3718   // guarantees that our caller has allocated the parameter save area
3719   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3720   // in the ELFv2 ABI, it is true if this is a vararg function or if
3721   // any parameter is located in a stack slot.
3722 
3723   bool HasParameterArea = !isELFv2ABI || isVarArg;
3724   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3725   unsigned NumBytes = LinkageSize;
3726   unsigned AvailableFPRs = Num_FPR_Regs;
3727   unsigned AvailableVRs = Num_VR_Regs;
3728   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3729     if (Ins[i].Flags.isNest())
3730       continue;
3731 
3732     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3733                                PtrByteSize, LinkageSize, ParamAreaSize,
3734                                NumBytes, AvailableFPRs, AvailableVRs,
3735                                Subtarget.hasQPX()))
3736       HasParameterArea = true;
3737   }
3738 
3739   // Add DAG nodes to load the arguments or copy them out of registers.  On
3740   // entry to a function on PPC, the arguments start after the linkage area,
3741   // although the first ones are often in registers.
3742 
3743   unsigned ArgOffset = LinkageSize;
3744   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3745   unsigned &QFPR_idx = FPR_idx;
3746   SmallVector<SDValue, 8> MemOps;
3747   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3748   unsigned CurArgIdx = 0;
3749   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3750     SDValue ArgVal;
3751     bool needsLoad = false;
3752     EVT ObjectVT = Ins[ArgNo].VT;
3753     EVT OrigVT = Ins[ArgNo].ArgVT;
3754     unsigned ObjSize = ObjectVT.getStoreSize();
3755     unsigned ArgSize = ObjSize;
3756     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3757     if (Ins[ArgNo].isOrigArg()) {
3758       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3759       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3760     }
3761     // We re-align the argument offset for each argument, except when using the
3762     // fast calling convention, when we need to make sure we do that only when
3763     // we'll actually use a stack slot.
3764     unsigned CurArgOffset, Align;
3765     auto ComputeArgOffset = [&]() {
3766       /* Respect alignment of argument on the stack.  */
3767       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3768       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3769       CurArgOffset = ArgOffset;
3770     };
3771 
3772     if (CallConv != CallingConv::Fast) {
3773       ComputeArgOffset();
3774 
3775       /* Compute GPR index associated with argument offset.  */
3776       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3777       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3778     }
3779 
3780     // FIXME the codegen can be much improved in some cases.
3781     // We do not have to keep everything in memory.
3782     if (Flags.isByVal()) {
3783       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3784 
3785       if (CallConv == CallingConv::Fast)
3786         ComputeArgOffset();
3787 
3788       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3789       ObjSize = Flags.getByValSize();
3790       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3791       // Empty aggregate parameters do not take up registers.  Examples:
3792       //   struct { } a;
3793       //   union  { } b;
3794       //   int c[0];
3795       // etc.  However, we have to provide a place-holder in InVals, so
3796       // pretend we have an 8-byte item at the current address for that
3797       // purpose.
3798       if (!ObjSize) {
3799         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3800         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3801         InVals.push_back(FIN);
3802         continue;
3803       }
3804 
3805       // Create a stack object covering all stack doublewords occupied
3806       // by the argument.  If the argument is (fully or partially) on
3807       // the stack, or if the argument is fully in registers but the
3808       // caller has allocated the parameter save anyway, we can refer
3809       // directly to the caller's stack frame.  Otherwise, create a
3810       // local copy in our own frame.
3811       int FI;
3812       if (HasParameterArea ||
3813           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3814         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3815       else
3816         FI = MFI.CreateStackObject(ArgSize, Align, false);
3817       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3818 
3819       // Handle aggregates smaller than 8 bytes.
3820       if (ObjSize < PtrByteSize) {
3821         // The value of the object is its address, which differs from the
3822         // address of the enclosing doubleword on big-endian systems.
3823         SDValue Arg = FIN;
3824         if (!isLittleEndian) {
3825           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3826           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3827         }
3828         InVals.push_back(Arg);
3829 
3830         if (GPR_idx != Num_GPR_Regs) {
3831           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3832           FuncInfo->addLiveInAttr(VReg, Flags);
3833           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3834           SDValue Store;
3835 
3836           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3837             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3838                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3839             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3840                                       MachinePointerInfo(&*FuncArg), ObjType);
3841           } else {
3842             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3843             // store the whole register as-is to the parameter save area
3844             // slot.
3845             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3846                                  MachinePointerInfo(&*FuncArg));
3847           }
3848 
3849           MemOps.push_back(Store);
3850         }
3851         // Whether we copied from a register or not, advance the offset
3852         // into the parameter save area by a full doubleword.
3853         ArgOffset += PtrByteSize;
3854         continue;
3855       }
3856 
3857       // The value of the object is its address, which is the address of
3858       // its first stack doubleword.
3859       InVals.push_back(FIN);
3860 
3861       // Store whatever pieces of the object are in registers to memory.
3862       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3863         if (GPR_idx == Num_GPR_Regs)
3864           break;
3865 
3866         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3867         FuncInfo->addLiveInAttr(VReg, Flags);
3868         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3869         SDValue Addr = FIN;
3870         if (j) {
3871           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3872           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3873         }
3874         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3875                                      MachinePointerInfo(&*FuncArg, j));
3876         MemOps.push_back(Store);
3877         ++GPR_idx;
3878       }
3879       ArgOffset += ArgSize;
3880       continue;
3881     }
3882 
3883     switch (ObjectVT.getSimpleVT().SimpleTy) {
3884     default: llvm_unreachable("Unhandled argument type!");
3885     case MVT::i1:
3886     case MVT::i32:
3887     case MVT::i64:
3888       if (Flags.isNest()) {
3889         // The 'nest' parameter, if any, is passed in R11.
3890         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3891         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3892 
3893         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3894           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3895 
3896         break;
3897       }
3898 
3899       // These can be scalar arguments or elements of an integer array type
3900       // passed directly.  Clang may use those instead of "byval" aggregate
3901       // types to avoid forcing arguments to memory unnecessarily.
3902       if (GPR_idx != Num_GPR_Regs) {
3903         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3904         FuncInfo->addLiveInAttr(VReg, Flags);
3905         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3906 
3907         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3908           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3909           // value to MVT::i64 and then truncate to the correct register size.
3910           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3911       } else {
3912         if (CallConv == CallingConv::Fast)
3913           ComputeArgOffset();
3914 
3915         needsLoad = true;
3916         ArgSize = PtrByteSize;
3917       }
3918       if (CallConv != CallingConv::Fast || needsLoad)
3919         ArgOffset += 8;
3920       break;
3921 
3922     case MVT::f32:
3923     case MVT::f64:
3924       // These can be scalar arguments or elements of a float array type
3925       // passed directly.  The latter are used to implement ELFv2 homogenous
3926       // float aggregates.
3927       if (FPR_idx != Num_FPR_Regs) {
3928         unsigned VReg;
3929 
3930         if (ObjectVT == MVT::f32)
3931           VReg = MF.addLiveIn(FPR[FPR_idx],
3932                               Subtarget.hasP8Vector()
3933                                   ? &PPC::VSSRCRegClass
3934                                   : &PPC::F4RCRegClass);
3935         else
3936           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3937                                                 ? &PPC::VSFRCRegClass
3938                                                 : &PPC::F8RCRegClass);
3939 
3940         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3941         ++FPR_idx;
3942       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3943         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3944         // once we support fp <-> gpr moves.
3945 
3946         // This can only ever happen in the presence of f32 array types,
3947         // since otherwise we never run out of FPRs before running out
3948         // of GPRs.
3949         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3950         FuncInfo->addLiveInAttr(VReg, Flags);
3951         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3952 
3953         if (ObjectVT == MVT::f32) {
3954           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3955             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3956                                  DAG.getConstant(32, dl, MVT::i32));
3957           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3958         }
3959 
3960         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3961       } else {
3962         if (CallConv == CallingConv::Fast)
3963           ComputeArgOffset();
3964 
3965         needsLoad = true;
3966       }
3967 
3968       // When passing an array of floats, the array occupies consecutive
3969       // space in the argument area; only round up to the next doubleword
3970       // at the end of the array.  Otherwise, each float takes 8 bytes.
3971       if (CallConv != CallingConv::Fast || needsLoad) {
3972         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3973         ArgOffset += ArgSize;
3974         if (Flags.isInConsecutiveRegsLast())
3975           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3976       }
3977       break;
3978     case MVT::v4f32:
3979     case MVT::v4i32:
3980     case MVT::v8i16:
3981     case MVT::v16i8:
3982     case MVT::v2f64:
3983     case MVT::v2i64:
3984     case MVT::v1i128:
3985     case MVT::f128:
3986       if (!Subtarget.hasQPX()) {
3987         // These can be scalar arguments or elements of a vector array type
3988         // passed directly.  The latter are used to implement ELFv2 homogenous
3989         // vector aggregates.
3990         if (VR_idx != Num_VR_Regs) {
3991           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3992           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3993           ++VR_idx;
3994         } else {
3995           if (CallConv == CallingConv::Fast)
3996             ComputeArgOffset();
3997           needsLoad = true;
3998         }
3999         if (CallConv != CallingConv::Fast || needsLoad)
4000           ArgOffset += 16;
4001         break;
4002       } // not QPX
4003 
4004       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
4005              "Invalid QPX parameter type");
4006       LLVM_FALLTHROUGH;
4007 
4008     case MVT::v4f64:
4009     case MVT::v4i1:
4010       // QPX vectors are treated like their scalar floating-point subregisters
4011       // (except that they're larger).
4012       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4013       if (QFPR_idx != Num_QFPR_Regs) {
4014         const TargetRegisterClass *RC;
4015         switch (ObjectVT.getSimpleVT().SimpleTy) {
4016         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4017         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4018         default:         RC = &PPC::QBRCRegClass; break;
4019         }
4020 
4021         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4022         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4023         ++QFPR_idx;
4024       } else {
4025         if (CallConv == CallingConv::Fast)
4026           ComputeArgOffset();
4027         needsLoad = true;
4028       }
4029       if (CallConv != CallingConv::Fast || needsLoad)
4030         ArgOffset += Sz;
4031       break;
4032     }
4033 
4034     // We need to load the argument to a virtual register if we determined
4035     // above that we ran out of physical registers of the appropriate type.
4036     if (needsLoad) {
4037       if (ObjSize < ArgSize && !isLittleEndian)
4038         CurArgOffset += ArgSize - ObjSize;
4039       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4040       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4041       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4042     }
4043 
4044     InVals.push_back(ArgVal);
4045   }
4046 
4047   // Area that is at least reserved in the caller of this function.
4048   unsigned MinReservedArea;
4049   if (HasParameterArea)
4050     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4051   else
4052     MinReservedArea = LinkageSize;
4053 
4054   // Set the size that is at least reserved in caller of this function.  Tail
4055   // call optimized functions' reserved stack space needs to be aligned so that
4056   // taking the difference between two stack areas will result in an aligned
4057   // stack.
4058   MinReservedArea =
4059       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4060   FuncInfo->setMinReservedArea(MinReservedArea);
4061 
4062   // If the function takes variable number of arguments, make a frame index for
4063   // the start of the first vararg value... for expansion of llvm.va_start.
4064   if (isVarArg) {
4065     int Depth = ArgOffset;
4066 
4067     FuncInfo->setVarArgsFrameIndex(
4068       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4069     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4070 
4071     // If this function is vararg, store any remaining integer argument regs
4072     // to their spots on the stack so that they may be loaded by dereferencing
4073     // the result of va_next.
4074     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4075          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4076       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4077       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4078       SDValue Store =
4079           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4080       MemOps.push_back(Store);
4081       // Increment the address by four for the next argument to store
4082       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4083       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4084     }
4085   }
4086 
4087   if (!MemOps.empty())
4088     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4089 
4090   return Chain;
4091 }
4092 
4093 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4094     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4095     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4096     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4097   // TODO: add description of PPC stack frame format, or at least some docs.
4098   //
4099   MachineFunction &MF = DAG.getMachineFunction();
4100   MachineFrameInfo &MFI = MF.getFrameInfo();
4101   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4102 
4103   EVT PtrVT = getPointerTy(MF.getDataLayout());
4104   bool isPPC64 = PtrVT == MVT::i64;
4105   // Potential tail calls could cause overwriting of argument stack slots.
4106   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4107                        (CallConv == CallingConv::Fast));
4108   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4109   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4110   unsigned ArgOffset = LinkageSize;
4111   // Area that is at least reserved in caller of this function.
4112   unsigned MinReservedArea = ArgOffset;
4113 
4114   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4115     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4116     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4117   };
4118   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4119     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4120     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4121   };
4122   static const MCPhysReg VR[] = {
4123     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4124     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4125   };
4126 
4127   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4128   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4129   const unsigned Num_VR_Regs  = array_lengthof( VR);
4130 
4131   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4132 
4133   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4134 
4135   // In 32-bit non-varargs functions, the stack space for vectors is after the
4136   // stack space for non-vectors.  We do not use this space unless we have
4137   // too many vectors to fit in registers, something that only occurs in
4138   // constructed examples:), but we have to walk the arglist to figure
4139   // that out...for the pathological case, compute VecArgOffset as the
4140   // start of the vector parameter area.  Computing VecArgOffset is the
4141   // entire point of the following loop.
4142   unsigned VecArgOffset = ArgOffset;
4143   if (!isVarArg && !isPPC64) {
4144     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4145          ++ArgNo) {
4146       EVT ObjectVT = Ins[ArgNo].VT;
4147       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4148 
4149       if (Flags.isByVal()) {
4150         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4151         unsigned ObjSize = Flags.getByValSize();
4152         unsigned ArgSize =
4153                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4154         VecArgOffset += ArgSize;
4155         continue;
4156       }
4157 
4158       switch(ObjectVT.getSimpleVT().SimpleTy) {
4159       default: llvm_unreachable("Unhandled argument type!");
4160       case MVT::i1:
4161       case MVT::i32:
4162       case MVT::f32:
4163         VecArgOffset += 4;
4164         break;
4165       case MVT::i64:  // PPC64
4166       case MVT::f64:
4167         // FIXME: We are guaranteed to be !isPPC64 at this point.
4168         // Does MVT::i64 apply?
4169         VecArgOffset += 8;
4170         break;
4171       case MVT::v4f32:
4172       case MVT::v4i32:
4173       case MVT::v8i16:
4174       case MVT::v16i8:
4175         // Nothing to do, we're only looking at Nonvector args here.
4176         break;
4177       }
4178     }
4179   }
4180   // We've found where the vector parameter area in memory is.  Skip the
4181   // first 12 parameters; these don't use that memory.
4182   VecArgOffset = ((VecArgOffset+15)/16)*16;
4183   VecArgOffset += 12*16;
4184 
4185   // Add DAG nodes to load the arguments or copy them out of registers.  On
4186   // entry to a function on PPC, the arguments start after the linkage area,
4187   // although the first ones are often in registers.
4188 
4189   SmallVector<SDValue, 8> MemOps;
4190   unsigned nAltivecParamsAtEnd = 0;
4191   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4192   unsigned CurArgIdx = 0;
4193   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4194     SDValue ArgVal;
4195     bool needsLoad = false;
4196     EVT ObjectVT = Ins[ArgNo].VT;
4197     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4198     unsigned ArgSize = ObjSize;
4199     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4200     if (Ins[ArgNo].isOrigArg()) {
4201       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4202       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4203     }
4204     unsigned CurArgOffset = ArgOffset;
4205 
4206     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4207     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4208         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4209       if (isVarArg || isPPC64) {
4210         MinReservedArea = ((MinReservedArea+15)/16)*16;
4211         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4212                                                   Flags,
4213                                                   PtrByteSize);
4214       } else  nAltivecParamsAtEnd++;
4215     } else
4216       // Calculate min reserved area.
4217       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4218                                                 Flags,
4219                                                 PtrByteSize);
4220 
4221     // FIXME the codegen can be much improved in some cases.
4222     // We do not have to keep everything in memory.
4223     if (Flags.isByVal()) {
4224       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4225 
4226       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4227       ObjSize = Flags.getByValSize();
4228       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4229       // Objects of size 1 and 2 are right justified, everything else is
4230       // left justified.  This means the memory address is adjusted forwards.
4231       if (ObjSize==1 || ObjSize==2) {
4232         CurArgOffset = CurArgOffset + (4 - ObjSize);
4233       }
4234       // The value of the object is its address.
4235       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4236       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4237       InVals.push_back(FIN);
4238       if (ObjSize==1 || ObjSize==2) {
4239         if (GPR_idx != Num_GPR_Regs) {
4240           unsigned VReg;
4241           if (isPPC64)
4242             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4243           else
4244             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4245           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4246           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4247           SDValue Store =
4248               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4249                                 MachinePointerInfo(&*FuncArg), ObjType);
4250           MemOps.push_back(Store);
4251           ++GPR_idx;
4252         }
4253 
4254         ArgOffset += PtrByteSize;
4255 
4256         continue;
4257       }
4258       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4259         // Store whatever pieces of the object are in registers
4260         // to memory.  ArgOffset will be the address of the beginning
4261         // of the object.
4262         if (GPR_idx != Num_GPR_Regs) {
4263           unsigned VReg;
4264           if (isPPC64)
4265             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4266           else
4267             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4268           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4269           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4270           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4271           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4272                                        MachinePointerInfo(&*FuncArg, j));
4273           MemOps.push_back(Store);
4274           ++GPR_idx;
4275           ArgOffset += PtrByteSize;
4276         } else {
4277           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4278           break;
4279         }
4280       }
4281       continue;
4282     }
4283 
4284     switch (ObjectVT.getSimpleVT().SimpleTy) {
4285     default: llvm_unreachable("Unhandled argument type!");
4286     case MVT::i1:
4287     case MVT::i32:
4288       if (!isPPC64) {
4289         if (GPR_idx != Num_GPR_Regs) {
4290           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4291           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4292 
4293           if (ObjectVT == MVT::i1)
4294             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4295 
4296           ++GPR_idx;
4297         } else {
4298           needsLoad = true;
4299           ArgSize = PtrByteSize;
4300         }
4301         // All int arguments reserve stack space in the Darwin ABI.
4302         ArgOffset += PtrByteSize;
4303         break;
4304       }
4305       LLVM_FALLTHROUGH;
4306     case MVT::i64:  // PPC64
4307       if (GPR_idx != Num_GPR_Regs) {
4308         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4309         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4310 
4311         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4312           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4313           // value to MVT::i64 and then truncate to the correct register size.
4314           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4315 
4316         ++GPR_idx;
4317       } else {
4318         needsLoad = true;
4319         ArgSize = PtrByteSize;
4320       }
4321       // All int arguments reserve stack space in the Darwin ABI.
4322       ArgOffset += 8;
4323       break;
4324 
4325     case MVT::f32:
4326     case MVT::f64:
4327       // Every 4 bytes of argument space consumes one of the GPRs available for
4328       // argument passing.
4329       if (GPR_idx != Num_GPR_Regs) {
4330         ++GPR_idx;
4331         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4332           ++GPR_idx;
4333       }
4334       if (FPR_idx != Num_FPR_Regs) {
4335         unsigned VReg;
4336 
4337         if (ObjectVT == MVT::f32)
4338           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4339         else
4340           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4341 
4342         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4343         ++FPR_idx;
4344       } else {
4345         needsLoad = true;
4346       }
4347 
4348       // All FP arguments reserve stack space in the Darwin ABI.
4349       ArgOffset += isPPC64 ? 8 : ObjSize;
4350       break;
4351     case MVT::v4f32:
4352     case MVT::v4i32:
4353     case MVT::v8i16:
4354     case MVT::v16i8:
4355       // Note that vector arguments in registers don't reserve stack space,
4356       // except in varargs functions.
4357       if (VR_idx != Num_VR_Regs) {
4358         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4359         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4360         if (isVarArg) {
4361           while ((ArgOffset % 16) != 0) {
4362             ArgOffset += PtrByteSize;
4363             if (GPR_idx != Num_GPR_Regs)
4364               GPR_idx++;
4365           }
4366           ArgOffset += 16;
4367           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4368         }
4369         ++VR_idx;
4370       } else {
4371         if (!isVarArg && !isPPC64) {
4372           // Vectors go after all the nonvectors.
4373           CurArgOffset = VecArgOffset;
4374           VecArgOffset += 16;
4375         } else {
4376           // Vectors are aligned.
4377           ArgOffset = ((ArgOffset+15)/16)*16;
4378           CurArgOffset = ArgOffset;
4379           ArgOffset += 16;
4380         }
4381         needsLoad = true;
4382       }
4383       break;
4384     }
4385 
4386     // We need to load the argument to a virtual register if we determined above
4387     // that we ran out of physical registers of the appropriate type.
4388     if (needsLoad) {
4389       int FI = MFI.CreateFixedObject(ObjSize,
4390                                      CurArgOffset + (ArgSize - ObjSize),
4391                                      isImmutable);
4392       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4393       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4394     }
4395 
4396     InVals.push_back(ArgVal);
4397   }
4398 
4399   // Allow for Altivec parameters at the end, if needed.
4400   if (nAltivecParamsAtEnd) {
4401     MinReservedArea = ((MinReservedArea+15)/16)*16;
4402     MinReservedArea += 16*nAltivecParamsAtEnd;
4403   }
4404 
4405   // Area that is at least reserved in the caller of this function.
4406   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4407 
4408   // Set the size that is at least reserved in caller of this function.  Tail
4409   // call optimized functions' reserved stack space needs to be aligned so that
4410   // taking the difference between two stack areas will result in an aligned
4411   // stack.
4412   MinReservedArea =
4413       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4414   FuncInfo->setMinReservedArea(MinReservedArea);
4415 
4416   // If the function takes variable number of arguments, make a frame index for
4417   // the start of the first vararg value... for expansion of llvm.va_start.
4418   if (isVarArg) {
4419     int Depth = ArgOffset;
4420 
4421     FuncInfo->setVarArgsFrameIndex(
4422       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4423                             Depth, true));
4424     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4425 
4426     // If this function is vararg, store any remaining integer argument regs
4427     // to their spots on the stack so that they may be loaded by dereferencing
4428     // the result of va_next.
4429     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4430       unsigned VReg;
4431 
4432       if (isPPC64)
4433         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4434       else
4435         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4436 
4437       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4438       SDValue Store =
4439           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4440       MemOps.push_back(Store);
4441       // Increment the address by four for the next argument to store
4442       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4443       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4444     }
4445   }
4446 
4447   if (!MemOps.empty())
4448     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4449 
4450   return Chain;
4451 }
4452 
4453 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4454 /// adjusted to accommodate the arguments for the tailcall.
4455 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4456                                    unsigned ParamSize) {
4457 
4458   if (!isTailCall) return 0;
4459 
4460   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4461   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4462   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4463   // Remember only if the new adjustment is bigger.
4464   if (SPDiff < FI->getTailCallSPDelta())
4465     FI->setTailCallSPDelta(SPDiff);
4466 
4467   return SPDiff;
4468 }
4469 
4470 static bool isFunctionGlobalAddress(SDValue Callee);
4471 
4472 static bool
4473 callsShareTOCBase(const Function *Caller, SDValue Callee,
4474                     const TargetMachine &TM) {
4475    // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4476    // don't have enough information to determine if the caller and calle share
4477    // the same  TOC base, so we have to pessimistically assume they don't for
4478    // correctness.
4479    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4480    if (!G)
4481      return false;
4482 
4483    const GlobalValue *GV = G->getGlobal();
4484   // The medium and large code models are expected to provide a sufficiently
4485   // large TOC to provide all data addressing needs of a module with a
4486   // single TOC. Since each module will be addressed with a single TOC then we
4487   // only need to check that caller and callee don't cross dso boundaries.
4488   if (CodeModel::Medium == TM.getCodeModel() ||
4489       CodeModel::Large == TM.getCodeModel())
4490     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4491 
4492   // Otherwise we need to ensure callee and caller are in the same section,
4493   // since the linker may allocate multiple TOCs, and we don't know which
4494   // sections will belong to the same TOC base.
4495 
4496   if (!GV->isStrongDefinitionForLinker())
4497     return false;
4498 
4499   // Any explicitly-specified sections and section prefixes must also match.
4500   // Also, if we're using -ffunction-sections, then each function is always in
4501   // a different section (the same is true for COMDAT functions).
4502   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4503       GV->getSection() != Caller->getSection())
4504     return false;
4505   if (const auto *F = dyn_cast<Function>(GV)) {
4506     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4507       return false;
4508   }
4509 
4510   // If the callee might be interposed, then we can't assume the ultimate call
4511   // target will be in the same section. Even in cases where we can assume that
4512   // interposition won't happen, in any case where the linker might insert a
4513   // stub to allow for interposition, we must generate code as though
4514   // interposition might occur. To understand why this matters, consider a
4515   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4516   // in the same section, but a is in a different module (i.e. has a different
4517   // TOC base pointer). If the linker allows for interposition between b and c,
4518   // then it will generate a stub for the call edge between b and c which will
4519   // save the TOC pointer into the designated stack slot allocated by b. If we
4520   // return true here, and therefore allow a tail call between b and c, that
4521   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4522   // pointer into the stack slot allocated by a (where the a -> b stub saved
4523   // a's TOC base pointer). If we're not considering a tail call, but rather,
4524   // whether a nop is needed after the call instruction in b, because the linker
4525   // will insert a stub, it might complain about a missing nop if we omit it
4526   // (although many don't complain in this case).
4527   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4528     return false;
4529 
4530   return true;
4531 }
4532 
4533 static bool
4534 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4535                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4536   assert(Subtarget.is64BitELFABI());
4537 
4538   const unsigned PtrByteSize = 8;
4539   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4540 
4541   static const MCPhysReg GPR[] = {
4542     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4543     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4544   };
4545   static const MCPhysReg VR[] = {
4546     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4547     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4548   };
4549 
4550   const unsigned NumGPRs = array_lengthof(GPR);
4551   const unsigned NumFPRs = 13;
4552   const unsigned NumVRs = array_lengthof(VR);
4553   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4554 
4555   unsigned NumBytes = LinkageSize;
4556   unsigned AvailableFPRs = NumFPRs;
4557   unsigned AvailableVRs = NumVRs;
4558 
4559   for (const ISD::OutputArg& Param : Outs) {
4560     if (Param.Flags.isNest()) continue;
4561 
4562     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4563                                PtrByteSize, LinkageSize, ParamAreaSize,
4564                                NumBytes, AvailableFPRs, AvailableVRs,
4565                                Subtarget.hasQPX()))
4566       return true;
4567   }
4568   return false;
4569 }
4570 
4571 static bool
4572 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4573   if (CS.arg_size() != CallerFn->arg_size())
4574     return false;
4575 
4576   ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4577   ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4578   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4579 
4580   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4581     const Value* CalleeArg = *CalleeArgIter;
4582     const Value* CallerArg = &(*CallerArgIter);
4583     if (CalleeArg == CallerArg)
4584       continue;
4585 
4586     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4587     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4588     //      }
4589     // 1st argument of callee is undef and has the same type as caller.
4590     if (CalleeArg->getType() == CallerArg->getType() &&
4591         isa<UndefValue>(CalleeArg))
4592       continue;
4593 
4594     return false;
4595   }
4596 
4597   return true;
4598 }
4599 
4600 // Returns true if TCO is possible between the callers and callees
4601 // calling conventions.
4602 static bool
4603 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4604                                     CallingConv::ID CalleeCC) {
4605   // Tail calls are possible with fastcc and ccc.
4606   auto isTailCallableCC  = [] (CallingConv::ID CC){
4607       return  CC == CallingConv::C || CC == CallingConv::Fast;
4608   };
4609   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4610     return false;
4611 
4612   // We can safely tail call both fastcc and ccc callees from a c calling
4613   // convention caller. If the caller is fastcc, we may have less stack space
4614   // than a non-fastcc caller with the same signature so disable tail-calls in
4615   // that case.
4616   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4617 }
4618 
4619 bool
4620 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4621                                     SDValue Callee,
4622                                     CallingConv::ID CalleeCC,
4623                                     ImmutableCallSite CS,
4624                                     bool isVarArg,
4625                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4626                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4627                                     SelectionDAG& DAG) const {
4628   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4629 
4630   if (DisableSCO && !TailCallOpt) return false;
4631 
4632   // Variadic argument functions are not supported.
4633   if (isVarArg) return false;
4634 
4635   auto &Caller = DAG.getMachineFunction().getFunction();
4636   // Check that the calling conventions are compatible for tco.
4637   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4638     return false;
4639 
4640   // Caller contains any byval parameter is not supported.
4641   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4642     return false;
4643 
4644   // Callee contains any byval parameter is not supported, too.
4645   // Note: This is a quick work around, because in some cases, e.g.
4646   // caller's stack size > callee's stack size, we are still able to apply
4647   // sibling call optimization. For example, gcc is able to do SCO for caller1
4648   // in the following example, but not for caller2.
4649   //   struct test {
4650   //     long int a;
4651   //     char ary[56];
4652   //   } gTest;
4653   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4654   //     b->a = v.a;
4655   //     return 0;
4656   //   }
4657   //   void caller1(struct test a, struct test c, struct test *b) {
4658   //     callee(gTest, b); }
4659   //   void caller2(struct test *b) { callee(gTest, b); }
4660   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4661     return false;
4662 
4663   // If callee and caller use different calling conventions, we cannot pass
4664   // parameters on stack since offsets for the parameter area may be different.
4665   if (Caller.getCallingConv() != CalleeCC &&
4666       needStackSlotPassParameters(Subtarget, Outs))
4667     return false;
4668 
4669   // No TCO/SCO on indirect call because Caller have to restore its TOC
4670   if (!isFunctionGlobalAddress(Callee) &&
4671       !isa<ExternalSymbolSDNode>(Callee))
4672     return false;
4673 
4674   // If the caller and callee potentially have different TOC bases then we
4675   // cannot tail call since we need to restore the TOC pointer after the call.
4676   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4677   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4678     return false;
4679 
4680   // TCO allows altering callee ABI, so we don't have to check further.
4681   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4682     return true;
4683 
4684   if (DisableSCO) return false;
4685 
4686   // If callee use the same argument list that caller is using, then we can
4687   // apply SCO on this case. If it is not, then we need to check if callee needs
4688   // stack for passing arguments.
4689   if (!hasSameArgumentList(&Caller, CS) &&
4690       needStackSlotPassParameters(Subtarget, Outs)) {
4691     return false;
4692   }
4693 
4694   return true;
4695 }
4696 
4697 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4698 /// for tail call optimization. Targets which want to do tail call
4699 /// optimization should implement this function.
4700 bool
4701 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4702                                                      CallingConv::ID CalleeCC,
4703                                                      bool isVarArg,
4704                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4705                                                      SelectionDAG& DAG) const {
4706   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4707     return false;
4708 
4709   // Variable argument functions are not supported.
4710   if (isVarArg)
4711     return false;
4712 
4713   MachineFunction &MF = DAG.getMachineFunction();
4714   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4715   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4716     // Functions containing by val parameters are not supported.
4717     for (unsigned i = 0; i != Ins.size(); i++) {
4718        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4719        if (Flags.isByVal()) return false;
4720     }
4721 
4722     // Non-PIC/GOT tail calls are supported.
4723     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4724       return true;
4725 
4726     // At the moment we can only do local tail calls (in same module, hidden
4727     // or protected) if we are generating PIC.
4728     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4729       return G->getGlobal()->hasHiddenVisibility()
4730           || G->getGlobal()->hasProtectedVisibility();
4731   }
4732 
4733   return false;
4734 }
4735 
4736 /// isCallCompatibleAddress - Return the immediate to use if the specified
4737 /// 32-bit value is representable in the immediate field of a BxA instruction.
4738 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4739   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4740   if (!C) return nullptr;
4741 
4742   int Addr = C->getZExtValue();
4743   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4744       SignExtend32<26>(Addr) != Addr)
4745     return nullptr;  // Top 6 bits have to be sext of immediate.
4746 
4747   return DAG
4748       .getConstant(
4749           (int)C->getZExtValue() >> 2, SDLoc(Op),
4750           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4751       .getNode();
4752 }
4753 
4754 namespace {
4755 
4756 struct TailCallArgumentInfo {
4757   SDValue Arg;
4758   SDValue FrameIdxOp;
4759   int FrameIdx = 0;
4760 
4761   TailCallArgumentInfo() = default;
4762 };
4763 
4764 } // end anonymous namespace
4765 
4766 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4767 static void StoreTailCallArgumentsToStackSlot(
4768     SelectionDAG &DAG, SDValue Chain,
4769     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4770     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4771   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4772     SDValue Arg = TailCallArgs[i].Arg;
4773     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4774     int FI = TailCallArgs[i].FrameIdx;
4775     // Store relative to framepointer.
4776     MemOpChains.push_back(DAG.getStore(
4777         Chain, dl, Arg, FIN,
4778         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4779   }
4780 }
4781 
4782 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4783 /// the appropriate stack slot for the tail call optimized function call.
4784 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4785                                              SDValue OldRetAddr, SDValue OldFP,
4786                                              int SPDiff, const SDLoc &dl) {
4787   if (SPDiff) {
4788     // Calculate the new stack slot for the return address.
4789     MachineFunction &MF = DAG.getMachineFunction();
4790     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4791     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4792     bool isPPC64 = Subtarget.isPPC64();
4793     int SlotSize = isPPC64 ? 8 : 4;
4794     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4795     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4796                                                          NewRetAddrLoc, true);
4797     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4798     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4799     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4800                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4801 
4802     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4803     // slot as the FP is never overwritten.
4804     if (Subtarget.isDarwinABI()) {
4805       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4806       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4807                                                          true);
4808       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4809       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4810                            MachinePointerInfo::getFixedStack(
4811                                DAG.getMachineFunction(), NewFPIdx));
4812     }
4813   }
4814   return Chain;
4815 }
4816 
4817 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4818 /// the position of the argument.
4819 static void
4820 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4821                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4822                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4823   int Offset = ArgOffset + SPDiff;
4824   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4825   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4826   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4827   SDValue FIN = DAG.getFrameIndex(FI, VT);
4828   TailCallArgumentInfo Info;
4829   Info.Arg = Arg;
4830   Info.FrameIdxOp = FIN;
4831   Info.FrameIdx = FI;
4832   TailCallArguments.push_back(Info);
4833 }
4834 
4835 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4836 /// stack slot. Returns the chain as result and the loaded frame pointers in
4837 /// LROpOut/FPOpout. Used when tail calling.
4838 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4839     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4840     SDValue &FPOpOut, const SDLoc &dl) const {
4841   if (SPDiff) {
4842     // Load the LR and FP stack slot for later adjusting.
4843     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4844     LROpOut = getReturnAddrFrameIndex(DAG);
4845     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4846     Chain = SDValue(LROpOut.getNode(), 1);
4847 
4848     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4849     // slot as the FP is never overwritten.
4850     if (Subtarget.isDarwinABI()) {
4851       FPOpOut = getFramePointerFrameIndex(DAG);
4852       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4853       Chain = SDValue(FPOpOut.getNode(), 1);
4854     }
4855   }
4856   return Chain;
4857 }
4858 
4859 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4860 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4861 /// specified by the specific parameter attribute. The copy will be passed as
4862 /// a byval function parameter.
4863 /// Sometimes what we are copying is the end of a larger object, the part that
4864 /// does not fit in registers.
4865 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4866                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4867                                          SelectionDAG &DAG, const SDLoc &dl) {
4868   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4869   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4870                        false, false, false, MachinePointerInfo(),
4871                        MachinePointerInfo());
4872 }
4873 
4874 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4875 /// tail calls.
4876 static void LowerMemOpCallTo(
4877     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4878     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4879     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4880     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4881   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4882   if (!isTailCall) {
4883     if (isVector) {
4884       SDValue StackPtr;
4885       if (isPPC64)
4886         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4887       else
4888         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4889       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4890                            DAG.getConstant(ArgOffset, dl, PtrVT));
4891     }
4892     MemOpChains.push_back(
4893         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4894     // Calculate and remember argument location.
4895   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4896                                   TailCallArguments);
4897 }
4898 
4899 static void
4900 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4901                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4902                 SDValue FPOp,
4903                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4904   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4905   // might overwrite each other in case of tail call optimization.
4906   SmallVector<SDValue, 8> MemOpChains2;
4907   // Do not flag preceding copytoreg stuff together with the following stuff.
4908   InFlag = SDValue();
4909   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4910                                     MemOpChains2, dl);
4911   if (!MemOpChains2.empty())
4912     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4913 
4914   // Store the return address to the appropriate stack slot.
4915   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4916 
4917   // Emit callseq_end just before tailcall node.
4918   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4919                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4920   InFlag = Chain.getValue(1);
4921 }
4922 
4923 // Is this global address that of a function that can be called by name? (as
4924 // opposed to something that must hold a descriptor for an indirect call).
4925 static bool isFunctionGlobalAddress(SDValue Callee) {
4926   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4927     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4928         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4929       return false;
4930 
4931     return G->getGlobal()->getValueType()->isFunctionTy();
4932   }
4933 
4934   return false;
4935 }
4936 
4937 static unsigned
4938 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4939             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4940             bool isPatchPoint, bool hasNest,
4941             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4942             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4943             ImmutableCallSite CS, const PPCSubtarget &Subtarget) {
4944   bool isPPC64 = Subtarget.isPPC64();
4945   bool isSVR4ABI = Subtarget.isSVR4ABI();
4946   bool is64BitELFv1ABI = isPPC64 && isSVR4ABI && !Subtarget.isELFv2ABI();
4947   bool isAIXABI = Subtarget.isAIXABI();
4948 
4949   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4950   NodeTys.push_back(MVT::Other);   // Returns a chain
4951   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4952 
4953   unsigned CallOpc = PPCISD::CALL;
4954 
4955   bool needIndirectCall = true;
4956   if (!isSVR4ABI || !isPPC64)
4957     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4958       // If this is an absolute destination address, use the munged value.
4959       Callee = SDValue(Dest, 0);
4960       needIndirectCall = false;
4961     }
4962 
4963   // PC-relative references to external symbols should go through $stub, unless
4964   // we're building with the leopard linker or later, which automatically
4965   // synthesizes these stubs.
4966   const TargetMachine &TM = DAG.getTarget();
4967   const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
4968   const GlobalValue *GV = nullptr;
4969   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4970     GV = G->getGlobal();
4971   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4972   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
4973   // a static relocation model causes some versions of GNU LD (2.17.50, at
4974   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
4975   // built with secure-PLT.
4976   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64 &&
4977     Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
4978 
4979   // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4980   // every direct call is) turn it into a TargetGlobalAddress /
4981   // TargetExternalSymbol node so that legalize doesn't hack it.
4982   if (isFunctionGlobalAddress(Callee)) {
4983     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4984 
4985     // A call to a TLS address is actually an indirect call to a
4986     // thread-specific pointer.
4987     unsigned OpFlags = 0;
4988     if (UsePlt)
4989       OpFlags = PPCII::MO_PLT;
4990 
4991     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4992                                         Callee.getValueType(), 0, OpFlags);
4993     needIndirectCall = false;
4994   }
4995 
4996   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4997     unsigned char OpFlags = 0;
4998 
4999     if (UsePlt)
5000       OpFlags = PPCII::MO_PLT;
5001 
5002     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
5003                                          OpFlags);
5004     needIndirectCall = false;
5005   }
5006 
5007   if (isPatchPoint) {
5008     // We'll form an invalid direct call when lowering a patchpoint; the full
5009     // sequence for an indirect call is complicated, and many of the
5010     // instructions introduced might have side effects (and, thus, can't be
5011     // removed later). The call itself will be removed as soon as the
5012     // argument/return lowering is complete, so the fact that it has the wrong
5013     // kind of operands should not really matter.
5014     needIndirectCall = false;
5015   }
5016 
5017   if (needIndirectCall) {
5018     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
5019     // to do the call, we can't use PPCISD::CALL.
5020     SDValue MTCTROps[] = {Chain, Callee, InFlag};
5021 
5022     if (is64BitELFv1ABI) {
5023       // Function pointers in the 64-bit SVR4 ABI do not point to the function
5024       // entry point, but to the function descriptor (the function entry point
5025       // address is part of the function descriptor though).
5026       // The function descriptor is a three doubleword structure with the
5027       // following fields: function entry point, TOC base address and
5028       // environment pointer.
5029       // Thus for a call through a function pointer, the following actions need
5030       // to be performed:
5031       //   1. Save the TOC of the caller in the TOC save area of its stack
5032       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5033       //   2. Load the address of the function entry point from the function
5034       //      descriptor.
5035       //   3. Load the TOC of the callee from the function descriptor into r2.
5036       //   4. Load the environment pointer from the function descriptor into
5037       //      r11.
5038       //   5. Branch to the function entry point address.
5039       //   6. On return of the callee, the TOC of the caller needs to be
5040       //      restored (this is done in FinishCall()).
5041       //
5042       // The loads are scheduled at the beginning of the call sequence, and the
5043       // register copies are flagged together to ensure that no other
5044       // operations can be scheduled in between. E.g. without flagging the
5045       // copies together, a TOC access in the caller could be scheduled between
5046       // the assignment of the callee TOC and the branch to the callee, which
5047       // results in the TOC access going through the TOC of the callee instead
5048       // of going through the TOC of the caller, which leads to incorrect code.
5049 
5050       // Load the address of the function entry point from the function
5051       // descriptor.
5052       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
5053       if (LDChain.getValueType() == MVT::Glue)
5054         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
5055 
5056       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5057                           ? (MachineMemOperand::MODereferenceable |
5058                              MachineMemOperand::MOInvariant)
5059                           : MachineMemOperand::MONone;
5060 
5061       MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
5062       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
5063                                         /* Alignment = */ 8, MMOFlags);
5064 
5065       // Load environment pointer into r11.
5066       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
5067       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
5068       SDValue LoadEnvPtr =
5069           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
5070                       /* Alignment = */ 8, MMOFlags);
5071 
5072       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
5073       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
5074       SDValue TOCPtr =
5075           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
5076                       /* Alignment = */ 8, MMOFlags);
5077 
5078       setUsesTOCBasePtr(DAG);
5079       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
5080                                         InFlag);
5081       Chain = TOCVal.getValue(0);
5082       InFlag = TOCVal.getValue(1);
5083 
5084       // If the function call has an explicit 'nest' parameter, it takes the
5085       // place of the environment pointer.
5086       if (!hasNest) {
5087         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
5088                                           InFlag);
5089 
5090         Chain = EnvVal.getValue(0);
5091         InFlag = EnvVal.getValue(1);
5092       }
5093 
5094       MTCTROps[0] = Chain;
5095       MTCTROps[1] = LoadFuncPtr;
5096       MTCTROps[2] = InFlag;
5097     }
5098 
5099     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
5100                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
5101     InFlag = Chain.getValue(1);
5102 
5103     NodeTys.clear();
5104     NodeTys.push_back(MVT::Other);
5105     NodeTys.push_back(MVT::Glue);
5106     Ops.push_back(Chain);
5107     CallOpc = PPCISD::BCTRL;
5108     Callee.setNode(nullptr);
5109     // Add use of X11 (holding environment pointer)
5110     if (is64BitELFv1ABI && !hasNest)
5111       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
5112     // Add CTR register as callee so a bctr can be emitted later.
5113     if (isTailCall)
5114       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
5115   }
5116 
5117   // If this is a direct call, pass the chain and the callee.
5118   if (Callee.getNode()) {
5119     Ops.push_back(Chain);
5120     Ops.push_back(Callee);
5121   }
5122   // If this is a tail call add stack pointer delta.
5123   if (isTailCall)
5124     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5125 
5126   // Add argument registers to the end of the list so that they are known live
5127   // into the call.
5128   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5129     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5130                                   RegsToPass[i].second.getValueType()));
5131 
5132   // All calls, in the AIX ABI and 64-bit ELF ABIs, need the TOC register
5133   // live into the call.
5134   // We do need to reserve R2/X2 to appease the verifier for the PATCHPOINT.
5135   if ((isSVR4ABI && isPPC64) || isAIXABI) {
5136     setUsesTOCBasePtr(DAG);
5137 
5138     // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5139     // no way to mark dependencies as implicit here.
5140     // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5141     if (!isPatchPoint)
5142       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::X2
5143                                             : PPC::R2, PtrVT));
5144   }
5145 
5146   return CallOpc;
5147 }
5148 
5149 SDValue PPCTargetLowering::LowerCallResult(
5150     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5151     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5152     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5153   SmallVector<CCValAssign, 16> RVLocs;
5154   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5155                     *DAG.getContext());
5156 
5157   CCRetInfo.AnalyzeCallResult(
5158       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5159                ? RetCC_PPC_Cold
5160                : RetCC_PPC);
5161 
5162   // Copy all of the result registers out of their specified physreg.
5163   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5164     CCValAssign &VA = RVLocs[i];
5165     assert(VA.isRegLoc() && "Can only return in registers!");
5166 
5167     SDValue Val;
5168 
5169     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5170       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5171                                       InFlag);
5172       Chain = Lo.getValue(1);
5173       InFlag = Lo.getValue(2);
5174       VA = RVLocs[++i]; // skip ahead to next loc
5175       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5176                                       InFlag);
5177       Chain = Hi.getValue(1);
5178       InFlag = Hi.getValue(2);
5179       if (!Subtarget.isLittleEndian())
5180         std::swap (Lo, Hi);
5181       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5182     } else {
5183       Val = DAG.getCopyFromReg(Chain, dl,
5184                                VA.getLocReg(), VA.getLocVT(), InFlag);
5185       Chain = Val.getValue(1);
5186       InFlag = Val.getValue(2);
5187     }
5188 
5189     switch (VA.getLocInfo()) {
5190     default: llvm_unreachable("Unknown loc info!");
5191     case CCValAssign::Full: break;
5192     case CCValAssign::AExt:
5193       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5194       break;
5195     case CCValAssign::ZExt:
5196       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5197                         DAG.getValueType(VA.getValVT()));
5198       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5199       break;
5200     case CCValAssign::SExt:
5201       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5202                         DAG.getValueType(VA.getValVT()));
5203       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5204       break;
5205     }
5206 
5207     InVals.push_back(Val);
5208   }
5209 
5210   return Chain;
5211 }
5212 
5213 SDValue PPCTargetLowering::FinishCall(
5214     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
5215     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5216     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
5217     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5218     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5219     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5220   std::vector<EVT> NodeTys;
5221   SmallVector<SDValue, 8> Ops;
5222   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
5223                                  SPDiff, isTailCall, isPatchPoint, hasNest,
5224                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
5225 
5226   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5227   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
5228     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5229 
5230   // When performing tail call optimization the callee pops its arguments off
5231   // the stack. Account for this here so these bytes can be pushed back on in
5232   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5233   int BytesCalleePops =
5234     (CallConv == CallingConv::Fast &&
5235      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
5236 
5237   // Add a register mask operand representing the call-preserved registers.
5238   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5239   const uint32_t *Mask =
5240       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
5241   assert(Mask && "Missing call preserved mask for calling convention");
5242   Ops.push_back(DAG.getRegisterMask(Mask));
5243 
5244   if (InFlag.getNode())
5245     Ops.push_back(InFlag);
5246 
5247   // Emit tail call.
5248   if (isTailCall) {
5249     assert(((Callee.getOpcode() == ISD::Register &&
5250              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5251             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5252             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5253             isa<ConstantSDNode>(Callee)) &&
5254     "Expecting an global address, external symbol, absolute value or register");
5255 
5256     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5257     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
5258   }
5259 
5260   // Add a NOP immediately after the branch instruction when using the 64-bit
5261   // SVR4 or the AIX ABI.
5262   // At link time, if caller and callee are in a different module and
5263   // thus have a different TOC, the call will be replaced with a call to a stub
5264   // function which saves the current TOC, loads the TOC of the callee and
5265   // branches to the callee. The NOP will be replaced with a load instruction
5266   // which restores the TOC of the caller from the TOC save slot of the current
5267   // stack frame. If caller and callee belong to the same module (and have the
5268   // same TOC), the NOP will remain unchanged, or become some other NOP.
5269 
5270   MachineFunction &MF = DAG.getMachineFunction();
5271   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5272   if (!isTailCall && !isPatchPoint &&
5273       ((Subtarget.isSVR4ABI() && Subtarget.isPPC64()) ||
5274        Subtarget.isAIXABI())) {
5275     if (CallOpc == PPCISD::BCTRL) {
5276       if (Subtarget.isAIXABI())
5277         report_fatal_error("Indirect call on AIX is not implemented.");
5278 
5279       // This is a call through a function pointer.
5280       // Restore the caller TOC from the save area into R2.
5281       // See PrepareCall() for more information about calls through function
5282       // pointers in the 64-bit SVR4 ABI.
5283       // We are using a target-specific load with r2 hard coded, because the
5284       // result of a target-independent load would never go directly into r2,
5285       // since r2 is a reserved register (which prevents the register allocator
5286       // from allocating it), resulting in an additional register being
5287       // allocated and an unnecessary move instruction being generated.
5288       CallOpc = PPCISD::BCTRL_LOAD_TOC;
5289 
5290       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
5291       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5292       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5293       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
5294 
5295       // The address needs to go after the chain input but before the flag (or
5296       // any other variadic arguments).
5297       Ops.insert(std::next(Ops.begin()), AddTOC);
5298     } else if (CallOpc == PPCISD::CALL &&
5299       !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) {
5300       // Otherwise insert NOP for non-local calls.
5301       CallOpc = PPCISD::CALL_NOP;
5302     }
5303   }
5304 
5305   if (Subtarget.isAIXABI() && isFunctionGlobalAddress(Callee)) {
5306     // On AIX, direct function calls reference the symbol for the function's
5307     // entry point, which is named by inserting a "." before the function's
5308     // C-linkage name.
5309     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5310     auto &Context = DAG.getMachineFunction().getMMI().getContext();
5311     MCSymbol *S = Context.getOrCreateSymbol(Twine(".") +
5312                                             Twine(G->getGlobal()->getName()));
5313     Callee = DAG.getMCSymbol(S, PtrVT);
5314     // Replace the GlobalAddressSDNode Callee with the MCSymbolSDNode.
5315     Ops[1] = Callee;
5316   }
5317 
5318   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
5319   InFlag = Chain.getValue(1);
5320 
5321   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5322                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5323                              InFlag, dl);
5324   if (!Ins.empty())
5325     InFlag = Chain.getValue(1);
5326 
5327   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
5328                          Ins, dl, DAG, InVals);
5329 }
5330 
5331 SDValue
5332 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5333                              SmallVectorImpl<SDValue> &InVals) const {
5334   SelectionDAG &DAG                     = CLI.DAG;
5335   SDLoc &dl                             = CLI.DL;
5336   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5337   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5338   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5339   SDValue Chain                         = CLI.Chain;
5340   SDValue Callee                        = CLI.Callee;
5341   bool &isTailCall                      = CLI.IsTailCall;
5342   CallingConv::ID CallConv              = CLI.CallConv;
5343   bool isVarArg                         = CLI.IsVarArg;
5344   bool isPatchPoint                     = CLI.IsPatchPoint;
5345   ImmutableCallSite CS                  = CLI.CS;
5346 
5347   if (isTailCall) {
5348     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5349       isTailCall = false;
5350     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5351       isTailCall =
5352         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5353                                                  isVarArg, Outs, Ins, DAG);
5354     else
5355       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5356                                                      Ins, DAG);
5357     if (isTailCall) {
5358       ++NumTailCalls;
5359       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5360         ++NumSiblingCalls;
5361 
5362       assert(isa<GlobalAddressSDNode>(Callee) &&
5363              "Callee should be an llvm::Function object.");
5364       LLVM_DEBUG(
5365           const GlobalValue *GV =
5366               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5367           const unsigned Width =
5368               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5369           dbgs() << "TCO caller: "
5370                  << left_justify(DAG.getMachineFunction().getName(), Width)
5371                  << ", callee linkage: " << GV->getVisibility() << ", "
5372                  << GV->getLinkage() << "\n");
5373     }
5374   }
5375 
5376   if (!isTailCall && CS && CS.isMustTailCall())
5377     report_fatal_error("failed to perform tail call elimination on a call "
5378                        "site marked musttail");
5379 
5380   // When long calls (i.e. indirect calls) are always used, calls are always
5381   // made via function pointer. If we have a function name, first translate it
5382   // into a pointer.
5383   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5384       !isTailCall)
5385     Callee = LowerGlobalAddress(Callee, DAG);
5386 
5387   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5388     return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
5389                             isTailCall, isPatchPoint, Outs, OutVals, Ins,
5390                             dl, DAG, InVals, CS);
5391 
5392   if (Subtarget.isSVR4ABI())
5393     return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
5394                             isTailCall, isPatchPoint, Outs, OutVals, Ins,
5395                             dl, DAG, InVals, CS);
5396 
5397   if (Subtarget.isAIXABI())
5398     return LowerCall_AIX(Chain, Callee, CallConv, isVarArg,
5399                          isTailCall, isPatchPoint, Outs, OutVals, Ins,
5400                          dl, DAG, InVals, CS);
5401 
5402   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
5403                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
5404                           dl, DAG, InVals, CS);
5405 }
5406 
5407 SDValue PPCTargetLowering::LowerCall_32SVR4(
5408     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5409     bool isTailCall, bool isPatchPoint,
5410     const SmallVectorImpl<ISD::OutputArg> &Outs,
5411     const SmallVectorImpl<SDValue> &OutVals,
5412     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5413     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5414     ImmutableCallSite CS) const {
5415   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5416   // of the 32-bit SVR4 ABI stack frame layout.
5417 
5418   assert((CallConv == CallingConv::C ||
5419           CallConv == CallingConv::Cold ||
5420           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5421 
5422   unsigned PtrByteSize = 4;
5423 
5424   MachineFunction &MF = DAG.getMachineFunction();
5425 
5426   // Mark this function as potentially containing a function that contains a
5427   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5428   // and restoring the callers stack pointer in this functions epilog. This is
5429   // done because by tail calling the called function might overwrite the value
5430   // in this function's (MF) stack pointer stack slot 0(SP).
5431   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5432       CallConv == CallingConv::Fast)
5433     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5434 
5435   // Count how many bytes are to be pushed on the stack, including the linkage
5436   // area, parameter list area and the part of the local variable space which
5437   // contains copies of aggregates which are passed by value.
5438 
5439   // Assign locations to all of the outgoing arguments.
5440   SmallVector<CCValAssign, 16> ArgLocs;
5441   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5442 
5443   // Reserve space for the linkage area on the stack.
5444   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5445                        PtrByteSize);
5446   if (useSoftFloat())
5447     CCInfo.PreAnalyzeCallOperands(Outs);
5448 
5449   if (isVarArg) {
5450     // Handle fixed and variable vector arguments differently.
5451     // Fixed vector arguments go into registers as long as registers are
5452     // available. Variable vector arguments always go into memory.
5453     unsigned NumArgs = Outs.size();
5454 
5455     for (unsigned i = 0; i != NumArgs; ++i) {
5456       MVT ArgVT = Outs[i].VT;
5457       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5458       bool Result;
5459 
5460       if (Outs[i].IsFixed) {
5461         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5462                                CCInfo);
5463       } else {
5464         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5465                                       ArgFlags, CCInfo);
5466       }
5467 
5468       if (Result) {
5469 #ifndef NDEBUG
5470         errs() << "Call operand #" << i << " has unhandled type "
5471              << EVT(ArgVT).getEVTString() << "\n";
5472 #endif
5473         llvm_unreachable(nullptr);
5474       }
5475     }
5476   } else {
5477     // All arguments are treated the same.
5478     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5479   }
5480   CCInfo.clearWasPPCF128();
5481 
5482   // Assign locations to all of the outgoing aggregate by value arguments.
5483   SmallVector<CCValAssign, 16> ByValArgLocs;
5484   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5485 
5486   // Reserve stack space for the allocations in CCInfo.
5487   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5488 
5489   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5490 
5491   // Size of the linkage area, parameter list area and the part of the local
5492   // space variable where copies of aggregates which are passed by value are
5493   // stored.
5494   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5495 
5496   // Calculate by how many bytes the stack has to be adjusted in case of tail
5497   // call optimization.
5498   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5499 
5500   // Adjust the stack pointer for the new arguments...
5501   // These operations are automatically eliminated by the prolog/epilog pass
5502   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5503   SDValue CallSeqStart = Chain;
5504 
5505   // Load the return address and frame pointer so it can be moved somewhere else
5506   // later.
5507   SDValue LROp, FPOp;
5508   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5509 
5510   // Set up a copy of the stack pointer for use loading and storing any
5511   // arguments that may not fit in the registers available for argument
5512   // passing.
5513   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5514 
5515   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5516   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5517   SmallVector<SDValue, 8> MemOpChains;
5518 
5519   bool seenFloatArg = false;
5520   // Walk the register/memloc assignments, inserting copies/loads.
5521   // i - Tracks the index into the list of registers allocated for the call
5522   // RealArgIdx - Tracks the index into the list of actual function arguments
5523   // j - Tracks the index into the list of byval arguments
5524   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5525        i != e;
5526        ++i, ++RealArgIdx) {
5527     CCValAssign &VA = ArgLocs[i];
5528     SDValue Arg = OutVals[RealArgIdx];
5529     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5530 
5531     if (Flags.isByVal()) {
5532       // Argument is an aggregate which is passed by value, thus we need to
5533       // create a copy of it in the local variable space of the current stack
5534       // frame (which is the stack frame of the caller) and pass the address of
5535       // this copy to the callee.
5536       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5537       CCValAssign &ByValVA = ByValArgLocs[j++];
5538       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5539 
5540       // Memory reserved in the local variable space of the callers stack frame.
5541       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5542 
5543       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5544       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5545                            StackPtr, PtrOff);
5546 
5547       // Create a copy of the argument in the local area of the current
5548       // stack frame.
5549       SDValue MemcpyCall =
5550         CreateCopyOfByValArgument(Arg, PtrOff,
5551                                   CallSeqStart.getNode()->getOperand(0),
5552                                   Flags, DAG, dl);
5553 
5554       // This must go outside the CALLSEQ_START..END.
5555       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5556                                                      SDLoc(MemcpyCall));
5557       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5558                              NewCallSeqStart.getNode());
5559       Chain = CallSeqStart = NewCallSeqStart;
5560 
5561       // Pass the address of the aggregate copy on the stack either in a
5562       // physical register or in the parameter list area of the current stack
5563       // frame to the callee.
5564       Arg = PtrOff;
5565     }
5566 
5567     // When useCRBits() is true, there can be i1 arguments.
5568     // It is because getRegisterType(MVT::i1) => MVT::i1,
5569     // and for other integer types getRegisterType() => MVT::i32.
5570     // Extend i1 and ensure callee will get i32.
5571     if (Arg.getValueType() == MVT::i1)
5572       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5573                         dl, MVT::i32, Arg);
5574 
5575     if (VA.isRegLoc()) {
5576       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5577       // Put argument in a physical register.
5578       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5579         bool IsLE = Subtarget.isLittleEndian();
5580         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5581                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5582         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5583         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5584                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5585         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5586                              SVal.getValue(0)));
5587       } else
5588         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5589     } else {
5590       // Put argument in the parameter list area of the current stack frame.
5591       assert(VA.isMemLoc());
5592       unsigned LocMemOffset = VA.getLocMemOffset();
5593 
5594       if (!isTailCall) {
5595         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5596         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5597                              StackPtr, PtrOff);
5598 
5599         MemOpChains.push_back(
5600             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5601       } else {
5602         // Calculate and remember argument location.
5603         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5604                                  TailCallArguments);
5605       }
5606     }
5607   }
5608 
5609   if (!MemOpChains.empty())
5610     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5611 
5612   // Build a sequence of copy-to-reg nodes chained together with token chain
5613   // and flag operands which copy the outgoing args into the appropriate regs.
5614   SDValue InFlag;
5615   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5616     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5617                              RegsToPass[i].second, InFlag);
5618     InFlag = Chain.getValue(1);
5619   }
5620 
5621   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5622   // registers.
5623   if (isVarArg) {
5624     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5625     SDValue Ops[] = { Chain, InFlag };
5626 
5627     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5628                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5629 
5630     InFlag = Chain.getValue(1);
5631   }
5632 
5633   if (isTailCall)
5634     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5635                     TailCallArguments);
5636 
5637   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5638                     /* unused except on PPC64 ELFv1 */ false, DAG,
5639                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5640                     NumBytes, Ins, InVals, CS);
5641 }
5642 
5643 // Copy an argument into memory, being careful to do this outside the
5644 // call sequence for the call to which the argument belongs.
5645 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5646     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5647     SelectionDAG &DAG, const SDLoc &dl) const {
5648   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5649                         CallSeqStart.getNode()->getOperand(0),
5650                         Flags, DAG, dl);
5651   // The MEMCPY must go outside the CALLSEQ_START..END.
5652   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5653   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5654                                                  SDLoc(MemcpyCall));
5655   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5656                          NewCallSeqStart.getNode());
5657   return NewCallSeqStart;
5658 }
5659 
5660 SDValue PPCTargetLowering::LowerCall_64SVR4(
5661     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5662     bool isTailCall, bool isPatchPoint,
5663     const SmallVectorImpl<ISD::OutputArg> &Outs,
5664     const SmallVectorImpl<SDValue> &OutVals,
5665     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5666     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5667     ImmutableCallSite CS) const {
5668   bool isELFv2ABI = Subtarget.isELFv2ABI();
5669   bool isLittleEndian = Subtarget.isLittleEndian();
5670   unsigned NumOps = Outs.size();
5671   bool hasNest = false;
5672   bool IsSibCall = false;
5673 
5674   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5675   unsigned PtrByteSize = 8;
5676 
5677   MachineFunction &MF = DAG.getMachineFunction();
5678 
5679   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5680     IsSibCall = true;
5681 
5682   // Mark this function as potentially containing a function that contains a
5683   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5684   // and restoring the callers stack pointer in this functions epilog. This is
5685   // done because by tail calling the called function might overwrite the value
5686   // in this function's (MF) stack pointer stack slot 0(SP).
5687   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5688       CallConv == CallingConv::Fast)
5689     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5690 
5691   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5692          "fastcc not supported on varargs functions");
5693 
5694   // Count how many bytes are to be pushed on the stack, including the linkage
5695   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5696   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5697   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5698   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5699   unsigned NumBytes = LinkageSize;
5700   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5701   unsigned &QFPR_idx = FPR_idx;
5702 
5703   static const MCPhysReg GPR[] = {
5704     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5705     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5706   };
5707   static const MCPhysReg VR[] = {
5708     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5709     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5710   };
5711 
5712   const unsigned NumGPRs = array_lengthof(GPR);
5713   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5714   const unsigned NumVRs  = array_lengthof(VR);
5715   const unsigned NumQFPRs = NumFPRs;
5716 
5717   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5718   // can be passed to the callee in registers.
5719   // For the fast calling convention, there is another check below.
5720   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5721   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5722   if (!HasParameterArea) {
5723     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5724     unsigned AvailableFPRs = NumFPRs;
5725     unsigned AvailableVRs = NumVRs;
5726     unsigned NumBytesTmp = NumBytes;
5727     for (unsigned i = 0; i != NumOps; ++i) {
5728       if (Outs[i].Flags.isNest()) continue;
5729       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5730                                 PtrByteSize, LinkageSize, ParamAreaSize,
5731                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5732                                 Subtarget.hasQPX()))
5733         HasParameterArea = true;
5734     }
5735   }
5736 
5737   // When using the fast calling convention, we don't provide backing for
5738   // arguments that will be in registers.
5739   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5740 
5741   // Avoid allocating parameter area for fastcc functions if all the arguments
5742   // can be passed in the registers.
5743   if (CallConv == CallingConv::Fast)
5744     HasParameterArea = false;
5745 
5746   // Add up all the space actually used.
5747   for (unsigned i = 0; i != NumOps; ++i) {
5748     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5749     EVT ArgVT = Outs[i].VT;
5750     EVT OrigVT = Outs[i].ArgVT;
5751 
5752     if (Flags.isNest())
5753       continue;
5754 
5755     if (CallConv == CallingConv::Fast) {
5756       if (Flags.isByVal()) {
5757         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5758         if (NumGPRsUsed > NumGPRs)
5759           HasParameterArea = true;
5760       } else {
5761         switch (ArgVT.getSimpleVT().SimpleTy) {
5762         default: llvm_unreachable("Unexpected ValueType for argument!");
5763         case MVT::i1:
5764         case MVT::i32:
5765         case MVT::i64:
5766           if (++NumGPRsUsed <= NumGPRs)
5767             continue;
5768           break;
5769         case MVT::v4i32:
5770         case MVT::v8i16:
5771         case MVT::v16i8:
5772         case MVT::v2f64:
5773         case MVT::v2i64:
5774         case MVT::v1i128:
5775         case MVT::f128:
5776           if (++NumVRsUsed <= NumVRs)
5777             continue;
5778           break;
5779         case MVT::v4f32:
5780           // When using QPX, this is handled like a FP register, otherwise, it
5781           // is an Altivec register.
5782           if (Subtarget.hasQPX()) {
5783             if (++NumFPRsUsed <= NumFPRs)
5784               continue;
5785           } else {
5786             if (++NumVRsUsed <= NumVRs)
5787               continue;
5788           }
5789           break;
5790         case MVT::f32:
5791         case MVT::f64:
5792         case MVT::v4f64: // QPX
5793         case MVT::v4i1:  // QPX
5794           if (++NumFPRsUsed <= NumFPRs)
5795             continue;
5796           break;
5797         }
5798         HasParameterArea = true;
5799       }
5800     }
5801 
5802     /* Respect alignment of argument on the stack.  */
5803     unsigned Align =
5804       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5805     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5806 
5807     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5808     if (Flags.isInConsecutiveRegsLast())
5809       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5810   }
5811 
5812   unsigned NumBytesActuallyUsed = NumBytes;
5813 
5814   // In the old ELFv1 ABI,
5815   // the prolog code of the callee may store up to 8 GPR argument registers to
5816   // the stack, allowing va_start to index over them in memory if its varargs.
5817   // Because we cannot tell if this is needed on the caller side, we have to
5818   // conservatively assume that it is needed.  As such, make sure we have at
5819   // least enough stack space for the caller to store the 8 GPRs.
5820   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5821   // really requires memory operands, e.g. a vararg function.
5822   if (HasParameterArea)
5823     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5824   else
5825     NumBytes = LinkageSize;
5826 
5827   // Tail call needs the stack to be aligned.
5828   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5829       CallConv == CallingConv::Fast)
5830     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5831 
5832   int SPDiff = 0;
5833 
5834   // Calculate by how many bytes the stack has to be adjusted in case of tail
5835   // call optimization.
5836   if (!IsSibCall)
5837     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5838 
5839   // To protect arguments on the stack from being clobbered in a tail call,
5840   // force all the loads to happen before doing any other lowering.
5841   if (isTailCall)
5842     Chain = DAG.getStackArgumentTokenFactor(Chain);
5843 
5844   // Adjust the stack pointer for the new arguments...
5845   // These operations are automatically eliminated by the prolog/epilog pass
5846   if (!IsSibCall)
5847     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5848   SDValue CallSeqStart = Chain;
5849 
5850   // Load the return address and frame pointer so it can be move somewhere else
5851   // later.
5852   SDValue LROp, FPOp;
5853   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5854 
5855   // Set up a copy of the stack pointer for use loading and storing any
5856   // arguments that may not fit in the registers available for argument
5857   // passing.
5858   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5859 
5860   // Figure out which arguments are going to go in registers, and which in
5861   // memory.  Also, if this is a vararg function, floating point operations
5862   // must be stored to our stack, and loaded into integer regs as well, if
5863   // any integer regs are available for argument passing.
5864   unsigned ArgOffset = LinkageSize;
5865 
5866   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5867   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5868 
5869   SmallVector<SDValue, 8> MemOpChains;
5870   for (unsigned i = 0; i != NumOps; ++i) {
5871     SDValue Arg = OutVals[i];
5872     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5873     EVT ArgVT = Outs[i].VT;
5874     EVT OrigVT = Outs[i].ArgVT;
5875 
5876     // PtrOff will be used to store the current argument to the stack if a
5877     // register cannot be found for it.
5878     SDValue PtrOff;
5879 
5880     // We re-align the argument offset for each argument, except when using the
5881     // fast calling convention, when we need to make sure we do that only when
5882     // we'll actually use a stack slot.
5883     auto ComputePtrOff = [&]() {
5884       /* Respect alignment of argument on the stack.  */
5885       unsigned Align =
5886         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5887       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5888 
5889       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5890 
5891       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5892     };
5893 
5894     if (CallConv != CallingConv::Fast) {
5895       ComputePtrOff();
5896 
5897       /* Compute GPR index associated with argument offset.  */
5898       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5899       GPR_idx = std::min(GPR_idx, NumGPRs);
5900     }
5901 
5902     // Promote integers to 64-bit values.
5903     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5904       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5905       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5906       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5907     }
5908 
5909     // FIXME memcpy is used way more than necessary.  Correctness first.
5910     // Note: "by value" is code for passing a structure by value, not
5911     // basic types.
5912     if (Flags.isByVal()) {
5913       // Note: Size includes alignment padding, so
5914       //   struct x { short a; char b; }
5915       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5916       // These are the proper values we need for right-justifying the
5917       // aggregate in a parameter register.
5918       unsigned Size = Flags.getByValSize();
5919 
5920       // An empty aggregate parameter takes up no storage and no
5921       // registers.
5922       if (Size == 0)
5923         continue;
5924 
5925       if (CallConv == CallingConv::Fast)
5926         ComputePtrOff();
5927 
5928       // All aggregates smaller than 8 bytes must be passed right-justified.
5929       if (Size==1 || Size==2 || Size==4) {
5930         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5931         if (GPR_idx != NumGPRs) {
5932           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5933                                         MachinePointerInfo(), VT);
5934           MemOpChains.push_back(Load.getValue(1));
5935           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5936 
5937           ArgOffset += PtrByteSize;
5938           continue;
5939         }
5940       }
5941 
5942       if (GPR_idx == NumGPRs && Size < 8) {
5943         SDValue AddPtr = PtrOff;
5944         if (!isLittleEndian) {
5945           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5946                                           PtrOff.getValueType());
5947           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5948         }
5949         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5950                                                           CallSeqStart,
5951                                                           Flags, DAG, dl);
5952         ArgOffset += PtrByteSize;
5953         continue;
5954       }
5955       // Copy entire object into memory.  There are cases where gcc-generated
5956       // code assumes it is there, even if it could be put entirely into
5957       // registers.  (This is not what the doc says.)
5958 
5959       // FIXME: The above statement is likely due to a misunderstanding of the
5960       // documents.  All arguments must be copied into the parameter area BY
5961       // THE CALLEE in the event that the callee takes the address of any
5962       // formal argument.  That has not yet been implemented.  However, it is
5963       // reasonable to use the stack area as a staging area for the register
5964       // load.
5965 
5966       // Skip this for small aggregates, as we will use the same slot for a
5967       // right-justified copy, below.
5968       if (Size >= 8)
5969         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5970                                                           CallSeqStart,
5971                                                           Flags, DAG, dl);
5972 
5973       // When a register is available, pass a small aggregate right-justified.
5974       if (Size < 8 && GPR_idx != NumGPRs) {
5975         // The easiest way to get this right-justified in a register
5976         // is to copy the structure into the rightmost portion of a
5977         // local variable slot, then load the whole slot into the
5978         // register.
5979         // FIXME: The memcpy seems to produce pretty awful code for
5980         // small aggregates, particularly for packed ones.
5981         // FIXME: It would be preferable to use the slot in the
5982         // parameter save area instead of a new local variable.
5983         SDValue AddPtr = PtrOff;
5984         if (!isLittleEndian) {
5985           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5986           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5987         }
5988         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5989                                                           CallSeqStart,
5990                                                           Flags, DAG, dl);
5991 
5992         // Load the slot into the register.
5993         SDValue Load =
5994             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5995         MemOpChains.push_back(Load.getValue(1));
5996         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5997 
5998         // Done with this argument.
5999         ArgOffset += PtrByteSize;
6000         continue;
6001       }
6002 
6003       // For aggregates larger than PtrByteSize, copy the pieces of the
6004       // object that fit into registers from the parameter save area.
6005       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6006         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6007         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6008         if (GPR_idx != NumGPRs) {
6009           SDValue Load =
6010               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6011           MemOpChains.push_back(Load.getValue(1));
6012           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6013           ArgOffset += PtrByteSize;
6014         } else {
6015           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6016           break;
6017         }
6018       }
6019       continue;
6020     }
6021 
6022     switch (Arg.getSimpleValueType().SimpleTy) {
6023     default: llvm_unreachable("Unexpected ValueType for argument!");
6024     case MVT::i1:
6025     case MVT::i32:
6026     case MVT::i64:
6027       if (Flags.isNest()) {
6028         // The 'nest' parameter, if any, is passed in R11.
6029         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6030         hasNest = true;
6031         break;
6032       }
6033 
6034       // These can be scalar arguments or elements of an integer array type
6035       // passed directly.  Clang may use those instead of "byval" aggregate
6036       // types to avoid forcing arguments to memory unnecessarily.
6037       if (GPR_idx != NumGPRs) {
6038         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6039       } else {
6040         if (CallConv == CallingConv::Fast)
6041           ComputePtrOff();
6042 
6043         assert(HasParameterArea &&
6044                "Parameter area must exist to pass an argument in memory.");
6045         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6046                          true, isTailCall, false, MemOpChains,
6047                          TailCallArguments, dl);
6048         if (CallConv == CallingConv::Fast)
6049           ArgOffset += PtrByteSize;
6050       }
6051       if (CallConv != CallingConv::Fast)
6052         ArgOffset += PtrByteSize;
6053       break;
6054     case MVT::f32:
6055     case MVT::f64: {
6056       // These can be scalar arguments or elements of a float array type
6057       // passed directly.  The latter are used to implement ELFv2 homogenous
6058       // float aggregates.
6059 
6060       // Named arguments go into FPRs first, and once they overflow, the
6061       // remaining arguments go into GPRs and then the parameter save area.
6062       // Unnamed arguments for vararg functions always go to GPRs and
6063       // then the parameter save area.  For now, put all arguments to vararg
6064       // routines always in both locations (FPR *and* GPR or stack slot).
6065       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
6066       bool NeededLoad = false;
6067 
6068       // First load the argument into the next available FPR.
6069       if (FPR_idx != NumFPRs)
6070         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6071 
6072       // Next, load the argument into GPR or stack slot if needed.
6073       if (!NeedGPROrStack)
6074         ;
6075       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
6076         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6077         // once we support fp <-> gpr moves.
6078 
6079         // In the non-vararg case, this can only ever happen in the
6080         // presence of f32 array types, since otherwise we never run
6081         // out of FPRs before running out of GPRs.
6082         SDValue ArgVal;
6083 
6084         // Double values are always passed in a single GPR.
6085         if (Arg.getValueType() != MVT::f32) {
6086           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6087 
6088         // Non-array float values are extended and passed in a GPR.
6089         } else if (!Flags.isInConsecutiveRegs()) {
6090           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6091           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6092 
6093         // If we have an array of floats, we collect every odd element
6094         // together with its predecessor into one GPR.
6095         } else if (ArgOffset % PtrByteSize != 0) {
6096           SDValue Lo, Hi;
6097           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6098           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6099           if (!isLittleEndian)
6100             std::swap(Lo, Hi);
6101           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6102 
6103         // The final element, if even, goes into the first half of a GPR.
6104         } else if (Flags.isInConsecutiveRegsLast()) {
6105           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6106           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6107           if (!isLittleEndian)
6108             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6109                                  DAG.getConstant(32, dl, MVT::i32));
6110 
6111         // Non-final even elements are skipped; they will be handled
6112         // together the with subsequent argument on the next go-around.
6113         } else
6114           ArgVal = SDValue();
6115 
6116         if (ArgVal.getNode())
6117           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6118       } else {
6119         if (CallConv == CallingConv::Fast)
6120           ComputePtrOff();
6121 
6122         // Single-precision floating-point values are mapped to the
6123         // second (rightmost) word of the stack doubleword.
6124         if (Arg.getValueType() == MVT::f32 &&
6125             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6126           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6127           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6128         }
6129 
6130         assert(HasParameterArea &&
6131                "Parameter area must exist to pass an argument in memory.");
6132         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6133                          true, isTailCall, false, MemOpChains,
6134                          TailCallArguments, dl);
6135 
6136         NeededLoad = true;
6137       }
6138       // When passing an array of floats, the array occupies consecutive
6139       // space in the argument area; only round up to the next doubleword
6140       // at the end of the array.  Otherwise, each float takes 8 bytes.
6141       if (CallConv != CallingConv::Fast || NeededLoad) {
6142         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6143                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6144         if (Flags.isInConsecutiveRegsLast())
6145           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6146       }
6147       break;
6148     }
6149     case MVT::v4f32:
6150     case MVT::v4i32:
6151     case MVT::v8i16:
6152     case MVT::v16i8:
6153     case MVT::v2f64:
6154     case MVT::v2i64:
6155     case MVT::v1i128:
6156     case MVT::f128:
6157       if (!Subtarget.hasQPX()) {
6158       // These can be scalar arguments or elements of a vector array type
6159       // passed directly.  The latter are used to implement ELFv2 homogenous
6160       // vector aggregates.
6161 
6162       // For a varargs call, named arguments go into VRs or on the stack as
6163       // usual; unnamed arguments always go to the stack or the corresponding
6164       // GPRs when within range.  For now, we always put the value in both
6165       // locations (or even all three).
6166       if (isVarArg) {
6167         assert(HasParameterArea &&
6168                "Parameter area must exist if we have a varargs call.");
6169         // We could elide this store in the case where the object fits
6170         // entirely in R registers.  Maybe later.
6171         SDValue Store =
6172             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6173         MemOpChains.push_back(Store);
6174         if (VR_idx != NumVRs) {
6175           SDValue Load =
6176               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6177           MemOpChains.push_back(Load.getValue(1));
6178           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6179         }
6180         ArgOffset += 16;
6181         for (unsigned i=0; i<16; i+=PtrByteSize) {
6182           if (GPR_idx == NumGPRs)
6183             break;
6184           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6185                                    DAG.getConstant(i, dl, PtrVT));
6186           SDValue Load =
6187               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6188           MemOpChains.push_back(Load.getValue(1));
6189           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6190         }
6191         break;
6192       }
6193 
6194       // Non-varargs Altivec params go into VRs or on the stack.
6195       if (VR_idx != NumVRs) {
6196         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6197       } else {
6198         if (CallConv == CallingConv::Fast)
6199           ComputePtrOff();
6200 
6201         assert(HasParameterArea &&
6202                "Parameter area must exist to pass an argument in memory.");
6203         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6204                          true, isTailCall, true, MemOpChains,
6205                          TailCallArguments, dl);
6206         if (CallConv == CallingConv::Fast)
6207           ArgOffset += 16;
6208       }
6209 
6210       if (CallConv != CallingConv::Fast)
6211         ArgOffset += 16;
6212       break;
6213       } // not QPX
6214 
6215       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6216              "Invalid QPX parameter type");
6217 
6218       LLVM_FALLTHROUGH;
6219     case MVT::v4f64:
6220     case MVT::v4i1: {
6221       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6222       if (isVarArg) {
6223         assert(HasParameterArea &&
6224                "Parameter area must exist if we have a varargs call.");
6225         // We could elide this store in the case where the object fits
6226         // entirely in R registers.  Maybe later.
6227         SDValue Store =
6228             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6229         MemOpChains.push_back(Store);
6230         if (QFPR_idx != NumQFPRs) {
6231           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6232                                      PtrOff, MachinePointerInfo());
6233           MemOpChains.push_back(Load.getValue(1));
6234           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6235         }
6236         ArgOffset += (IsF32 ? 16 : 32);
6237         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6238           if (GPR_idx == NumGPRs)
6239             break;
6240           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6241                                    DAG.getConstant(i, dl, PtrVT));
6242           SDValue Load =
6243               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6244           MemOpChains.push_back(Load.getValue(1));
6245           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6246         }
6247         break;
6248       }
6249 
6250       // Non-varargs QPX params go into registers or on the stack.
6251       if (QFPR_idx != NumQFPRs) {
6252         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6253       } else {
6254         if (CallConv == CallingConv::Fast)
6255           ComputePtrOff();
6256 
6257         assert(HasParameterArea &&
6258                "Parameter area must exist to pass an argument in memory.");
6259         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6260                          true, isTailCall, true, MemOpChains,
6261                          TailCallArguments, dl);
6262         if (CallConv == CallingConv::Fast)
6263           ArgOffset += (IsF32 ? 16 : 32);
6264       }
6265 
6266       if (CallConv != CallingConv::Fast)
6267         ArgOffset += (IsF32 ? 16 : 32);
6268       break;
6269       }
6270     }
6271   }
6272 
6273   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6274          "mismatch in size of parameter area");
6275   (void)NumBytesActuallyUsed;
6276 
6277   if (!MemOpChains.empty())
6278     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6279 
6280   // Check if this is an indirect call (MTCTR/BCTRL).
6281   // See PrepareCall() for more information about calls through function
6282   // pointers in the 64-bit SVR4 ABI.
6283   if (!isTailCall && !isPatchPoint &&
6284       !isFunctionGlobalAddress(Callee) &&
6285       !isa<ExternalSymbolSDNode>(Callee)) {
6286     // Load r2 into a virtual register and store it to the TOC save area.
6287     setUsesTOCBasePtr(DAG);
6288     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6289     // TOC save area offset.
6290     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6291     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6292     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6293     Chain = DAG.getStore(
6294         Val.getValue(1), dl, Val, AddPtr,
6295         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6296     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6297     // This does not mean the MTCTR instruction must use R12; it's easier
6298     // to model this as an extra parameter, so do that.
6299     if (isELFv2ABI && !isPatchPoint)
6300       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6301   }
6302 
6303   // Build a sequence of copy-to-reg nodes chained together with token chain
6304   // and flag operands which copy the outgoing args into the appropriate regs.
6305   SDValue InFlag;
6306   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6307     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6308                              RegsToPass[i].second, InFlag);
6309     InFlag = Chain.getValue(1);
6310   }
6311 
6312   if (isTailCall && !IsSibCall)
6313     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6314                     TailCallArguments);
6315 
6316   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
6317                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
6318                     SPDiff, NumBytes, Ins, InVals, CS);
6319 }
6320 
6321 SDValue PPCTargetLowering::LowerCall_Darwin(
6322     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6323     bool isTailCall, bool isPatchPoint,
6324     const SmallVectorImpl<ISD::OutputArg> &Outs,
6325     const SmallVectorImpl<SDValue> &OutVals,
6326     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6327     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6328     ImmutableCallSite CS) const {
6329   unsigned NumOps = Outs.size();
6330 
6331   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6332   bool isPPC64 = PtrVT == MVT::i64;
6333   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6334 
6335   MachineFunction &MF = DAG.getMachineFunction();
6336 
6337   // Mark this function as potentially containing a function that contains a
6338   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6339   // and restoring the callers stack pointer in this functions epilog. This is
6340   // done because by tail calling the called function might overwrite the value
6341   // in this function's (MF) stack pointer stack slot 0(SP).
6342   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6343       CallConv == CallingConv::Fast)
6344     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6345 
6346   // Count how many bytes are to be pushed on the stack, including the linkage
6347   // area, and parameter passing area.  We start with 24/48 bytes, which is
6348   // prereserved space for [SP][CR][LR][3 x unused].
6349   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6350   unsigned NumBytes = LinkageSize;
6351 
6352   // Add up all the space actually used.
6353   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6354   // they all go in registers, but we must reserve stack space for them for
6355   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6356   // assigned stack space in order, with padding so Altivec parameters are
6357   // 16-byte aligned.
6358   unsigned nAltivecParamsAtEnd = 0;
6359   for (unsigned i = 0; i != NumOps; ++i) {
6360     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6361     EVT ArgVT = Outs[i].VT;
6362     // Varargs Altivec parameters are padded to a 16 byte boundary.
6363     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6364         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6365         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6366       if (!isVarArg && !isPPC64) {
6367         // Non-varargs Altivec parameters go after all the non-Altivec
6368         // parameters; handle those later so we know how much padding we need.
6369         nAltivecParamsAtEnd++;
6370         continue;
6371       }
6372       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6373       NumBytes = ((NumBytes+15)/16)*16;
6374     }
6375     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6376   }
6377 
6378   // Allow for Altivec parameters at the end, if needed.
6379   if (nAltivecParamsAtEnd) {
6380     NumBytes = ((NumBytes+15)/16)*16;
6381     NumBytes += 16*nAltivecParamsAtEnd;
6382   }
6383 
6384   // The prolog code of the callee may store up to 8 GPR argument registers to
6385   // the stack, allowing va_start to index over them in memory if its varargs.
6386   // Because we cannot tell if this is needed on the caller side, we have to
6387   // conservatively assume that it is needed.  As such, make sure we have at
6388   // least enough stack space for the caller to store the 8 GPRs.
6389   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6390 
6391   // Tail call needs the stack to be aligned.
6392   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6393       CallConv == CallingConv::Fast)
6394     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6395 
6396   // Calculate by how many bytes the stack has to be adjusted in case of tail
6397   // call optimization.
6398   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
6399 
6400   // To protect arguments on the stack from being clobbered in a tail call,
6401   // force all the loads to happen before doing any other lowering.
6402   if (isTailCall)
6403     Chain = DAG.getStackArgumentTokenFactor(Chain);
6404 
6405   // Adjust the stack pointer for the new arguments...
6406   // These operations are automatically eliminated by the prolog/epilog pass
6407   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6408   SDValue CallSeqStart = Chain;
6409 
6410   // Load the return address and frame pointer so it can be move somewhere else
6411   // later.
6412   SDValue LROp, FPOp;
6413   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6414 
6415   // Set up a copy of the stack pointer for use loading and storing any
6416   // arguments that may not fit in the registers available for argument
6417   // passing.
6418   SDValue StackPtr;
6419   if (isPPC64)
6420     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6421   else
6422     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6423 
6424   // Figure out which arguments are going to go in registers, and which in
6425   // memory.  Also, if this is a vararg function, floating point operations
6426   // must be stored to our stack, and loaded into integer regs as well, if
6427   // any integer regs are available for argument passing.
6428   unsigned ArgOffset = LinkageSize;
6429   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6430 
6431   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6432     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6433     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6434   };
6435   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6436     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6437     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6438   };
6439   static const MCPhysReg VR[] = {
6440     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6441     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6442   };
6443   const unsigned NumGPRs = array_lengthof(GPR_32);
6444   const unsigned NumFPRs = 13;
6445   const unsigned NumVRs  = array_lengthof(VR);
6446 
6447   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6448 
6449   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6450   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6451 
6452   SmallVector<SDValue, 8> MemOpChains;
6453   for (unsigned i = 0; i != NumOps; ++i) {
6454     SDValue Arg = OutVals[i];
6455     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6456 
6457     // PtrOff will be used to store the current argument to the stack if a
6458     // register cannot be found for it.
6459     SDValue PtrOff;
6460 
6461     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6462 
6463     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6464 
6465     // On PPC64, promote integers to 64-bit values.
6466     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6467       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6468       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6469       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6470     }
6471 
6472     // FIXME memcpy is used way more than necessary.  Correctness first.
6473     // Note: "by value" is code for passing a structure by value, not
6474     // basic types.
6475     if (Flags.isByVal()) {
6476       unsigned Size = Flags.getByValSize();
6477       // Very small objects are passed right-justified.  Everything else is
6478       // passed left-justified.
6479       if (Size==1 || Size==2) {
6480         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6481         if (GPR_idx != NumGPRs) {
6482           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6483                                         MachinePointerInfo(), VT);
6484           MemOpChains.push_back(Load.getValue(1));
6485           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6486 
6487           ArgOffset += PtrByteSize;
6488         } else {
6489           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6490                                           PtrOff.getValueType());
6491           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6492           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6493                                                             CallSeqStart,
6494                                                             Flags, DAG, dl);
6495           ArgOffset += PtrByteSize;
6496         }
6497         continue;
6498       }
6499       // Copy entire object into memory.  There are cases where gcc-generated
6500       // code assumes it is there, even if it could be put entirely into
6501       // registers.  (This is not what the doc says.)
6502       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6503                                                         CallSeqStart,
6504                                                         Flags, DAG, dl);
6505 
6506       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6507       // copy the pieces of the object that fit into registers from the
6508       // parameter save area.
6509       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6510         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6511         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6512         if (GPR_idx != NumGPRs) {
6513           SDValue Load =
6514               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6515           MemOpChains.push_back(Load.getValue(1));
6516           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6517           ArgOffset += PtrByteSize;
6518         } else {
6519           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6520           break;
6521         }
6522       }
6523       continue;
6524     }
6525 
6526     switch (Arg.getSimpleValueType().SimpleTy) {
6527     default: llvm_unreachable("Unexpected ValueType for argument!");
6528     case MVT::i1:
6529     case MVT::i32:
6530     case MVT::i64:
6531       if (GPR_idx != NumGPRs) {
6532         if (Arg.getValueType() == MVT::i1)
6533           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6534 
6535         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6536       } else {
6537         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6538                          isPPC64, isTailCall, false, MemOpChains,
6539                          TailCallArguments, dl);
6540       }
6541       ArgOffset += PtrByteSize;
6542       break;
6543     case MVT::f32:
6544     case MVT::f64:
6545       if (FPR_idx != NumFPRs) {
6546         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6547 
6548         if (isVarArg) {
6549           SDValue Store =
6550               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6551           MemOpChains.push_back(Store);
6552 
6553           // Float varargs are always shadowed in available integer registers
6554           if (GPR_idx != NumGPRs) {
6555             SDValue Load =
6556                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6557             MemOpChains.push_back(Load.getValue(1));
6558             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6559           }
6560           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6561             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6562             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6563             SDValue Load =
6564                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6565             MemOpChains.push_back(Load.getValue(1));
6566             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6567           }
6568         } else {
6569           // If we have any FPRs remaining, we may also have GPRs remaining.
6570           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6571           // GPRs.
6572           if (GPR_idx != NumGPRs)
6573             ++GPR_idx;
6574           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6575               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6576             ++GPR_idx;
6577         }
6578       } else
6579         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6580                          isPPC64, isTailCall, false, MemOpChains,
6581                          TailCallArguments, dl);
6582       if (isPPC64)
6583         ArgOffset += 8;
6584       else
6585         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6586       break;
6587     case MVT::v4f32:
6588     case MVT::v4i32:
6589     case MVT::v8i16:
6590     case MVT::v16i8:
6591       if (isVarArg) {
6592         // These go aligned on the stack, or in the corresponding R registers
6593         // when within range.  The Darwin PPC ABI doc claims they also go in
6594         // V registers; in fact gcc does this only for arguments that are
6595         // prototyped, not for those that match the ...  We do it for all
6596         // arguments, seems to work.
6597         while (ArgOffset % 16 !=0) {
6598           ArgOffset += PtrByteSize;
6599           if (GPR_idx != NumGPRs)
6600             GPR_idx++;
6601         }
6602         // We could elide this store in the case where the object fits
6603         // entirely in R registers.  Maybe later.
6604         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6605                              DAG.getConstant(ArgOffset, dl, PtrVT));
6606         SDValue Store =
6607             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6608         MemOpChains.push_back(Store);
6609         if (VR_idx != NumVRs) {
6610           SDValue Load =
6611               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6612           MemOpChains.push_back(Load.getValue(1));
6613           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6614         }
6615         ArgOffset += 16;
6616         for (unsigned i=0; i<16; i+=PtrByteSize) {
6617           if (GPR_idx == NumGPRs)
6618             break;
6619           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6620                                    DAG.getConstant(i, dl, PtrVT));
6621           SDValue Load =
6622               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6623           MemOpChains.push_back(Load.getValue(1));
6624           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6625         }
6626         break;
6627       }
6628 
6629       // Non-varargs Altivec params generally go in registers, but have
6630       // stack space allocated at the end.
6631       if (VR_idx != NumVRs) {
6632         // Doesn't have GPR space allocated.
6633         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6634       } else if (nAltivecParamsAtEnd==0) {
6635         // We are emitting Altivec params in order.
6636         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6637                          isPPC64, isTailCall, true, MemOpChains,
6638                          TailCallArguments, dl);
6639         ArgOffset += 16;
6640       }
6641       break;
6642     }
6643   }
6644   // If all Altivec parameters fit in registers, as they usually do,
6645   // they get stack space following the non-Altivec parameters.  We
6646   // don't track this here because nobody below needs it.
6647   // If there are more Altivec parameters than fit in registers emit
6648   // the stores here.
6649   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6650     unsigned j = 0;
6651     // Offset is aligned; skip 1st 12 params which go in V registers.
6652     ArgOffset = ((ArgOffset+15)/16)*16;
6653     ArgOffset += 12*16;
6654     for (unsigned i = 0; i != NumOps; ++i) {
6655       SDValue Arg = OutVals[i];
6656       EVT ArgType = Outs[i].VT;
6657       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6658           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6659         if (++j > NumVRs) {
6660           SDValue PtrOff;
6661           // We are emitting Altivec params in order.
6662           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6663                            isPPC64, isTailCall, true, MemOpChains,
6664                            TailCallArguments, dl);
6665           ArgOffset += 16;
6666         }
6667       }
6668     }
6669   }
6670 
6671   if (!MemOpChains.empty())
6672     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6673 
6674   // On Darwin, R12 must contain the address of an indirect callee.  This does
6675   // not mean the MTCTR instruction must use R12; it's easier to model this as
6676   // an extra parameter, so do that.
6677   if (!isTailCall &&
6678       !isFunctionGlobalAddress(Callee) &&
6679       !isa<ExternalSymbolSDNode>(Callee) &&
6680       !isBLACompatibleAddress(Callee, DAG))
6681     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6682                                                    PPC::R12), Callee));
6683 
6684   // Build a sequence of copy-to-reg nodes chained together with token chain
6685   // and flag operands which copy the outgoing args into the appropriate regs.
6686   SDValue InFlag;
6687   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6688     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6689                              RegsToPass[i].second, InFlag);
6690     InFlag = Chain.getValue(1);
6691   }
6692 
6693   if (isTailCall)
6694     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6695                     TailCallArguments);
6696 
6697   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6698                     /* unused except on PPC64 ELFv1 */ false, DAG,
6699                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6700                     NumBytes, Ins, InVals, CS);
6701 }
6702 
6703 
6704 SDValue PPCTargetLowering::LowerCall_AIX(
6705     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6706     bool isTailCall, bool isPatchPoint,
6707     const SmallVectorImpl<ISD::OutputArg> &Outs,
6708     const SmallVectorImpl<SDValue> &OutVals,
6709     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6710     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6711     ImmutableCallSite CS) const {
6712 
6713   assert((CallConv == CallingConv::C || CallConv == CallingConv::Fast) &&
6714          "Unimplemented calling convention!");
6715   if (isVarArg || isPatchPoint)
6716     report_fatal_error("This call type is unimplemented on AIX.");
6717 
6718   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6719   bool isPPC64 = PtrVT == MVT::i64;
6720   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6721   unsigned NumOps = Outs.size();
6722 
6723 
6724   // Count how many bytes are to be pushed on the stack, including the linkage
6725   // area, parameter list area.
6726   // On XCOFF, we start with 24/48, which is reserved space for
6727   // [SP][CR][LR][2 x reserved][TOC].
6728   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6729 
6730   // The prolog code of the callee may store up to 8 GPR argument registers to
6731   // the stack, allowing va_start to index over them in memory if the callee
6732   // is variadic.
6733   // Because we cannot tell if this is needed on the caller side, we have to
6734   // conservatively assume that it is needed.  As such, make sure we have at
6735   // least enough stack space for the caller to store the 8 GPRs.
6736   unsigned NumBytes = LinkageSize + 8 * PtrByteSize;
6737 
6738   // Adjust the stack pointer for the new arguments...
6739   // These operations are automatically eliminated by the prolog/epilog
6740   // inserter pass.
6741   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6742   SDValue CallSeqStart = Chain;
6743 
6744   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6745     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6746     PPC::R7, PPC::R8, PPC::R9, PPC::R10
6747   };
6748   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6749     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6750     PPC::X7, PPC::X8, PPC::X9, PPC::X10
6751   };
6752 
6753   const unsigned NumGPRs = isPPC64 ? array_lengthof(GPR_64)
6754                                    : array_lengthof(GPR_32);
6755   const unsigned NumFPRs = array_lengthof(FPR);
6756   assert(NumFPRs == 13 && "Only FPR 1-13 could be used for parameter passing "
6757                           "on AIX");
6758 
6759   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6760   unsigned GPR_idx = 0, FPR_idx = 0;
6761 
6762   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6763 
6764   if (isTailCall)
6765     report_fatal_error("Handling of tail call is unimplemented!");
6766   int SPDiff = 0;
6767 
6768   for (unsigned i = 0; i != NumOps; ++i) {
6769     SDValue Arg = OutVals[i];
6770     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6771 
6772     // Promote integers if needed.
6773     if (Arg.getValueType() == MVT::i1 ||
6774         (isPPC64 && Arg.getValueType() == MVT::i32)) {
6775       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6776       Arg = DAG.getNode(ExtOp, dl, PtrVT, Arg);
6777     }
6778 
6779     // Note: "by value" is code for passing a structure by value, not
6780     // basic types.
6781     if (Flags.isByVal())
6782       report_fatal_error("Passing structure by value is unimplemented!");
6783 
6784     switch (Arg.getSimpleValueType().SimpleTy) {
6785     default: llvm_unreachable("Unexpected ValueType for argument!");
6786     case MVT::i1:
6787     case MVT::i32:
6788     case MVT::i64:
6789       if (GPR_idx != NumGPRs)
6790         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6791       else
6792         report_fatal_error("Handling of placing parameters on the stack is "
6793                            "unimplemented!");
6794       break;
6795     case MVT::f32:
6796     case MVT::f64:
6797       if (FPR_idx != NumFPRs) {
6798         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6799 
6800         // If we have any FPRs remaining, we may also have GPRs remaining.
6801         // Args passed in FPRs consume 1 or 2 (f64 in 32 bit mode) available
6802         // GPRs.
6803         if (GPR_idx != NumGPRs)
6804           ++GPR_idx;
6805         if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64)
6806           ++GPR_idx;
6807       } else
6808         report_fatal_error("Handling of placing parameters on the stack is "
6809                            "unimplemented!");
6810       break;
6811     case MVT::v4f32:
6812     case MVT::v4i32:
6813     case MVT::v8i16:
6814     case MVT::v16i8:
6815     case MVT::v2f64:
6816     case MVT::v2i64:
6817     case MVT::v1i128:
6818     case MVT::f128:
6819     case MVT::v4f64:
6820     case MVT::v4i1:
6821       report_fatal_error("Handling of this parameter type is unimplemented!");
6822     }
6823   }
6824 
6825   if (!isFunctionGlobalAddress(Callee) &&
6826       !isa<ExternalSymbolSDNode>(Callee))
6827     report_fatal_error("Handling of indirect call is unimplemented!");
6828 
6829   // Build a sequence of copy-to-reg nodes chained together with token chain
6830   // and flag operands which copy the outgoing args into the appropriate regs.
6831   SDValue InFlag;
6832   for (auto Reg : RegsToPass) {
6833     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
6834     InFlag = Chain.getValue(1);
6835   }
6836 
6837   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6838                     /* unused except on PPC64 ELFv1 */ false, DAG,
6839                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6840                     NumBytes, Ins, InVals, CS);
6841 }
6842 
6843 bool
6844 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6845                                   MachineFunction &MF, bool isVarArg,
6846                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
6847                                   LLVMContext &Context) const {
6848   SmallVector<CCValAssign, 16> RVLocs;
6849   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6850   return CCInfo.CheckReturn(
6851       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6852                 ? RetCC_PPC_Cold
6853                 : RetCC_PPC);
6854 }
6855 
6856 SDValue
6857 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6858                                bool isVarArg,
6859                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6860                                const SmallVectorImpl<SDValue> &OutVals,
6861                                const SDLoc &dl, SelectionDAG &DAG) const {
6862   SmallVector<CCValAssign, 16> RVLocs;
6863   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6864                  *DAG.getContext());
6865   CCInfo.AnalyzeReturn(Outs,
6866                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6867                            ? RetCC_PPC_Cold
6868                            : RetCC_PPC);
6869 
6870   SDValue Flag;
6871   SmallVector<SDValue, 4> RetOps(1, Chain);
6872 
6873   // Copy the result values into the output registers.
6874   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
6875     CCValAssign &VA = RVLocs[i];
6876     assert(VA.isRegLoc() && "Can only return in registers!");
6877 
6878     SDValue Arg = OutVals[RealResIdx];
6879 
6880     switch (VA.getLocInfo()) {
6881     default: llvm_unreachable("Unknown loc info!");
6882     case CCValAssign::Full: break;
6883     case CCValAssign::AExt:
6884       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6885       break;
6886     case CCValAssign::ZExt:
6887       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6888       break;
6889     case CCValAssign::SExt:
6890       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6891       break;
6892     }
6893     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
6894       bool isLittleEndian = Subtarget.isLittleEndian();
6895       // Legalize ret f64 -> ret 2 x i32.
6896       SDValue SVal =
6897           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
6898                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
6899       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
6900       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6901       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
6902                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
6903       Flag = Chain.getValue(1);
6904       VA = RVLocs[++i]; // skip ahead to next loc
6905       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
6906     } else
6907       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6908     Flag = Chain.getValue(1);
6909     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6910   }
6911 
6912   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6913   const MCPhysReg *I =
6914     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6915   if (I) {
6916     for (; *I; ++I) {
6917 
6918       if (PPC::G8RCRegClass.contains(*I))
6919         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6920       else if (PPC::F8RCRegClass.contains(*I))
6921         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6922       else if (PPC::CRRCRegClass.contains(*I))
6923         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6924       else if (PPC::VRRCRegClass.contains(*I))
6925         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6926       else
6927         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6928     }
6929   }
6930 
6931   RetOps[0] = Chain;  // Update chain.
6932 
6933   // Add the flag if we have it.
6934   if (Flag.getNode())
6935     RetOps.push_back(Flag);
6936 
6937   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6938 }
6939 
6940 SDValue
6941 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6942                                                 SelectionDAG &DAG) const {
6943   SDLoc dl(Op);
6944 
6945   // Get the correct type for integers.
6946   EVT IntVT = Op.getValueType();
6947 
6948   // Get the inputs.
6949   SDValue Chain = Op.getOperand(0);
6950   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6951   // Build a DYNAREAOFFSET node.
6952   SDValue Ops[2] = {Chain, FPSIdx};
6953   SDVTList VTs = DAG.getVTList(IntVT);
6954   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6955 }
6956 
6957 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6958                                              SelectionDAG &DAG) const {
6959   // When we pop the dynamic allocation we need to restore the SP link.
6960   SDLoc dl(Op);
6961 
6962   // Get the correct type for pointers.
6963   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6964 
6965   // Construct the stack pointer operand.
6966   bool isPPC64 = Subtarget.isPPC64();
6967   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6968   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6969 
6970   // Get the operands for the STACKRESTORE.
6971   SDValue Chain = Op.getOperand(0);
6972   SDValue SaveSP = Op.getOperand(1);
6973 
6974   // Load the old link SP.
6975   SDValue LoadLinkSP =
6976       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6977 
6978   // Restore the stack pointer.
6979   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6980 
6981   // Store the old link SP.
6982   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6983 }
6984 
6985 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6986   MachineFunction &MF = DAG.getMachineFunction();
6987   bool isPPC64 = Subtarget.isPPC64();
6988   EVT PtrVT = getPointerTy(MF.getDataLayout());
6989 
6990   // Get current frame pointer save index.  The users of this index will be
6991   // primarily DYNALLOC instructions.
6992   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6993   int RASI = FI->getReturnAddrSaveIndex();
6994 
6995   // If the frame pointer save index hasn't been defined yet.
6996   if (!RASI) {
6997     // Find out what the fix offset of the frame pointer save area.
6998     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6999     // Allocate the frame index for frame pointer save area.
7000     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7001     // Save the result.
7002     FI->setReturnAddrSaveIndex(RASI);
7003   }
7004   return DAG.getFrameIndex(RASI, PtrVT);
7005 }
7006 
7007 SDValue
7008 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7009   MachineFunction &MF = DAG.getMachineFunction();
7010   bool isPPC64 = Subtarget.isPPC64();
7011   EVT PtrVT = getPointerTy(MF.getDataLayout());
7012 
7013   // Get current frame pointer save index.  The users of this index will be
7014   // primarily DYNALLOC instructions.
7015   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7016   int FPSI = FI->getFramePointerSaveIndex();
7017 
7018   // If the frame pointer save index hasn't been defined yet.
7019   if (!FPSI) {
7020     // Find out what the fix offset of the frame pointer save area.
7021     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7022     // Allocate the frame index for frame pointer save area.
7023     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7024     // Save the result.
7025     FI->setFramePointerSaveIndex(FPSI);
7026   }
7027   return DAG.getFrameIndex(FPSI, PtrVT);
7028 }
7029 
7030 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7031                                                    SelectionDAG &DAG) const {
7032   // Get the inputs.
7033   SDValue Chain = Op.getOperand(0);
7034   SDValue Size  = Op.getOperand(1);
7035   SDLoc dl(Op);
7036 
7037   // Get the correct type for pointers.
7038   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7039   // Negate the size.
7040   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7041                                 DAG.getConstant(0, dl, PtrVT), Size);
7042   // Construct a node for the frame pointer save index.
7043   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7044   // Build a DYNALLOC node.
7045   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7046   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7047   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7048 }
7049 
7050 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7051                                                      SelectionDAG &DAG) const {
7052   MachineFunction &MF = DAG.getMachineFunction();
7053 
7054   bool isPPC64 = Subtarget.isPPC64();
7055   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7056 
7057   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7058   return DAG.getFrameIndex(FI, PtrVT);
7059 }
7060 
7061 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7062                                                SelectionDAG &DAG) const {
7063   SDLoc DL(Op);
7064   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7065                      DAG.getVTList(MVT::i32, MVT::Other),
7066                      Op.getOperand(0), Op.getOperand(1));
7067 }
7068 
7069 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7070                                                 SelectionDAG &DAG) const {
7071   SDLoc DL(Op);
7072   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7073                      Op.getOperand(0), Op.getOperand(1));
7074 }
7075 
7076 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7077   if (Op.getValueType().isVector())
7078     return LowerVectorLoad(Op, DAG);
7079 
7080   assert(Op.getValueType() == MVT::i1 &&
7081          "Custom lowering only for i1 loads");
7082 
7083   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7084 
7085   SDLoc dl(Op);
7086   LoadSDNode *LD = cast<LoadSDNode>(Op);
7087 
7088   SDValue Chain = LD->getChain();
7089   SDValue BasePtr = LD->getBasePtr();
7090   MachineMemOperand *MMO = LD->getMemOperand();
7091 
7092   SDValue NewLD =
7093       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7094                      BasePtr, MVT::i8, MMO);
7095   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7096 
7097   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7098   return DAG.getMergeValues(Ops, dl);
7099 }
7100 
7101 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7102   if (Op.getOperand(1).getValueType().isVector())
7103     return LowerVectorStore(Op, DAG);
7104 
7105   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7106          "Custom lowering only for i1 stores");
7107 
7108   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7109 
7110   SDLoc dl(Op);
7111   StoreSDNode *ST = cast<StoreSDNode>(Op);
7112 
7113   SDValue Chain = ST->getChain();
7114   SDValue BasePtr = ST->getBasePtr();
7115   SDValue Value = ST->getValue();
7116   MachineMemOperand *MMO = ST->getMemOperand();
7117 
7118   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7119                       Value);
7120   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7121 }
7122 
7123 // FIXME: Remove this once the ANDI glue bug is fixed:
7124 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7125   assert(Op.getValueType() == MVT::i1 &&
7126          "Custom lowering only for i1 results");
7127 
7128   SDLoc DL(Op);
7129   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
7130                      Op.getOperand(0));
7131 }
7132 
7133 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7134                                                SelectionDAG &DAG) const {
7135 
7136   // Implements a vector truncate that fits in a vector register as a shuffle.
7137   // We want to legalize vector truncates down to where the source fits in
7138   // a vector register (and target is therefore smaller than vector register
7139   // size).  At that point legalization will try to custom lower the sub-legal
7140   // result and get here - where we can contain the truncate as a single target
7141   // operation.
7142 
7143   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7144   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7145   //
7146   // We will implement it for big-endian ordering as this (where x denotes
7147   // undefined):
7148   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7149   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7150   //
7151   // The same operation in little-endian ordering will be:
7152   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7153   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7154 
7155   assert(Op.getValueType().isVector() && "Vector type expected.");
7156 
7157   SDLoc DL(Op);
7158   SDValue N1 = Op.getOperand(0);
7159   unsigned SrcSize = N1.getValueType().getSizeInBits();
7160   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7161   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7162 
7163   EVT TrgVT = Op.getValueType();
7164   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7165   EVT EltVT = TrgVT.getVectorElementType();
7166   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7167   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7168 
7169   // First list the elements we want to keep.
7170   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7171   SmallVector<int, 16> ShuffV;
7172   if (Subtarget.isLittleEndian())
7173     for (unsigned i = 0; i < TrgNumElts; ++i)
7174       ShuffV.push_back(i * SizeMult);
7175   else
7176     for (unsigned i = 1; i <= TrgNumElts; ++i)
7177       ShuffV.push_back(i * SizeMult - 1);
7178 
7179   // Populate the remaining elements with undefs.
7180   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7181     // ShuffV.push_back(i + WideNumElts);
7182     ShuffV.push_back(WideNumElts + 1);
7183 
7184   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7185   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7186 }
7187 
7188 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7189 /// possible.
7190 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7191   // Not FP? Not a fsel.
7192   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7193       !Op.getOperand(2).getValueType().isFloatingPoint())
7194     return Op;
7195 
7196   // We might be able to do better than this under some circumstances, but in
7197   // general, fsel-based lowering of select is a finite-math-only optimization.
7198   // For more information, see section F.3 of the 2.06 ISA specification.
7199   if (!DAG.getTarget().Options.NoInfsFPMath ||
7200       !DAG.getTarget().Options.NoNaNsFPMath)
7201     return Op;
7202   // TODO: Propagate flags from the select rather than global settings.
7203   SDNodeFlags Flags;
7204   Flags.setNoInfs(true);
7205   Flags.setNoNaNs(true);
7206 
7207   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7208 
7209   EVT ResVT = Op.getValueType();
7210   EVT CmpVT = Op.getOperand(0).getValueType();
7211   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7212   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7213   SDLoc dl(Op);
7214 
7215   // If the RHS of the comparison is a 0.0, we don't need to do the
7216   // subtraction at all.
7217   SDValue Sel1;
7218   if (isFloatingPointZero(RHS))
7219     switch (CC) {
7220     default: break;       // SETUO etc aren't handled by fsel.
7221     case ISD::SETNE:
7222       std::swap(TV, FV);
7223       LLVM_FALLTHROUGH;
7224     case ISD::SETEQ:
7225       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7226         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7227       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7228       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7229         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7230       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7231                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7232     case ISD::SETULT:
7233     case ISD::SETLT:
7234       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7235       LLVM_FALLTHROUGH;
7236     case ISD::SETOGE:
7237     case ISD::SETGE:
7238       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7239         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7240       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7241     case ISD::SETUGT:
7242     case ISD::SETGT:
7243       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7244       LLVM_FALLTHROUGH;
7245     case ISD::SETOLE:
7246     case ISD::SETLE:
7247       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7248         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7249       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7250                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7251     }
7252 
7253   SDValue Cmp;
7254   switch (CC) {
7255   default: break;       // SETUO etc aren't handled by fsel.
7256   case ISD::SETNE:
7257     std::swap(TV, FV);
7258     LLVM_FALLTHROUGH;
7259   case ISD::SETEQ:
7260     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7261     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7262       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7263     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7264     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7265       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7266     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7267                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7268   case ISD::SETULT:
7269   case ISD::SETLT:
7270     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7271     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7272       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7273     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7274   case ISD::SETOGE:
7275   case ISD::SETGE:
7276     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7277     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7278       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7279     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7280   case ISD::SETUGT:
7281   case ISD::SETGT:
7282     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7283     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7284       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7285     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7286   case ISD::SETOLE:
7287   case ISD::SETLE:
7288     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7289     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7290       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7291     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7292   }
7293   return Op;
7294 }
7295 
7296 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7297                                                SelectionDAG &DAG,
7298                                                const SDLoc &dl) const {
7299   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7300   SDValue Src = Op.getOperand(0);
7301   if (Src.getValueType() == MVT::f32)
7302     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7303 
7304   SDValue Tmp;
7305   switch (Op.getSimpleValueType().SimpleTy) {
7306   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7307   case MVT::i32:
7308     Tmp = DAG.getNode(
7309         Op.getOpcode() == ISD::FP_TO_SINT
7310             ? PPCISD::FCTIWZ
7311             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7312         dl, MVT::f64, Src);
7313     break;
7314   case MVT::i64:
7315     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7316            "i64 FP_TO_UINT is supported only with FPCVT");
7317     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7318                                                         PPCISD::FCTIDUZ,
7319                       dl, MVT::f64, Src);
7320     break;
7321   }
7322 
7323   // Convert the FP value to an int value through memory.
7324   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7325     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
7326   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7327   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7328   MachinePointerInfo MPI =
7329       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7330 
7331   // Emit a store to the stack slot.
7332   SDValue Chain;
7333   if (i32Stack) {
7334     MachineFunction &MF = DAG.getMachineFunction();
7335     MachineMemOperand *MMO =
7336       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
7337     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
7338     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7339               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7340   } else
7341     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
7342 
7343   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7344   // add in a bias on big endian.
7345   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7346     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7347                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7348     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7349   }
7350 
7351   RLI.Chain = Chain;
7352   RLI.Ptr = FIPtr;
7353   RLI.MPI = MPI;
7354 }
7355 
7356 /// Custom lowers floating point to integer conversions to use
7357 /// the direct move instructions available in ISA 2.07 to avoid the
7358 /// need for load/store combinations.
7359 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7360                                                     SelectionDAG &DAG,
7361                                                     const SDLoc &dl) const {
7362   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7363   SDValue Src = Op.getOperand(0);
7364 
7365   if (Src.getValueType() == MVT::f32)
7366     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7367 
7368   SDValue Tmp;
7369   switch (Op.getSimpleValueType().SimpleTy) {
7370   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7371   case MVT::i32:
7372     Tmp = DAG.getNode(
7373         Op.getOpcode() == ISD::FP_TO_SINT
7374             ? PPCISD::FCTIWZ
7375             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7376         dl, MVT::f64, Src);
7377     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
7378     break;
7379   case MVT::i64:
7380     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7381            "i64 FP_TO_UINT is supported only with FPCVT");
7382     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7383                                                         PPCISD::FCTIDUZ,
7384                       dl, MVT::f64, Src);
7385     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
7386     break;
7387   }
7388   return Tmp;
7389 }
7390 
7391 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7392                                           const SDLoc &dl) const {
7393 
7394   // FP to INT conversions are legal for f128.
7395   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
7396     return Op;
7397 
7398   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7399   // PPC (the libcall is not available).
7400   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
7401     if (Op.getValueType() == MVT::i32) {
7402       if (Op.getOpcode() == ISD::FP_TO_SINT) {
7403         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7404                                  MVT::f64, Op.getOperand(0),
7405                                  DAG.getIntPtrConstant(0, dl));
7406         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7407                                  MVT::f64, Op.getOperand(0),
7408                                  DAG.getIntPtrConstant(1, dl));
7409 
7410         // Add the two halves of the long double in round-to-zero mode.
7411         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7412 
7413         // Now use a smaller FP_TO_SINT.
7414         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7415       }
7416       if (Op.getOpcode() == ISD::FP_TO_UINT) {
7417         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7418         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7419         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
7420         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7421         // FIXME: generated code sucks.
7422         // TODO: Are there fast-math-flags to propagate to this FSUB?
7423         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
7424                                    Op.getOperand(0), Tmp);
7425         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7426         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
7427                            DAG.getConstant(0x80000000, dl, MVT::i32));
7428         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
7429                                     Op.getOperand(0));
7430         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
7431                                ISD::SETGE);
7432       }
7433     }
7434 
7435     return SDValue();
7436   }
7437 
7438   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
7439     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
7440 
7441   ReuseLoadInfo RLI;
7442   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7443 
7444   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7445                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7446 }
7447 
7448 // We're trying to insert a regular store, S, and then a load, L. If the
7449 // incoming value, O, is a load, we might just be able to have our load use the
7450 // address used by O. However, we don't know if anything else will store to
7451 // that address before we can load from it. To prevent this situation, we need
7452 // to insert our load, L, into the chain as a peer of O. To do this, we give L
7453 // the same chain operand as O, we create a token factor from the chain results
7454 // of O and L, and we replace all uses of O's chain result with that token
7455 // factor (see spliceIntoChain below for this last part).
7456 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
7457                                             ReuseLoadInfo &RLI,
7458                                             SelectionDAG &DAG,
7459                                             ISD::LoadExtType ET) const {
7460   SDLoc dl(Op);
7461   if (ET == ISD::NON_EXTLOAD &&
7462       (Op.getOpcode() == ISD::FP_TO_UINT ||
7463        Op.getOpcode() == ISD::FP_TO_SINT) &&
7464       isOperationLegalOrCustom(Op.getOpcode(),
7465                                Op.getOperand(0).getValueType())) {
7466 
7467     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7468     return true;
7469   }
7470 
7471   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
7472   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
7473       LD->isNonTemporal())
7474     return false;
7475   if (LD->getMemoryVT() != MemVT)
7476     return false;
7477 
7478   RLI.Ptr = LD->getBasePtr();
7479   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
7480     assert(LD->getAddressingMode() == ISD::PRE_INC &&
7481            "Non-pre-inc AM on PPC?");
7482     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
7483                           LD->getOffset());
7484   }
7485 
7486   RLI.Chain = LD->getChain();
7487   RLI.MPI = LD->getPointerInfo();
7488   RLI.IsDereferenceable = LD->isDereferenceable();
7489   RLI.IsInvariant = LD->isInvariant();
7490   RLI.Alignment = LD->getAlignment();
7491   RLI.AAInfo = LD->getAAInfo();
7492   RLI.Ranges = LD->getRanges();
7493 
7494   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
7495   return true;
7496 }
7497 
7498 // Given the head of the old chain, ResChain, insert a token factor containing
7499 // it and NewResChain, and make users of ResChain now be users of that token
7500 // factor.
7501 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
7502 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
7503                                         SDValue NewResChain,
7504                                         SelectionDAG &DAG) const {
7505   if (!ResChain)
7506     return;
7507 
7508   SDLoc dl(NewResChain);
7509 
7510   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7511                            NewResChain, DAG.getUNDEF(MVT::Other));
7512   assert(TF.getNode() != NewResChain.getNode() &&
7513          "A new TF really is required here");
7514 
7515   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
7516   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
7517 }
7518 
7519 /// Analyze profitability of direct move
7520 /// prefer float load to int load plus direct move
7521 /// when there is no integer use of int load
7522 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
7523   SDNode *Origin = Op.getOperand(0).getNode();
7524   if (Origin->getOpcode() != ISD::LOAD)
7525     return true;
7526 
7527   // If there is no LXSIBZX/LXSIHZX, like Power8,
7528   // prefer direct move if the memory size is 1 or 2 bytes.
7529   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
7530   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
7531     return true;
7532 
7533   for (SDNode::use_iterator UI = Origin->use_begin(),
7534                             UE = Origin->use_end();
7535        UI != UE; ++UI) {
7536 
7537     // Only look at the users of the loaded value.
7538     if (UI.getUse().get().getResNo() != 0)
7539       continue;
7540 
7541     if (UI->getOpcode() != ISD::SINT_TO_FP &&
7542         UI->getOpcode() != ISD::UINT_TO_FP)
7543       return true;
7544   }
7545 
7546   return false;
7547 }
7548 
7549 /// Custom lowers integer to floating point conversions to use
7550 /// the direct move instructions available in ISA 2.07 to avoid the
7551 /// need for load/store combinations.
7552 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
7553                                                     SelectionDAG &DAG,
7554                                                     const SDLoc &dl) const {
7555   assert((Op.getValueType() == MVT::f32 ||
7556           Op.getValueType() == MVT::f64) &&
7557          "Invalid floating point type as target of conversion");
7558   assert(Subtarget.hasFPCVT() &&
7559          "Int to FP conversions with direct moves require FPCVT");
7560   SDValue FP;
7561   SDValue Src = Op.getOperand(0);
7562   bool SinglePrec = Op.getValueType() == MVT::f32;
7563   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
7564   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
7565   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
7566                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
7567 
7568   if (WordInt) {
7569     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
7570                      dl, MVT::f64, Src);
7571     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7572   }
7573   else {
7574     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
7575     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7576   }
7577 
7578   return FP;
7579 }
7580 
7581 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
7582 
7583   EVT VecVT = Vec.getValueType();
7584   assert(VecVT.isVector() && "Expected a vector type.");
7585   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
7586 
7587   EVT EltVT = VecVT.getVectorElementType();
7588   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7589   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7590 
7591   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
7592   SmallVector<SDValue, 16> Ops(NumConcat);
7593   Ops[0] = Vec;
7594   SDValue UndefVec = DAG.getUNDEF(VecVT);
7595   for (unsigned i = 1; i < NumConcat; ++i)
7596     Ops[i] = UndefVec;
7597 
7598   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
7599 }
7600 
7601 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
7602                                                 const SDLoc &dl) const {
7603 
7604   unsigned Opc = Op.getOpcode();
7605   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
7606          "Unexpected conversion type");
7607   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
7608          "Supports conversions to v2f64/v4f32 only.");
7609 
7610   bool SignedConv = Opc == ISD::SINT_TO_FP;
7611   bool FourEltRes = Op.getValueType() == MVT::v4f32;
7612 
7613   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
7614   EVT WideVT = Wide.getValueType();
7615   unsigned WideNumElts = WideVT.getVectorNumElements();
7616   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
7617 
7618   SmallVector<int, 16> ShuffV;
7619   for (unsigned i = 0; i < WideNumElts; ++i)
7620     ShuffV.push_back(i + WideNumElts);
7621 
7622   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
7623   int SaveElts = FourEltRes ? 4 : 2;
7624   if (Subtarget.isLittleEndian())
7625     for (int i = 0; i < SaveElts; i++)
7626       ShuffV[i * Stride] = i;
7627   else
7628     for (int i = 1; i <= SaveElts; i++)
7629       ShuffV[i * Stride - 1] = i - 1;
7630 
7631   SDValue ShuffleSrc2 =
7632       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
7633   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
7634   unsigned ExtendOp =
7635       SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST;
7636 
7637   SDValue Extend;
7638   if (!Subtarget.hasP9Altivec() && SignedConv) {
7639     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
7640     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
7641                          DAG.getValueType(Op.getOperand(0).getValueType()));
7642   } else
7643     Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange);
7644 
7645   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
7646 }
7647 
7648 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
7649                                           SelectionDAG &DAG) const {
7650   SDLoc dl(Op);
7651 
7652   EVT InVT = Op.getOperand(0).getValueType();
7653   EVT OutVT = Op.getValueType();
7654   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
7655       isOperationCustom(Op.getOpcode(), InVT))
7656     return LowerINT_TO_FPVector(Op, DAG, dl);
7657 
7658   // Conversions to f128 are legal.
7659   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
7660     return Op;
7661 
7662   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
7663     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
7664       return SDValue();
7665 
7666     SDValue Value = Op.getOperand(0);
7667     // The values are now known to be -1 (false) or 1 (true). To convert this
7668     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7669     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7670     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7671 
7672     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7673 
7674     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7675 
7676     if (Op.getValueType() != MVT::v4f64)
7677       Value = DAG.getNode(ISD::FP_ROUND, dl,
7678                           Op.getValueType(), Value,
7679                           DAG.getIntPtrConstant(1, dl));
7680     return Value;
7681   }
7682 
7683   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
7684   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
7685     return SDValue();
7686 
7687   if (Op.getOperand(0).getValueType() == MVT::i1)
7688     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
7689                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
7690                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
7691 
7692   // If we have direct moves, we can do all the conversion, skip the store/load
7693   // however, without FPCVT we can't do most conversions.
7694   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
7695       Subtarget.isPPC64() && Subtarget.hasFPCVT())
7696     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
7697 
7698   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
7699          "UINT_TO_FP is supported only with FPCVT");
7700 
7701   // If we have FCFIDS, then use it when converting to single-precision.
7702   // Otherwise, convert to double-precision and then round.
7703   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7704                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
7705                                                             : PPCISD::FCFIDS)
7706                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
7707                                                             : PPCISD::FCFID);
7708   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7709                   ? MVT::f32
7710                   : MVT::f64;
7711 
7712   if (Op.getOperand(0).getValueType() == MVT::i64) {
7713     SDValue SINT = Op.getOperand(0);
7714     // When converting to single-precision, we actually need to convert
7715     // to double-precision first and then round to single-precision.
7716     // To avoid double-rounding effects during that operation, we have
7717     // to prepare the input operand.  Bits that might be truncated when
7718     // converting to double-precision are replaced by a bit that won't
7719     // be lost at this stage, but is below the single-precision rounding
7720     // position.
7721     //
7722     // However, if -enable-unsafe-fp-math is in effect, accept double
7723     // rounding to avoid the extra overhead.
7724     if (Op.getValueType() == MVT::f32 &&
7725         !Subtarget.hasFPCVT() &&
7726         !DAG.getTarget().Options.UnsafeFPMath) {
7727 
7728       // Twiddle input to make sure the low 11 bits are zero.  (If this
7729       // is the case, we are guaranteed the value will fit into the 53 bit
7730       // mantissa of an IEEE double-precision value without rounding.)
7731       // If any of those low 11 bits were not zero originally, make sure
7732       // bit 12 (value 2048) is set instead, so that the final rounding
7733       // to single-precision gets the correct result.
7734       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7735                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
7736       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
7737                           Round, DAG.getConstant(2047, dl, MVT::i64));
7738       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
7739       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7740                           Round, DAG.getConstant(-2048, dl, MVT::i64));
7741 
7742       // However, we cannot use that value unconditionally: if the magnitude
7743       // of the input value is small, the bit-twiddling we did above might
7744       // end up visibly changing the output.  Fortunately, in that case, we
7745       // don't need to twiddle bits since the original input will convert
7746       // exactly to double-precision floating-point already.  Therefore,
7747       // construct a conditional to use the original value if the top 11
7748       // bits are all sign-bit copies, and use the rounded value computed
7749       // above otherwise.
7750       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
7751                                  SINT, DAG.getConstant(53, dl, MVT::i32));
7752       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
7753                          Cond, DAG.getConstant(1, dl, MVT::i64));
7754       Cond = DAG.getSetCC(dl, MVT::i32,
7755                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
7756 
7757       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
7758     }
7759 
7760     ReuseLoadInfo RLI;
7761     SDValue Bits;
7762 
7763     MachineFunction &MF = DAG.getMachineFunction();
7764     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
7765       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7766                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7767       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7768     } else if (Subtarget.hasLFIWAX() &&
7769                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
7770       MachineMemOperand *MMO =
7771         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7772                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7773       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7774       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
7775                                      DAG.getVTList(MVT::f64, MVT::Other),
7776                                      Ops, MVT::i32, MMO);
7777       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7778     } else if (Subtarget.hasFPCVT() &&
7779                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
7780       MachineMemOperand *MMO =
7781         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7782                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7783       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7784       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
7785                                      DAG.getVTList(MVT::f64, MVT::Other),
7786                                      Ops, MVT::i32, MMO);
7787       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7788     } else if (((Subtarget.hasLFIWAX() &&
7789                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
7790                 (Subtarget.hasFPCVT() &&
7791                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
7792                SINT.getOperand(0).getValueType() == MVT::i32) {
7793       MachineFrameInfo &MFI = MF.getFrameInfo();
7794       EVT PtrVT = getPointerTy(DAG.getDataLayout());
7795 
7796       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7797       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7798 
7799       SDValue Store =
7800           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
7801                        MachinePointerInfo::getFixedStack(
7802                            DAG.getMachineFunction(), FrameIdx));
7803 
7804       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7805              "Expected an i32 store");
7806 
7807       RLI.Ptr = FIdx;
7808       RLI.Chain = Store;
7809       RLI.MPI =
7810           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7811       RLI.Alignment = 4;
7812 
7813       MachineMemOperand *MMO =
7814         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7815                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7816       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7817       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
7818                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
7819                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
7820                                      Ops, MVT::i32, MMO);
7821     } else
7822       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
7823 
7824     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
7825 
7826     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7827       FP = DAG.getNode(ISD::FP_ROUND, dl,
7828                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
7829     return FP;
7830   }
7831 
7832   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
7833          "Unhandled INT_TO_FP type in custom expander!");
7834   // Since we only generate this in 64-bit mode, we can take advantage of
7835   // 64-bit registers.  In particular, sign extend the input value into the
7836   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
7837   // then lfd it and fcfid it.
7838   MachineFunction &MF = DAG.getMachineFunction();
7839   MachineFrameInfo &MFI = MF.getFrameInfo();
7840   EVT PtrVT = getPointerTy(MF.getDataLayout());
7841 
7842   SDValue Ld;
7843   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
7844     ReuseLoadInfo RLI;
7845     bool ReusingLoad;
7846     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
7847                                             DAG))) {
7848       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7849       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7850 
7851       SDValue Store =
7852           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7853                        MachinePointerInfo::getFixedStack(
7854                            DAG.getMachineFunction(), FrameIdx));
7855 
7856       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7857              "Expected an i32 store");
7858 
7859       RLI.Ptr = FIdx;
7860       RLI.Chain = Store;
7861       RLI.MPI =
7862           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7863       RLI.Alignment = 4;
7864     }
7865 
7866     MachineMemOperand *MMO =
7867       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7868                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7869     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7870     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
7871                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
7872                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
7873                                  Ops, MVT::i32, MMO);
7874     if (ReusingLoad)
7875       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
7876   } else {
7877     assert(Subtarget.isPPC64() &&
7878            "i32->FP without LFIWAX supported only on PPC64");
7879 
7880     int FrameIdx = MFI.CreateStackObject(8, 8, false);
7881     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7882 
7883     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
7884                                 Op.getOperand(0));
7885 
7886     // STD the extended value into the stack slot.
7887     SDValue Store = DAG.getStore(
7888         DAG.getEntryNode(), dl, Ext64, FIdx,
7889         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7890 
7891     // Load the value as a double.
7892     Ld = DAG.getLoad(
7893         MVT::f64, dl, Store, FIdx,
7894         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7895   }
7896 
7897   // FCFID it and return it.
7898   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
7899   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7900     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
7901                      DAG.getIntPtrConstant(0, dl));
7902   return FP;
7903 }
7904 
7905 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7906                                             SelectionDAG &DAG) const {
7907   SDLoc dl(Op);
7908   /*
7909    The rounding mode is in bits 30:31 of FPSR, and has the following
7910    settings:
7911      00 Round to nearest
7912      01 Round to 0
7913      10 Round to +inf
7914      11 Round to -inf
7915 
7916   FLT_ROUNDS, on the other hand, expects the following:
7917     -1 Undefined
7918      0 Round to 0
7919      1 Round to nearest
7920      2 Round to +inf
7921      3 Round to -inf
7922 
7923   To perform the conversion, we do:
7924     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7925   */
7926 
7927   MachineFunction &MF = DAG.getMachineFunction();
7928   EVT VT = Op.getValueType();
7929   EVT PtrVT = getPointerTy(MF.getDataLayout());
7930 
7931   // Save FP Control Word to register
7932   EVT NodeTys[] = {
7933     MVT::f64,    // return register
7934     MVT::Glue    // unused in this context
7935   };
7936   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7937 
7938   // Save FP register to stack slot
7939   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7940   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7941   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7942                                MachinePointerInfo());
7943 
7944   // Load FP Control Word from low 32 bits of stack slot.
7945   SDValue Four = DAG.getConstant(4, dl, PtrVT);
7946   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7947   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7948 
7949   // Transform as necessary
7950   SDValue CWD1 =
7951     DAG.getNode(ISD::AND, dl, MVT::i32,
7952                 CWD, DAG.getConstant(3, dl, MVT::i32));
7953   SDValue CWD2 =
7954     DAG.getNode(ISD::SRL, dl, MVT::i32,
7955                 DAG.getNode(ISD::AND, dl, MVT::i32,
7956                             DAG.getNode(ISD::XOR, dl, MVT::i32,
7957                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
7958                             DAG.getConstant(3, dl, MVT::i32)),
7959                 DAG.getConstant(1, dl, MVT::i32));
7960 
7961   SDValue RetVal =
7962     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7963 
7964   return DAG.getNode((VT.getSizeInBits() < 16 ?
7965                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7966 }
7967 
7968 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7969   EVT VT = Op.getValueType();
7970   unsigned BitWidth = VT.getSizeInBits();
7971   SDLoc dl(Op);
7972   assert(Op.getNumOperands() == 3 &&
7973          VT == Op.getOperand(1).getValueType() &&
7974          "Unexpected SHL!");
7975 
7976   // Expand into a bunch of logical ops.  Note that these ops
7977   // depend on the PPC behavior for oversized shift amounts.
7978   SDValue Lo = Op.getOperand(0);
7979   SDValue Hi = Op.getOperand(1);
7980   SDValue Amt = Op.getOperand(2);
7981   EVT AmtVT = Amt.getValueType();
7982 
7983   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7984                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7985   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7986   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7987   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7988   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7989                              DAG.getConstant(-BitWidth, dl, AmtVT));
7990   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7991   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7992   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7993   SDValue OutOps[] = { OutLo, OutHi };
7994   return DAG.getMergeValues(OutOps, dl);
7995 }
7996 
7997 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7998   EVT VT = Op.getValueType();
7999   SDLoc dl(Op);
8000   unsigned BitWidth = VT.getSizeInBits();
8001   assert(Op.getNumOperands() == 3 &&
8002          VT == Op.getOperand(1).getValueType() &&
8003          "Unexpected SRL!");
8004 
8005   // Expand into a bunch of logical ops.  Note that these ops
8006   // depend on the PPC behavior for oversized shift amounts.
8007   SDValue Lo = Op.getOperand(0);
8008   SDValue Hi = Op.getOperand(1);
8009   SDValue Amt = Op.getOperand(2);
8010   EVT AmtVT = Amt.getValueType();
8011 
8012   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8013                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8014   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8015   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8016   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8017   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8018                              DAG.getConstant(-BitWidth, dl, AmtVT));
8019   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8020   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8021   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8022   SDValue OutOps[] = { OutLo, OutHi };
8023   return DAG.getMergeValues(OutOps, dl);
8024 }
8025 
8026 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8027   SDLoc dl(Op);
8028   EVT VT = Op.getValueType();
8029   unsigned BitWidth = VT.getSizeInBits();
8030   assert(Op.getNumOperands() == 3 &&
8031          VT == Op.getOperand(1).getValueType() &&
8032          "Unexpected SRA!");
8033 
8034   // Expand into a bunch of logical ops, followed by a select_cc.
8035   SDValue Lo = Op.getOperand(0);
8036   SDValue Hi = Op.getOperand(1);
8037   SDValue Amt = Op.getOperand(2);
8038   EVT AmtVT = Amt.getValueType();
8039 
8040   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8041                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8042   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8043   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8044   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8045   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8046                              DAG.getConstant(-BitWidth, dl, AmtVT));
8047   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8048   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8049   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8050                                   Tmp4, Tmp6, ISD::SETLE);
8051   SDValue OutOps[] = { OutLo, OutHi };
8052   return DAG.getMergeValues(OutOps, dl);
8053 }
8054 
8055 //===----------------------------------------------------------------------===//
8056 // Vector related lowering.
8057 //
8058 
8059 /// BuildSplatI - Build a canonical splati of Val with an element size of
8060 /// SplatSize.  Cast the result to VT.
8061 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8062                            SelectionDAG &DAG, const SDLoc &dl) {
8063   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
8064 
8065   static const MVT VTys[] = { // canonical VT to use for each size.
8066     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8067   };
8068 
8069   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8070 
8071   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8072   if (Val == -1)
8073     SplatSize = 1;
8074 
8075   EVT CanonicalVT = VTys[SplatSize-1];
8076 
8077   // Build a canonical splat for this value.
8078   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8079 }
8080 
8081 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8082 /// specified intrinsic ID.
8083 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8084                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8085   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8086   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8087                      DAG.getConstant(IID, dl, MVT::i32), Op);
8088 }
8089 
8090 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8091 /// specified intrinsic ID.
8092 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8093                                 SelectionDAG &DAG, const SDLoc &dl,
8094                                 EVT DestVT = MVT::Other) {
8095   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8096   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8097                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8098 }
8099 
8100 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8101 /// specified intrinsic ID.
8102 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8103                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8104                                 EVT DestVT = MVT::Other) {
8105   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8106   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8107                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8108 }
8109 
8110 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8111 /// amount.  The result has the specified value type.
8112 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8113                            SelectionDAG &DAG, const SDLoc &dl) {
8114   // Force LHS/RHS to be the right type.
8115   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8116   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8117 
8118   int Ops[16];
8119   for (unsigned i = 0; i != 16; ++i)
8120     Ops[i] = i + Amt;
8121   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8122   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8123 }
8124 
8125 /// Do we have an efficient pattern in a .td file for this node?
8126 ///
8127 /// \param V - pointer to the BuildVectorSDNode being matched
8128 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8129 ///
8130 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8131 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8132 /// the opposite is true (expansion is beneficial) are:
8133 /// - The node builds a vector out of integers that are not 32 or 64-bits
8134 /// - The node builds a vector out of constants
8135 /// - The node is a "load-and-splat"
8136 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8137 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8138                                             bool HasDirectMove,
8139                                             bool HasP8Vector) {
8140   EVT VecVT = V->getValueType(0);
8141   bool RightType = VecVT == MVT::v2f64 ||
8142     (HasP8Vector && VecVT == MVT::v4f32) ||
8143     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8144   if (!RightType)
8145     return false;
8146 
8147   bool IsSplat = true;
8148   bool IsLoad = false;
8149   SDValue Op0 = V->getOperand(0);
8150 
8151   // This function is called in a block that confirms the node is not a constant
8152   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8153   // different constants.
8154   if (V->isConstant())
8155     return false;
8156   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8157     if (V->getOperand(i).isUndef())
8158       return false;
8159     // We want to expand nodes that represent load-and-splat even if the
8160     // loaded value is a floating point truncation or conversion to int.
8161     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8162         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8163          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8164         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8165          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8166         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8167          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8168       IsLoad = true;
8169     // If the operands are different or the input is not a load and has more
8170     // uses than just this BV node, then it isn't a splat.
8171     if (V->getOperand(i) != Op0 ||
8172         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8173       IsSplat = false;
8174   }
8175   return !(IsSplat && IsLoad);
8176 }
8177 
8178 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8179 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8180 
8181   SDLoc dl(Op);
8182   SDValue Op0 = Op->getOperand(0);
8183 
8184   if (!EnableQuadPrecision ||
8185       (Op.getValueType() != MVT::f128 ) ||
8186       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8187       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
8188       (Op0.getOperand(1).getValueType() != MVT::i64))
8189     return SDValue();
8190 
8191   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8192                      Op0.getOperand(1));
8193 }
8194 
8195 static const SDValue *getNormalLoadInput(const SDValue &Op) {
8196   const SDValue *InputLoad = &Op;
8197   if (InputLoad->getOpcode() == ISD::BITCAST)
8198     InputLoad = &InputLoad->getOperand(0);
8199   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR)
8200     InputLoad = &InputLoad->getOperand(0);
8201   if (InputLoad->getOpcode() != ISD::LOAD)
8202     return nullptr;
8203   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8204   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8205 }
8206 
8207 // If this is a case we can't handle, return null and let the default
8208 // expansion code take care of it.  If we CAN select this case, and if it
8209 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8210 // this case more efficiently than a constant pool load, lower it to the
8211 // sequence of ops that should be used.
8212 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8213                                              SelectionDAG &DAG) const {
8214   SDLoc dl(Op);
8215   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8216   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8217 
8218   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
8219     // We first build an i32 vector, load it into a QPX register,
8220     // then convert it to a floating-point vector and compare it
8221     // to a zero vector to get the boolean result.
8222     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8223     int FrameIdx = MFI.CreateStackObject(16, 16, false);
8224     MachinePointerInfo PtrInfo =
8225         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8226     EVT PtrVT = getPointerTy(DAG.getDataLayout());
8227     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8228 
8229     assert(BVN->getNumOperands() == 4 &&
8230       "BUILD_VECTOR for v4i1 does not have 4 operands");
8231 
8232     bool IsConst = true;
8233     for (unsigned i = 0; i < 4; ++i) {
8234       if (BVN->getOperand(i).isUndef()) continue;
8235       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
8236         IsConst = false;
8237         break;
8238       }
8239     }
8240 
8241     if (IsConst) {
8242       Constant *One =
8243         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
8244       Constant *NegOne =
8245         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
8246 
8247       Constant *CV[4];
8248       for (unsigned i = 0; i < 4; ++i) {
8249         if (BVN->getOperand(i).isUndef())
8250           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
8251         else if (isNullConstant(BVN->getOperand(i)))
8252           CV[i] = NegOne;
8253         else
8254           CV[i] = One;
8255       }
8256 
8257       Constant *CP = ConstantVector::get(CV);
8258       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
8259                                           16 /* alignment */);
8260 
8261       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
8262       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
8263       return DAG.getMemIntrinsicNode(
8264           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
8265           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
8266     }
8267 
8268     SmallVector<SDValue, 4> Stores;
8269     for (unsigned i = 0; i < 4; ++i) {
8270       if (BVN->getOperand(i).isUndef()) continue;
8271 
8272       unsigned Offset = 4*i;
8273       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8274       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8275 
8276       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
8277       if (StoreSize > 4) {
8278         Stores.push_back(
8279             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
8280                               PtrInfo.getWithOffset(Offset), MVT::i32));
8281       } else {
8282         SDValue StoreValue = BVN->getOperand(i);
8283         if (StoreSize < 4)
8284           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
8285 
8286         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
8287                                       PtrInfo.getWithOffset(Offset)));
8288       }
8289     }
8290 
8291     SDValue StoreChain;
8292     if (!Stores.empty())
8293       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8294     else
8295       StoreChain = DAG.getEntryNode();
8296 
8297     // Now load from v4i32 into the QPX register; this will extend it to
8298     // v4i64 but not yet convert it to a floating point. Nevertheless, this
8299     // is typed as v4f64 because the QPX register integer states are not
8300     // explicitly represented.
8301 
8302     SDValue Ops[] = {StoreChain,
8303                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
8304                      FIdx};
8305     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
8306 
8307     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
8308       dl, VTs, Ops, MVT::v4i32, PtrInfo);
8309     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8310       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
8311       LoadedVect);
8312 
8313     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
8314 
8315     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
8316   }
8317 
8318   // All other QPX vectors are handled by generic code.
8319   if (Subtarget.hasQPX())
8320     return SDValue();
8321 
8322   // Check if this is a splat of a constant value.
8323   APInt APSplatBits, APSplatUndef;
8324   unsigned SplatBitSize;
8325   bool HasAnyUndefs;
8326   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8327                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
8328       SplatBitSize > 32) {
8329 
8330     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
8331     // Handle load-and-splat patterns as we have instructions that will do this
8332     // in one go.
8333     if (InputLoad && DAG.isSplatValue(Op, true)) {
8334       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8335 
8336       // We have handling for 4 and 8 byte elements.
8337       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
8338 
8339       // Checking for a single use of this load, we have to check for vector
8340       // width (128 bits) / ElementSize uses (since each operand of the
8341       // BUILD_VECTOR is a separate use of the value.
8342       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
8343           ((Subtarget.hasVSX() && ElementSize == 64) ||
8344            (Subtarget.hasP9Vector() && ElementSize == 32))) {
8345         SDValue Ops[] = {
8346           LD->getChain(),    // Chain
8347           LD->getBasePtr(),  // Ptr
8348           DAG.getValueType(Op.getValueType()) // VT
8349         };
8350         return
8351           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
8352                                   DAG.getVTList(Op.getValueType(), MVT::Other),
8353                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
8354       }
8355     }
8356 
8357     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
8358     // lowered to VSX instructions under certain conditions.
8359     // Without VSX, there is no pattern more efficient than expanding the node.
8360     if (Subtarget.hasVSX() &&
8361         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8362                                         Subtarget.hasP8Vector()))
8363       return Op;
8364     return SDValue();
8365   }
8366 
8367   unsigned SplatBits = APSplatBits.getZExtValue();
8368   unsigned SplatUndef = APSplatUndef.getZExtValue();
8369   unsigned SplatSize = SplatBitSize / 8;
8370 
8371   // First, handle single instruction cases.
8372 
8373   // All zeros?
8374   if (SplatBits == 0) {
8375     // Canonicalize all zero vectors to be v4i32.
8376     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8377       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8378       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8379     }
8380     return Op;
8381   }
8382 
8383   // We have XXSPLTIB for constant splats one byte wide
8384   if (Subtarget.hasP9Vector() && SplatSize == 1) {
8385     // This is a splat of 1-byte elements with some elements potentially undef.
8386     // Rather than trying to match undef in the SDAG patterns, ensure that all
8387     // elements are the same constant.
8388     if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
8389       SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
8390                                                        dl, MVT::i32));
8391       SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
8392       if (Op.getValueType() != MVT::v16i8)
8393         return DAG.getBitcast(Op.getValueType(), NewBV);
8394       return NewBV;
8395     }
8396 
8397     // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll
8398     // detect that constant splats like v8i16: 0xABAB are really just splats
8399     // of a 1-byte constant. In this case, we need to convert the node to a
8400     // splat of v16i8 and a bitcast.
8401     if (Op.getValueType() != MVT::v16i8)
8402       return DAG.getBitcast(Op.getValueType(),
8403                             DAG.getConstant(SplatBits, dl, MVT::v16i8));
8404 
8405     return Op;
8406   }
8407 
8408   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8409   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8410                     (32-SplatBitSize));
8411   if (SextVal >= -16 && SextVal <= 15)
8412     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
8413 
8414   // Two instruction sequences.
8415 
8416   // If this value is in the range [-32,30] and is even, use:
8417   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8418   // If this value is in the range [17,31] and is odd, use:
8419   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8420   // If this value is in the range [-31,-17] and is odd, use:
8421   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8422   // Note the last two are three-instruction sequences.
8423   if (SextVal >= -32 && SextVal <= 31) {
8424     // To avoid having these optimizations undone by constant folding,
8425     // we convert to a pseudo that will be expanded later into one of
8426     // the above forms.
8427     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8428     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8429               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8430     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8431     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8432     if (VT == Op.getValueType())
8433       return RetVal;
8434     else
8435       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8436   }
8437 
8438   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
8439   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
8440   // for fneg/fabs.
8441   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8442     // Make -1 and vspltisw -1:
8443     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
8444 
8445     // Make the VSLW intrinsic, computing 0x8000_0000.
8446     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
8447                                    OnesV, DAG, dl);
8448 
8449     // xor by OnesV to invert it.
8450     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
8451     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8452   }
8453 
8454   // Check to see if this is a wide variety of vsplti*, binop self cases.
8455   static const signed char SplatCsts[] = {
8456     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
8457     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
8458   };
8459 
8460   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
8461     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
8462     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
8463     int i = SplatCsts[idx];
8464 
8465     // Figure out what shift amount will be used by altivec if shifted by i in
8466     // this splat size.
8467     unsigned TypeShiftAmt = i & (SplatBitSize-1);
8468 
8469     // vsplti + shl self.
8470     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
8471       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8472       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8473         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
8474         Intrinsic::ppc_altivec_vslw
8475       };
8476       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8477       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8478     }
8479 
8480     // vsplti + srl self.
8481     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8482       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8483       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8484         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
8485         Intrinsic::ppc_altivec_vsrw
8486       };
8487       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8488       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8489     }
8490 
8491     // vsplti + sra self.
8492     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8493       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8494       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8495         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
8496         Intrinsic::ppc_altivec_vsraw
8497       };
8498       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8499       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8500     }
8501 
8502     // vsplti + rol self.
8503     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
8504                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
8505       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8506       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8507         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
8508         Intrinsic::ppc_altivec_vrlw
8509       };
8510       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8511       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8512     }
8513 
8514     // t = vsplti c, result = vsldoi t, t, 1
8515     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
8516       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8517       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
8518       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8519     }
8520     // t = vsplti c, result = vsldoi t, t, 2
8521     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
8522       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8523       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
8524       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8525     }
8526     // t = vsplti c, result = vsldoi t, t, 3
8527     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
8528       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8529       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
8530       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8531     }
8532   }
8533 
8534   return SDValue();
8535 }
8536 
8537 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8538 /// the specified operations to build the shuffle.
8539 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8540                                       SDValue RHS, SelectionDAG &DAG,
8541                                       const SDLoc &dl) {
8542   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8543   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8544   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8545 
8546   enum {
8547     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8548     OP_VMRGHW,
8549     OP_VMRGLW,
8550     OP_VSPLTISW0,
8551     OP_VSPLTISW1,
8552     OP_VSPLTISW2,
8553     OP_VSPLTISW3,
8554     OP_VSLDOI4,
8555     OP_VSLDOI8,
8556     OP_VSLDOI12
8557   };
8558 
8559   if (OpNum == OP_COPY) {
8560     if (LHSID == (1*9+2)*9+3) return LHS;
8561     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8562     return RHS;
8563   }
8564 
8565   SDValue OpLHS, OpRHS;
8566   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8567   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8568 
8569   int ShufIdxs[16];
8570   switch (OpNum) {
8571   default: llvm_unreachable("Unknown i32 permute!");
8572   case OP_VMRGHW:
8573     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
8574     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
8575     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
8576     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
8577     break;
8578   case OP_VMRGLW:
8579     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
8580     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
8581     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
8582     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
8583     break;
8584   case OP_VSPLTISW0:
8585     for (unsigned i = 0; i != 16; ++i)
8586       ShufIdxs[i] = (i&3)+0;
8587     break;
8588   case OP_VSPLTISW1:
8589     for (unsigned i = 0; i != 16; ++i)
8590       ShufIdxs[i] = (i&3)+4;
8591     break;
8592   case OP_VSPLTISW2:
8593     for (unsigned i = 0; i != 16; ++i)
8594       ShufIdxs[i] = (i&3)+8;
8595     break;
8596   case OP_VSPLTISW3:
8597     for (unsigned i = 0; i != 16; ++i)
8598       ShufIdxs[i] = (i&3)+12;
8599     break;
8600   case OP_VSLDOI4:
8601     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
8602   case OP_VSLDOI8:
8603     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
8604   case OP_VSLDOI12:
8605     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
8606   }
8607   EVT VT = OpLHS.getValueType();
8608   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
8609   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
8610   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
8611   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8612 }
8613 
8614 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
8615 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
8616 /// SDValue.
8617 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
8618                                            SelectionDAG &DAG) const {
8619   const unsigned BytesInVector = 16;
8620   bool IsLE = Subtarget.isLittleEndian();
8621   SDLoc dl(N);
8622   SDValue V1 = N->getOperand(0);
8623   SDValue V2 = N->getOperand(1);
8624   unsigned ShiftElts = 0, InsertAtByte = 0;
8625   bool Swap = false;
8626 
8627   // Shifts required to get the byte we want at element 7.
8628   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
8629                                    0, 15, 14, 13, 12, 11, 10, 9};
8630   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
8631                                 1, 2,  3,  4,  5,  6,  7,  8};
8632 
8633   ArrayRef<int> Mask = N->getMask();
8634   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
8635 
8636   // For each mask element, find out if we're just inserting something
8637   // from V2 into V1 or vice versa.
8638   // Possible permutations inserting an element from V2 into V1:
8639   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8640   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8641   //   ...
8642   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
8643   // Inserting from V1 into V2 will be similar, except mask range will be
8644   // [16,31].
8645 
8646   bool FoundCandidate = false;
8647   // If both vector operands for the shuffle are the same vector, the mask
8648   // will contain only elements from the first one and the second one will be
8649   // undef.
8650   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
8651   // Go through the mask of half-words to find an element that's being moved
8652   // from one vector to the other.
8653   for (unsigned i = 0; i < BytesInVector; ++i) {
8654     unsigned CurrentElement = Mask[i];
8655     // If 2nd operand is undefined, we should only look for element 7 in the
8656     // Mask.
8657     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
8658       continue;
8659 
8660     bool OtherElementsInOrder = true;
8661     // Examine the other elements in the Mask to see if they're in original
8662     // order.
8663     for (unsigned j = 0; j < BytesInVector; ++j) {
8664       if (j == i)
8665         continue;
8666       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
8667       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
8668       // in which we always assume we're always picking from the 1st operand.
8669       int MaskOffset =
8670           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
8671       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
8672         OtherElementsInOrder = false;
8673         break;
8674       }
8675     }
8676     // If other elements are in original order, we record the number of shifts
8677     // we need to get the element we want into element 7. Also record which byte
8678     // in the vector we should insert into.
8679     if (OtherElementsInOrder) {
8680       // If 2nd operand is undefined, we assume no shifts and no swapping.
8681       if (V2.isUndef()) {
8682         ShiftElts = 0;
8683         Swap = false;
8684       } else {
8685         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
8686         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
8687                          : BigEndianShifts[CurrentElement & 0xF];
8688         Swap = CurrentElement < BytesInVector;
8689       }
8690       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
8691       FoundCandidate = true;
8692       break;
8693     }
8694   }
8695 
8696   if (!FoundCandidate)
8697     return SDValue();
8698 
8699   // Candidate found, construct the proper SDAG sequence with VINSERTB,
8700   // optionally with VECSHL if shift is required.
8701   if (Swap)
8702     std::swap(V1, V2);
8703   if (V2.isUndef())
8704     V2 = V1;
8705   if (ShiftElts) {
8706     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8707                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8708     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
8709                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
8710   }
8711   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
8712                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
8713 }
8714 
8715 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
8716 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
8717 /// SDValue.
8718 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
8719                                            SelectionDAG &DAG) const {
8720   const unsigned NumHalfWords = 8;
8721   const unsigned BytesInVector = NumHalfWords * 2;
8722   // Check that the shuffle is on half-words.
8723   if (!isNByteElemShuffleMask(N, 2, 1))
8724     return SDValue();
8725 
8726   bool IsLE = Subtarget.isLittleEndian();
8727   SDLoc dl(N);
8728   SDValue V1 = N->getOperand(0);
8729   SDValue V2 = N->getOperand(1);
8730   unsigned ShiftElts = 0, InsertAtByte = 0;
8731   bool Swap = false;
8732 
8733   // Shifts required to get the half-word we want at element 3.
8734   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
8735   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
8736 
8737   uint32_t Mask = 0;
8738   uint32_t OriginalOrderLow = 0x1234567;
8739   uint32_t OriginalOrderHigh = 0x89ABCDEF;
8740   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
8741   // 32-bit space, only need 4-bit nibbles per element.
8742   for (unsigned i = 0; i < NumHalfWords; ++i) {
8743     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8744     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
8745   }
8746 
8747   // For each mask element, find out if we're just inserting something
8748   // from V2 into V1 or vice versa.  Possible permutations inserting an element
8749   // from V2 into V1:
8750   //   X, 1, 2, 3, 4, 5, 6, 7
8751   //   0, X, 2, 3, 4, 5, 6, 7
8752   //   0, 1, X, 3, 4, 5, 6, 7
8753   //   0, 1, 2, X, 4, 5, 6, 7
8754   //   0, 1, 2, 3, X, 5, 6, 7
8755   //   0, 1, 2, 3, 4, X, 6, 7
8756   //   0, 1, 2, 3, 4, 5, X, 7
8757   //   0, 1, 2, 3, 4, 5, 6, X
8758   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
8759 
8760   bool FoundCandidate = false;
8761   // Go through the mask of half-words to find an element that's being moved
8762   // from one vector to the other.
8763   for (unsigned i = 0; i < NumHalfWords; ++i) {
8764     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8765     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
8766     uint32_t MaskOtherElts = ~(0xF << MaskShift);
8767     uint32_t TargetOrder = 0x0;
8768 
8769     // If both vector operands for the shuffle are the same vector, the mask
8770     // will contain only elements from the first one and the second one will be
8771     // undef.
8772     if (V2.isUndef()) {
8773       ShiftElts = 0;
8774       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
8775       TargetOrder = OriginalOrderLow;
8776       Swap = false;
8777       // Skip if not the correct element or mask of other elements don't equal
8778       // to our expected order.
8779       if (MaskOneElt == VINSERTHSrcElem &&
8780           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8781         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8782         FoundCandidate = true;
8783         break;
8784       }
8785     } else { // If both operands are defined.
8786       // Target order is [8,15] if the current mask is between [0,7].
8787       TargetOrder =
8788           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
8789       // Skip if mask of other elements don't equal our expected order.
8790       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8791         // We only need the last 3 bits for the number of shifts.
8792         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
8793                          : BigEndianShifts[MaskOneElt & 0x7];
8794         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8795         Swap = MaskOneElt < NumHalfWords;
8796         FoundCandidate = true;
8797         break;
8798       }
8799     }
8800   }
8801 
8802   if (!FoundCandidate)
8803     return SDValue();
8804 
8805   // Candidate found, construct the proper SDAG sequence with VINSERTH,
8806   // optionally with VECSHL if shift is required.
8807   if (Swap)
8808     std::swap(V1, V2);
8809   if (V2.isUndef())
8810     V2 = V1;
8811   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8812   if (ShiftElts) {
8813     // Double ShiftElts because we're left shifting on v16i8 type.
8814     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8815                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
8816     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
8817     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8818                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8819     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8820   }
8821   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8822   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8823                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
8824   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8825 }
8826 
8827 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
8828 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
8829 /// return the code it can be lowered into.  Worst case, it can always be
8830 /// lowered into a vperm.
8831 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
8832                                                SelectionDAG &DAG) const {
8833   SDLoc dl(Op);
8834   SDValue V1 = Op.getOperand(0);
8835   SDValue V2 = Op.getOperand(1);
8836   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8837   EVT VT = Op.getValueType();
8838   bool isLittleEndian = Subtarget.isLittleEndian();
8839 
8840   unsigned ShiftElts, InsertAtByte;
8841   bool Swap = false;
8842 
8843   // If this is a load-and-splat, we can do that with a single instruction
8844   // in some cases. However if the load has multiple uses, we don't want to
8845   // combine it because that will just produce multiple loads.
8846   const SDValue *InputLoad = getNormalLoadInput(V1);
8847   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
8848       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
8849       InputLoad->hasOneUse()) {
8850     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
8851     int SplatIdx =
8852       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
8853 
8854     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8855     // For 4-byte load-and-splat, we need Power9.
8856     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
8857       uint64_t Offset = 0;
8858       if (IsFourByte)
8859         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
8860       else
8861         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
8862       SDValue BasePtr = LD->getBasePtr();
8863       if (Offset != 0)
8864         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
8865                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
8866       SDValue Ops[] = {
8867         LD->getChain(),    // Chain
8868         BasePtr,           // BasePtr
8869         DAG.getValueType(Op.getValueType()) // VT
8870       };
8871       SDVTList VTL =
8872         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
8873       SDValue LdSplt =
8874         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
8875                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
8876       if (LdSplt.getValueType() != SVOp->getValueType(0))
8877         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
8878       return LdSplt;
8879     }
8880   }
8881   if (Subtarget.hasP9Vector() &&
8882       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
8883                            isLittleEndian)) {
8884     if (Swap)
8885       std::swap(V1, V2);
8886     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8887     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
8888     if (ShiftElts) {
8889       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
8890                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
8891       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
8892                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8893       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8894     }
8895     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
8896                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8897     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8898   }
8899 
8900   if (Subtarget.hasP9Altivec()) {
8901     SDValue NewISDNode;
8902     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
8903       return NewISDNode;
8904 
8905     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
8906       return NewISDNode;
8907   }
8908 
8909   if (Subtarget.hasVSX() &&
8910       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8911     if (Swap)
8912       std::swap(V1, V2);
8913     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8914     SDValue Conv2 =
8915         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
8916 
8917     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
8918                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8919     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
8920   }
8921 
8922   if (Subtarget.hasVSX() &&
8923     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8924     if (Swap)
8925       std::swap(V1, V2);
8926     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8927     SDValue Conv2 =
8928         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
8929 
8930     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
8931                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8932     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
8933   }
8934 
8935   if (Subtarget.hasP9Vector()) {
8936      if (PPC::isXXBRHShuffleMask(SVOp)) {
8937       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8938       SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv);
8939       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
8940     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
8941       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8942       SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv);
8943       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
8944     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
8945       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8946       SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv);
8947       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
8948     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
8949       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
8950       SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv);
8951       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
8952     }
8953   }
8954 
8955   if (Subtarget.hasVSX()) {
8956     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
8957       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
8958 
8959       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8960       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
8961                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
8962       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
8963     }
8964 
8965     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
8966     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
8967       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8968       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
8969       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
8970     }
8971   }
8972 
8973   if (Subtarget.hasQPX()) {
8974     if (VT.getVectorNumElements() != 4)
8975       return SDValue();
8976 
8977     if (V2.isUndef()) V2 = V1;
8978 
8979     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
8980     if (AlignIdx != -1) {
8981       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
8982                          DAG.getConstant(AlignIdx, dl, MVT::i32));
8983     } else if (SVOp->isSplat()) {
8984       int SplatIdx = SVOp->getSplatIndex();
8985       if (SplatIdx >= 4) {
8986         std::swap(V1, V2);
8987         SplatIdx -= 4;
8988       }
8989 
8990       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
8991                          DAG.getConstant(SplatIdx, dl, MVT::i32));
8992     }
8993 
8994     // Lower this into a qvgpci/qvfperm pair.
8995 
8996     // Compute the qvgpci literal
8997     unsigned idx = 0;
8998     for (unsigned i = 0; i < 4; ++i) {
8999       int m = SVOp->getMaskElt(i);
9000       unsigned mm = m >= 0 ? (unsigned) m : i;
9001       idx |= mm << (3-i)*3;
9002     }
9003 
9004     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
9005                              DAG.getConstant(idx, dl, MVT::i32));
9006     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
9007   }
9008 
9009   // Cases that are handled by instructions that take permute immediates
9010   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9011   // selected by the instruction selector.
9012   if (V2.isUndef()) {
9013     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9014         PPC::isSplatShuffleMask(SVOp, 2) ||
9015         PPC::isSplatShuffleMask(SVOp, 4) ||
9016         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9017         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9018         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9019         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9020         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9021         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9022         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9023         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9024         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9025         (Subtarget.hasP8Altivec() && (
9026          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9027          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9028          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9029       return Op;
9030     }
9031   }
9032 
9033   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9034   // and produce a fixed permutation.  If any of these match, do not lower to
9035   // VPERM.
9036   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9037   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9038       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9039       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9040       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9041       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9042       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9043       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9044       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9045       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9046       (Subtarget.hasP8Altivec() && (
9047        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9048        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9049        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9050     return Op;
9051 
9052   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9053   // perfect shuffle table to emit an optimal matching sequence.
9054   ArrayRef<int> PermMask = SVOp->getMask();
9055 
9056   unsigned PFIndexes[4];
9057   bool isFourElementShuffle = true;
9058   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9059     unsigned EltNo = 8;   // Start out undef.
9060     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9061       if (PermMask[i*4+j] < 0)
9062         continue;   // Undef, ignore it.
9063 
9064       unsigned ByteSource = PermMask[i*4+j];
9065       if ((ByteSource & 3) != j) {
9066         isFourElementShuffle = false;
9067         break;
9068       }
9069 
9070       if (EltNo == 8) {
9071         EltNo = ByteSource/4;
9072       } else if (EltNo != ByteSource/4) {
9073         isFourElementShuffle = false;
9074         break;
9075       }
9076     }
9077     PFIndexes[i] = EltNo;
9078   }
9079 
9080   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9081   // perfect shuffle vector to determine if it is cost effective to do this as
9082   // discrete instructions, or whether we should use a vperm.
9083   // For now, we skip this for little endian until such time as we have a
9084   // little-endian perfect shuffle table.
9085   if (isFourElementShuffle && !isLittleEndian) {
9086     // Compute the index in the perfect shuffle table.
9087     unsigned PFTableIndex =
9088       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9089 
9090     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9091     unsigned Cost  = (PFEntry >> 30);
9092 
9093     // Determining when to avoid vperm is tricky.  Many things affect the cost
9094     // of vperm, particularly how many times the perm mask needs to be computed.
9095     // For example, if the perm mask can be hoisted out of a loop or is already
9096     // used (perhaps because there are multiple permutes with the same shuffle
9097     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9098     // the loop requires an extra register.
9099     //
9100     // As a compromise, we only emit discrete instructions if the shuffle can be
9101     // generated in 3 or fewer operations.  When we have loop information
9102     // available, if this block is within a loop, we should avoid using vperm
9103     // for 3-operation perms and use a constant pool load instead.
9104     if (Cost < 3)
9105       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9106   }
9107 
9108   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9109   // vector that will get spilled to the constant pool.
9110   if (V2.isUndef()) V2 = V1;
9111 
9112   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9113   // that it is in input element units, not in bytes.  Convert now.
9114 
9115   // For little endian, the order of the input vectors is reversed, and
9116   // the permutation mask is complemented with respect to 31.  This is
9117   // necessary to produce proper semantics with the big-endian-biased vperm
9118   // instruction.
9119   EVT EltVT = V1.getValueType().getVectorElementType();
9120   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9121 
9122   SmallVector<SDValue, 16> ResultMask;
9123   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9124     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9125 
9126     for (unsigned j = 0; j != BytesPerElement; ++j)
9127       if (isLittleEndian)
9128         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9129                                              dl, MVT::i32));
9130       else
9131         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9132                                              MVT::i32));
9133   }
9134 
9135   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9136   if (isLittleEndian)
9137     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9138                        V2, V1, VPermMask);
9139   else
9140     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9141                        V1, V2, VPermMask);
9142 }
9143 
9144 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9145 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9146 /// information about the intrinsic.
9147 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9148                                  bool &isDot, const PPCSubtarget &Subtarget) {
9149   unsigned IntrinsicID =
9150       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9151   CompareOpc = -1;
9152   isDot = false;
9153   switch (IntrinsicID) {
9154   default:
9155     return false;
9156   // Comparison predicates.
9157   case Intrinsic::ppc_altivec_vcmpbfp_p:
9158     CompareOpc = 966;
9159     isDot = true;
9160     break;
9161   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9162     CompareOpc = 198;
9163     isDot = true;
9164     break;
9165   case Intrinsic::ppc_altivec_vcmpequb_p:
9166     CompareOpc = 6;
9167     isDot = true;
9168     break;
9169   case Intrinsic::ppc_altivec_vcmpequh_p:
9170     CompareOpc = 70;
9171     isDot = true;
9172     break;
9173   case Intrinsic::ppc_altivec_vcmpequw_p:
9174     CompareOpc = 134;
9175     isDot = true;
9176     break;
9177   case Intrinsic::ppc_altivec_vcmpequd_p:
9178     if (Subtarget.hasP8Altivec()) {
9179       CompareOpc = 199;
9180       isDot = true;
9181     } else
9182       return false;
9183     break;
9184   case Intrinsic::ppc_altivec_vcmpneb_p:
9185   case Intrinsic::ppc_altivec_vcmpneh_p:
9186   case Intrinsic::ppc_altivec_vcmpnew_p:
9187   case Intrinsic::ppc_altivec_vcmpnezb_p:
9188   case Intrinsic::ppc_altivec_vcmpnezh_p:
9189   case Intrinsic::ppc_altivec_vcmpnezw_p:
9190     if (Subtarget.hasP9Altivec()) {
9191       switch (IntrinsicID) {
9192       default:
9193         llvm_unreachable("Unknown comparison intrinsic.");
9194       case Intrinsic::ppc_altivec_vcmpneb_p:
9195         CompareOpc = 7;
9196         break;
9197       case Intrinsic::ppc_altivec_vcmpneh_p:
9198         CompareOpc = 71;
9199         break;
9200       case Intrinsic::ppc_altivec_vcmpnew_p:
9201         CompareOpc = 135;
9202         break;
9203       case Intrinsic::ppc_altivec_vcmpnezb_p:
9204         CompareOpc = 263;
9205         break;
9206       case Intrinsic::ppc_altivec_vcmpnezh_p:
9207         CompareOpc = 327;
9208         break;
9209       case Intrinsic::ppc_altivec_vcmpnezw_p:
9210         CompareOpc = 391;
9211         break;
9212       }
9213       isDot = true;
9214     } else
9215       return false;
9216     break;
9217   case Intrinsic::ppc_altivec_vcmpgefp_p:
9218     CompareOpc = 454;
9219     isDot = true;
9220     break;
9221   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9222     CompareOpc = 710;
9223     isDot = true;
9224     break;
9225   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9226     CompareOpc = 774;
9227     isDot = true;
9228     break;
9229   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9230     CompareOpc = 838;
9231     isDot = true;
9232     break;
9233   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9234     CompareOpc = 902;
9235     isDot = true;
9236     break;
9237   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9238     if (Subtarget.hasP8Altivec()) {
9239       CompareOpc = 967;
9240       isDot = true;
9241     } else
9242       return false;
9243     break;
9244   case Intrinsic::ppc_altivec_vcmpgtub_p:
9245     CompareOpc = 518;
9246     isDot = true;
9247     break;
9248   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9249     CompareOpc = 582;
9250     isDot = true;
9251     break;
9252   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9253     CompareOpc = 646;
9254     isDot = true;
9255     break;
9256   case Intrinsic::ppc_altivec_vcmpgtud_p:
9257     if (Subtarget.hasP8Altivec()) {
9258       CompareOpc = 711;
9259       isDot = true;
9260     } else
9261       return false;
9262     break;
9263 
9264   // VSX predicate comparisons use the same infrastructure
9265   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9266   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9267   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9268   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9269   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9270   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9271     if (Subtarget.hasVSX()) {
9272       switch (IntrinsicID) {
9273       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9274         CompareOpc = 99;
9275         break;
9276       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9277         CompareOpc = 115;
9278         break;
9279       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9280         CompareOpc = 107;
9281         break;
9282       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9283         CompareOpc = 67;
9284         break;
9285       case Intrinsic::ppc_vsx_xvcmpgesp_p:
9286         CompareOpc = 83;
9287         break;
9288       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9289         CompareOpc = 75;
9290         break;
9291       }
9292       isDot = true;
9293     } else
9294       return false;
9295     break;
9296 
9297   // Normal Comparisons.
9298   case Intrinsic::ppc_altivec_vcmpbfp:
9299     CompareOpc = 966;
9300     break;
9301   case Intrinsic::ppc_altivec_vcmpeqfp:
9302     CompareOpc = 198;
9303     break;
9304   case Intrinsic::ppc_altivec_vcmpequb:
9305     CompareOpc = 6;
9306     break;
9307   case Intrinsic::ppc_altivec_vcmpequh:
9308     CompareOpc = 70;
9309     break;
9310   case Intrinsic::ppc_altivec_vcmpequw:
9311     CompareOpc = 134;
9312     break;
9313   case Intrinsic::ppc_altivec_vcmpequd:
9314     if (Subtarget.hasP8Altivec())
9315       CompareOpc = 199;
9316     else
9317       return false;
9318     break;
9319   case Intrinsic::ppc_altivec_vcmpneb:
9320   case Intrinsic::ppc_altivec_vcmpneh:
9321   case Intrinsic::ppc_altivec_vcmpnew:
9322   case Intrinsic::ppc_altivec_vcmpnezb:
9323   case Intrinsic::ppc_altivec_vcmpnezh:
9324   case Intrinsic::ppc_altivec_vcmpnezw:
9325     if (Subtarget.hasP9Altivec())
9326       switch (IntrinsicID) {
9327       default:
9328         llvm_unreachable("Unknown comparison intrinsic.");
9329       case Intrinsic::ppc_altivec_vcmpneb:
9330         CompareOpc = 7;
9331         break;
9332       case Intrinsic::ppc_altivec_vcmpneh:
9333         CompareOpc = 71;
9334         break;
9335       case Intrinsic::ppc_altivec_vcmpnew:
9336         CompareOpc = 135;
9337         break;
9338       case Intrinsic::ppc_altivec_vcmpnezb:
9339         CompareOpc = 263;
9340         break;
9341       case Intrinsic::ppc_altivec_vcmpnezh:
9342         CompareOpc = 327;
9343         break;
9344       case Intrinsic::ppc_altivec_vcmpnezw:
9345         CompareOpc = 391;
9346         break;
9347       }
9348     else
9349       return false;
9350     break;
9351   case Intrinsic::ppc_altivec_vcmpgefp:
9352     CompareOpc = 454;
9353     break;
9354   case Intrinsic::ppc_altivec_vcmpgtfp:
9355     CompareOpc = 710;
9356     break;
9357   case Intrinsic::ppc_altivec_vcmpgtsb:
9358     CompareOpc = 774;
9359     break;
9360   case Intrinsic::ppc_altivec_vcmpgtsh:
9361     CompareOpc = 838;
9362     break;
9363   case Intrinsic::ppc_altivec_vcmpgtsw:
9364     CompareOpc = 902;
9365     break;
9366   case Intrinsic::ppc_altivec_vcmpgtsd:
9367     if (Subtarget.hasP8Altivec())
9368       CompareOpc = 967;
9369     else
9370       return false;
9371     break;
9372   case Intrinsic::ppc_altivec_vcmpgtub:
9373     CompareOpc = 518;
9374     break;
9375   case Intrinsic::ppc_altivec_vcmpgtuh:
9376     CompareOpc = 582;
9377     break;
9378   case Intrinsic::ppc_altivec_vcmpgtuw:
9379     CompareOpc = 646;
9380     break;
9381   case Intrinsic::ppc_altivec_vcmpgtud:
9382     if (Subtarget.hasP8Altivec())
9383       CompareOpc = 711;
9384     else
9385       return false;
9386     break;
9387   }
9388   return true;
9389 }
9390 
9391 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
9392 /// lower, do it, otherwise return null.
9393 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
9394                                                    SelectionDAG &DAG) const {
9395   unsigned IntrinsicID =
9396     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9397 
9398   SDLoc dl(Op);
9399 
9400   if (IntrinsicID == Intrinsic::thread_pointer) {
9401     // Reads the thread pointer register, used for __builtin_thread_pointer.
9402     if (Subtarget.isPPC64())
9403       return DAG.getRegister(PPC::X13, MVT::i64);
9404     return DAG.getRegister(PPC::R2, MVT::i32);
9405   }
9406 
9407   // If this is a lowered altivec predicate compare, CompareOpc is set to the
9408   // opcode number of the comparison.
9409   int CompareOpc;
9410   bool isDot;
9411   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
9412     return SDValue();    // Don't custom lower most intrinsics.
9413 
9414   // If this is a non-dot comparison, make the VCMP node and we are done.
9415   if (!isDot) {
9416     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
9417                               Op.getOperand(1), Op.getOperand(2),
9418                               DAG.getConstant(CompareOpc, dl, MVT::i32));
9419     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
9420   }
9421 
9422   // Create the PPCISD altivec 'dot' comparison node.
9423   SDValue Ops[] = {
9424     Op.getOperand(2),  // LHS
9425     Op.getOperand(3),  // RHS
9426     DAG.getConstant(CompareOpc, dl, MVT::i32)
9427   };
9428   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
9429   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9430 
9431   // Now that we have the comparison, emit a copy from the CR to a GPR.
9432   // This is flagged to the above dot comparison.
9433   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
9434                                 DAG.getRegister(PPC::CR6, MVT::i32),
9435                                 CompNode.getValue(1));
9436 
9437   // Unpack the result based on how the target uses it.
9438   unsigned BitNo;   // Bit # of CR6.
9439   bool InvertBit;   // Invert result?
9440   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
9441   default:  // Can't happen, don't crash on invalid number though.
9442   case 0:   // Return the value of the EQ bit of CR6.
9443     BitNo = 0; InvertBit = false;
9444     break;
9445   case 1:   // Return the inverted value of the EQ bit of CR6.
9446     BitNo = 0; InvertBit = true;
9447     break;
9448   case 2:   // Return the value of the LT bit of CR6.
9449     BitNo = 2; InvertBit = false;
9450     break;
9451   case 3:   // Return the inverted value of the LT bit of CR6.
9452     BitNo = 2; InvertBit = true;
9453     break;
9454   }
9455 
9456   // Shift the bit into the low position.
9457   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
9458                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
9459   // Isolate the bit.
9460   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
9461                       DAG.getConstant(1, dl, MVT::i32));
9462 
9463   // If we are supposed to, toggle the bit.
9464   if (InvertBit)
9465     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
9466                         DAG.getConstant(1, dl, MVT::i32));
9467   return Flags;
9468 }
9469 
9470 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
9471                                                SelectionDAG &DAG) const {
9472   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
9473   // the beginning of the argument list.
9474   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
9475   SDLoc DL(Op);
9476   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
9477   case Intrinsic::ppc_cfence: {
9478     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
9479     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
9480     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
9481                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
9482                                                   Op.getOperand(ArgStart + 1)),
9483                                       Op.getOperand(0)),
9484                    0);
9485   }
9486   default:
9487     break;
9488   }
9489   return SDValue();
9490 }
9491 
9492 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
9493   // Check for a DIV with the same operands as this REM.
9494   for (auto UI : Op.getOperand(1)->uses()) {
9495     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
9496         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
9497       if (UI->getOperand(0) == Op.getOperand(0) &&
9498           UI->getOperand(1) == Op.getOperand(1))
9499         return SDValue();
9500   }
9501   return Op;
9502 }
9503 
9504 // Lower scalar BSWAP64 to xxbrd.
9505 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
9506   SDLoc dl(Op);
9507   // MTVSRDD
9508   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
9509                    Op.getOperand(0));
9510   // XXBRD
9511   Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op);
9512   // MFVSRD
9513   int VectorIndex = 0;
9514   if (Subtarget.isLittleEndian())
9515     VectorIndex = 1;
9516   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
9517                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
9518   return Op;
9519 }
9520 
9521 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
9522 // compared to a value that is atomically loaded (atomic loads zero-extend).
9523 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
9524                                                 SelectionDAG &DAG) const {
9525   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
9526          "Expecting an atomic compare-and-swap here.");
9527   SDLoc dl(Op);
9528   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
9529   EVT MemVT = AtomicNode->getMemoryVT();
9530   if (MemVT.getSizeInBits() >= 32)
9531     return Op;
9532 
9533   SDValue CmpOp = Op.getOperand(2);
9534   // If this is already correctly zero-extended, leave it alone.
9535   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
9536   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
9537     return Op;
9538 
9539   // Clear the high bits of the compare operand.
9540   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
9541   SDValue NewCmpOp =
9542     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
9543                 DAG.getConstant(MaskVal, dl, MVT::i32));
9544 
9545   // Replace the existing compare operand with the properly zero-extended one.
9546   SmallVector<SDValue, 4> Ops;
9547   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
9548     Ops.push_back(AtomicNode->getOperand(i));
9549   Ops[2] = NewCmpOp;
9550   MachineMemOperand *MMO = AtomicNode->getMemOperand();
9551   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
9552   auto NodeTy =
9553     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
9554   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
9555 }
9556 
9557 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
9558                                                  SelectionDAG &DAG) const {
9559   SDLoc dl(Op);
9560   // Create a stack slot that is 16-byte aligned.
9561   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9562   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9563   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9564   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9565 
9566   // Store the input value into Value#0 of the stack slot.
9567   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
9568                                MachinePointerInfo());
9569   // Load it out.
9570   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
9571 }
9572 
9573 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9574                                                   SelectionDAG &DAG) const {
9575   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
9576          "Should only be called for ISD::INSERT_VECTOR_ELT");
9577 
9578   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9579   // We have legal lowering for constant indices but not for variable ones.
9580   if (!C)
9581     return SDValue();
9582 
9583   EVT VT = Op.getValueType();
9584   SDLoc dl(Op);
9585   SDValue V1 = Op.getOperand(0);
9586   SDValue V2 = Op.getOperand(1);
9587   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
9588   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
9589     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
9590     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
9591     unsigned InsertAtElement = C->getZExtValue();
9592     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
9593     if (Subtarget.isLittleEndian()) {
9594       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
9595     }
9596     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
9597                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9598   }
9599   return Op;
9600 }
9601 
9602 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9603                                                    SelectionDAG &DAG) const {
9604   SDLoc dl(Op);
9605   SDNode *N = Op.getNode();
9606 
9607   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
9608          "Unknown extract_vector_elt type");
9609 
9610   SDValue Value = N->getOperand(0);
9611 
9612   // The first part of this is like the store lowering except that we don't
9613   // need to track the chain.
9614 
9615   // The values are now known to be -1 (false) or 1 (true). To convert this
9616   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9617   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9618   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9619 
9620   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9621   // understand how to form the extending load.
9622   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9623 
9624   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9625 
9626   // Now convert to an integer and store.
9627   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9628     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9629     Value);
9630 
9631   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9632   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9633   MachinePointerInfo PtrInfo =
9634       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9635   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9636   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9637 
9638   SDValue StoreChain = DAG.getEntryNode();
9639   SDValue Ops[] = {StoreChain,
9640                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9641                    Value, FIdx};
9642   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9643 
9644   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9645     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9646 
9647   // Extract the value requested.
9648   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9649   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9650   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9651 
9652   SDValue IntVal =
9653       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
9654 
9655   if (!Subtarget.useCRBits())
9656     return IntVal;
9657 
9658   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
9659 }
9660 
9661 /// Lowering for QPX v4i1 loads
9662 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
9663                                            SelectionDAG &DAG) const {
9664   SDLoc dl(Op);
9665   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
9666   SDValue LoadChain = LN->getChain();
9667   SDValue BasePtr = LN->getBasePtr();
9668 
9669   if (Op.getValueType() == MVT::v4f64 ||
9670       Op.getValueType() == MVT::v4f32) {
9671     EVT MemVT = LN->getMemoryVT();
9672     unsigned Alignment = LN->getAlignment();
9673 
9674     // If this load is properly aligned, then it is legal.
9675     if (Alignment >= MemVT.getStoreSize())
9676       return Op;
9677 
9678     EVT ScalarVT = Op.getValueType().getScalarType(),
9679         ScalarMemVT = MemVT.getScalarType();
9680     unsigned Stride = ScalarMemVT.getStoreSize();
9681 
9682     SDValue Vals[4], LoadChains[4];
9683     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9684       SDValue Load;
9685       if (ScalarVT != ScalarMemVT)
9686         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
9687                               BasePtr,
9688                               LN->getPointerInfo().getWithOffset(Idx * Stride),
9689                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9690                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
9691       else
9692         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
9693                            LN->getPointerInfo().getWithOffset(Idx * Stride),
9694                            MinAlign(Alignment, Idx * Stride),
9695                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
9696 
9697       if (Idx == 0 && LN->isIndexed()) {
9698         assert(LN->getAddressingMode() == ISD::PRE_INC &&
9699                "Unknown addressing mode on vector load");
9700         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
9701                                   LN->getAddressingMode());
9702       }
9703 
9704       Vals[Idx] = Load;
9705       LoadChains[Idx] = Load.getValue(1);
9706 
9707       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9708                             DAG.getConstant(Stride, dl,
9709                                             BasePtr.getValueType()));
9710     }
9711 
9712     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9713     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
9714 
9715     if (LN->isIndexed()) {
9716       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
9717       return DAG.getMergeValues(RetOps, dl);
9718     }
9719 
9720     SDValue RetOps[] = { Value, TF };
9721     return DAG.getMergeValues(RetOps, dl);
9722   }
9723 
9724   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
9725   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
9726 
9727   // To lower v4i1 from a byte array, we load the byte elements of the
9728   // vector and then reuse the BUILD_VECTOR logic.
9729 
9730   SDValue VectElmts[4], VectElmtChains[4];
9731   for (unsigned i = 0; i < 4; ++i) {
9732     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9733     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9734 
9735     VectElmts[i] = DAG.getExtLoad(
9736         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
9737         LN->getPointerInfo().getWithOffset(i), MVT::i8,
9738         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
9739     VectElmtChains[i] = VectElmts[i].getValue(1);
9740   }
9741 
9742   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
9743   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
9744 
9745   SDValue RVals[] = { Value, LoadChain };
9746   return DAG.getMergeValues(RVals, dl);
9747 }
9748 
9749 /// Lowering for QPX v4i1 stores
9750 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
9751                                             SelectionDAG &DAG) const {
9752   SDLoc dl(Op);
9753   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
9754   SDValue StoreChain = SN->getChain();
9755   SDValue BasePtr = SN->getBasePtr();
9756   SDValue Value = SN->getValue();
9757 
9758   if (Value.getValueType() == MVT::v4f64 ||
9759       Value.getValueType() == MVT::v4f32) {
9760     EVT MemVT = SN->getMemoryVT();
9761     unsigned Alignment = SN->getAlignment();
9762 
9763     // If this store is properly aligned, then it is legal.
9764     if (Alignment >= MemVT.getStoreSize())
9765       return Op;
9766 
9767     EVT ScalarVT = Value.getValueType().getScalarType(),
9768         ScalarMemVT = MemVT.getScalarType();
9769     unsigned Stride = ScalarMemVT.getStoreSize();
9770 
9771     SDValue Stores[4];
9772     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9773       SDValue Ex = DAG.getNode(
9774           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
9775           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
9776       SDValue Store;
9777       if (ScalarVT != ScalarMemVT)
9778         Store =
9779             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
9780                               SN->getPointerInfo().getWithOffset(Idx * Stride),
9781                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9782                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
9783       else
9784         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
9785                              SN->getPointerInfo().getWithOffset(Idx * Stride),
9786                              MinAlign(Alignment, Idx * Stride),
9787                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
9788 
9789       if (Idx == 0 && SN->isIndexed()) {
9790         assert(SN->getAddressingMode() == ISD::PRE_INC &&
9791                "Unknown addressing mode on vector store");
9792         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
9793                                     SN->getAddressingMode());
9794       }
9795 
9796       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9797                             DAG.getConstant(Stride, dl,
9798                                             BasePtr.getValueType()));
9799       Stores[Idx] = Store;
9800     }
9801 
9802     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9803 
9804     if (SN->isIndexed()) {
9805       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
9806       return DAG.getMergeValues(RetOps, dl);
9807     }
9808 
9809     return TF;
9810   }
9811 
9812   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
9813   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
9814 
9815   // The values are now known to be -1 (false) or 1 (true). To convert this
9816   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9817   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9818   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9819 
9820   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9821   // understand how to form the extending load.
9822   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9823 
9824   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9825 
9826   // Now convert to an integer and store.
9827   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9828     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9829     Value);
9830 
9831   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9832   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9833   MachinePointerInfo PtrInfo =
9834       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9835   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9836   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9837 
9838   SDValue Ops[] = {StoreChain,
9839                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9840                    Value, FIdx};
9841   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9842 
9843   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9844     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9845 
9846   // Move data into the byte array.
9847   SDValue Loads[4], LoadChains[4];
9848   for (unsigned i = 0; i < 4; ++i) {
9849     unsigned Offset = 4*i;
9850     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9851     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9852 
9853     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
9854                            PtrInfo.getWithOffset(Offset));
9855     LoadChains[i] = Loads[i].getValue(1);
9856   }
9857 
9858   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9859 
9860   SDValue Stores[4];
9861   for (unsigned i = 0; i < 4; ++i) {
9862     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9863     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9864 
9865     Stores[i] = DAG.getTruncStore(
9866         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
9867         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
9868         SN->getAAInfo());
9869   }
9870 
9871   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9872 
9873   return StoreChain;
9874 }
9875 
9876 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9877   SDLoc dl(Op);
9878   if (Op.getValueType() == MVT::v4i32) {
9879     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9880 
9881     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
9882     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
9883 
9884     SDValue RHSSwap =   // = vrlw RHS, 16
9885       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
9886 
9887     // Shrinkify inputs to v8i16.
9888     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
9889     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
9890     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
9891 
9892     // Low parts multiplied together, generating 32-bit results (we ignore the
9893     // top parts).
9894     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
9895                                         LHS, RHS, DAG, dl, MVT::v4i32);
9896 
9897     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
9898                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
9899     // Shift the high parts up 16 bits.
9900     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
9901                               Neg16, DAG, dl);
9902     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
9903   } else if (Op.getValueType() == MVT::v8i16) {
9904     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9905 
9906     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
9907 
9908     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
9909                             LHS, RHS, Zero, DAG, dl);
9910   } else if (Op.getValueType() == MVT::v16i8) {
9911     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9912     bool isLittleEndian = Subtarget.isLittleEndian();
9913 
9914     // Multiply the even 8-bit parts, producing 16-bit sums.
9915     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
9916                                            LHS, RHS, DAG, dl, MVT::v8i16);
9917     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
9918 
9919     // Multiply the odd 8-bit parts, producing 16-bit sums.
9920     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
9921                                           LHS, RHS, DAG, dl, MVT::v8i16);
9922     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
9923 
9924     // Merge the results together.  Because vmuleub and vmuloub are
9925     // instructions with a big-endian bias, we must reverse the
9926     // element numbering and reverse the meaning of "odd" and "even"
9927     // when generating little endian code.
9928     int Ops[16];
9929     for (unsigned i = 0; i != 8; ++i) {
9930       if (isLittleEndian) {
9931         Ops[i*2  ] = 2*i;
9932         Ops[i*2+1] = 2*i+16;
9933       } else {
9934         Ops[i*2  ] = 2*i+1;
9935         Ops[i*2+1] = 2*i+1+16;
9936       }
9937     }
9938     if (isLittleEndian)
9939       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
9940     else
9941       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
9942   } else {
9943     llvm_unreachable("Unknown mul to lower!");
9944   }
9945 }
9946 
9947 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
9948 
9949   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
9950 
9951   EVT VT = Op.getValueType();
9952   assert(VT.isVector() &&
9953          "Only set vector abs as custom, scalar abs shouldn't reach here!");
9954   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
9955           VT == MVT::v16i8) &&
9956          "Unexpected vector element type!");
9957   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
9958          "Current subtarget doesn't support smax v2i64!");
9959 
9960   // For vector abs, it can be lowered to:
9961   // abs x
9962   // ==>
9963   // y = -x
9964   // smax(x, y)
9965 
9966   SDLoc dl(Op);
9967   SDValue X = Op.getOperand(0);
9968   SDValue Zero = DAG.getConstant(0, dl, VT);
9969   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
9970 
9971   // SMAX patch https://reviews.llvm.org/D47332
9972   // hasn't landed yet, so use intrinsic first here.
9973   // TODO: Should use SMAX directly once SMAX patch landed
9974   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
9975   if (VT == MVT::v2i64)
9976     BifID = Intrinsic::ppc_altivec_vmaxsd;
9977   else if (VT == MVT::v8i16)
9978     BifID = Intrinsic::ppc_altivec_vmaxsh;
9979   else if (VT == MVT::v16i8)
9980     BifID = Intrinsic::ppc_altivec_vmaxsb;
9981 
9982   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
9983 }
9984 
9985 // Custom lowering for fpext vf32 to v2f64
9986 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
9987 
9988   assert(Op.getOpcode() == ISD::FP_EXTEND &&
9989          "Should only be called for ISD::FP_EXTEND");
9990 
9991   // We only want to custom lower an extend from v2f32 to v2f64.
9992   if (Op.getValueType() != MVT::v2f64 ||
9993       Op.getOperand(0).getValueType() != MVT::v2f32)
9994     return SDValue();
9995 
9996   SDLoc dl(Op);
9997   SDValue Op0 = Op.getOperand(0);
9998 
9999   switch (Op0.getOpcode()) {
10000   default:
10001     return SDValue();
10002   case ISD::EXTRACT_SUBVECTOR: {
10003     assert(Op0.getNumOperands() == 2 &&
10004            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10005            "Node should have 2 operands with second one being a constant!");
10006 
10007     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10008       return SDValue();
10009 
10010     // Custom lower is only done for high or low doubleword.
10011     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10012     if (Idx % 2 != 0)
10013       return SDValue();
10014 
10015     // Since input is v4f32, at this point Idx is either 0 or 2.
10016     // Shift to get the doubleword position we want.
10017     int DWord = Idx >> 1;
10018 
10019     // High and low word positions are different on little endian.
10020     if (Subtarget.isLittleEndian())
10021       DWord ^= 0x1;
10022 
10023     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10024                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10025   }
10026   case ISD::FADD:
10027   case ISD::FMUL:
10028   case ISD::FSUB: {
10029     SDValue NewLoad[2];
10030     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10031       // Ensure both input are loads.
10032       SDValue LdOp = Op0.getOperand(i);
10033       if (LdOp.getOpcode() != ISD::LOAD)
10034         return SDValue();
10035       // Generate new load node.
10036       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10037       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10038       NewLoad[i] = DAG.getMemIntrinsicNode(
10039           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10040           LD->getMemoryVT(), LD->getMemOperand());
10041     }
10042     SDValue NewOp =
10043         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10044                     NewLoad[1], Op0.getNode()->getFlags());
10045     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10046                        DAG.getConstant(0, dl, MVT::i32));
10047   }
10048   case ISD::LOAD: {
10049     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10050     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10051     SDValue NewLd = DAG.getMemIntrinsicNode(
10052         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10053         LD->getMemoryVT(), LD->getMemOperand());
10054     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10055                        DAG.getConstant(0, dl, MVT::i32));
10056   }
10057   }
10058   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10059 }
10060 
10061 /// LowerOperation - Provide custom lowering hooks for some operations.
10062 ///
10063 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10064   switch (Op.getOpcode()) {
10065   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10066   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10067   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10068   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10069   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10070   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10071   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10072   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10073   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10074 
10075   // Variable argument lowering.
10076   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10077   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10078   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10079 
10080   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10081   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10082   case ISD::GET_DYNAMIC_AREA_OFFSET:
10083     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10084 
10085   // Exception handling lowering.
10086   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10087   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10088   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10089 
10090   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10091   case ISD::STORE:              return LowerSTORE(Op, DAG);
10092   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10093   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10094   case ISD::FP_TO_UINT:
10095   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10096   case ISD::UINT_TO_FP:
10097   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10098   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10099 
10100   // Lower 64-bit shifts.
10101   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10102   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10103   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10104 
10105   // Vector-related lowering.
10106   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10107   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10108   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10109   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10110   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10111   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10112   case ISD::MUL:                return LowerMUL(Op, DAG);
10113   case ISD::ABS:                return LowerABS(Op, DAG);
10114   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10115 
10116   // For counter-based loop handling.
10117   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10118 
10119   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10120 
10121   // Frame & Return address.
10122   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10123   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10124 
10125   case ISD::INTRINSIC_VOID:
10126     return LowerINTRINSIC_VOID(Op, DAG);
10127   case ISD::SREM:
10128   case ISD::UREM:
10129     return LowerREM(Op, DAG);
10130   case ISD::BSWAP:
10131     return LowerBSWAP(Op, DAG);
10132   case ISD::ATOMIC_CMP_SWAP:
10133     return LowerATOMIC_CMP_SWAP(Op, DAG);
10134   }
10135 }
10136 
10137 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10138                                            SmallVectorImpl<SDValue>&Results,
10139                                            SelectionDAG &DAG) const {
10140   SDLoc dl(N);
10141   switch (N->getOpcode()) {
10142   default:
10143     llvm_unreachable("Do not know how to custom type legalize this operation!");
10144   case ISD::READCYCLECOUNTER: {
10145     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10146     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10147 
10148     Results.push_back(RTB);
10149     Results.push_back(RTB.getValue(1));
10150     Results.push_back(RTB.getValue(2));
10151     break;
10152   }
10153   case ISD::INTRINSIC_W_CHAIN: {
10154     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10155         Intrinsic::loop_decrement)
10156       break;
10157 
10158     assert(N->getValueType(0) == MVT::i1 &&
10159            "Unexpected result type for CTR decrement intrinsic");
10160     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10161                                  N->getValueType(0));
10162     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10163     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10164                                  N->getOperand(1));
10165 
10166     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10167     Results.push_back(NewInt.getValue(1));
10168     break;
10169   }
10170   case ISD::VAARG: {
10171     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10172       return;
10173 
10174     EVT VT = N->getValueType(0);
10175 
10176     if (VT == MVT::i64) {
10177       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10178 
10179       Results.push_back(NewNode);
10180       Results.push_back(NewNode.getValue(1));
10181     }
10182     return;
10183   }
10184   case ISD::FP_TO_SINT:
10185   case ISD::FP_TO_UINT:
10186     // LowerFP_TO_INT() can only handle f32 and f64.
10187     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10188       return;
10189     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10190     return;
10191   case ISD::TRUNCATE: {
10192     EVT TrgVT = N->getValueType(0);
10193     EVT OpVT = N->getOperand(0).getValueType();
10194     if (TrgVT.isVector() &&
10195         isOperationCustom(N->getOpcode(), TrgVT) &&
10196         OpVT.getSizeInBits() <= 128 &&
10197         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10198       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10199     return;
10200   }
10201   case ISD::BITCAST:
10202     // Don't handle bitcast here.
10203     return;
10204   }
10205 }
10206 
10207 //===----------------------------------------------------------------------===//
10208 //  Other Lowering Code
10209 //===----------------------------------------------------------------------===//
10210 
10211 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10212   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10213   Function *Func = Intrinsic::getDeclaration(M, Id);
10214   return Builder.CreateCall(Func, {});
10215 }
10216 
10217 // The mappings for emitLeading/TrailingFence is taken from
10218 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10219 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10220                                                  Instruction *Inst,
10221                                                  AtomicOrdering Ord) const {
10222   if (Ord == AtomicOrdering::SequentiallyConsistent)
10223     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10224   if (isReleaseOrStronger(Ord))
10225     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10226   return nullptr;
10227 }
10228 
10229 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10230                                                   Instruction *Inst,
10231                                                   AtomicOrdering Ord) const {
10232   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10233     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10234     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10235     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10236     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10237       return Builder.CreateCall(
10238           Intrinsic::getDeclaration(
10239               Builder.GetInsertBlock()->getParent()->getParent(),
10240               Intrinsic::ppc_cfence, {Inst->getType()}),
10241           {Inst});
10242     // FIXME: Can use isync for rmw operation.
10243     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10244   }
10245   return nullptr;
10246 }
10247 
10248 MachineBasicBlock *
10249 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10250                                     unsigned AtomicSize,
10251                                     unsigned BinOpcode,
10252                                     unsigned CmpOpcode,
10253                                     unsigned CmpPred) const {
10254   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10255   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10256 
10257   auto LoadMnemonic = PPC::LDARX;
10258   auto StoreMnemonic = PPC::STDCX;
10259   switch (AtomicSize) {
10260   default:
10261     llvm_unreachable("Unexpected size of atomic entity");
10262   case 1:
10263     LoadMnemonic = PPC::LBARX;
10264     StoreMnemonic = PPC::STBCX;
10265     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10266     break;
10267   case 2:
10268     LoadMnemonic = PPC::LHARX;
10269     StoreMnemonic = PPC::STHCX;
10270     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10271     break;
10272   case 4:
10273     LoadMnemonic = PPC::LWARX;
10274     StoreMnemonic = PPC::STWCX;
10275     break;
10276   case 8:
10277     LoadMnemonic = PPC::LDARX;
10278     StoreMnemonic = PPC::STDCX;
10279     break;
10280   }
10281 
10282   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10283   MachineFunction *F = BB->getParent();
10284   MachineFunction::iterator It = ++BB->getIterator();
10285 
10286   Register dest = MI.getOperand(0).getReg();
10287   Register ptrA = MI.getOperand(1).getReg();
10288   Register ptrB = MI.getOperand(2).getReg();
10289   Register incr = MI.getOperand(3).getReg();
10290   DebugLoc dl = MI.getDebugLoc();
10291 
10292   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10293   MachineBasicBlock *loop2MBB =
10294     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10295   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10296   F->insert(It, loopMBB);
10297   if (CmpOpcode)
10298     F->insert(It, loop2MBB);
10299   F->insert(It, exitMBB);
10300   exitMBB->splice(exitMBB->begin(), BB,
10301                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10302   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10303 
10304   MachineRegisterInfo &RegInfo = F->getRegInfo();
10305   Register TmpReg = (!BinOpcode) ? incr :
10306     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10307                                            : &PPC::GPRCRegClass);
10308 
10309   //  thisMBB:
10310   //   ...
10311   //   fallthrough --> loopMBB
10312   BB->addSuccessor(loopMBB);
10313 
10314   //  loopMBB:
10315   //   l[wd]arx dest, ptr
10316   //   add r0, dest, incr
10317   //   st[wd]cx. r0, ptr
10318   //   bne- loopMBB
10319   //   fallthrough --> exitMBB
10320 
10321   // For max/min...
10322   //  loopMBB:
10323   //   l[wd]arx dest, ptr
10324   //   cmpl?[wd] incr, dest
10325   //   bgt exitMBB
10326   //  loop2MBB:
10327   //   st[wd]cx. dest, ptr
10328   //   bne- loopMBB
10329   //   fallthrough --> exitMBB
10330 
10331   BB = loopMBB;
10332   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10333     .addReg(ptrA).addReg(ptrB);
10334   if (BinOpcode)
10335     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10336   if (CmpOpcode) {
10337     // Signed comparisons of byte or halfword values must be sign-extended.
10338     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10339       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10340       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10341               ExtReg).addReg(dest);
10342       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10343         .addReg(incr).addReg(ExtReg);
10344     } else
10345       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10346         .addReg(incr).addReg(dest);
10347 
10348     BuildMI(BB, dl, TII->get(PPC::BCC))
10349       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10350     BB->addSuccessor(loop2MBB);
10351     BB->addSuccessor(exitMBB);
10352     BB = loop2MBB;
10353   }
10354   BuildMI(BB, dl, TII->get(StoreMnemonic))
10355     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10356   BuildMI(BB, dl, TII->get(PPC::BCC))
10357     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10358   BB->addSuccessor(loopMBB);
10359   BB->addSuccessor(exitMBB);
10360 
10361   //  exitMBB:
10362   //   ...
10363   BB = exitMBB;
10364   return BB;
10365 }
10366 
10367 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10368     MachineInstr &MI, MachineBasicBlock *BB,
10369     bool is8bit, // operation
10370     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10371   // If we support part-word atomic mnemonics, just use them
10372   if (Subtarget.hasPartwordAtomics())
10373     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10374                             CmpPred);
10375 
10376   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10377   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10378   // In 64 bit mode we have to use 64 bits for addresses, even though the
10379   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10380   // registers without caring whether they're 32 or 64, but here we're
10381   // doing actual arithmetic on the addresses.
10382   bool is64bit = Subtarget.isPPC64();
10383   bool isLittleEndian = Subtarget.isLittleEndian();
10384   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10385 
10386   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10387   MachineFunction *F = BB->getParent();
10388   MachineFunction::iterator It = ++BB->getIterator();
10389 
10390   Register dest = MI.getOperand(0).getReg();
10391   Register ptrA = MI.getOperand(1).getReg();
10392   Register ptrB = MI.getOperand(2).getReg();
10393   Register incr = MI.getOperand(3).getReg();
10394   DebugLoc dl = MI.getDebugLoc();
10395 
10396   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10397   MachineBasicBlock *loop2MBB =
10398       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10399   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10400   F->insert(It, loopMBB);
10401   if (CmpOpcode)
10402     F->insert(It, loop2MBB);
10403   F->insert(It, exitMBB);
10404   exitMBB->splice(exitMBB->begin(), BB,
10405                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10406   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10407 
10408   MachineRegisterInfo &RegInfo = F->getRegInfo();
10409   const TargetRegisterClass *RC =
10410       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10411   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10412 
10413   Register PtrReg = RegInfo.createVirtualRegister(RC);
10414   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10415   Register ShiftReg =
10416       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10417   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10418   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
10419   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10420   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10421   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10422   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10423   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10424   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10425   Register Ptr1Reg;
10426   Register TmpReg =
10427       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10428 
10429   //  thisMBB:
10430   //   ...
10431   //   fallthrough --> loopMBB
10432   BB->addSuccessor(loopMBB);
10433 
10434   // The 4-byte load must be aligned, while a char or short may be
10435   // anywhere in the word.  Hence all this nasty bookkeeping code.
10436   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10437   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10438   //   xori shift, shift1, 24 [16]
10439   //   rlwinm ptr, ptr1, 0, 0, 29
10440   //   slw incr2, incr, shift
10441   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10442   //   slw mask, mask2, shift
10443   //  loopMBB:
10444   //   lwarx tmpDest, ptr
10445   //   add tmp, tmpDest, incr2
10446   //   andc tmp2, tmpDest, mask
10447   //   and tmp3, tmp, mask
10448   //   or tmp4, tmp3, tmp2
10449   //   stwcx. tmp4, ptr
10450   //   bne- loopMBB
10451   //   fallthrough --> exitMBB
10452   //   srw dest, tmpDest, shift
10453   if (ptrA != ZeroReg) {
10454     Ptr1Reg = RegInfo.createVirtualRegister(RC);
10455     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10456         .addReg(ptrA)
10457         .addReg(ptrB);
10458   } else {
10459     Ptr1Reg = ptrB;
10460   }
10461   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10462   // mode.
10463   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10464       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10465       .addImm(3)
10466       .addImm(27)
10467       .addImm(is8bit ? 28 : 27);
10468   if (!isLittleEndian)
10469     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10470         .addReg(Shift1Reg)
10471         .addImm(is8bit ? 24 : 16);
10472   if (is64bit)
10473     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10474         .addReg(Ptr1Reg)
10475         .addImm(0)
10476         .addImm(61);
10477   else
10478     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10479         .addReg(Ptr1Reg)
10480         .addImm(0)
10481         .addImm(0)
10482         .addImm(29);
10483   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
10484   if (is8bit)
10485     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10486   else {
10487     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10488     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10489         .addReg(Mask3Reg)
10490         .addImm(65535);
10491   }
10492   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10493       .addReg(Mask2Reg)
10494       .addReg(ShiftReg);
10495 
10496   BB = loopMBB;
10497   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10498       .addReg(ZeroReg)
10499       .addReg(PtrReg);
10500   if (BinOpcode)
10501     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
10502         .addReg(Incr2Reg)
10503         .addReg(TmpDestReg);
10504   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
10505       .addReg(TmpDestReg)
10506       .addReg(MaskReg);
10507   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
10508   if (CmpOpcode) {
10509     // For unsigned comparisons, we can directly compare the shifted values.
10510     // For signed comparisons we shift and sign extend.
10511     Register SReg = RegInfo.createVirtualRegister(GPRC);
10512     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
10513         .addReg(TmpDestReg)
10514         .addReg(MaskReg);
10515     unsigned ValueReg = SReg;
10516     unsigned CmpReg = Incr2Reg;
10517     if (CmpOpcode == PPC::CMPW) {
10518       ValueReg = RegInfo.createVirtualRegister(GPRC);
10519       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
10520           .addReg(SReg)
10521           .addReg(ShiftReg);
10522       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
10523       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
10524           .addReg(ValueReg);
10525       ValueReg = ValueSReg;
10526       CmpReg = incr;
10527     }
10528     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10529         .addReg(CmpReg)
10530         .addReg(ValueReg);
10531     BuildMI(BB, dl, TII->get(PPC::BCC))
10532         .addImm(CmpPred)
10533         .addReg(PPC::CR0)
10534         .addMBB(exitMBB);
10535     BB->addSuccessor(loop2MBB);
10536     BB->addSuccessor(exitMBB);
10537     BB = loop2MBB;
10538   }
10539   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
10540   BuildMI(BB, dl, TII->get(PPC::STWCX))
10541       .addReg(Tmp4Reg)
10542       .addReg(ZeroReg)
10543       .addReg(PtrReg);
10544   BuildMI(BB, dl, TII->get(PPC::BCC))
10545       .addImm(PPC::PRED_NE)
10546       .addReg(PPC::CR0)
10547       .addMBB(loopMBB);
10548   BB->addSuccessor(loopMBB);
10549   BB->addSuccessor(exitMBB);
10550 
10551   //  exitMBB:
10552   //   ...
10553   BB = exitMBB;
10554   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
10555       .addReg(TmpDestReg)
10556       .addReg(ShiftReg);
10557   return BB;
10558 }
10559 
10560 llvm::MachineBasicBlock *
10561 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
10562                                     MachineBasicBlock *MBB) const {
10563   DebugLoc DL = MI.getDebugLoc();
10564   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10565   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
10566 
10567   MachineFunction *MF = MBB->getParent();
10568   MachineRegisterInfo &MRI = MF->getRegInfo();
10569 
10570   const BasicBlock *BB = MBB->getBasicBlock();
10571   MachineFunction::iterator I = ++MBB->getIterator();
10572 
10573   Register DstReg = MI.getOperand(0).getReg();
10574   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
10575   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
10576   Register mainDstReg = MRI.createVirtualRegister(RC);
10577   Register restoreDstReg = MRI.createVirtualRegister(RC);
10578 
10579   MVT PVT = getPointerTy(MF->getDataLayout());
10580   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10581          "Invalid Pointer Size!");
10582   // For v = setjmp(buf), we generate
10583   //
10584   // thisMBB:
10585   //  SjLjSetup mainMBB
10586   //  bl mainMBB
10587   //  v_restore = 1
10588   //  b sinkMBB
10589   //
10590   // mainMBB:
10591   //  buf[LabelOffset] = LR
10592   //  v_main = 0
10593   //
10594   // sinkMBB:
10595   //  v = phi(main, restore)
10596   //
10597 
10598   MachineBasicBlock *thisMBB = MBB;
10599   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
10600   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
10601   MF->insert(I, mainMBB);
10602   MF->insert(I, sinkMBB);
10603 
10604   MachineInstrBuilder MIB;
10605 
10606   // Transfer the remainder of BB and its successor edges to sinkMBB.
10607   sinkMBB->splice(sinkMBB->begin(), MBB,
10608                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10609   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
10610 
10611   // Note that the structure of the jmp_buf used here is not compatible
10612   // with that used by libc, and is not designed to be. Specifically, it
10613   // stores only those 'reserved' registers that LLVM does not otherwise
10614   // understand how to spill. Also, by convention, by the time this
10615   // intrinsic is called, Clang has already stored the frame address in the
10616   // first slot of the buffer and stack address in the third. Following the
10617   // X86 target code, we'll store the jump address in the second slot. We also
10618   // need to save the TOC pointer (R2) to handle jumps between shared
10619   // libraries, and that will be stored in the fourth slot. The thread
10620   // identifier (R13) is not affected.
10621 
10622   // thisMBB:
10623   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10624   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10625   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10626 
10627   // Prepare IP either in reg.
10628   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
10629   Register LabelReg = MRI.createVirtualRegister(PtrRC);
10630   Register BufReg = MI.getOperand(1).getReg();
10631 
10632   if (Subtarget.is64BitELFABI()) {
10633     setUsesTOCBasePtr(*MBB->getParent());
10634     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
10635               .addReg(PPC::X2)
10636               .addImm(TOCOffset)
10637               .addReg(BufReg)
10638               .cloneMemRefs(MI);
10639   }
10640 
10641   // Naked functions never have a base pointer, and so we use r1. For all
10642   // other functions, this decision must be delayed until during PEI.
10643   unsigned BaseReg;
10644   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
10645     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
10646   else
10647     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
10648 
10649   MIB = BuildMI(*thisMBB, MI, DL,
10650                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
10651             .addReg(BaseReg)
10652             .addImm(BPOffset)
10653             .addReg(BufReg)
10654             .cloneMemRefs(MI);
10655 
10656   // Setup
10657   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
10658   MIB.addRegMask(TRI->getNoPreservedMask());
10659 
10660   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
10661 
10662   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
10663           .addMBB(mainMBB);
10664   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
10665 
10666   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
10667   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
10668 
10669   // mainMBB:
10670   //  mainDstReg = 0
10671   MIB =
10672       BuildMI(mainMBB, DL,
10673               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
10674 
10675   // Store IP
10676   if (Subtarget.isPPC64()) {
10677     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
10678             .addReg(LabelReg)
10679             .addImm(LabelOffset)
10680             .addReg(BufReg);
10681   } else {
10682     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
10683             .addReg(LabelReg)
10684             .addImm(LabelOffset)
10685             .addReg(BufReg);
10686   }
10687   MIB.cloneMemRefs(MI);
10688 
10689   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
10690   mainMBB->addSuccessor(sinkMBB);
10691 
10692   // sinkMBB:
10693   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10694           TII->get(PPC::PHI), DstReg)
10695     .addReg(mainDstReg).addMBB(mainMBB)
10696     .addReg(restoreDstReg).addMBB(thisMBB);
10697 
10698   MI.eraseFromParent();
10699   return sinkMBB;
10700 }
10701 
10702 MachineBasicBlock *
10703 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
10704                                      MachineBasicBlock *MBB) const {
10705   DebugLoc DL = MI.getDebugLoc();
10706   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10707 
10708   MachineFunction *MF = MBB->getParent();
10709   MachineRegisterInfo &MRI = MF->getRegInfo();
10710 
10711   MVT PVT = getPointerTy(MF->getDataLayout());
10712   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10713          "Invalid Pointer Size!");
10714 
10715   const TargetRegisterClass *RC =
10716     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10717   Register Tmp = MRI.createVirtualRegister(RC);
10718   // Since FP is only updated here but NOT referenced, it's treated as GPR.
10719   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
10720   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
10721   unsigned BP =
10722       (PVT == MVT::i64)
10723           ? PPC::X30
10724           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
10725                                                               : PPC::R30);
10726 
10727   MachineInstrBuilder MIB;
10728 
10729   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10730   const int64_t SPOffset    = 2 * PVT.getStoreSize();
10731   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10732   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10733 
10734   Register BufReg = MI.getOperand(0).getReg();
10735 
10736   // Reload FP (the jumped-to function may not have had a
10737   // frame pointer, and if so, then its r31 will be restored
10738   // as necessary).
10739   if (PVT == MVT::i64) {
10740     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
10741             .addImm(0)
10742             .addReg(BufReg);
10743   } else {
10744     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
10745             .addImm(0)
10746             .addReg(BufReg);
10747   }
10748   MIB.cloneMemRefs(MI);
10749 
10750   // Reload IP
10751   if (PVT == MVT::i64) {
10752     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
10753             .addImm(LabelOffset)
10754             .addReg(BufReg);
10755   } else {
10756     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
10757             .addImm(LabelOffset)
10758             .addReg(BufReg);
10759   }
10760   MIB.cloneMemRefs(MI);
10761 
10762   // Reload SP
10763   if (PVT == MVT::i64) {
10764     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
10765             .addImm(SPOffset)
10766             .addReg(BufReg);
10767   } else {
10768     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
10769             .addImm(SPOffset)
10770             .addReg(BufReg);
10771   }
10772   MIB.cloneMemRefs(MI);
10773 
10774   // Reload BP
10775   if (PVT == MVT::i64) {
10776     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
10777             .addImm(BPOffset)
10778             .addReg(BufReg);
10779   } else {
10780     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
10781             .addImm(BPOffset)
10782             .addReg(BufReg);
10783   }
10784   MIB.cloneMemRefs(MI);
10785 
10786   // Reload TOC
10787   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
10788     setUsesTOCBasePtr(*MBB->getParent());
10789     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
10790               .addImm(TOCOffset)
10791               .addReg(BufReg)
10792               .cloneMemRefs(MI);
10793   }
10794 
10795   // Jump
10796   BuildMI(*MBB, MI, DL,
10797           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
10798   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
10799 
10800   MI.eraseFromParent();
10801   return MBB;
10802 }
10803 
10804 MachineBasicBlock *
10805 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10806                                                MachineBasicBlock *BB) const {
10807   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
10808       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10809     if (Subtarget.is64BitELFABI() &&
10810         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10811       // Call lowering should have added an r2 operand to indicate a dependence
10812       // on the TOC base pointer value. It can't however, because there is no
10813       // way to mark the dependence as implicit there, and so the stackmap code
10814       // will confuse it with a regular operand. Instead, add the dependence
10815       // here.
10816       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
10817     }
10818 
10819     return emitPatchPoint(MI, BB);
10820   }
10821 
10822   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
10823       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
10824     return emitEHSjLjSetJmp(MI, BB);
10825   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
10826              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
10827     return emitEHSjLjLongJmp(MI, BB);
10828   }
10829 
10830   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10831 
10832   // To "insert" these instructions we actually have to insert their
10833   // control-flow patterns.
10834   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10835   MachineFunction::iterator It = ++BB->getIterator();
10836 
10837   MachineFunction *F = BB->getParent();
10838 
10839   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10840       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
10841       MI.getOpcode() == PPC::SELECT_I8) {
10842     SmallVector<MachineOperand, 2> Cond;
10843     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10844         MI.getOpcode() == PPC::SELECT_CC_I8)
10845       Cond.push_back(MI.getOperand(4));
10846     else
10847       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
10848     Cond.push_back(MI.getOperand(1));
10849 
10850     DebugLoc dl = MI.getDebugLoc();
10851     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
10852                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
10853   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10854              MI.getOpcode() == PPC::SELECT_CC_I8 ||
10855              MI.getOpcode() == PPC::SELECT_CC_F4 ||
10856              MI.getOpcode() == PPC::SELECT_CC_F8 ||
10857              MI.getOpcode() == PPC::SELECT_CC_F16 ||
10858              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
10859              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
10860              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
10861              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
10862              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
10863              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
10864              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
10865              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
10866              MI.getOpcode() == PPC::SELECT_CC_SPE ||
10867              MI.getOpcode() == PPC::SELECT_I4 ||
10868              MI.getOpcode() == PPC::SELECT_I8 ||
10869              MI.getOpcode() == PPC::SELECT_F4 ||
10870              MI.getOpcode() == PPC::SELECT_F8 ||
10871              MI.getOpcode() == PPC::SELECT_F16 ||
10872              MI.getOpcode() == PPC::SELECT_QFRC ||
10873              MI.getOpcode() == PPC::SELECT_QSRC ||
10874              MI.getOpcode() == PPC::SELECT_QBRC ||
10875              MI.getOpcode() == PPC::SELECT_SPE ||
10876              MI.getOpcode() == PPC::SELECT_SPE4 ||
10877              MI.getOpcode() == PPC::SELECT_VRRC ||
10878              MI.getOpcode() == PPC::SELECT_VSFRC ||
10879              MI.getOpcode() == PPC::SELECT_VSSRC ||
10880              MI.getOpcode() == PPC::SELECT_VSRC) {
10881     // The incoming instruction knows the destination vreg to set, the
10882     // condition code register to branch on, the true/false values to
10883     // select between, and a branch opcode to use.
10884 
10885     //  thisMBB:
10886     //  ...
10887     //   TrueVal = ...
10888     //   cmpTY ccX, r1, r2
10889     //   bCC copy1MBB
10890     //   fallthrough --> copy0MBB
10891     MachineBasicBlock *thisMBB = BB;
10892     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10893     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10894     DebugLoc dl = MI.getDebugLoc();
10895     F->insert(It, copy0MBB);
10896     F->insert(It, sinkMBB);
10897 
10898     // Transfer the remainder of BB and its successor edges to sinkMBB.
10899     sinkMBB->splice(sinkMBB->begin(), BB,
10900                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10901     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10902 
10903     // Next, add the true and fallthrough blocks as its successors.
10904     BB->addSuccessor(copy0MBB);
10905     BB->addSuccessor(sinkMBB);
10906 
10907     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
10908         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
10909         MI.getOpcode() == PPC::SELECT_F16 ||
10910         MI.getOpcode() == PPC::SELECT_SPE4 ||
10911         MI.getOpcode() == PPC::SELECT_SPE ||
10912         MI.getOpcode() == PPC::SELECT_QFRC ||
10913         MI.getOpcode() == PPC::SELECT_QSRC ||
10914         MI.getOpcode() == PPC::SELECT_QBRC ||
10915         MI.getOpcode() == PPC::SELECT_VRRC ||
10916         MI.getOpcode() == PPC::SELECT_VSFRC ||
10917         MI.getOpcode() == PPC::SELECT_VSSRC ||
10918         MI.getOpcode() == PPC::SELECT_VSRC) {
10919       BuildMI(BB, dl, TII->get(PPC::BC))
10920           .addReg(MI.getOperand(1).getReg())
10921           .addMBB(sinkMBB);
10922     } else {
10923       unsigned SelectPred = MI.getOperand(4).getImm();
10924       BuildMI(BB, dl, TII->get(PPC::BCC))
10925           .addImm(SelectPred)
10926           .addReg(MI.getOperand(1).getReg())
10927           .addMBB(sinkMBB);
10928     }
10929 
10930     //  copy0MBB:
10931     //   %FalseValue = ...
10932     //   # fallthrough to sinkMBB
10933     BB = copy0MBB;
10934 
10935     // Update machine-CFG edges
10936     BB->addSuccessor(sinkMBB);
10937 
10938     //  sinkMBB:
10939     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10940     //  ...
10941     BB = sinkMBB;
10942     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
10943         .addReg(MI.getOperand(3).getReg())
10944         .addMBB(copy0MBB)
10945         .addReg(MI.getOperand(2).getReg())
10946         .addMBB(thisMBB);
10947   } else if (MI.getOpcode() == PPC::ReadTB) {
10948     // To read the 64-bit time-base register on a 32-bit target, we read the
10949     // two halves. Should the counter have wrapped while it was being read, we
10950     // need to try again.
10951     // ...
10952     // readLoop:
10953     // mfspr Rx,TBU # load from TBU
10954     // mfspr Ry,TB  # load from TB
10955     // mfspr Rz,TBU # load from TBU
10956     // cmpw crX,Rx,Rz # check if 'old'='new'
10957     // bne readLoop   # branch if they're not equal
10958     // ...
10959 
10960     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
10961     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10962     DebugLoc dl = MI.getDebugLoc();
10963     F->insert(It, readMBB);
10964     F->insert(It, sinkMBB);
10965 
10966     // Transfer the remainder of BB and its successor edges to sinkMBB.
10967     sinkMBB->splice(sinkMBB->begin(), BB,
10968                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10969     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10970 
10971     BB->addSuccessor(readMBB);
10972     BB = readMBB;
10973 
10974     MachineRegisterInfo &RegInfo = F->getRegInfo();
10975     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10976     Register LoReg = MI.getOperand(0).getReg();
10977     Register HiReg = MI.getOperand(1).getReg();
10978 
10979     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
10980     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
10981     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
10982 
10983     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10984 
10985     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
10986         .addReg(HiReg)
10987         .addReg(ReadAgainReg);
10988     BuildMI(BB, dl, TII->get(PPC::BCC))
10989         .addImm(PPC::PRED_NE)
10990         .addReg(CmpReg)
10991         .addMBB(readMBB);
10992 
10993     BB->addSuccessor(readMBB);
10994     BB->addSuccessor(sinkMBB);
10995   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
10996     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
10997   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
10998     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
10999   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11000     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11001   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11002     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11003 
11004   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11005     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11006   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11007     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11008   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11009     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11010   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11011     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11012 
11013   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11014     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11015   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11016     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11017   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11018     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11019   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11020     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11021 
11022   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11023     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11024   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11025     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11026   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11027     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11028   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11029     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11030 
11031   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11032     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11033   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11034     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11035   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11036     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11037   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11038     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11039 
11040   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11041     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11042   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11043     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11044   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11045     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11046   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11047     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11048 
11049   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11050     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11051   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11052     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11053   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11054     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11055   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11056     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11057 
11058   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11059     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11060   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11061     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11062   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11063     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11064   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11065     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11066 
11067   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11068     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11069   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11070     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11071   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11072     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11073   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11074     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11075 
11076   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11077     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11078   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11079     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11080   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11081     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11082   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11083     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11084 
11085   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11086     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11087   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11088     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11089   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11090     BB = EmitAtomicBinary(MI, BB, 4, 0);
11091   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11092     BB = EmitAtomicBinary(MI, BB, 8, 0);
11093   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11094            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11095            (Subtarget.hasPartwordAtomics() &&
11096             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11097            (Subtarget.hasPartwordAtomics() &&
11098             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11099     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11100 
11101     auto LoadMnemonic = PPC::LDARX;
11102     auto StoreMnemonic = PPC::STDCX;
11103     switch (MI.getOpcode()) {
11104     default:
11105       llvm_unreachable("Compare and swap of unknown size");
11106     case PPC::ATOMIC_CMP_SWAP_I8:
11107       LoadMnemonic = PPC::LBARX;
11108       StoreMnemonic = PPC::STBCX;
11109       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11110       break;
11111     case PPC::ATOMIC_CMP_SWAP_I16:
11112       LoadMnemonic = PPC::LHARX;
11113       StoreMnemonic = PPC::STHCX;
11114       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11115       break;
11116     case PPC::ATOMIC_CMP_SWAP_I32:
11117       LoadMnemonic = PPC::LWARX;
11118       StoreMnemonic = PPC::STWCX;
11119       break;
11120     case PPC::ATOMIC_CMP_SWAP_I64:
11121       LoadMnemonic = PPC::LDARX;
11122       StoreMnemonic = PPC::STDCX;
11123       break;
11124     }
11125     Register dest = MI.getOperand(0).getReg();
11126     Register ptrA = MI.getOperand(1).getReg();
11127     Register ptrB = MI.getOperand(2).getReg();
11128     Register oldval = MI.getOperand(3).getReg();
11129     Register newval = MI.getOperand(4).getReg();
11130     DebugLoc dl = MI.getDebugLoc();
11131 
11132     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11133     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11134     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11135     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11136     F->insert(It, loop1MBB);
11137     F->insert(It, loop2MBB);
11138     F->insert(It, midMBB);
11139     F->insert(It, exitMBB);
11140     exitMBB->splice(exitMBB->begin(), BB,
11141                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11142     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11143 
11144     //  thisMBB:
11145     //   ...
11146     //   fallthrough --> loopMBB
11147     BB->addSuccessor(loop1MBB);
11148 
11149     // loop1MBB:
11150     //   l[bhwd]arx dest, ptr
11151     //   cmp[wd] dest, oldval
11152     //   bne- midMBB
11153     // loop2MBB:
11154     //   st[bhwd]cx. newval, ptr
11155     //   bne- loopMBB
11156     //   b exitBB
11157     // midMBB:
11158     //   st[bhwd]cx. dest, ptr
11159     // exitBB:
11160     BB = loop1MBB;
11161     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11162     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11163         .addReg(oldval)
11164         .addReg(dest);
11165     BuildMI(BB, dl, TII->get(PPC::BCC))
11166         .addImm(PPC::PRED_NE)
11167         .addReg(PPC::CR0)
11168         .addMBB(midMBB);
11169     BB->addSuccessor(loop2MBB);
11170     BB->addSuccessor(midMBB);
11171 
11172     BB = loop2MBB;
11173     BuildMI(BB, dl, TII->get(StoreMnemonic))
11174         .addReg(newval)
11175         .addReg(ptrA)
11176         .addReg(ptrB);
11177     BuildMI(BB, dl, TII->get(PPC::BCC))
11178         .addImm(PPC::PRED_NE)
11179         .addReg(PPC::CR0)
11180         .addMBB(loop1MBB);
11181     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11182     BB->addSuccessor(loop1MBB);
11183     BB->addSuccessor(exitMBB);
11184 
11185     BB = midMBB;
11186     BuildMI(BB, dl, TII->get(StoreMnemonic))
11187         .addReg(dest)
11188         .addReg(ptrA)
11189         .addReg(ptrB);
11190     BB->addSuccessor(exitMBB);
11191 
11192     //  exitMBB:
11193     //   ...
11194     BB = exitMBB;
11195   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11196              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11197     // We must use 64-bit registers for addresses when targeting 64-bit,
11198     // since we're actually doing arithmetic on them.  Other registers
11199     // can be 32-bit.
11200     bool is64bit = Subtarget.isPPC64();
11201     bool isLittleEndian = Subtarget.isLittleEndian();
11202     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11203 
11204     Register dest = MI.getOperand(0).getReg();
11205     Register ptrA = MI.getOperand(1).getReg();
11206     Register ptrB = MI.getOperand(2).getReg();
11207     Register oldval = MI.getOperand(3).getReg();
11208     Register newval = MI.getOperand(4).getReg();
11209     DebugLoc dl = MI.getDebugLoc();
11210 
11211     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11212     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11213     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11214     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11215     F->insert(It, loop1MBB);
11216     F->insert(It, loop2MBB);
11217     F->insert(It, midMBB);
11218     F->insert(It, exitMBB);
11219     exitMBB->splice(exitMBB->begin(), BB,
11220                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11221     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11222 
11223     MachineRegisterInfo &RegInfo = F->getRegInfo();
11224     const TargetRegisterClass *RC =
11225         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11226     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11227 
11228     Register PtrReg = RegInfo.createVirtualRegister(RC);
11229     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11230     Register ShiftReg =
11231         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11232     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11233     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11234     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11235     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11236     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11237     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11238     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11239     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11240     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11241     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11242     Register Ptr1Reg;
11243     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11244     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11245     //  thisMBB:
11246     //   ...
11247     //   fallthrough --> loopMBB
11248     BB->addSuccessor(loop1MBB);
11249 
11250     // The 4-byte load must be aligned, while a char or short may be
11251     // anywhere in the word.  Hence all this nasty bookkeeping code.
11252     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11253     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11254     //   xori shift, shift1, 24 [16]
11255     //   rlwinm ptr, ptr1, 0, 0, 29
11256     //   slw newval2, newval, shift
11257     //   slw oldval2, oldval,shift
11258     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11259     //   slw mask, mask2, shift
11260     //   and newval3, newval2, mask
11261     //   and oldval3, oldval2, mask
11262     // loop1MBB:
11263     //   lwarx tmpDest, ptr
11264     //   and tmp, tmpDest, mask
11265     //   cmpw tmp, oldval3
11266     //   bne- midMBB
11267     // loop2MBB:
11268     //   andc tmp2, tmpDest, mask
11269     //   or tmp4, tmp2, newval3
11270     //   stwcx. tmp4, ptr
11271     //   bne- loop1MBB
11272     //   b exitBB
11273     // midMBB:
11274     //   stwcx. tmpDest, ptr
11275     // exitBB:
11276     //   srw dest, tmpDest, shift
11277     if (ptrA != ZeroReg) {
11278       Ptr1Reg = RegInfo.createVirtualRegister(RC);
11279       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11280           .addReg(ptrA)
11281           .addReg(ptrB);
11282     } else {
11283       Ptr1Reg = ptrB;
11284     }
11285 
11286     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11287     // mode.
11288     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11289         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11290         .addImm(3)
11291         .addImm(27)
11292         .addImm(is8bit ? 28 : 27);
11293     if (!isLittleEndian)
11294       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11295           .addReg(Shift1Reg)
11296           .addImm(is8bit ? 24 : 16);
11297     if (is64bit)
11298       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11299           .addReg(Ptr1Reg)
11300           .addImm(0)
11301           .addImm(61);
11302     else
11303       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11304           .addReg(Ptr1Reg)
11305           .addImm(0)
11306           .addImm(0)
11307           .addImm(29);
11308     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
11309         .addReg(newval)
11310         .addReg(ShiftReg);
11311     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
11312         .addReg(oldval)
11313         .addReg(ShiftReg);
11314     if (is8bit)
11315       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11316     else {
11317       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11318       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11319           .addReg(Mask3Reg)
11320           .addImm(65535);
11321     }
11322     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11323         .addReg(Mask2Reg)
11324         .addReg(ShiftReg);
11325     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
11326         .addReg(NewVal2Reg)
11327         .addReg(MaskReg);
11328     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
11329         .addReg(OldVal2Reg)
11330         .addReg(MaskReg);
11331 
11332     BB = loop1MBB;
11333     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11334         .addReg(ZeroReg)
11335         .addReg(PtrReg);
11336     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
11337         .addReg(TmpDestReg)
11338         .addReg(MaskReg);
11339     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
11340         .addReg(TmpReg)
11341         .addReg(OldVal3Reg);
11342     BuildMI(BB, dl, TII->get(PPC::BCC))
11343         .addImm(PPC::PRED_NE)
11344         .addReg(PPC::CR0)
11345         .addMBB(midMBB);
11346     BB->addSuccessor(loop2MBB);
11347     BB->addSuccessor(midMBB);
11348 
11349     BB = loop2MBB;
11350     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11351         .addReg(TmpDestReg)
11352         .addReg(MaskReg);
11353     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
11354         .addReg(Tmp2Reg)
11355         .addReg(NewVal3Reg);
11356     BuildMI(BB, dl, TII->get(PPC::STWCX))
11357         .addReg(Tmp4Reg)
11358         .addReg(ZeroReg)
11359         .addReg(PtrReg);
11360     BuildMI(BB, dl, TII->get(PPC::BCC))
11361         .addImm(PPC::PRED_NE)
11362         .addReg(PPC::CR0)
11363         .addMBB(loop1MBB);
11364     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11365     BB->addSuccessor(loop1MBB);
11366     BB->addSuccessor(exitMBB);
11367 
11368     BB = midMBB;
11369     BuildMI(BB, dl, TII->get(PPC::STWCX))
11370         .addReg(TmpDestReg)
11371         .addReg(ZeroReg)
11372         .addReg(PtrReg);
11373     BB->addSuccessor(exitMBB);
11374 
11375     //  exitMBB:
11376     //   ...
11377     BB = exitMBB;
11378     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11379         .addReg(TmpReg)
11380         .addReg(ShiftReg);
11381   } else if (MI.getOpcode() == PPC::FADDrtz) {
11382     // This pseudo performs an FADD with rounding mode temporarily forced
11383     // to round-to-zero.  We emit this via custom inserter since the FPSCR
11384     // is not modeled at the SelectionDAG level.
11385     Register Dest = MI.getOperand(0).getReg();
11386     Register Src1 = MI.getOperand(1).getReg();
11387     Register Src2 = MI.getOperand(2).getReg();
11388     DebugLoc dl = MI.getDebugLoc();
11389 
11390     MachineRegisterInfo &RegInfo = F->getRegInfo();
11391     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11392 
11393     // Save FPSCR value.
11394     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
11395 
11396     // Set rounding mode to round-to-zero.
11397     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
11398     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
11399 
11400     // Perform addition.
11401     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
11402 
11403     // Restore FPSCR value.
11404     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
11405   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11406              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
11407              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11408              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
11409     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11410                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
11411                           ? PPC::ANDIo8
11412                           : PPC::ANDIo;
11413     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11414                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
11415 
11416     MachineRegisterInfo &RegInfo = F->getRegInfo();
11417     Register Dest = RegInfo.createVirtualRegister(
11418         Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
11419 
11420     DebugLoc dl = MI.getDebugLoc();
11421     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
11422         .addReg(MI.getOperand(1).getReg())
11423         .addImm(1);
11424     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
11425             MI.getOperand(0).getReg())
11426         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
11427   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
11428     DebugLoc Dl = MI.getDebugLoc();
11429     MachineRegisterInfo &RegInfo = F->getRegInfo();
11430     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11431     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
11432     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11433             MI.getOperand(0).getReg())
11434         .addReg(CRReg);
11435   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
11436     DebugLoc Dl = MI.getDebugLoc();
11437     unsigned Imm = MI.getOperand(1).getImm();
11438     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
11439     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11440             MI.getOperand(0).getReg())
11441         .addReg(PPC::CR0EQ);
11442   } else if (MI.getOpcode() == PPC::SETRNDi) {
11443     DebugLoc dl = MI.getDebugLoc();
11444     Register OldFPSCRReg = MI.getOperand(0).getReg();
11445 
11446     // Save FPSCR value.
11447     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11448 
11449     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
11450     // the following settings:
11451     //   00 Round to nearest
11452     //   01 Round to 0
11453     //   10 Round to +inf
11454     //   11 Round to -inf
11455 
11456     // When the operand is immediate, using the two least significant bits of
11457     // the immediate to set the bits 62:63 of FPSCR.
11458     unsigned Mode = MI.getOperand(1).getImm();
11459     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
11460       .addImm(31);
11461 
11462     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
11463       .addImm(30);
11464   } else if (MI.getOpcode() == PPC::SETRND) {
11465     DebugLoc dl = MI.getDebugLoc();
11466 
11467     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
11468     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
11469     // If the target doesn't have DirectMove, we should use stack to do the
11470     // conversion, because the target doesn't have the instructions like mtvsrd
11471     // or mfvsrd to do this conversion directly.
11472     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
11473       if (Subtarget.hasDirectMove()) {
11474         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
11475           .addReg(SrcReg);
11476       } else {
11477         // Use stack to do the register copy.
11478         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
11479         MachineRegisterInfo &RegInfo = F->getRegInfo();
11480         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
11481         if (RC == &PPC::F8RCRegClass) {
11482           // Copy register from F8RCRegClass to G8RCRegclass.
11483           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
11484                  "Unsupported RegClass.");
11485 
11486           StoreOp = PPC::STFD;
11487           LoadOp = PPC::LD;
11488         } else {
11489           // Copy register from G8RCRegClass to F8RCRegclass.
11490           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
11491                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
11492                  "Unsupported RegClass.");
11493         }
11494 
11495         MachineFrameInfo &MFI = F->getFrameInfo();
11496         int FrameIdx = MFI.CreateStackObject(8, 8, false);
11497 
11498         MachineMemOperand *MMOStore = F->getMachineMemOperand(
11499           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11500           MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
11501           MFI.getObjectAlignment(FrameIdx));
11502 
11503         // Store the SrcReg into the stack.
11504         BuildMI(*BB, MI, dl, TII->get(StoreOp))
11505           .addReg(SrcReg)
11506           .addImm(0)
11507           .addFrameIndex(FrameIdx)
11508           .addMemOperand(MMOStore);
11509 
11510         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
11511           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11512           MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
11513           MFI.getObjectAlignment(FrameIdx));
11514 
11515         // Load from the stack where SrcReg is stored, and save to DestReg,
11516         // so we have done the RegClass conversion from RegClass::SrcReg to
11517         // RegClass::DestReg.
11518         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
11519           .addImm(0)
11520           .addFrameIndex(FrameIdx)
11521           .addMemOperand(MMOLoad);
11522       }
11523     };
11524 
11525     Register OldFPSCRReg = MI.getOperand(0).getReg();
11526 
11527     // Save FPSCR value.
11528     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11529 
11530     // When the operand is gprc register, use two least significant bits of the
11531     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
11532     //
11533     // copy OldFPSCRTmpReg, OldFPSCRReg
11534     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
11535     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
11536     // copy NewFPSCRReg, NewFPSCRTmpReg
11537     // mtfsf 255, NewFPSCRReg
11538     MachineOperand SrcOp = MI.getOperand(1);
11539     MachineRegisterInfo &RegInfo = F->getRegInfo();
11540     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11541 
11542     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
11543 
11544     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11545     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11546 
11547     // The first operand of INSERT_SUBREG should be a register which has
11548     // subregisters, we only care about its RegClass, so we should use an
11549     // IMPLICIT_DEF register.
11550     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
11551     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
11552       .addReg(ImDefReg)
11553       .add(SrcOp)
11554       .addImm(1);
11555 
11556     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11557     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
11558       .addReg(OldFPSCRTmpReg)
11559       .addReg(ExtSrcReg)
11560       .addImm(0)
11561       .addImm(62);
11562 
11563     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11564     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
11565 
11566     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
11567     // bits of FPSCR.
11568     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
11569       .addImm(255)
11570       .addReg(NewFPSCRReg)
11571       .addImm(0)
11572       .addImm(0);
11573   } else {
11574     llvm_unreachable("Unexpected instr type to insert");
11575   }
11576 
11577   MI.eraseFromParent(); // The pseudo instruction is gone now.
11578   return BB;
11579 }
11580 
11581 //===----------------------------------------------------------------------===//
11582 // Target Optimization Hooks
11583 //===----------------------------------------------------------------------===//
11584 
11585 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
11586   // For the estimates, convergence is quadratic, so we essentially double the
11587   // number of digits correct after every iteration. For both FRE and FRSQRTE,
11588   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
11589   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
11590   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
11591   if (VT.getScalarType() == MVT::f64)
11592     RefinementSteps++;
11593   return RefinementSteps;
11594 }
11595 
11596 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
11597                                            int Enabled, int &RefinementSteps,
11598                                            bool &UseOneConstNR,
11599                                            bool Reciprocal) const {
11600   EVT VT = Operand.getValueType();
11601   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
11602       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
11603       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11604       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11605       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11606       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11607     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11608       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11609 
11610     // The Newton-Raphson computation with a single constant does not provide
11611     // enough accuracy on some CPUs.
11612     UseOneConstNR = !Subtarget.needsTwoConstNR();
11613     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
11614   }
11615   return SDValue();
11616 }
11617 
11618 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
11619                                             int Enabled,
11620                                             int &RefinementSteps) const {
11621   EVT VT = Operand.getValueType();
11622   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
11623       (VT == MVT::f64 && Subtarget.hasFRE()) ||
11624       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11625       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11626       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11627       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11628     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11629       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11630     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
11631   }
11632   return SDValue();
11633 }
11634 
11635 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
11636   // Note: This functionality is used only when unsafe-fp-math is enabled, and
11637   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
11638   // enabled for division), this functionality is redundant with the default
11639   // combiner logic (once the division -> reciprocal/multiply transformation
11640   // has taken place). As a result, this matters more for older cores than for
11641   // newer ones.
11642 
11643   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11644   // reciprocal if there are two or more FDIVs (for embedded cores with only
11645   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
11646   switch (Subtarget.getDarwinDirective()) {
11647   default:
11648     return 3;
11649   case PPC::DIR_440:
11650   case PPC::DIR_A2:
11651   case PPC::DIR_E500:
11652   case PPC::DIR_E500mc:
11653   case PPC::DIR_E5500:
11654     return 2;
11655   }
11656 }
11657 
11658 // isConsecutiveLSLoc needs to work even if all adds have not yet been
11659 // collapsed, and so we need to look through chains of them.
11660 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
11661                                      int64_t& Offset, SelectionDAG &DAG) {
11662   if (DAG.isBaseWithConstantOffset(Loc)) {
11663     Base = Loc.getOperand(0);
11664     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
11665 
11666     // The base might itself be a base plus an offset, and if so, accumulate
11667     // that as well.
11668     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
11669   }
11670 }
11671 
11672 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
11673                             unsigned Bytes, int Dist,
11674                             SelectionDAG &DAG) {
11675   if (VT.getSizeInBits() / 8 != Bytes)
11676     return false;
11677 
11678   SDValue BaseLoc = Base->getBasePtr();
11679   if (Loc.getOpcode() == ISD::FrameIndex) {
11680     if (BaseLoc.getOpcode() != ISD::FrameIndex)
11681       return false;
11682     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
11683     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
11684     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
11685     int FS  = MFI.getObjectSize(FI);
11686     int BFS = MFI.getObjectSize(BFI);
11687     if (FS != BFS || FS != (int)Bytes) return false;
11688     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
11689   }
11690 
11691   SDValue Base1 = Loc, Base2 = BaseLoc;
11692   int64_t Offset1 = 0, Offset2 = 0;
11693   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
11694   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
11695   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
11696     return true;
11697 
11698   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11699   const GlobalValue *GV1 = nullptr;
11700   const GlobalValue *GV2 = nullptr;
11701   Offset1 = 0;
11702   Offset2 = 0;
11703   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
11704   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
11705   if (isGA1 && isGA2 && GV1 == GV2)
11706     return Offset1 == (Offset2 + Dist*Bytes);
11707   return false;
11708 }
11709 
11710 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
11711 // not enforce equality of the chain operands.
11712 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
11713                             unsigned Bytes, int Dist,
11714                             SelectionDAG &DAG) {
11715   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
11716     EVT VT = LS->getMemoryVT();
11717     SDValue Loc = LS->getBasePtr();
11718     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
11719   }
11720 
11721   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
11722     EVT VT;
11723     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11724     default: return false;
11725     case Intrinsic::ppc_qpx_qvlfd:
11726     case Intrinsic::ppc_qpx_qvlfda:
11727       VT = MVT::v4f64;
11728       break;
11729     case Intrinsic::ppc_qpx_qvlfs:
11730     case Intrinsic::ppc_qpx_qvlfsa:
11731       VT = MVT::v4f32;
11732       break;
11733     case Intrinsic::ppc_qpx_qvlfcd:
11734     case Intrinsic::ppc_qpx_qvlfcda:
11735       VT = MVT::v2f64;
11736       break;
11737     case Intrinsic::ppc_qpx_qvlfcs:
11738     case Intrinsic::ppc_qpx_qvlfcsa:
11739       VT = MVT::v2f32;
11740       break;
11741     case Intrinsic::ppc_qpx_qvlfiwa:
11742     case Intrinsic::ppc_qpx_qvlfiwz:
11743     case Intrinsic::ppc_altivec_lvx:
11744     case Intrinsic::ppc_altivec_lvxl:
11745     case Intrinsic::ppc_vsx_lxvw4x:
11746     case Intrinsic::ppc_vsx_lxvw4x_be:
11747       VT = MVT::v4i32;
11748       break;
11749     case Intrinsic::ppc_vsx_lxvd2x:
11750     case Intrinsic::ppc_vsx_lxvd2x_be:
11751       VT = MVT::v2f64;
11752       break;
11753     case Intrinsic::ppc_altivec_lvebx:
11754       VT = MVT::i8;
11755       break;
11756     case Intrinsic::ppc_altivec_lvehx:
11757       VT = MVT::i16;
11758       break;
11759     case Intrinsic::ppc_altivec_lvewx:
11760       VT = MVT::i32;
11761       break;
11762     }
11763 
11764     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
11765   }
11766 
11767   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
11768     EVT VT;
11769     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11770     default: return false;
11771     case Intrinsic::ppc_qpx_qvstfd:
11772     case Intrinsic::ppc_qpx_qvstfda:
11773       VT = MVT::v4f64;
11774       break;
11775     case Intrinsic::ppc_qpx_qvstfs:
11776     case Intrinsic::ppc_qpx_qvstfsa:
11777       VT = MVT::v4f32;
11778       break;
11779     case Intrinsic::ppc_qpx_qvstfcd:
11780     case Intrinsic::ppc_qpx_qvstfcda:
11781       VT = MVT::v2f64;
11782       break;
11783     case Intrinsic::ppc_qpx_qvstfcs:
11784     case Intrinsic::ppc_qpx_qvstfcsa:
11785       VT = MVT::v2f32;
11786       break;
11787     case Intrinsic::ppc_qpx_qvstfiw:
11788     case Intrinsic::ppc_qpx_qvstfiwa:
11789     case Intrinsic::ppc_altivec_stvx:
11790     case Intrinsic::ppc_altivec_stvxl:
11791     case Intrinsic::ppc_vsx_stxvw4x:
11792       VT = MVT::v4i32;
11793       break;
11794     case Intrinsic::ppc_vsx_stxvd2x:
11795       VT = MVT::v2f64;
11796       break;
11797     case Intrinsic::ppc_vsx_stxvw4x_be:
11798       VT = MVT::v4i32;
11799       break;
11800     case Intrinsic::ppc_vsx_stxvd2x_be:
11801       VT = MVT::v2f64;
11802       break;
11803     case Intrinsic::ppc_altivec_stvebx:
11804       VT = MVT::i8;
11805       break;
11806     case Intrinsic::ppc_altivec_stvehx:
11807       VT = MVT::i16;
11808       break;
11809     case Intrinsic::ppc_altivec_stvewx:
11810       VT = MVT::i32;
11811       break;
11812     }
11813 
11814     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
11815   }
11816 
11817   return false;
11818 }
11819 
11820 // Return true is there is a nearyby consecutive load to the one provided
11821 // (regardless of alignment). We search up and down the chain, looking though
11822 // token factors and other loads (but nothing else). As a result, a true result
11823 // indicates that it is safe to create a new consecutive load adjacent to the
11824 // load provided.
11825 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
11826   SDValue Chain = LD->getChain();
11827   EVT VT = LD->getMemoryVT();
11828 
11829   SmallSet<SDNode *, 16> LoadRoots;
11830   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
11831   SmallSet<SDNode *, 16> Visited;
11832 
11833   // First, search up the chain, branching to follow all token-factor operands.
11834   // If we find a consecutive load, then we're done, otherwise, record all
11835   // nodes just above the top-level loads and token factors.
11836   while (!Queue.empty()) {
11837     SDNode *ChainNext = Queue.pop_back_val();
11838     if (!Visited.insert(ChainNext).second)
11839       continue;
11840 
11841     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
11842       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
11843         return true;
11844 
11845       if (!Visited.count(ChainLD->getChain().getNode()))
11846         Queue.push_back(ChainLD->getChain().getNode());
11847     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
11848       for (const SDUse &O : ChainNext->ops())
11849         if (!Visited.count(O.getNode()))
11850           Queue.push_back(O.getNode());
11851     } else
11852       LoadRoots.insert(ChainNext);
11853   }
11854 
11855   // Second, search down the chain, starting from the top-level nodes recorded
11856   // in the first phase. These top-level nodes are the nodes just above all
11857   // loads and token factors. Starting with their uses, recursively look though
11858   // all loads (just the chain uses) and token factors to find a consecutive
11859   // load.
11860   Visited.clear();
11861   Queue.clear();
11862 
11863   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
11864        IE = LoadRoots.end(); I != IE; ++I) {
11865     Queue.push_back(*I);
11866 
11867     while (!Queue.empty()) {
11868       SDNode *LoadRoot = Queue.pop_back_val();
11869       if (!Visited.insert(LoadRoot).second)
11870         continue;
11871 
11872       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
11873         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
11874           return true;
11875 
11876       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
11877            UE = LoadRoot->use_end(); UI != UE; ++UI)
11878         if (((isa<MemSDNode>(*UI) &&
11879             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
11880             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
11881           Queue.push_back(*UI);
11882     }
11883   }
11884 
11885   return false;
11886 }
11887 
11888 /// This function is called when we have proved that a SETCC node can be replaced
11889 /// by subtraction (and other supporting instructions) so that the result of
11890 /// comparison is kept in a GPR instead of CR. This function is purely for
11891 /// codegen purposes and has some flags to guide the codegen process.
11892 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
11893                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
11894   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
11895 
11896   // Zero extend the operands to the largest legal integer. Originally, they
11897   // must be of a strictly smaller size.
11898   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
11899                          DAG.getConstant(Size, DL, MVT::i32));
11900   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
11901                          DAG.getConstant(Size, DL, MVT::i32));
11902 
11903   // Swap if needed. Depends on the condition code.
11904   if (Swap)
11905     std::swap(Op0, Op1);
11906 
11907   // Subtract extended integers.
11908   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
11909 
11910   // Move the sign bit to the least significant position and zero out the rest.
11911   // Now the least significant bit carries the result of original comparison.
11912   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
11913                              DAG.getConstant(Size - 1, DL, MVT::i32));
11914   auto Final = Shifted;
11915 
11916   // Complement the result if needed. Based on the condition code.
11917   if (Complement)
11918     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
11919                         DAG.getConstant(1, DL, MVT::i64));
11920 
11921   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
11922 }
11923 
11924 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
11925                                                   DAGCombinerInfo &DCI) const {
11926   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
11927 
11928   SelectionDAG &DAG = DCI.DAG;
11929   SDLoc DL(N);
11930 
11931   // Size of integers being compared has a critical role in the following
11932   // analysis, so we prefer to do this when all types are legal.
11933   if (!DCI.isAfterLegalizeDAG())
11934     return SDValue();
11935 
11936   // If all users of SETCC extend its value to a legal integer type
11937   // then we replace SETCC with a subtraction
11938   for (SDNode::use_iterator UI = N->use_begin(),
11939        UE = N->use_end(); UI != UE; ++UI) {
11940     if (UI->getOpcode() != ISD::ZERO_EXTEND)
11941       return SDValue();
11942   }
11943 
11944   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
11945   auto OpSize = N->getOperand(0).getValueSizeInBits();
11946 
11947   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
11948 
11949   if (OpSize < Size) {
11950     switch (CC) {
11951     default: break;
11952     case ISD::SETULT:
11953       return generateEquivalentSub(N, Size, false, false, DL, DAG);
11954     case ISD::SETULE:
11955       return generateEquivalentSub(N, Size, true, true, DL, DAG);
11956     case ISD::SETUGT:
11957       return generateEquivalentSub(N, Size, false, true, DL, DAG);
11958     case ISD::SETUGE:
11959       return generateEquivalentSub(N, Size, true, false, DL, DAG);
11960     }
11961   }
11962 
11963   return SDValue();
11964 }
11965 
11966 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
11967                                                   DAGCombinerInfo &DCI) const {
11968   SelectionDAG &DAG = DCI.DAG;
11969   SDLoc dl(N);
11970 
11971   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
11972   // If we're tracking CR bits, we need to be careful that we don't have:
11973   //   trunc(binary-ops(zext(x), zext(y)))
11974   // or
11975   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
11976   // such that we're unnecessarily moving things into GPRs when it would be
11977   // better to keep them in CR bits.
11978 
11979   // Note that trunc here can be an actual i1 trunc, or can be the effective
11980   // truncation that comes from a setcc or select_cc.
11981   if (N->getOpcode() == ISD::TRUNCATE &&
11982       N->getValueType(0) != MVT::i1)
11983     return SDValue();
11984 
11985   if (N->getOperand(0).getValueType() != MVT::i32 &&
11986       N->getOperand(0).getValueType() != MVT::i64)
11987     return SDValue();
11988 
11989   if (N->getOpcode() == ISD::SETCC ||
11990       N->getOpcode() == ISD::SELECT_CC) {
11991     // If we're looking at a comparison, then we need to make sure that the
11992     // high bits (all except for the first) don't matter the result.
11993     ISD::CondCode CC =
11994       cast<CondCodeSDNode>(N->getOperand(
11995         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
11996     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
11997 
11998     if (ISD::isSignedIntSetCC(CC)) {
11999       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12000           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12001         return SDValue();
12002     } else if (ISD::isUnsignedIntSetCC(CC)) {
12003       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12004                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12005           !DAG.MaskedValueIsZero(N->getOperand(1),
12006                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12007         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12008                                              : SDValue());
12009     } else {
12010       // This is neither a signed nor an unsigned comparison, just make sure
12011       // that the high bits are equal.
12012       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12013       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12014 
12015       // We don't really care about what is known about the first bit (if
12016       // anything), so clear it in all masks prior to comparing them.
12017       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12018       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12019 
12020       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12021         return SDValue();
12022     }
12023   }
12024 
12025   // We now know that the higher-order bits are irrelevant, we just need to
12026   // make sure that all of the intermediate operations are bit operations, and
12027   // all inputs are extensions.
12028   if (N->getOperand(0).getOpcode() != ISD::AND &&
12029       N->getOperand(0).getOpcode() != ISD::OR  &&
12030       N->getOperand(0).getOpcode() != ISD::XOR &&
12031       N->getOperand(0).getOpcode() != ISD::SELECT &&
12032       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12033       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12034       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12035       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12036       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12037     return SDValue();
12038 
12039   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12040       N->getOperand(1).getOpcode() != ISD::AND &&
12041       N->getOperand(1).getOpcode() != ISD::OR  &&
12042       N->getOperand(1).getOpcode() != ISD::XOR &&
12043       N->getOperand(1).getOpcode() != ISD::SELECT &&
12044       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12045       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12046       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12047       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12048       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12049     return SDValue();
12050 
12051   SmallVector<SDValue, 4> Inputs;
12052   SmallVector<SDValue, 8> BinOps, PromOps;
12053   SmallPtrSet<SDNode *, 16> Visited;
12054 
12055   for (unsigned i = 0; i < 2; ++i) {
12056     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12057           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12058           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12059           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12060         isa<ConstantSDNode>(N->getOperand(i)))
12061       Inputs.push_back(N->getOperand(i));
12062     else
12063       BinOps.push_back(N->getOperand(i));
12064 
12065     if (N->getOpcode() == ISD::TRUNCATE)
12066       break;
12067   }
12068 
12069   // Visit all inputs, collect all binary operations (and, or, xor and
12070   // select) that are all fed by extensions.
12071   while (!BinOps.empty()) {
12072     SDValue BinOp = BinOps.back();
12073     BinOps.pop_back();
12074 
12075     if (!Visited.insert(BinOp.getNode()).second)
12076       continue;
12077 
12078     PromOps.push_back(BinOp);
12079 
12080     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12081       // The condition of the select is not promoted.
12082       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12083         continue;
12084       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12085         continue;
12086 
12087       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12088             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12089             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12090            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12091           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12092         Inputs.push_back(BinOp.getOperand(i));
12093       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12094                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12095                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12096                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12097                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12098                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12099                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12100                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12101                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12102         BinOps.push_back(BinOp.getOperand(i));
12103       } else {
12104         // We have an input that is not an extension or another binary
12105         // operation; we'll abort this transformation.
12106         return SDValue();
12107       }
12108     }
12109   }
12110 
12111   // Make sure that this is a self-contained cluster of operations (which
12112   // is not quite the same thing as saying that everything has only one
12113   // use).
12114   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12115     if (isa<ConstantSDNode>(Inputs[i]))
12116       continue;
12117 
12118     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12119                               UE = Inputs[i].getNode()->use_end();
12120          UI != UE; ++UI) {
12121       SDNode *User = *UI;
12122       if (User != N && !Visited.count(User))
12123         return SDValue();
12124 
12125       // Make sure that we're not going to promote the non-output-value
12126       // operand(s) or SELECT or SELECT_CC.
12127       // FIXME: Although we could sometimes handle this, and it does occur in
12128       // practice that one of the condition inputs to the select is also one of
12129       // the outputs, we currently can't deal with this.
12130       if (User->getOpcode() == ISD::SELECT) {
12131         if (User->getOperand(0) == Inputs[i])
12132           return SDValue();
12133       } else if (User->getOpcode() == ISD::SELECT_CC) {
12134         if (User->getOperand(0) == Inputs[i] ||
12135             User->getOperand(1) == Inputs[i])
12136           return SDValue();
12137       }
12138     }
12139   }
12140 
12141   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12142     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12143                               UE = PromOps[i].getNode()->use_end();
12144          UI != UE; ++UI) {
12145       SDNode *User = *UI;
12146       if (User != N && !Visited.count(User))
12147         return SDValue();
12148 
12149       // Make sure that we're not going to promote the non-output-value
12150       // operand(s) or SELECT or SELECT_CC.
12151       // FIXME: Although we could sometimes handle this, and it does occur in
12152       // practice that one of the condition inputs to the select is also one of
12153       // the outputs, we currently can't deal with this.
12154       if (User->getOpcode() == ISD::SELECT) {
12155         if (User->getOperand(0) == PromOps[i])
12156           return SDValue();
12157       } else if (User->getOpcode() == ISD::SELECT_CC) {
12158         if (User->getOperand(0) == PromOps[i] ||
12159             User->getOperand(1) == PromOps[i])
12160           return SDValue();
12161       }
12162     }
12163   }
12164 
12165   // Replace all inputs with the extension operand.
12166   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12167     // Constants may have users outside the cluster of to-be-promoted nodes,
12168     // and so we need to replace those as we do the promotions.
12169     if (isa<ConstantSDNode>(Inputs[i]))
12170       continue;
12171     else
12172       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12173   }
12174 
12175   std::list<HandleSDNode> PromOpHandles;
12176   for (auto &PromOp : PromOps)
12177     PromOpHandles.emplace_back(PromOp);
12178 
12179   // Replace all operations (these are all the same, but have a different
12180   // (i1) return type). DAG.getNode will validate that the types of
12181   // a binary operator match, so go through the list in reverse so that
12182   // we've likely promoted both operands first. Any intermediate truncations or
12183   // extensions disappear.
12184   while (!PromOpHandles.empty()) {
12185     SDValue PromOp = PromOpHandles.back().getValue();
12186     PromOpHandles.pop_back();
12187 
12188     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12189         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12190         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12191         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12192       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12193           PromOp.getOperand(0).getValueType() != MVT::i1) {
12194         // The operand is not yet ready (see comment below).
12195         PromOpHandles.emplace_front(PromOp);
12196         continue;
12197       }
12198 
12199       SDValue RepValue = PromOp.getOperand(0);
12200       if (isa<ConstantSDNode>(RepValue))
12201         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12202 
12203       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12204       continue;
12205     }
12206 
12207     unsigned C;
12208     switch (PromOp.getOpcode()) {
12209     default:             C = 0; break;
12210     case ISD::SELECT:    C = 1; break;
12211     case ISD::SELECT_CC: C = 2; break;
12212     }
12213 
12214     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12215          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12216         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12217          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12218       // The to-be-promoted operands of this node have not yet been
12219       // promoted (this should be rare because we're going through the
12220       // list backward, but if one of the operands has several users in
12221       // this cluster of to-be-promoted nodes, it is possible).
12222       PromOpHandles.emplace_front(PromOp);
12223       continue;
12224     }
12225 
12226     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12227                                 PromOp.getNode()->op_end());
12228 
12229     // If there are any constant inputs, make sure they're replaced now.
12230     for (unsigned i = 0; i < 2; ++i)
12231       if (isa<ConstantSDNode>(Ops[C+i]))
12232         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12233 
12234     DAG.ReplaceAllUsesOfValueWith(PromOp,
12235       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12236   }
12237 
12238   // Now we're left with the initial truncation itself.
12239   if (N->getOpcode() == ISD::TRUNCATE)
12240     return N->getOperand(0);
12241 
12242   // Otherwise, this is a comparison. The operands to be compared have just
12243   // changed type (to i1), but everything else is the same.
12244   return SDValue(N, 0);
12245 }
12246 
12247 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12248                                                   DAGCombinerInfo &DCI) const {
12249   SelectionDAG &DAG = DCI.DAG;
12250   SDLoc dl(N);
12251 
12252   // If we're tracking CR bits, we need to be careful that we don't have:
12253   //   zext(binary-ops(trunc(x), trunc(y)))
12254   // or
12255   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12256   // such that we're unnecessarily moving things into CR bits that can more
12257   // efficiently stay in GPRs. Note that if we're not certain that the high
12258   // bits are set as required by the final extension, we still may need to do
12259   // some masking to get the proper behavior.
12260 
12261   // This same functionality is important on PPC64 when dealing with
12262   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12263   // the return values of functions. Because it is so similar, it is handled
12264   // here as well.
12265 
12266   if (N->getValueType(0) != MVT::i32 &&
12267       N->getValueType(0) != MVT::i64)
12268     return SDValue();
12269 
12270   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12271         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12272     return SDValue();
12273 
12274   if (N->getOperand(0).getOpcode() != ISD::AND &&
12275       N->getOperand(0).getOpcode() != ISD::OR  &&
12276       N->getOperand(0).getOpcode() != ISD::XOR &&
12277       N->getOperand(0).getOpcode() != ISD::SELECT &&
12278       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12279     return SDValue();
12280 
12281   SmallVector<SDValue, 4> Inputs;
12282   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12283   SmallPtrSet<SDNode *, 16> Visited;
12284 
12285   // Visit all inputs, collect all binary operations (and, or, xor and
12286   // select) that are all fed by truncations.
12287   while (!BinOps.empty()) {
12288     SDValue BinOp = BinOps.back();
12289     BinOps.pop_back();
12290 
12291     if (!Visited.insert(BinOp.getNode()).second)
12292       continue;
12293 
12294     PromOps.push_back(BinOp);
12295 
12296     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12297       // The condition of the select is not promoted.
12298       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12299         continue;
12300       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12301         continue;
12302 
12303       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12304           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12305         Inputs.push_back(BinOp.getOperand(i));
12306       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12307                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12308                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12309                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12310                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
12311         BinOps.push_back(BinOp.getOperand(i));
12312       } else {
12313         // We have an input that is not a truncation or another binary
12314         // operation; we'll abort this transformation.
12315         return SDValue();
12316       }
12317     }
12318   }
12319 
12320   // The operands of a select that must be truncated when the select is
12321   // promoted because the operand is actually part of the to-be-promoted set.
12322   DenseMap<SDNode *, EVT> SelectTruncOp[2];
12323 
12324   // Make sure that this is a self-contained cluster of operations (which
12325   // is not quite the same thing as saying that everything has only one
12326   // use).
12327   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12328     if (isa<ConstantSDNode>(Inputs[i]))
12329       continue;
12330 
12331     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12332                               UE = Inputs[i].getNode()->use_end();
12333          UI != UE; ++UI) {
12334       SDNode *User = *UI;
12335       if (User != N && !Visited.count(User))
12336         return SDValue();
12337 
12338       // If we're going to promote the non-output-value operand(s) or SELECT or
12339       // SELECT_CC, record them for truncation.
12340       if (User->getOpcode() == ISD::SELECT) {
12341         if (User->getOperand(0) == Inputs[i])
12342           SelectTruncOp[0].insert(std::make_pair(User,
12343                                     User->getOperand(0).getValueType()));
12344       } else if (User->getOpcode() == ISD::SELECT_CC) {
12345         if (User->getOperand(0) == Inputs[i])
12346           SelectTruncOp[0].insert(std::make_pair(User,
12347                                     User->getOperand(0).getValueType()));
12348         if (User->getOperand(1) == Inputs[i])
12349           SelectTruncOp[1].insert(std::make_pair(User,
12350                                     User->getOperand(1).getValueType()));
12351       }
12352     }
12353   }
12354 
12355   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12356     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12357                               UE = PromOps[i].getNode()->use_end();
12358          UI != UE; ++UI) {
12359       SDNode *User = *UI;
12360       if (User != N && !Visited.count(User))
12361         return SDValue();
12362 
12363       // If we're going to promote the non-output-value operand(s) or SELECT or
12364       // SELECT_CC, record them for truncation.
12365       if (User->getOpcode() == ISD::SELECT) {
12366         if (User->getOperand(0) == PromOps[i])
12367           SelectTruncOp[0].insert(std::make_pair(User,
12368                                     User->getOperand(0).getValueType()));
12369       } else if (User->getOpcode() == ISD::SELECT_CC) {
12370         if (User->getOperand(0) == PromOps[i])
12371           SelectTruncOp[0].insert(std::make_pair(User,
12372                                     User->getOperand(0).getValueType()));
12373         if (User->getOperand(1) == PromOps[i])
12374           SelectTruncOp[1].insert(std::make_pair(User,
12375                                     User->getOperand(1).getValueType()));
12376       }
12377     }
12378   }
12379 
12380   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
12381   bool ReallyNeedsExt = false;
12382   if (N->getOpcode() != ISD::ANY_EXTEND) {
12383     // If all of the inputs are not already sign/zero extended, then
12384     // we'll still need to do that at the end.
12385     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12386       if (isa<ConstantSDNode>(Inputs[i]))
12387         continue;
12388 
12389       unsigned OpBits =
12390         Inputs[i].getOperand(0).getValueSizeInBits();
12391       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
12392 
12393       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
12394            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
12395                                   APInt::getHighBitsSet(OpBits,
12396                                                         OpBits-PromBits))) ||
12397           (N->getOpcode() == ISD::SIGN_EXTEND &&
12398            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
12399              (OpBits-(PromBits-1)))) {
12400         ReallyNeedsExt = true;
12401         break;
12402       }
12403     }
12404   }
12405 
12406   // Replace all inputs, either with the truncation operand, or a
12407   // truncation or extension to the final output type.
12408   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12409     // Constant inputs need to be replaced with the to-be-promoted nodes that
12410     // use them because they might have users outside of the cluster of
12411     // promoted nodes.
12412     if (isa<ConstantSDNode>(Inputs[i]))
12413       continue;
12414 
12415     SDValue InSrc = Inputs[i].getOperand(0);
12416     if (Inputs[i].getValueType() == N->getValueType(0))
12417       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
12418     else if (N->getOpcode() == ISD::SIGN_EXTEND)
12419       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12420         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
12421     else if (N->getOpcode() == ISD::ZERO_EXTEND)
12422       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12423         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
12424     else
12425       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12426         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
12427   }
12428 
12429   std::list<HandleSDNode> PromOpHandles;
12430   for (auto &PromOp : PromOps)
12431     PromOpHandles.emplace_back(PromOp);
12432 
12433   // Replace all operations (these are all the same, but have a different
12434   // (promoted) return type). DAG.getNode will validate that the types of
12435   // a binary operator match, so go through the list in reverse so that
12436   // we've likely promoted both operands first.
12437   while (!PromOpHandles.empty()) {
12438     SDValue PromOp = PromOpHandles.back().getValue();
12439     PromOpHandles.pop_back();
12440 
12441     unsigned C;
12442     switch (PromOp.getOpcode()) {
12443     default:             C = 0; break;
12444     case ISD::SELECT:    C = 1; break;
12445     case ISD::SELECT_CC: C = 2; break;
12446     }
12447 
12448     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12449          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
12450         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12451          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
12452       // The to-be-promoted operands of this node have not yet been
12453       // promoted (this should be rare because we're going through the
12454       // list backward, but if one of the operands has several users in
12455       // this cluster of to-be-promoted nodes, it is possible).
12456       PromOpHandles.emplace_front(PromOp);
12457       continue;
12458     }
12459 
12460     // For SELECT and SELECT_CC nodes, we do a similar check for any
12461     // to-be-promoted comparison inputs.
12462     if (PromOp.getOpcode() == ISD::SELECT ||
12463         PromOp.getOpcode() == ISD::SELECT_CC) {
12464       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
12465            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
12466           (SelectTruncOp[1].count(PromOp.getNode()) &&
12467            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
12468         PromOpHandles.emplace_front(PromOp);
12469         continue;
12470       }
12471     }
12472 
12473     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12474                                 PromOp.getNode()->op_end());
12475 
12476     // If this node has constant inputs, then they'll need to be promoted here.
12477     for (unsigned i = 0; i < 2; ++i) {
12478       if (!isa<ConstantSDNode>(Ops[C+i]))
12479         continue;
12480       if (Ops[C+i].getValueType() == N->getValueType(0))
12481         continue;
12482 
12483       if (N->getOpcode() == ISD::SIGN_EXTEND)
12484         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12485       else if (N->getOpcode() == ISD::ZERO_EXTEND)
12486         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12487       else
12488         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12489     }
12490 
12491     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
12492     // truncate them again to the original value type.
12493     if (PromOp.getOpcode() == ISD::SELECT ||
12494         PromOp.getOpcode() == ISD::SELECT_CC) {
12495       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
12496       if (SI0 != SelectTruncOp[0].end())
12497         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
12498       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
12499       if (SI1 != SelectTruncOp[1].end())
12500         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
12501     }
12502 
12503     DAG.ReplaceAllUsesOfValueWith(PromOp,
12504       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
12505   }
12506 
12507   // Now we're left with the initial extension itself.
12508   if (!ReallyNeedsExt)
12509     return N->getOperand(0);
12510 
12511   // To zero extend, just mask off everything except for the first bit (in the
12512   // i1 case).
12513   if (N->getOpcode() == ISD::ZERO_EXTEND)
12514     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
12515                        DAG.getConstant(APInt::getLowBitsSet(
12516                                          N->getValueSizeInBits(0), PromBits),
12517                                        dl, N->getValueType(0)));
12518 
12519   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
12520          "Invalid extension type");
12521   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
12522   SDValue ShiftCst =
12523       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
12524   return DAG.getNode(
12525       ISD::SRA, dl, N->getValueType(0),
12526       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
12527       ShiftCst);
12528 }
12529 
12530 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
12531                                         DAGCombinerInfo &DCI) const {
12532   assert(N->getOpcode() == ISD::SETCC &&
12533          "Should be called with a SETCC node");
12534 
12535   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12536   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
12537     SDValue LHS = N->getOperand(0);
12538     SDValue RHS = N->getOperand(1);
12539 
12540     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
12541     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
12542         LHS.hasOneUse())
12543       std::swap(LHS, RHS);
12544 
12545     // x == 0-y --> x+y == 0
12546     // x != 0-y --> x+y != 0
12547     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
12548         RHS.hasOneUse()) {
12549       SDLoc DL(N);
12550       SelectionDAG &DAG = DCI.DAG;
12551       EVT VT = N->getValueType(0);
12552       EVT OpVT = LHS.getValueType();
12553       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
12554       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
12555     }
12556   }
12557 
12558   return DAGCombineTruncBoolExt(N, DCI);
12559 }
12560 
12561 // Is this an extending load from an f32 to an f64?
12562 static bool isFPExtLoad(SDValue Op) {
12563   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
12564     return LD->getExtensionType() == ISD::EXTLOAD &&
12565       Op.getValueType() == MVT::f64;
12566   return false;
12567 }
12568 
12569 /// Reduces the number of fp-to-int conversion when building a vector.
12570 ///
12571 /// If this vector is built out of floating to integer conversions,
12572 /// transform it to a vector built out of floating point values followed by a
12573 /// single floating to integer conversion of the vector.
12574 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
12575 /// becomes (fptosi (build_vector ($A, $B, ...)))
12576 SDValue PPCTargetLowering::
12577 combineElementTruncationToVectorTruncation(SDNode *N,
12578                                            DAGCombinerInfo &DCI) const {
12579   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12580          "Should be called with a BUILD_VECTOR node");
12581 
12582   SelectionDAG &DAG = DCI.DAG;
12583   SDLoc dl(N);
12584 
12585   SDValue FirstInput = N->getOperand(0);
12586   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
12587          "The input operand must be an fp-to-int conversion.");
12588 
12589   // This combine happens after legalization so the fp_to_[su]i nodes are
12590   // already converted to PPCSISD nodes.
12591   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
12592   if (FirstConversion == PPCISD::FCTIDZ ||
12593       FirstConversion == PPCISD::FCTIDUZ ||
12594       FirstConversion == PPCISD::FCTIWZ ||
12595       FirstConversion == PPCISD::FCTIWUZ) {
12596     bool IsSplat = true;
12597     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
12598       FirstConversion == PPCISD::FCTIWUZ;
12599     EVT SrcVT = FirstInput.getOperand(0).getValueType();
12600     SmallVector<SDValue, 4> Ops;
12601     EVT TargetVT = N->getValueType(0);
12602     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12603       SDValue NextOp = N->getOperand(i);
12604       if (NextOp.getOpcode() != PPCISD::MFVSR)
12605         return SDValue();
12606       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
12607       if (NextConversion != FirstConversion)
12608         return SDValue();
12609       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
12610       // This is not valid if the input was originally double precision. It is
12611       // also not profitable to do unless this is an extending load in which
12612       // case doing this combine will allow us to combine consecutive loads.
12613       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
12614         return SDValue();
12615       if (N->getOperand(i) != FirstInput)
12616         IsSplat = false;
12617     }
12618 
12619     // If this is a splat, we leave it as-is since there will be only a single
12620     // fp-to-int conversion followed by a splat of the integer. This is better
12621     // for 32-bit and smaller ints and neutral for 64-bit ints.
12622     if (IsSplat)
12623       return SDValue();
12624 
12625     // Now that we know we have the right type of node, get its operands
12626     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12627       SDValue In = N->getOperand(i).getOperand(0);
12628       if (Is32Bit) {
12629         // For 32-bit values, we need to add an FP_ROUND node (if we made it
12630         // here, we know that all inputs are extending loads so this is safe).
12631         if (In.isUndef())
12632           Ops.push_back(DAG.getUNDEF(SrcVT));
12633         else {
12634           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
12635                                       MVT::f32, In.getOperand(0),
12636                                       DAG.getIntPtrConstant(1, dl));
12637           Ops.push_back(Trunc);
12638         }
12639       } else
12640         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
12641     }
12642 
12643     unsigned Opcode;
12644     if (FirstConversion == PPCISD::FCTIDZ ||
12645         FirstConversion == PPCISD::FCTIWZ)
12646       Opcode = ISD::FP_TO_SINT;
12647     else
12648       Opcode = ISD::FP_TO_UINT;
12649 
12650     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
12651     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
12652     return DAG.getNode(Opcode, dl, TargetVT, BV);
12653   }
12654   return SDValue();
12655 }
12656 
12657 /// Reduce the number of loads when building a vector.
12658 ///
12659 /// Building a vector out of multiple loads can be converted to a load
12660 /// of the vector type if the loads are consecutive. If the loads are
12661 /// consecutive but in descending order, a shuffle is added at the end
12662 /// to reorder the vector.
12663 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
12664   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12665          "Should be called with a BUILD_VECTOR node");
12666 
12667   SDLoc dl(N);
12668 
12669   // Return early for non byte-sized type, as they can't be consecutive.
12670   if (!N->getValueType(0).getVectorElementType().isByteSized())
12671     return SDValue();
12672 
12673   bool InputsAreConsecutiveLoads = true;
12674   bool InputsAreReverseConsecutive = true;
12675   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
12676   SDValue FirstInput = N->getOperand(0);
12677   bool IsRoundOfExtLoad = false;
12678 
12679   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
12680       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
12681     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
12682     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
12683   }
12684   // Not a build vector of (possibly fp_rounded) loads.
12685   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
12686       N->getNumOperands() == 1)
12687     return SDValue();
12688 
12689   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
12690     // If any inputs are fp_round(extload), they all must be.
12691     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
12692       return SDValue();
12693 
12694     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
12695       N->getOperand(i);
12696     if (NextInput.getOpcode() != ISD::LOAD)
12697       return SDValue();
12698 
12699     SDValue PreviousInput =
12700       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
12701     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
12702     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
12703 
12704     // If any inputs are fp_round(extload), they all must be.
12705     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
12706       return SDValue();
12707 
12708     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
12709       InputsAreConsecutiveLoads = false;
12710     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
12711       InputsAreReverseConsecutive = false;
12712 
12713     // Exit early if the loads are neither consecutive nor reverse consecutive.
12714     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
12715       return SDValue();
12716   }
12717 
12718   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
12719          "The loads cannot be both consecutive and reverse consecutive.");
12720 
12721   SDValue FirstLoadOp =
12722     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
12723   SDValue LastLoadOp =
12724     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
12725                        N->getOperand(N->getNumOperands()-1);
12726 
12727   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
12728   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
12729   if (InputsAreConsecutiveLoads) {
12730     assert(LD1 && "Input needs to be a LoadSDNode.");
12731     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
12732                        LD1->getBasePtr(), LD1->getPointerInfo(),
12733                        LD1->getAlignment());
12734   }
12735   if (InputsAreReverseConsecutive) {
12736     assert(LDL && "Input needs to be a LoadSDNode.");
12737     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
12738                                LDL->getBasePtr(), LDL->getPointerInfo(),
12739                                LDL->getAlignment());
12740     SmallVector<int, 16> Ops;
12741     for (int i = N->getNumOperands() - 1; i >= 0; i--)
12742       Ops.push_back(i);
12743 
12744     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
12745                                 DAG.getUNDEF(N->getValueType(0)), Ops);
12746   }
12747   return SDValue();
12748 }
12749 
12750 // This function adds the required vector_shuffle needed to get
12751 // the elements of the vector extract in the correct position
12752 // as specified by the CorrectElems encoding.
12753 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
12754                                       SDValue Input, uint64_t Elems,
12755                                       uint64_t CorrectElems) {
12756   SDLoc dl(N);
12757 
12758   unsigned NumElems = Input.getValueType().getVectorNumElements();
12759   SmallVector<int, 16> ShuffleMask(NumElems, -1);
12760 
12761   // Knowing the element indices being extracted from the original
12762   // vector and the order in which they're being inserted, just put
12763   // them at element indices required for the instruction.
12764   for (unsigned i = 0; i < N->getNumOperands(); i++) {
12765     if (DAG.getDataLayout().isLittleEndian())
12766       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
12767     else
12768       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
12769     CorrectElems = CorrectElems >> 8;
12770     Elems = Elems >> 8;
12771   }
12772 
12773   SDValue Shuffle =
12774       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
12775                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
12776 
12777   EVT Ty = N->getValueType(0);
12778   SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
12779   return BV;
12780 }
12781 
12782 // Look for build vector patterns where input operands come from sign
12783 // extended vector_extract elements of specific indices. If the correct indices
12784 // aren't used, add a vector shuffle to fix up the indices and create a new
12785 // PPCISD:SExtVElems node which selects the vector sign extend instructions
12786 // during instruction selection.
12787 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
12788   // This array encodes the indices that the vector sign extend instructions
12789   // extract from when extending from one type to another for both BE and LE.
12790   // The right nibble of each byte corresponds to the LE incides.
12791   // and the left nibble of each byte corresponds to the BE incides.
12792   // For example: 0x3074B8FC  byte->word
12793   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
12794   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
12795   // For example: 0x000070F8  byte->double word
12796   // For LE: the allowed indices are: 0x0,0x8
12797   // For BE: the allowed indices are: 0x7,0xF
12798   uint64_t TargetElems[] = {
12799       0x3074B8FC, // b->w
12800       0x000070F8, // b->d
12801       0x10325476, // h->w
12802       0x00003074, // h->d
12803       0x00001032, // w->d
12804   };
12805 
12806   uint64_t Elems = 0;
12807   int Index;
12808   SDValue Input;
12809 
12810   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
12811     if (!Op)
12812       return false;
12813     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
12814         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
12815       return false;
12816 
12817     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
12818     // of the right width.
12819     SDValue Extract = Op.getOperand(0);
12820     if (Extract.getOpcode() == ISD::ANY_EXTEND)
12821       Extract = Extract.getOperand(0);
12822     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12823       return false;
12824 
12825     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
12826     if (!ExtOp)
12827       return false;
12828 
12829     Index = ExtOp->getZExtValue();
12830     if (Input && Input != Extract.getOperand(0))
12831       return false;
12832 
12833     if (!Input)
12834       Input = Extract.getOperand(0);
12835 
12836     Elems = Elems << 8;
12837     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
12838     Elems |= Index;
12839 
12840     return true;
12841   };
12842 
12843   // If the build vector operands aren't sign extended vector extracts,
12844   // of the same input vector, then return.
12845   for (unsigned i = 0; i < N->getNumOperands(); i++) {
12846     if (!isSExtOfVecExtract(N->getOperand(i))) {
12847       return SDValue();
12848     }
12849   }
12850 
12851   // If the vector extract indicies are not correct, add the appropriate
12852   // vector_shuffle.
12853   int TgtElemArrayIdx;
12854   int InputSize = Input.getValueType().getScalarSizeInBits();
12855   int OutputSize = N->getValueType(0).getScalarSizeInBits();
12856   if (InputSize + OutputSize == 40)
12857     TgtElemArrayIdx = 0;
12858   else if (InputSize + OutputSize == 72)
12859     TgtElemArrayIdx = 1;
12860   else if (InputSize + OutputSize == 48)
12861     TgtElemArrayIdx = 2;
12862   else if (InputSize + OutputSize == 80)
12863     TgtElemArrayIdx = 3;
12864   else if (InputSize + OutputSize == 96)
12865     TgtElemArrayIdx = 4;
12866   else
12867     return SDValue();
12868 
12869   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
12870   CorrectElems = DAG.getDataLayout().isLittleEndian()
12871                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
12872                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
12873   if (Elems != CorrectElems) {
12874     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
12875   }
12876 
12877   // Regular lowering will catch cases where a shuffle is not needed.
12878   return SDValue();
12879 }
12880 
12881 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
12882                                                  DAGCombinerInfo &DCI) const {
12883   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12884          "Should be called with a BUILD_VECTOR node");
12885 
12886   SelectionDAG &DAG = DCI.DAG;
12887   SDLoc dl(N);
12888 
12889   if (!Subtarget.hasVSX())
12890     return SDValue();
12891 
12892   // The target independent DAG combiner will leave a build_vector of
12893   // float-to-int conversions intact. We can generate MUCH better code for
12894   // a float-to-int conversion of a vector of floats.
12895   SDValue FirstInput = N->getOperand(0);
12896   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
12897     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
12898     if (Reduced)
12899       return Reduced;
12900   }
12901 
12902   // If we're building a vector out of consecutive loads, just load that
12903   // vector type.
12904   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
12905   if (Reduced)
12906     return Reduced;
12907 
12908   // If we're building a vector out of extended elements from another vector
12909   // we have P9 vector integer extend instructions. The code assumes legal
12910   // input types (i.e. it can't handle things like v4i16) so do not run before
12911   // legalization.
12912   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
12913     Reduced = combineBVOfVecSExt(N, DAG);
12914     if (Reduced)
12915       return Reduced;
12916   }
12917 
12918 
12919   if (N->getValueType(0) != MVT::v2f64)
12920     return SDValue();
12921 
12922   // Looking for:
12923   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
12924   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
12925       FirstInput.getOpcode() != ISD::UINT_TO_FP)
12926     return SDValue();
12927   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
12928       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
12929     return SDValue();
12930   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
12931     return SDValue();
12932 
12933   SDValue Ext1 = FirstInput.getOperand(0);
12934   SDValue Ext2 = N->getOperand(1).getOperand(0);
12935   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12936      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12937     return SDValue();
12938 
12939   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
12940   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
12941   if (!Ext1Op || !Ext2Op)
12942     return SDValue();
12943   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
12944       Ext1.getOperand(0) != Ext2.getOperand(0))
12945     return SDValue();
12946 
12947   int FirstElem = Ext1Op->getZExtValue();
12948   int SecondElem = Ext2Op->getZExtValue();
12949   int SubvecIdx;
12950   if (FirstElem == 0 && SecondElem == 1)
12951     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
12952   else if (FirstElem == 2 && SecondElem == 3)
12953     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
12954   else
12955     return SDValue();
12956 
12957   SDValue SrcVec = Ext1.getOperand(0);
12958   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
12959     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
12960   return DAG.getNode(NodeType, dl, MVT::v2f64,
12961                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
12962 }
12963 
12964 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
12965                                               DAGCombinerInfo &DCI) const {
12966   assert((N->getOpcode() == ISD::SINT_TO_FP ||
12967           N->getOpcode() == ISD::UINT_TO_FP) &&
12968          "Need an int -> FP conversion node here");
12969 
12970   if (useSoftFloat() || !Subtarget.has64BitSupport())
12971     return SDValue();
12972 
12973   SelectionDAG &DAG = DCI.DAG;
12974   SDLoc dl(N);
12975   SDValue Op(N, 0);
12976 
12977   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
12978   // from the hardware.
12979   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
12980     return SDValue();
12981   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
12982       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
12983     return SDValue();
12984 
12985   SDValue FirstOperand(Op.getOperand(0));
12986   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
12987     (FirstOperand.getValueType() == MVT::i8 ||
12988      FirstOperand.getValueType() == MVT::i16);
12989   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
12990     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
12991     bool DstDouble = Op.getValueType() == MVT::f64;
12992     unsigned ConvOp = Signed ?
12993       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
12994       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
12995     SDValue WidthConst =
12996       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
12997                             dl, false);
12998     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
12999     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13000     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13001                                          DAG.getVTList(MVT::f64, MVT::Other),
13002                                          Ops, MVT::i8, LDN->getMemOperand());
13003 
13004     // For signed conversion, we need to sign-extend the value in the VSR
13005     if (Signed) {
13006       SDValue ExtOps[] = { Ld, WidthConst };
13007       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13008       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13009     } else
13010       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13011   }
13012 
13013 
13014   // For i32 intermediate values, unfortunately, the conversion functions
13015   // leave the upper 32 bits of the value are undefined. Within the set of
13016   // scalar instructions, we have no method for zero- or sign-extending the
13017   // value. Thus, we cannot handle i32 intermediate values here.
13018   if (Op.getOperand(0).getValueType() == MVT::i32)
13019     return SDValue();
13020 
13021   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13022          "UINT_TO_FP is supported only with FPCVT");
13023 
13024   // If we have FCFIDS, then use it when converting to single-precision.
13025   // Otherwise, convert to double-precision and then round.
13026   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13027                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13028                                                             : PPCISD::FCFIDS)
13029                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13030                                                             : PPCISD::FCFID);
13031   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13032                   ? MVT::f32
13033                   : MVT::f64;
13034 
13035   // If we're converting from a float, to an int, and back to a float again,
13036   // then we don't need the store/load pair at all.
13037   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13038        Subtarget.hasFPCVT()) ||
13039       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13040     SDValue Src = Op.getOperand(0).getOperand(0);
13041     if (Src.getValueType() == MVT::f32) {
13042       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13043       DCI.AddToWorklist(Src.getNode());
13044     } else if (Src.getValueType() != MVT::f64) {
13045       // Make sure that we don't pick up a ppc_fp128 source value.
13046       return SDValue();
13047     }
13048 
13049     unsigned FCTOp =
13050       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13051                                                         PPCISD::FCTIDUZ;
13052 
13053     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13054     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13055 
13056     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13057       FP = DAG.getNode(ISD::FP_ROUND, dl,
13058                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13059       DCI.AddToWorklist(FP.getNode());
13060     }
13061 
13062     return FP;
13063   }
13064 
13065   return SDValue();
13066 }
13067 
13068 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13069 // builtins) into loads with swaps.
13070 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13071                                               DAGCombinerInfo &DCI) const {
13072   SelectionDAG &DAG = DCI.DAG;
13073   SDLoc dl(N);
13074   SDValue Chain;
13075   SDValue Base;
13076   MachineMemOperand *MMO;
13077 
13078   switch (N->getOpcode()) {
13079   default:
13080     llvm_unreachable("Unexpected opcode for little endian VSX load");
13081   case ISD::LOAD: {
13082     LoadSDNode *LD = cast<LoadSDNode>(N);
13083     Chain = LD->getChain();
13084     Base = LD->getBasePtr();
13085     MMO = LD->getMemOperand();
13086     // If the MMO suggests this isn't a load of a full vector, leave
13087     // things alone.  For a built-in, we have to make the change for
13088     // correctness, so if there is a size problem that will be a bug.
13089     if (MMO->getSize() < 16)
13090       return SDValue();
13091     break;
13092   }
13093   case ISD::INTRINSIC_W_CHAIN: {
13094     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13095     Chain = Intrin->getChain();
13096     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13097     // us what we want. Get operand 2 instead.
13098     Base = Intrin->getOperand(2);
13099     MMO = Intrin->getMemOperand();
13100     break;
13101   }
13102   }
13103 
13104   MVT VecTy = N->getValueType(0).getSimpleVT();
13105 
13106   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13107   // aligned and the type is a vector with elements up to 4 bytes
13108   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13109       && VecTy.getScalarSizeInBits() <= 32 ) {
13110     return SDValue();
13111   }
13112 
13113   SDValue LoadOps[] = { Chain, Base };
13114   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13115                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13116                                          LoadOps, MVT::v2f64, MMO);
13117 
13118   DCI.AddToWorklist(Load.getNode());
13119   Chain = Load.getValue(1);
13120   SDValue Swap = DAG.getNode(
13121       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13122   DCI.AddToWorklist(Swap.getNode());
13123 
13124   // Add a bitcast if the resulting load type doesn't match v2f64.
13125   if (VecTy != MVT::v2f64) {
13126     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13127     DCI.AddToWorklist(N.getNode());
13128     // Package {bitcast value, swap's chain} to match Load's shape.
13129     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13130                        N, Swap.getValue(1));
13131   }
13132 
13133   return Swap;
13134 }
13135 
13136 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13137 // builtins) into stores with swaps.
13138 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13139                                                DAGCombinerInfo &DCI) const {
13140   SelectionDAG &DAG = DCI.DAG;
13141   SDLoc dl(N);
13142   SDValue Chain;
13143   SDValue Base;
13144   unsigned SrcOpnd;
13145   MachineMemOperand *MMO;
13146 
13147   switch (N->getOpcode()) {
13148   default:
13149     llvm_unreachable("Unexpected opcode for little endian VSX store");
13150   case ISD::STORE: {
13151     StoreSDNode *ST = cast<StoreSDNode>(N);
13152     Chain = ST->getChain();
13153     Base = ST->getBasePtr();
13154     MMO = ST->getMemOperand();
13155     SrcOpnd = 1;
13156     // If the MMO suggests this isn't a store of a full vector, leave
13157     // things alone.  For a built-in, we have to make the change for
13158     // correctness, so if there is a size problem that will be a bug.
13159     if (MMO->getSize() < 16)
13160       return SDValue();
13161     break;
13162   }
13163   case ISD::INTRINSIC_VOID: {
13164     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13165     Chain = Intrin->getChain();
13166     // Intrin->getBasePtr() oddly does not get what we want.
13167     Base = Intrin->getOperand(3);
13168     MMO = Intrin->getMemOperand();
13169     SrcOpnd = 2;
13170     break;
13171   }
13172   }
13173 
13174   SDValue Src = N->getOperand(SrcOpnd);
13175   MVT VecTy = Src.getValueType().getSimpleVT();
13176 
13177   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13178   // aligned and the type is a vector with elements up to 4 bytes
13179   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13180       && VecTy.getScalarSizeInBits() <= 32 ) {
13181     return SDValue();
13182   }
13183 
13184   // All stores are done as v2f64 and possible bit cast.
13185   if (VecTy != MVT::v2f64) {
13186     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13187     DCI.AddToWorklist(Src.getNode());
13188   }
13189 
13190   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13191                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13192   DCI.AddToWorklist(Swap.getNode());
13193   Chain = Swap.getValue(1);
13194   SDValue StoreOps[] = { Chain, Swap, Base };
13195   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13196                                           DAG.getVTList(MVT::Other),
13197                                           StoreOps, VecTy, MMO);
13198   DCI.AddToWorklist(Store.getNode());
13199   return Store;
13200 }
13201 
13202 // Handle DAG combine for STORE (FP_TO_INT F).
13203 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13204                                                DAGCombinerInfo &DCI) const {
13205 
13206   SelectionDAG &DAG = DCI.DAG;
13207   SDLoc dl(N);
13208   unsigned Opcode = N->getOperand(1).getOpcode();
13209 
13210   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13211          && "Not a FP_TO_INT Instruction!");
13212 
13213   SDValue Val = N->getOperand(1).getOperand(0);
13214   EVT Op1VT = N->getOperand(1).getValueType();
13215   EVT ResVT = Val.getValueType();
13216 
13217   // Floating point types smaller than 32 bits are not legal on Power.
13218   if (ResVT.getScalarSizeInBits() < 32)
13219     return SDValue();
13220 
13221   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13222   bool ValidTypeForStoreFltAsInt =
13223         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13224          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13225 
13226   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() ||
13227       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13228     return SDValue();
13229 
13230   // Extend f32 values to f64
13231   if (ResVT.getScalarSizeInBits() == 32) {
13232     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13233     DCI.AddToWorklist(Val.getNode());
13234   }
13235 
13236   // Set signed or unsigned conversion opcode.
13237   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13238                           PPCISD::FP_TO_SINT_IN_VSR :
13239                           PPCISD::FP_TO_UINT_IN_VSR;
13240 
13241   Val = DAG.getNode(ConvOpcode,
13242                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13243   DCI.AddToWorklist(Val.getNode());
13244 
13245   // Set number of bytes being converted.
13246   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13247   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13248                     DAG.getIntPtrConstant(ByteSize, dl, false),
13249                     DAG.getValueType(Op1VT) };
13250 
13251   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13252           DAG.getVTList(MVT::Other), Ops,
13253           cast<StoreSDNode>(N)->getMemoryVT(),
13254           cast<StoreSDNode>(N)->getMemOperand());
13255 
13256   DCI.AddToWorklist(Val.getNode());
13257   return Val;
13258 }
13259 
13260 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
13261                                                 LSBaseSDNode *LSBase,
13262                                                 DAGCombinerInfo &DCI) const {
13263   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
13264         "Not a reverse memop pattern!");
13265 
13266   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
13267     auto Mask = SVN->getMask();
13268     int i = 0;
13269     auto I = Mask.rbegin();
13270     auto E = Mask.rend();
13271 
13272     for (; I != E; ++I) {
13273       if (*I != i)
13274         return false;
13275       i++;
13276     }
13277     return true;
13278   };
13279 
13280   SelectionDAG &DAG = DCI.DAG;
13281   EVT VT = SVN->getValueType(0);
13282 
13283   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
13284     return SDValue();
13285 
13286   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
13287   // See comment in PPCVSXSwapRemoval.cpp.
13288   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
13289   if (!Subtarget.hasP9Vector())
13290     return SDValue();
13291 
13292   if(!IsElementReverse(SVN))
13293     return SDValue();
13294 
13295   if (LSBase->getOpcode() == ISD::LOAD) {
13296     SDLoc dl(SVN);
13297     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
13298     return DAG.getMemIntrinsicNode(
13299         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
13300         LSBase->getMemoryVT(), LSBase->getMemOperand());
13301   }
13302 
13303   if (LSBase->getOpcode() == ISD::STORE) {
13304     SDLoc dl(LSBase);
13305     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
13306                           LSBase->getBasePtr()};
13307     return DAG.getMemIntrinsicNode(
13308         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
13309         LSBase->getMemoryVT(), LSBase->getMemOperand());
13310   }
13311 
13312   llvm_unreachable("Expected a load or store node here");
13313 }
13314 
13315 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
13316                                              DAGCombinerInfo &DCI) const {
13317   SelectionDAG &DAG = DCI.DAG;
13318   SDLoc dl(N);
13319   switch (N->getOpcode()) {
13320   default: break;
13321   case ISD::ADD:
13322     return combineADD(N, DCI);
13323   case ISD::SHL:
13324     return combineSHL(N, DCI);
13325   case ISD::SRA:
13326     return combineSRA(N, DCI);
13327   case ISD::SRL:
13328     return combineSRL(N, DCI);
13329   case ISD::MUL:
13330     return combineMUL(N, DCI);
13331   case PPCISD::SHL:
13332     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
13333         return N->getOperand(0);
13334     break;
13335   case PPCISD::SRL:
13336     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
13337         return N->getOperand(0);
13338     break;
13339   case PPCISD::SRA:
13340     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
13341       if (C->isNullValue() ||   //  0 >>s V -> 0.
13342           C->isAllOnesValue())    // -1 >>s V -> -1.
13343         return N->getOperand(0);
13344     }
13345     break;
13346   case ISD::SIGN_EXTEND:
13347   case ISD::ZERO_EXTEND:
13348   case ISD::ANY_EXTEND:
13349     return DAGCombineExtBoolTrunc(N, DCI);
13350   case ISD::TRUNCATE:
13351     return combineTRUNCATE(N, DCI);
13352   case ISD::SETCC:
13353     if (SDValue CSCC = combineSetCC(N, DCI))
13354       return CSCC;
13355     LLVM_FALLTHROUGH;
13356   case ISD::SELECT_CC:
13357     return DAGCombineTruncBoolExt(N, DCI);
13358   case ISD::SINT_TO_FP:
13359   case ISD::UINT_TO_FP:
13360     return combineFPToIntToFP(N, DCI);
13361   case ISD::VECTOR_SHUFFLE:
13362     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
13363       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
13364       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
13365     }
13366     break;
13367   case ISD::STORE: {
13368 
13369     EVT Op1VT = N->getOperand(1).getValueType();
13370     unsigned Opcode = N->getOperand(1).getOpcode();
13371 
13372     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
13373       SDValue Val= combineStoreFPToInt(N, DCI);
13374       if (Val)
13375         return Val;
13376     }
13377 
13378     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
13379       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
13380       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
13381       if (Val)
13382         return Val;
13383     }
13384 
13385     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
13386     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
13387         N->getOperand(1).getNode()->hasOneUse() &&
13388         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
13389          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
13390 
13391       // STBRX can only handle simple types and it makes no sense to store less
13392       // two bytes in byte-reversed order.
13393       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
13394       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
13395         break;
13396 
13397       SDValue BSwapOp = N->getOperand(1).getOperand(0);
13398       // Do an any-extend to 32-bits if this is a half-word input.
13399       if (BSwapOp.getValueType() == MVT::i16)
13400         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
13401 
13402       // If the type of BSWAP operand is wider than stored memory width
13403       // it need to be shifted to the right side before STBRX.
13404       if (Op1VT.bitsGT(mVT)) {
13405         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
13406         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
13407                               DAG.getConstant(Shift, dl, MVT::i32));
13408         // Need to truncate if this is a bswap of i64 stored as i32/i16.
13409         if (Op1VT == MVT::i64)
13410           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
13411       }
13412 
13413       SDValue Ops[] = {
13414         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
13415       };
13416       return
13417         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
13418                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
13419                                 cast<StoreSDNode>(N)->getMemOperand());
13420     }
13421 
13422     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
13423     // So it can increase the chance of CSE constant construction.
13424     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
13425         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
13426       // Need to sign-extended to 64-bits to handle negative values.
13427       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
13428       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
13429                                     MemVT.getSizeInBits());
13430       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
13431 
13432       // DAG.getTruncStore() can't be used here because it doesn't accept
13433       // the general (base + offset) addressing mode.
13434       // So we use UpdateNodeOperands and setTruncatingStore instead.
13435       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
13436                              N->getOperand(3));
13437       cast<StoreSDNode>(N)->setTruncatingStore(true);
13438       return SDValue(N, 0);
13439     }
13440 
13441     // For little endian, VSX stores require generating xxswapd/lxvd2x.
13442     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13443     if (Op1VT.isSimple()) {
13444       MVT StoreVT = Op1VT.getSimpleVT();
13445       if (Subtarget.needsSwapsForVSXMemOps() &&
13446           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
13447            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
13448         return expandVSXStoreForLE(N, DCI);
13449     }
13450     break;
13451   }
13452   case ISD::LOAD: {
13453     LoadSDNode *LD = cast<LoadSDNode>(N);
13454     EVT VT = LD->getValueType(0);
13455 
13456     // For little endian, VSX loads require generating lxvd2x/xxswapd.
13457     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
13458     if (VT.isSimple()) {
13459       MVT LoadVT = VT.getSimpleVT();
13460       if (Subtarget.needsSwapsForVSXMemOps() &&
13461           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
13462            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
13463         return expandVSXLoadForLE(N, DCI);
13464     }
13465 
13466     // We sometimes end up with a 64-bit integer load, from which we extract
13467     // two single-precision floating-point numbers. This happens with
13468     // std::complex<float>, and other similar structures, because of the way we
13469     // canonicalize structure copies. However, if we lack direct moves,
13470     // then the final bitcasts from the extracted integer values to the
13471     // floating-point numbers turn into store/load pairs. Even with direct moves,
13472     // just loading the two floating-point numbers is likely better.
13473     auto ReplaceTwoFloatLoad = [&]() {
13474       if (VT != MVT::i64)
13475         return false;
13476 
13477       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
13478           LD->isVolatile())
13479         return false;
13480 
13481       //  We're looking for a sequence like this:
13482       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
13483       //      t16: i64 = srl t13, Constant:i32<32>
13484       //    t17: i32 = truncate t16
13485       //  t18: f32 = bitcast t17
13486       //    t19: i32 = truncate t13
13487       //  t20: f32 = bitcast t19
13488 
13489       if (!LD->hasNUsesOfValue(2, 0))
13490         return false;
13491 
13492       auto UI = LD->use_begin();
13493       while (UI.getUse().getResNo() != 0) ++UI;
13494       SDNode *Trunc = *UI++;
13495       while (UI.getUse().getResNo() != 0) ++UI;
13496       SDNode *RightShift = *UI;
13497       if (Trunc->getOpcode() != ISD::TRUNCATE)
13498         std::swap(Trunc, RightShift);
13499 
13500       if (Trunc->getOpcode() != ISD::TRUNCATE ||
13501           Trunc->getValueType(0) != MVT::i32 ||
13502           !Trunc->hasOneUse())
13503         return false;
13504       if (RightShift->getOpcode() != ISD::SRL ||
13505           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
13506           RightShift->getConstantOperandVal(1) != 32 ||
13507           !RightShift->hasOneUse())
13508         return false;
13509 
13510       SDNode *Trunc2 = *RightShift->use_begin();
13511       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
13512           Trunc2->getValueType(0) != MVT::i32 ||
13513           !Trunc2->hasOneUse())
13514         return false;
13515 
13516       SDNode *Bitcast = *Trunc->use_begin();
13517       SDNode *Bitcast2 = *Trunc2->use_begin();
13518 
13519       if (Bitcast->getOpcode() != ISD::BITCAST ||
13520           Bitcast->getValueType(0) != MVT::f32)
13521         return false;
13522       if (Bitcast2->getOpcode() != ISD::BITCAST ||
13523           Bitcast2->getValueType(0) != MVT::f32)
13524         return false;
13525 
13526       if (Subtarget.isLittleEndian())
13527         std::swap(Bitcast, Bitcast2);
13528 
13529       // Bitcast has the second float (in memory-layout order) and Bitcast2
13530       // has the first one.
13531 
13532       SDValue BasePtr = LD->getBasePtr();
13533       if (LD->isIndexed()) {
13534         assert(LD->getAddressingMode() == ISD::PRE_INC &&
13535                "Non-pre-inc AM on PPC?");
13536         BasePtr =
13537           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
13538                       LD->getOffset());
13539       }
13540 
13541       auto MMOFlags =
13542           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
13543       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
13544                                       LD->getPointerInfo(), LD->getAlignment(),
13545                                       MMOFlags, LD->getAAInfo());
13546       SDValue AddPtr =
13547         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
13548                     BasePtr, DAG.getIntPtrConstant(4, dl));
13549       SDValue FloatLoad2 = DAG.getLoad(
13550           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
13551           LD->getPointerInfo().getWithOffset(4),
13552           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
13553 
13554       if (LD->isIndexed()) {
13555         // Note that DAGCombine should re-form any pre-increment load(s) from
13556         // what is produced here if that makes sense.
13557         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
13558       }
13559 
13560       DCI.CombineTo(Bitcast2, FloatLoad);
13561       DCI.CombineTo(Bitcast, FloatLoad2);
13562 
13563       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
13564                                     SDValue(FloatLoad2.getNode(), 1));
13565       return true;
13566     };
13567 
13568     if (ReplaceTwoFloatLoad())
13569       return SDValue(N, 0);
13570 
13571     EVT MemVT = LD->getMemoryVT();
13572     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
13573     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
13574     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
13575     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
13576     if (LD->isUnindexed() && VT.isVector() &&
13577         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
13578           // P8 and later hardware should just use LOAD.
13579           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
13580                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
13581          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
13582           LD->getAlignment() >= ScalarABIAlignment)) &&
13583         LD->getAlignment() < ABIAlignment) {
13584       // This is a type-legal unaligned Altivec or QPX load.
13585       SDValue Chain = LD->getChain();
13586       SDValue Ptr = LD->getBasePtr();
13587       bool isLittleEndian = Subtarget.isLittleEndian();
13588 
13589       // This implements the loading of unaligned vectors as described in
13590       // the venerable Apple Velocity Engine overview. Specifically:
13591       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
13592       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
13593       //
13594       // The general idea is to expand a sequence of one or more unaligned
13595       // loads into an alignment-based permutation-control instruction (lvsl
13596       // or lvsr), a series of regular vector loads (which always truncate
13597       // their input address to an aligned address), and a series of
13598       // permutations.  The results of these permutations are the requested
13599       // loaded values.  The trick is that the last "extra" load is not taken
13600       // from the address you might suspect (sizeof(vector) bytes after the
13601       // last requested load), but rather sizeof(vector) - 1 bytes after the
13602       // last requested vector. The point of this is to avoid a page fault if
13603       // the base address happened to be aligned. This works because if the
13604       // base address is aligned, then adding less than a full vector length
13605       // will cause the last vector in the sequence to be (re)loaded.
13606       // Otherwise, the next vector will be fetched as you might suspect was
13607       // necessary.
13608 
13609       // We might be able to reuse the permutation generation from
13610       // a different base address offset from this one by an aligned amount.
13611       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
13612       // optimization later.
13613       Intrinsic::ID Intr, IntrLD, IntrPerm;
13614       MVT PermCntlTy, PermTy, LDTy;
13615       if (Subtarget.hasAltivec()) {
13616         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
13617                                  Intrinsic::ppc_altivec_lvsl;
13618         IntrLD = Intrinsic::ppc_altivec_lvx;
13619         IntrPerm = Intrinsic::ppc_altivec_vperm;
13620         PermCntlTy = MVT::v16i8;
13621         PermTy = MVT::v4i32;
13622         LDTy = MVT::v4i32;
13623       } else {
13624         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
13625                                        Intrinsic::ppc_qpx_qvlpcls;
13626         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
13627                                        Intrinsic::ppc_qpx_qvlfs;
13628         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
13629         PermCntlTy = MVT::v4f64;
13630         PermTy = MVT::v4f64;
13631         LDTy = MemVT.getSimpleVT();
13632       }
13633 
13634       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
13635 
13636       // Create the new MMO for the new base load. It is like the original MMO,
13637       // but represents an area in memory almost twice the vector size centered
13638       // on the original address. If the address is unaligned, we might start
13639       // reading up to (sizeof(vector)-1) bytes below the address of the
13640       // original unaligned load.
13641       MachineFunction &MF = DAG.getMachineFunction();
13642       MachineMemOperand *BaseMMO =
13643         MF.getMachineMemOperand(LD->getMemOperand(),
13644                                 -(long)MemVT.getStoreSize()+1,
13645                                 2*MemVT.getStoreSize()-1);
13646 
13647       // Create the new base load.
13648       SDValue LDXIntID =
13649           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
13650       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
13651       SDValue BaseLoad =
13652         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13653                                 DAG.getVTList(PermTy, MVT::Other),
13654                                 BaseLoadOps, LDTy, BaseMMO);
13655 
13656       // Note that the value of IncOffset (which is provided to the next
13657       // load's pointer info offset value, and thus used to calculate the
13658       // alignment), and the value of IncValue (which is actually used to
13659       // increment the pointer value) are different! This is because we
13660       // require the next load to appear to be aligned, even though it
13661       // is actually offset from the base pointer by a lesser amount.
13662       int IncOffset = VT.getSizeInBits() / 8;
13663       int IncValue = IncOffset;
13664 
13665       // Walk (both up and down) the chain looking for another load at the real
13666       // (aligned) offset (the alignment of the other load does not matter in
13667       // this case). If found, then do not use the offset reduction trick, as
13668       // that will prevent the loads from being later combined (as they would
13669       // otherwise be duplicates).
13670       if (!findConsecutiveLoad(LD, DAG))
13671         --IncValue;
13672 
13673       SDValue Increment =
13674           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
13675       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13676 
13677       MachineMemOperand *ExtraMMO =
13678         MF.getMachineMemOperand(LD->getMemOperand(),
13679                                 1, 2*MemVT.getStoreSize()-1);
13680       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
13681       SDValue ExtraLoad =
13682         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13683                                 DAG.getVTList(PermTy, MVT::Other),
13684                                 ExtraLoadOps, LDTy, ExtraMMO);
13685 
13686       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
13687         BaseLoad.getValue(1), ExtraLoad.getValue(1));
13688 
13689       // Because vperm has a big-endian bias, we must reverse the order
13690       // of the input vectors and complement the permute control vector
13691       // when generating little endian code.  We have already handled the
13692       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
13693       // and ExtraLoad here.
13694       SDValue Perm;
13695       if (isLittleEndian)
13696         Perm = BuildIntrinsicOp(IntrPerm,
13697                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
13698       else
13699         Perm = BuildIntrinsicOp(IntrPerm,
13700                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
13701 
13702       if (VT != PermTy)
13703         Perm = Subtarget.hasAltivec() ?
13704                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
13705                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
13706                                DAG.getTargetConstant(1, dl, MVT::i64));
13707                                // second argument is 1 because this rounding
13708                                // is always exact.
13709 
13710       // The output of the permutation is our loaded result, the TokenFactor is
13711       // our new chain.
13712       DCI.CombineTo(N, Perm, TF);
13713       return SDValue(N, 0);
13714     }
13715     }
13716     break;
13717     case ISD::INTRINSIC_WO_CHAIN: {
13718       bool isLittleEndian = Subtarget.isLittleEndian();
13719       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13720       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
13721                                            : Intrinsic::ppc_altivec_lvsl);
13722       if ((IID == Intr ||
13723            IID == Intrinsic::ppc_qpx_qvlpcld  ||
13724            IID == Intrinsic::ppc_qpx_qvlpcls) &&
13725         N->getOperand(1)->getOpcode() == ISD::ADD) {
13726         SDValue Add = N->getOperand(1);
13727 
13728         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
13729                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
13730 
13731         if (DAG.MaskedValueIsZero(Add->getOperand(1),
13732                                   APInt::getAllOnesValue(Bits /* alignment */)
13733                                       .zext(Add.getScalarValueSizeInBits()))) {
13734           SDNode *BasePtr = Add->getOperand(0).getNode();
13735           for (SDNode::use_iterator UI = BasePtr->use_begin(),
13736                                     UE = BasePtr->use_end();
13737                UI != UE; ++UI) {
13738             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13739                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
13740               // We've found another LVSL/LVSR, and this address is an aligned
13741               // multiple of that one. The results will be the same, so use the
13742               // one we've just found instead.
13743 
13744               return SDValue(*UI, 0);
13745             }
13746           }
13747         }
13748 
13749         if (isa<ConstantSDNode>(Add->getOperand(1))) {
13750           SDNode *BasePtr = Add->getOperand(0).getNode();
13751           for (SDNode::use_iterator UI = BasePtr->use_begin(),
13752                UE = BasePtr->use_end(); UI != UE; ++UI) {
13753             if (UI->getOpcode() == ISD::ADD &&
13754                 isa<ConstantSDNode>(UI->getOperand(1)) &&
13755                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
13756                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
13757                 (1ULL << Bits) == 0) {
13758               SDNode *OtherAdd = *UI;
13759               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
13760                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
13761                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13762                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
13763                   return SDValue(*VI, 0);
13764                 }
13765               }
13766             }
13767           }
13768         }
13769       }
13770 
13771       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
13772       // Expose the vabsduw/h/b opportunity for down stream
13773       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
13774           (IID == Intrinsic::ppc_altivec_vmaxsw ||
13775            IID == Intrinsic::ppc_altivec_vmaxsh ||
13776            IID == Intrinsic::ppc_altivec_vmaxsb)) {
13777         SDValue V1 = N->getOperand(1);
13778         SDValue V2 = N->getOperand(2);
13779         if ((V1.getSimpleValueType() == MVT::v4i32 ||
13780              V1.getSimpleValueType() == MVT::v8i16 ||
13781              V1.getSimpleValueType() == MVT::v16i8) &&
13782             V1.getSimpleValueType() == V2.getSimpleValueType()) {
13783           // (0-a, a)
13784           if (V1.getOpcode() == ISD::SUB &&
13785               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
13786               V1.getOperand(1) == V2) {
13787             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
13788           }
13789           // (a, 0-a)
13790           if (V2.getOpcode() == ISD::SUB &&
13791               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
13792               V2.getOperand(1) == V1) {
13793             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
13794           }
13795           // (x-y, y-x)
13796           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
13797               V1.getOperand(0) == V2.getOperand(1) &&
13798               V1.getOperand(1) == V2.getOperand(0)) {
13799             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
13800           }
13801         }
13802       }
13803     }
13804 
13805     break;
13806   case ISD::INTRINSIC_W_CHAIN:
13807     // For little endian, VSX loads require generating lxvd2x/xxswapd.
13808     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
13809     if (Subtarget.needsSwapsForVSXMemOps()) {
13810       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13811       default:
13812         break;
13813       case Intrinsic::ppc_vsx_lxvw4x:
13814       case Intrinsic::ppc_vsx_lxvd2x:
13815         return expandVSXLoadForLE(N, DCI);
13816       }
13817     }
13818     break;
13819   case ISD::INTRINSIC_VOID:
13820     // For little endian, VSX stores require generating xxswapd/stxvd2x.
13821     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13822     if (Subtarget.needsSwapsForVSXMemOps()) {
13823       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13824       default:
13825         break;
13826       case Intrinsic::ppc_vsx_stxvw4x:
13827       case Intrinsic::ppc_vsx_stxvd2x:
13828         return expandVSXStoreForLE(N, DCI);
13829       }
13830     }
13831     break;
13832   case ISD::BSWAP:
13833     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
13834     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
13835         N->getOperand(0).hasOneUse() &&
13836         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
13837          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
13838           N->getValueType(0) == MVT::i64))) {
13839       SDValue Load = N->getOperand(0);
13840       LoadSDNode *LD = cast<LoadSDNode>(Load);
13841       // Create the byte-swapping load.
13842       SDValue Ops[] = {
13843         LD->getChain(),    // Chain
13844         LD->getBasePtr(),  // Ptr
13845         DAG.getValueType(N->getValueType(0)) // VT
13846       };
13847       SDValue BSLoad =
13848         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
13849                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
13850                                               MVT::i64 : MVT::i32, MVT::Other),
13851                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
13852 
13853       // If this is an i16 load, insert the truncate.
13854       SDValue ResVal = BSLoad;
13855       if (N->getValueType(0) == MVT::i16)
13856         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
13857 
13858       // First, combine the bswap away.  This makes the value produced by the
13859       // load dead.
13860       DCI.CombineTo(N, ResVal);
13861 
13862       // Next, combine the load away, we give it a bogus result value but a real
13863       // chain result.  The result value is dead because the bswap is dead.
13864       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
13865 
13866       // Return N so it doesn't get rechecked!
13867       return SDValue(N, 0);
13868     }
13869     break;
13870   case PPCISD::VCMP:
13871     // If a VCMPo node already exists with exactly the same operands as this
13872     // node, use its result instead of this node (VCMPo computes both a CR6 and
13873     // a normal output).
13874     //
13875     if (!N->getOperand(0).hasOneUse() &&
13876         !N->getOperand(1).hasOneUse() &&
13877         !N->getOperand(2).hasOneUse()) {
13878 
13879       // Scan all of the users of the LHS, looking for VCMPo's that match.
13880       SDNode *VCMPoNode = nullptr;
13881 
13882       SDNode *LHSN = N->getOperand(0).getNode();
13883       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
13884            UI != E; ++UI)
13885         if (UI->getOpcode() == PPCISD::VCMPo &&
13886             UI->getOperand(1) == N->getOperand(1) &&
13887             UI->getOperand(2) == N->getOperand(2) &&
13888             UI->getOperand(0) == N->getOperand(0)) {
13889           VCMPoNode = *UI;
13890           break;
13891         }
13892 
13893       // If there is no VCMPo node, or if the flag value has a single use, don't
13894       // transform this.
13895       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
13896         break;
13897 
13898       // Look at the (necessarily single) use of the flag value.  If it has a
13899       // chain, this transformation is more complex.  Note that multiple things
13900       // could use the value result, which we should ignore.
13901       SDNode *FlagUser = nullptr;
13902       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
13903            FlagUser == nullptr; ++UI) {
13904         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
13905         SDNode *User = *UI;
13906         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
13907           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
13908             FlagUser = User;
13909             break;
13910           }
13911         }
13912       }
13913 
13914       // If the user is a MFOCRF instruction, we know this is safe.
13915       // Otherwise we give up for right now.
13916       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
13917         return SDValue(VCMPoNode, 0);
13918     }
13919     break;
13920   case ISD::BRCOND: {
13921     SDValue Cond = N->getOperand(1);
13922     SDValue Target = N->getOperand(2);
13923 
13924     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13925         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
13926           Intrinsic::loop_decrement) {
13927 
13928       // We now need to make the intrinsic dead (it cannot be instruction
13929       // selected).
13930       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
13931       assert(Cond.getNode()->hasOneUse() &&
13932              "Counter decrement has more than one use");
13933 
13934       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
13935                          N->getOperand(0), Target);
13936     }
13937   }
13938   break;
13939   case ISD::BR_CC: {
13940     // If this is a branch on an altivec predicate comparison, lower this so
13941     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
13942     // lowering is done pre-legalize, because the legalizer lowers the predicate
13943     // compare down to code that is difficult to reassemble.
13944     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
13945     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
13946 
13947     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
13948     // value. If so, pass-through the AND to get to the intrinsic.
13949     if (LHS.getOpcode() == ISD::AND &&
13950         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13951         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
13952           Intrinsic::loop_decrement &&
13953         isa<ConstantSDNode>(LHS.getOperand(1)) &&
13954         !isNullConstant(LHS.getOperand(1)))
13955       LHS = LHS.getOperand(0);
13956 
13957     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13958         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
13959           Intrinsic::loop_decrement &&
13960         isa<ConstantSDNode>(RHS)) {
13961       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
13962              "Counter decrement comparison is not EQ or NE");
13963 
13964       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
13965       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
13966                     (CC == ISD::SETNE && !Val);
13967 
13968       // We now need to make the intrinsic dead (it cannot be instruction
13969       // selected).
13970       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
13971       assert(LHS.getNode()->hasOneUse() &&
13972              "Counter decrement has more than one use");
13973 
13974       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
13975                          N->getOperand(0), N->getOperand(4));
13976     }
13977 
13978     int CompareOpc;
13979     bool isDot;
13980 
13981     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13982         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
13983         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
13984       assert(isDot && "Can't compare against a vector result!");
13985 
13986       // If this is a comparison against something other than 0/1, then we know
13987       // that the condition is never/always true.
13988       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
13989       if (Val != 0 && Val != 1) {
13990         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
13991           return N->getOperand(0);
13992         // Always !=, turn it into an unconditional branch.
13993         return DAG.getNode(ISD::BR, dl, MVT::Other,
13994                            N->getOperand(0), N->getOperand(4));
13995       }
13996 
13997       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
13998 
13999       // Create the PPCISD altivec 'dot' comparison node.
14000       SDValue Ops[] = {
14001         LHS.getOperand(2),  // LHS of compare
14002         LHS.getOperand(3),  // RHS of compare
14003         DAG.getConstant(CompareOpc, dl, MVT::i32)
14004       };
14005       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14006       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14007 
14008       // Unpack the result based on how the target uses it.
14009       PPC::Predicate CompOpc;
14010       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14011       default:  // Can't happen, don't crash on invalid number though.
14012       case 0:   // Branch on the value of the EQ bit of CR6.
14013         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14014         break;
14015       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14016         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14017         break;
14018       case 2:   // Branch on the value of the LT bit of CR6.
14019         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14020         break;
14021       case 3:   // Branch on the inverted value of the LT bit of CR6.
14022         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14023         break;
14024       }
14025 
14026       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14027                          DAG.getConstant(CompOpc, dl, MVT::i32),
14028                          DAG.getRegister(PPC::CR6, MVT::i32),
14029                          N->getOperand(4), CompNode.getValue(1));
14030     }
14031     break;
14032   }
14033   case ISD::BUILD_VECTOR:
14034     return DAGCombineBuildVector(N, DCI);
14035   case ISD::ABS:
14036     return combineABS(N, DCI);
14037   case ISD::VSELECT:
14038     return combineVSelect(N, DCI);
14039   }
14040 
14041   return SDValue();
14042 }
14043 
14044 SDValue
14045 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14046                                  SelectionDAG &DAG,
14047                                  SmallVectorImpl<SDNode *> &Created) const {
14048   // fold (sdiv X, pow2)
14049   EVT VT = N->getValueType(0);
14050   if (VT == MVT::i64 && !Subtarget.isPPC64())
14051     return SDValue();
14052   if ((VT != MVT::i32 && VT != MVT::i64) ||
14053       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14054     return SDValue();
14055 
14056   SDLoc DL(N);
14057   SDValue N0 = N->getOperand(0);
14058 
14059   bool IsNegPow2 = (-Divisor).isPowerOf2();
14060   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14061   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14062 
14063   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14064   Created.push_back(Op.getNode());
14065 
14066   if (IsNegPow2) {
14067     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14068     Created.push_back(Op.getNode());
14069   }
14070 
14071   return Op;
14072 }
14073 
14074 //===----------------------------------------------------------------------===//
14075 // Inline Assembly Support
14076 //===----------------------------------------------------------------------===//
14077 
14078 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14079                                                       KnownBits &Known,
14080                                                       const APInt &DemandedElts,
14081                                                       const SelectionDAG &DAG,
14082                                                       unsigned Depth) const {
14083   Known.resetAll();
14084   switch (Op.getOpcode()) {
14085   default: break;
14086   case PPCISD::LBRX: {
14087     // lhbrx is known to have the top bits cleared out.
14088     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14089       Known.Zero = 0xFFFF0000;
14090     break;
14091   }
14092   case ISD::INTRINSIC_WO_CHAIN: {
14093     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14094     default: break;
14095     case Intrinsic::ppc_altivec_vcmpbfp_p:
14096     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14097     case Intrinsic::ppc_altivec_vcmpequb_p:
14098     case Intrinsic::ppc_altivec_vcmpequh_p:
14099     case Intrinsic::ppc_altivec_vcmpequw_p:
14100     case Intrinsic::ppc_altivec_vcmpequd_p:
14101     case Intrinsic::ppc_altivec_vcmpgefp_p:
14102     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14103     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14104     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14105     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14106     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14107     case Intrinsic::ppc_altivec_vcmpgtub_p:
14108     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14109     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14110     case Intrinsic::ppc_altivec_vcmpgtud_p:
14111       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14112       break;
14113     }
14114   }
14115   }
14116 }
14117 
14118 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14119   switch (Subtarget.getDarwinDirective()) {
14120   default: break;
14121   case PPC::DIR_970:
14122   case PPC::DIR_PWR4:
14123   case PPC::DIR_PWR5:
14124   case PPC::DIR_PWR5X:
14125   case PPC::DIR_PWR6:
14126   case PPC::DIR_PWR6X:
14127   case PPC::DIR_PWR7:
14128   case PPC::DIR_PWR8:
14129   case PPC::DIR_PWR9: {
14130     if (!ML)
14131       break;
14132 
14133     if (!DisableInnermostLoopAlign32) {
14134       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14135       // so that we can decrease cache misses and branch-prediction misses.
14136       // Actual alignment of the loop will depend on the hotness check and other
14137       // logic in alignBlocks.
14138       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14139         return Align(32);
14140     }
14141 
14142     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14143 
14144     // For small loops (between 5 and 8 instructions), align to a 32-byte
14145     // boundary so that the entire loop fits in one instruction-cache line.
14146     uint64_t LoopSize = 0;
14147     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14148       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14149         LoopSize += TII->getInstSizeInBytes(*J);
14150         if (LoopSize > 32)
14151           break;
14152       }
14153 
14154     if (LoopSize > 16 && LoopSize <= 32)
14155       return Align(32);
14156 
14157     break;
14158   }
14159   }
14160 
14161   return TargetLowering::getPrefLoopAlignment(ML);
14162 }
14163 
14164 /// getConstraintType - Given a constraint, return the type of
14165 /// constraint it is for this target.
14166 PPCTargetLowering::ConstraintType
14167 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14168   if (Constraint.size() == 1) {
14169     switch (Constraint[0]) {
14170     default: break;
14171     case 'b':
14172     case 'r':
14173     case 'f':
14174     case 'd':
14175     case 'v':
14176     case 'y':
14177       return C_RegisterClass;
14178     case 'Z':
14179       // FIXME: While Z does indicate a memory constraint, it specifically
14180       // indicates an r+r address (used in conjunction with the 'y' modifier
14181       // in the replacement string). Currently, we're forcing the base
14182       // register to be r0 in the asm printer (which is interpreted as zero)
14183       // and forming the complete address in the second register. This is
14184       // suboptimal.
14185       return C_Memory;
14186     }
14187   } else if (Constraint == "wc") { // individual CR bits.
14188     return C_RegisterClass;
14189   } else if (Constraint == "wa" || Constraint == "wd" ||
14190              Constraint == "wf" || Constraint == "ws" ||
14191              Constraint == "wi" || Constraint == "ww") {
14192     return C_RegisterClass; // VSX registers.
14193   }
14194   return TargetLowering::getConstraintType(Constraint);
14195 }
14196 
14197 /// Examine constraint type and operand type and determine a weight value.
14198 /// This object must already have been set up with the operand type
14199 /// and the current alternative constraint selected.
14200 TargetLowering::ConstraintWeight
14201 PPCTargetLowering::getSingleConstraintMatchWeight(
14202     AsmOperandInfo &info, const char *constraint) const {
14203   ConstraintWeight weight = CW_Invalid;
14204   Value *CallOperandVal = info.CallOperandVal;
14205     // If we don't have a value, we can't do a match,
14206     // but allow it at the lowest weight.
14207   if (!CallOperandVal)
14208     return CW_Default;
14209   Type *type = CallOperandVal->getType();
14210 
14211   // Look at the constraint type.
14212   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
14213     return CW_Register; // an individual CR bit.
14214   else if ((StringRef(constraint) == "wa" ||
14215             StringRef(constraint) == "wd" ||
14216             StringRef(constraint) == "wf") &&
14217            type->isVectorTy())
14218     return CW_Register;
14219   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
14220     return CW_Register; // just hold 64-bit integers data.
14221   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
14222     return CW_Register;
14223   else if (StringRef(constraint) == "ww" && type->isFloatTy())
14224     return CW_Register;
14225 
14226   switch (*constraint) {
14227   default:
14228     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14229     break;
14230   case 'b':
14231     if (type->isIntegerTy())
14232       weight = CW_Register;
14233     break;
14234   case 'f':
14235     if (type->isFloatTy())
14236       weight = CW_Register;
14237     break;
14238   case 'd':
14239     if (type->isDoubleTy())
14240       weight = CW_Register;
14241     break;
14242   case 'v':
14243     if (type->isVectorTy())
14244       weight = CW_Register;
14245     break;
14246   case 'y':
14247     weight = CW_Register;
14248     break;
14249   case 'Z':
14250     weight = CW_Memory;
14251     break;
14252   }
14253   return weight;
14254 }
14255 
14256 std::pair<unsigned, const TargetRegisterClass *>
14257 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
14258                                                 StringRef Constraint,
14259                                                 MVT VT) const {
14260   if (Constraint.size() == 1) {
14261     // GCC RS6000 Constraint Letters
14262     switch (Constraint[0]) {
14263     case 'b':   // R1-R31
14264       if (VT == MVT::i64 && Subtarget.isPPC64())
14265         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
14266       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
14267     case 'r':   // R0-R31
14268       if (VT == MVT::i64 && Subtarget.isPPC64())
14269         return std::make_pair(0U, &PPC::G8RCRegClass);
14270       return std::make_pair(0U, &PPC::GPRCRegClass);
14271     // 'd' and 'f' constraints are both defined to be "the floating point
14272     // registers", where one is for 32-bit and the other for 64-bit. We don't
14273     // really care overly much here so just give them all the same reg classes.
14274     case 'd':
14275     case 'f':
14276       if (Subtarget.hasSPE()) {
14277         if (VT == MVT::f32 || VT == MVT::i32)
14278           return std::make_pair(0U, &PPC::GPRCRegClass);
14279         if (VT == MVT::f64 || VT == MVT::i64)
14280           return std::make_pair(0U, &PPC::SPERCRegClass);
14281       } else {
14282         if (VT == MVT::f32 || VT == MVT::i32)
14283           return std::make_pair(0U, &PPC::F4RCRegClass);
14284         if (VT == MVT::f64 || VT == MVT::i64)
14285           return std::make_pair(0U, &PPC::F8RCRegClass);
14286         if (VT == MVT::v4f64 && Subtarget.hasQPX())
14287           return std::make_pair(0U, &PPC::QFRCRegClass);
14288         if (VT == MVT::v4f32 && Subtarget.hasQPX())
14289           return std::make_pair(0U, &PPC::QSRCRegClass);
14290       }
14291       break;
14292     case 'v':
14293       if (VT == MVT::v4f64 && Subtarget.hasQPX())
14294         return std::make_pair(0U, &PPC::QFRCRegClass);
14295       if (VT == MVT::v4f32 && Subtarget.hasQPX())
14296         return std::make_pair(0U, &PPC::QSRCRegClass);
14297       if (Subtarget.hasAltivec())
14298         return std::make_pair(0U, &PPC::VRRCRegClass);
14299       break;
14300     case 'y':   // crrc
14301       return std::make_pair(0U, &PPC::CRRCRegClass);
14302     }
14303   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
14304     // An individual CR bit.
14305     return std::make_pair(0U, &PPC::CRBITRCRegClass);
14306   } else if ((Constraint == "wa" || Constraint == "wd" ||
14307              Constraint == "wf" || Constraint == "wi") &&
14308              Subtarget.hasVSX()) {
14309     return std::make_pair(0U, &PPC::VSRCRegClass);
14310   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
14311     if (VT == MVT::f32 && Subtarget.hasP8Vector())
14312       return std::make_pair(0U, &PPC::VSSRCRegClass);
14313     else
14314       return std::make_pair(0U, &PPC::VSFRCRegClass);
14315   }
14316 
14317   std::pair<unsigned, const TargetRegisterClass *> R =
14318       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
14319 
14320   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
14321   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
14322   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
14323   // register.
14324   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
14325   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
14326   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
14327       PPC::GPRCRegClass.contains(R.first))
14328     return std::make_pair(TRI->getMatchingSuperReg(R.first,
14329                             PPC::sub_32, &PPC::G8RCRegClass),
14330                           &PPC::G8RCRegClass);
14331 
14332   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
14333   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
14334     R.first = PPC::CR0;
14335     R.second = &PPC::CRRCRegClass;
14336   }
14337 
14338   return R;
14339 }
14340 
14341 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14342 /// vector.  If it is invalid, don't add anything to Ops.
14343 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14344                                                      std::string &Constraint,
14345                                                      std::vector<SDValue>&Ops,
14346                                                      SelectionDAG &DAG) const {
14347   SDValue Result;
14348 
14349   // Only support length 1 constraints.
14350   if (Constraint.length() > 1) return;
14351 
14352   char Letter = Constraint[0];
14353   switch (Letter) {
14354   default: break;
14355   case 'I':
14356   case 'J':
14357   case 'K':
14358   case 'L':
14359   case 'M':
14360   case 'N':
14361   case 'O':
14362   case 'P': {
14363     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
14364     if (!CST) return; // Must be an immediate to match.
14365     SDLoc dl(Op);
14366     int64_t Value = CST->getSExtValue();
14367     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
14368                          // numbers are printed as such.
14369     switch (Letter) {
14370     default: llvm_unreachable("Unknown constraint letter!");
14371     case 'I':  // "I" is a signed 16-bit constant.
14372       if (isInt<16>(Value))
14373         Result = DAG.getTargetConstant(Value, dl, TCVT);
14374       break;
14375     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
14376       if (isShiftedUInt<16, 16>(Value))
14377         Result = DAG.getTargetConstant(Value, dl, TCVT);
14378       break;
14379     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
14380       if (isShiftedInt<16, 16>(Value))
14381         Result = DAG.getTargetConstant(Value, dl, TCVT);
14382       break;
14383     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
14384       if (isUInt<16>(Value))
14385         Result = DAG.getTargetConstant(Value, dl, TCVT);
14386       break;
14387     case 'M':  // "M" is a constant that is greater than 31.
14388       if (Value > 31)
14389         Result = DAG.getTargetConstant(Value, dl, TCVT);
14390       break;
14391     case 'N':  // "N" is a positive constant that is an exact power of two.
14392       if (Value > 0 && isPowerOf2_64(Value))
14393         Result = DAG.getTargetConstant(Value, dl, TCVT);
14394       break;
14395     case 'O':  // "O" is the constant zero.
14396       if (Value == 0)
14397         Result = DAG.getTargetConstant(Value, dl, TCVT);
14398       break;
14399     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
14400       if (isInt<16>(-Value))
14401         Result = DAG.getTargetConstant(Value, dl, TCVT);
14402       break;
14403     }
14404     break;
14405   }
14406   }
14407 
14408   if (Result.getNode()) {
14409     Ops.push_back(Result);
14410     return;
14411   }
14412 
14413   // Handle standard constraint letters.
14414   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14415 }
14416 
14417 // isLegalAddressingMode - Return true if the addressing mode represented
14418 // by AM is legal for this target, for a load/store of the specified type.
14419 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14420                                               const AddrMode &AM, Type *Ty,
14421                                               unsigned AS, Instruction *I) const {
14422   // PPC does not allow r+i addressing modes for vectors!
14423   if (Ty->isVectorTy() && AM.BaseOffs != 0)
14424     return false;
14425 
14426   // PPC allows a sign-extended 16-bit immediate field.
14427   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
14428     return false;
14429 
14430   // No global is ever allowed as a base.
14431   if (AM.BaseGV)
14432     return false;
14433 
14434   // PPC only support r+r,
14435   switch (AM.Scale) {
14436   case 0:  // "r+i" or just "i", depending on HasBaseReg.
14437     break;
14438   case 1:
14439     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
14440       return false;
14441     // Otherwise we have r+r or r+i.
14442     break;
14443   case 2:
14444     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
14445       return false;
14446     // Allow 2*r as r+r.
14447     break;
14448   default:
14449     // No other scales are supported.
14450     return false;
14451   }
14452 
14453   return true;
14454 }
14455 
14456 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
14457                                            SelectionDAG &DAG) const {
14458   MachineFunction &MF = DAG.getMachineFunction();
14459   MachineFrameInfo &MFI = MF.getFrameInfo();
14460   MFI.setReturnAddressIsTaken(true);
14461 
14462   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14463     return SDValue();
14464 
14465   SDLoc dl(Op);
14466   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14467 
14468   // Make sure the function does not optimize away the store of the RA to
14469   // the stack.
14470   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
14471   FuncInfo->setLRStoreRequired();
14472   bool isPPC64 = Subtarget.isPPC64();
14473   auto PtrVT = getPointerTy(MF.getDataLayout());
14474 
14475   if (Depth > 0) {
14476     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14477     SDValue Offset =
14478         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
14479                         isPPC64 ? MVT::i64 : MVT::i32);
14480     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14481                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
14482                        MachinePointerInfo());
14483   }
14484 
14485   // Just load the return address off the stack.
14486   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
14487   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
14488                      MachinePointerInfo());
14489 }
14490 
14491 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
14492                                           SelectionDAG &DAG) const {
14493   SDLoc dl(Op);
14494   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14495 
14496   MachineFunction &MF = DAG.getMachineFunction();
14497   MachineFrameInfo &MFI = MF.getFrameInfo();
14498   MFI.setFrameAddressIsTaken(true);
14499 
14500   EVT PtrVT = getPointerTy(MF.getDataLayout());
14501   bool isPPC64 = PtrVT == MVT::i64;
14502 
14503   // Naked functions never have a frame pointer, and so we use r1. For all
14504   // other functions, this decision must be delayed until during PEI.
14505   unsigned FrameReg;
14506   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
14507     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
14508   else
14509     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
14510 
14511   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
14512                                          PtrVT);
14513   while (Depth--)
14514     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
14515                             FrameAddr, MachinePointerInfo());
14516   return FrameAddr;
14517 }
14518 
14519 // FIXME? Maybe this could be a TableGen attribute on some registers and
14520 // this table could be generated automatically from RegInfo.
14521 Register PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
14522                                               const MachineFunction &MF) const {
14523   bool isPPC64 = Subtarget.isPPC64();
14524   bool IsDarwinABI = Subtarget.isDarwinABI();
14525 
14526   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
14527       (!isPPC64 && VT != MVT::i32))
14528     report_fatal_error("Invalid register global variable type");
14529 
14530   bool is64Bit = isPPC64 && VT == MVT::i64;
14531   Register Reg = StringSwitch<Register>(RegName)
14532                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
14533                    .Case("r2", (IsDarwinABI || isPPC64) ? Register() : PPC::R2)
14534                    .Case("r13", (!isPPC64 && IsDarwinABI) ? Register() :
14535                                   (is64Bit ? PPC::X13 : PPC::R13))
14536                    .Default(Register());
14537 
14538   if (Reg)
14539     return Reg;
14540   report_fatal_error("Invalid register name global variable");
14541 }
14542 
14543 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
14544   // 32-bit SVR4 ABI access everything as got-indirect.
14545   if (Subtarget.is32BitELFABI())
14546     return true;
14547 
14548   // AIX accesses everything indirectly through the TOC, which is similar to
14549   // the GOT.
14550   if (Subtarget.isAIXABI())
14551     return true;
14552 
14553   CodeModel::Model CModel = getTargetMachine().getCodeModel();
14554   // If it is small or large code model, module locals are accessed
14555   // indirectly by loading their address from .toc/.got.
14556   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
14557     return true;
14558 
14559   // JumpTable and BlockAddress are accessed as got-indirect.
14560   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
14561     return true;
14562 
14563   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
14564     return Subtarget.isGVIndirectSymbol(G->getGlobal());
14565 
14566   return false;
14567 }
14568 
14569 bool
14570 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14571   // The PowerPC target isn't yet aware of offsets.
14572   return false;
14573 }
14574 
14575 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14576                                            const CallInst &I,
14577                                            MachineFunction &MF,
14578                                            unsigned Intrinsic) const {
14579   switch (Intrinsic) {
14580   case Intrinsic::ppc_qpx_qvlfd:
14581   case Intrinsic::ppc_qpx_qvlfs:
14582   case Intrinsic::ppc_qpx_qvlfcd:
14583   case Intrinsic::ppc_qpx_qvlfcs:
14584   case Intrinsic::ppc_qpx_qvlfiwa:
14585   case Intrinsic::ppc_qpx_qvlfiwz:
14586   case Intrinsic::ppc_altivec_lvx:
14587   case Intrinsic::ppc_altivec_lvxl:
14588   case Intrinsic::ppc_altivec_lvebx:
14589   case Intrinsic::ppc_altivec_lvehx:
14590   case Intrinsic::ppc_altivec_lvewx:
14591   case Intrinsic::ppc_vsx_lxvd2x:
14592   case Intrinsic::ppc_vsx_lxvw4x: {
14593     EVT VT;
14594     switch (Intrinsic) {
14595     case Intrinsic::ppc_altivec_lvebx:
14596       VT = MVT::i8;
14597       break;
14598     case Intrinsic::ppc_altivec_lvehx:
14599       VT = MVT::i16;
14600       break;
14601     case Intrinsic::ppc_altivec_lvewx:
14602       VT = MVT::i32;
14603       break;
14604     case Intrinsic::ppc_vsx_lxvd2x:
14605       VT = MVT::v2f64;
14606       break;
14607     case Intrinsic::ppc_qpx_qvlfd:
14608       VT = MVT::v4f64;
14609       break;
14610     case Intrinsic::ppc_qpx_qvlfs:
14611       VT = MVT::v4f32;
14612       break;
14613     case Intrinsic::ppc_qpx_qvlfcd:
14614       VT = MVT::v2f64;
14615       break;
14616     case Intrinsic::ppc_qpx_qvlfcs:
14617       VT = MVT::v2f32;
14618       break;
14619     default:
14620       VT = MVT::v4i32;
14621       break;
14622     }
14623 
14624     Info.opc = ISD::INTRINSIC_W_CHAIN;
14625     Info.memVT = VT;
14626     Info.ptrVal = I.getArgOperand(0);
14627     Info.offset = -VT.getStoreSize()+1;
14628     Info.size = 2*VT.getStoreSize()-1;
14629     Info.align = Align::None();
14630     Info.flags = MachineMemOperand::MOLoad;
14631     return true;
14632   }
14633   case Intrinsic::ppc_qpx_qvlfda:
14634   case Intrinsic::ppc_qpx_qvlfsa:
14635   case Intrinsic::ppc_qpx_qvlfcda:
14636   case Intrinsic::ppc_qpx_qvlfcsa:
14637   case Intrinsic::ppc_qpx_qvlfiwaa:
14638   case Intrinsic::ppc_qpx_qvlfiwza: {
14639     EVT VT;
14640     switch (Intrinsic) {
14641     case Intrinsic::ppc_qpx_qvlfda:
14642       VT = MVT::v4f64;
14643       break;
14644     case Intrinsic::ppc_qpx_qvlfsa:
14645       VT = MVT::v4f32;
14646       break;
14647     case Intrinsic::ppc_qpx_qvlfcda:
14648       VT = MVT::v2f64;
14649       break;
14650     case Intrinsic::ppc_qpx_qvlfcsa:
14651       VT = MVT::v2f32;
14652       break;
14653     default:
14654       VT = MVT::v4i32;
14655       break;
14656     }
14657 
14658     Info.opc = ISD::INTRINSIC_W_CHAIN;
14659     Info.memVT = VT;
14660     Info.ptrVal = I.getArgOperand(0);
14661     Info.offset = 0;
14662     Info.size = VT.getStoreSize();
14663     Info.align = Align::None();
14664     Info.flags = MachineMemOperand::MOLoad;
14665     return true;
14666   }
14667   case Intrinsic::ppc_qpx_qvstfd:
14668   case Intrinsic::ppc_qpx_qvstfs:
14669   case Intrinsic::ppc_qpx_qvstfcd:
14670   case Intrinsic::ppc_qpx_qvstfcs:
14671   case Intrinsic::ppc_qpx_qvstfiw:
14672   case Intrinsic::ppc_altivec_stvx:
14673   case Intrinsic::ppc_altivec_stvxl:
14674   case Intrinsic::ppc_altivec_stvebx:
14675   case Intrinsic::ppc_altivec_stvehx:
14676   case Intrinsic::ppc_altivec_stvewx:
14677   case Intrinsic::ppc_vsx_stxvd2x:
14678   case Intrinsic::ppc_vsx_stxvw4x: {
14679     EVT VT;
14680     switch (Intrinsic) {
14681     case Intrinsic::ppc_altivec_stvebx:
14682       VT = MVT::i8;
14683       break;
14684     case Intrinsic::ppc_altivec_stvehx:
14685       VT = MVT::i16;
14686       break;
14687     case Intrinsic::ppc_altivec_stvewx:
14688       VT = MVT::i32;
14689       break;
14690     case Intrinsic::ppc_vsx_stxvd2x:
14691       VT = MVT::v2f64;
14692       break;
14693     case Intrinsic::ppc_qpx_qvstfd:
14694       VT = MVT::v4f64;
14695       break;
14696     case Intrinsic::ppc_qpx_qvstfs:
14697       VT = MVT::v4f32;
14698       break;
14699     case Intrinsic::ppc_qpx_qvstfcd:
14700       VT = MVT::v2f64;
14701       break;
14702     case Intrinsic::ppc_qpx_qvstfcs:
14703       VT = MVT::v2f32;
14704       break;
14705     default:
14706       VT = MVT::v4i32;
14707       break;
14708     }
14709 
14710     Info.opc = ISD::INTRINSIC_VOID;
14711     Info.memVT = VT;
14712     Info.ptrVal = I.getArgOperand(1);
14713     Info.offset = -VT.getStoreSize()+1;
14714     Info.size = 2*VT.getStoreSize()-1;
14715     Info.align = Align::None();
14716     Info.flags = MachineMemOperand::MOStore;
14717     return true;
14718   }
14719   case Intrinsic::ppc_qpx_qvstfda:
14720   case Intrinsic::ppc_qpx_qvstfsa:
14721   case Intrinsic::ppc_qpx_qvstfcda:
14722   case Intrinsic::ppc_qpx_qvstfcsa:
14723   case Intrinsic::ppc_qpx_qvstfiwa: {
14724     EVT VT;
14725     switch (Intrinsic) {
14726     case Intrinsic::ppc_qpx_qvstfda:
14727       VT = MVT::v4f64;
14728       break;
14729     case Intrinsic::ppc_qpx_qvstfsa:
14730       VT = MVT::v4f32;
14731       break;
14732     case Intrinsic::ppc_qpx_qvstfcda:
14733       VT = MVT::v2f64;
14734       break;
14735     case Intrinsic::ppc_qpx_qvstfcsa:
14736       VT = MVT::v2f32;
14737       break;
14738     default:
14739       VT = MVT::v4i32;
14740       break;
14741     }
14742 
14743     Info.opc = ISD::INTRINSIC_VOID;
14744     Info.memVT = VT;
14745     Info.ptrVal = I.getArgOperand(1);
14746     Info.offset = 0;
14747     Info.size = VT.getStoreSize();
14748     Info.align = Align::None();
14749     Info.flags = MachineMemOperand::MOStore;
14750     return true;
14751   }
14752   default:
14753     break;
14754   }
14755 
14756   return false;
14757 }
14758 
14759 /// getOptimalMemOpType - Returns the target specific optimal type for load
14760 /// and store operations as a result of memset, memcpy, and memmove
14761 /// lowering. If DstAlign is zero that means it's safe to destination
14762 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
14763 /// means there isn't a need to check it against alignment requirement,
14764 /// probably because the source does not need to be loaded. If 'IsMemset' is
14765 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
14766 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
14767 /// source is constant so it does not need to be loaded.
14768 /// It returns EVT::Other if the type should be determined using generic
14769 /// target-independent logic.
14770 EVT PPCTargetLowering::getOptimalMemOpType(
14771     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
14772     bool ZeroMemset, bool MemcpyStrSrc,
14773     const AttributeList &FuncAttributes) const {
14774   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
14775     // When expanding a memset, require at least two QPX instructions to cover
14776     // the cost of loading the value to be stored from the constant pool.
14777     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
14778        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
14779         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
14780       return MVT::v4f64;
14781     }
14782 
14783     // We should use Altivec/VSX loads and stores when available. For unaligned
14784     // addresses, unaligned VSX loads are only fast starting with the P8.
14785     if (Subtarget.hasAltivec() && Size >= 16 &&
14786         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
14787          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
14788       return MVT::v4i32;
14789   }
14790 
14791   if (Subtarget.isPPC64()) {
14792     return MVT::i64;
14793   }
14794 
14795   return MVT::i32;
14796 }
14797 
14798 /// Returns true if it is beneficial to convert a load of a constant
14799 /// to just the constant itself.
14800 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
14801                                                           Type *Ty) const {
14802   assert(Ty->isIntegerTy());
14803 
14804   unsigned BitSize = Ty->getPrimitiveSizeInBits();
14805   return !(BitSize == 0 || BitSize > 64);
14806 }
14807 
14808 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14809   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14810     return false;
14811   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14812   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14813   return NumBits1 == 64 && NumBits2 == 32;
14814 }
14815 
14816 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14817   if (!VT1.isInteger() || !VT2.isInteger())
14818     return false;
14819   unsigned NumBits1 = VT1.getSizeInBits();
14820   unsigned NumBits2 = VT2.getSizeInBits();
14821   return NumBits1 == 64 && NumBits2 == 32;
14822 }
14823 
14824 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14825   // Generally speaking, zexts are not free, but they are free when they can be
14826   // folded with other operations.
14827   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
14828     EVT MemVT = LD->getMemoryVT();
14829     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
14830          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
14831         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
14832          LD->getExtensionType() == ISD::ZEXTLOAD))
14833       return true;
14834   }
14835 
14836   // FIXME: Add other cases...
14837   //  - 32-bit shifts with a zext to i64
14838   //  - zext after ctlz, bswap, etc.
14839   //  - zext after and by a constant mask
14840 
14841   return TargetLowering::isZExtFree(Val, VT2);
14842 }
14843 
14844 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
14845   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
14846          "invalid fpext types");
14847   // Extending to float128 is not free.
14848   if (DestVT == MVT::f128)
14849     return false;
14850   return true;
14851 }
14852 
14853 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14854   return isInt<16>(Imm) || isUInt<16>(Imm);
14855 }
14856 
14857 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
14858   return isInt<16>(Imm) || isUInt<16>(Imm);
14859 }
14860 
14861 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
14862                                                        unsigned,
14863                                                        unsigned,
14864                                                        MachineMemOperand::Flags,
14865                                                        bool *Fast) const {
14866   if (DisablePPCUnaligned)
14867     return false;
14868 
14869   // PowerPC supports unaligned memory access for simple non-vector types.
14870   // Although accessing unaligned addresses is not as efficient as accessing
14871   // aligned addresses, it is generally more efficient than manual expansion,
14872   // and generally only traps for software emulation when crossing page
14873   // boundaries.
14874 
14875   if (!VT.isSimple())
14876     return false;
14877 
14878   if (VT.getSimpleVT().isVector()) {
14879     if (Subtarget.hasVSX()) {
14880       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
14881           VT != MVT::v4f32 && VT != MVT::v4i32)
14882         return false;
14883     } else {
14884       return false;
14885     }
14886   }
14887 
14888   if (VT == MVT::ppcf128)
14889     return false;
14890 
14891   if (Fast)
14892     *Fast = true;
14893 
14894   return true;
14895 }
14896 
14897 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14898   VT = VT.getScalarType();
14899 
14900   if (!VT.isSimple())
14901     return false;
14902 
14903   switch (VT.getSimpleVT().SimpleTy) {
14904   case MVT::f32:
14905   case MVT::f64:
14906     return true;
14907   case MVT::f128:
14908     return (EnableQuadPrecision && Subtarget.hasP9Vector());
14909   default:
14910     break;
14911   }
14912 
14913   return false;
14914 }
14915 
14916 const MCPhysReg *
14917 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
14918   // LR is a callee-save register, but we must treat it as clobbered by any call
14919   // site. Hence we include LR in the scratch registers, which are in turn added
14920   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
14921   // to CTR, which is used by any indirect call.
14922   static const MCPhysReg ScratchRegs[] = {
14923     PPC::X12, PPC::LR8, PPC::CTR8, 0
14924   };
14925 
14926   return ScratchRegs;
14927 }
14928 
14929 unsigned PPCTargetLowering::getExceptionPointerRegister(
14930     const Constant *PersonalityFn) const {
14931   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
14932 }
14933 
14934 unsigned PPCTargetLowering::getExceptionSelectorRegister(
14935     const Constant *PersonalityFn) const {
14936   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
14937 }
14938 
14939 bool
14940 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
14941                      EVT VT , unsigned DefinedValues) const {
14942   if (VT == MVT::v2i64)
14943     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
14944 
14945   if (Subtarget.hasVSX() || Subtarget.hasQPX())
14946     return true;
14947 
14948   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
14949 }
14950 
14951 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
14952   if (DisableILPPref || Subtarget.enableMachineScheduler())
14953     return TargetLowering::getSchedulingPreference(N);
14954 
14955   return Sched::ILP;
14956 }
14957 
14958 // Create a fast isel object.
14959 FastISel *
14960 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
14961                                   const TargetLibraryInfo *LibInfo) const {
14962   return PPC::createFastISel(FuncInfo, LibInfo);
14963 }
14964 
14965 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14966   if (Subtarget.isDarwinABI()) return;
14967   if (!Subtarget.isPPC64()) return;
14968 
14969   // Update IsSplitCSR in PPCFunctionInfo
14970   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
14971   PFI->setIsSplitCSR(true);
14972 }
14973 
14974 void PPCTargetLowering::insertCopiesSplitCSR(
14975   MachineBasicBlock *Entry,
14976   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14977   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
14978   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14979   if (!IStart)
14980     return;
14981 
14982   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
14983   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14984   MachineBasicBlock::iterator MBBI = Entry->begin();
14985   for (const MCPhysReg *I = IStart; *I; ++I) {
14986     const TargetRegisterClass *RC = nullptr;
14987     if (PPC::G8RCRegClass.contains(*I))
14988       RC = &PPC::G8RCRegClass;
14989     else if (PPC::F8RCRegClass.contains(*I))
14990       RC = &PPC::F8RCRegClass;
14991     else if (PPC::CRRCRegClass.contains(*I))
14992       RC = &PPC::CRRCRegClass;
14993     else if (PPC::VRRCRegClass.contains(*I))
14994       RC = &PPC::VRRCRegClass;
14995     else
14996       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14997 
14998     Register NewVR = MRI->createVirtualRegister(RC);
14999     // Create copy from CSR to a virtual register.
15000     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15001     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15002     // nounwind. If we want to generalize this later, we may need to emit
15003     // CFI pseudo-instructions.
15004     assert(Entry->getParent()->getFunction().hasFnAttribute(
15005              Attribute::NoUnwind) &&
15006            "Function should be nounwind in insertCopiesSplitCSR!");
15007     Entry->addLiveIn(*I);
15008     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15009       .addReg(*I);
15010 
15011     // Insert the copy-back instructions right before the terminator.
15012     for (auto *Exit : Exits)
15013       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15014               TII->get(TargetOpcode::COPY), *I)
15015         .addReg(NewVR);
15016   }
15017 }
15018 
15019 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15020 bool PPCTargetLowering::useLoadStackGuardNode() const {
15021   if (!Subtarget.isTargetLinux())
15022     return TargetLowering::useLoadStackGuardNode();
15023   return true;
15024 }
15025 
15026 // Override to disable global variable loading on Linux.
15027 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15028   if (!Subtarget.isTargetLinux())
15029     return TargetLowering::insertSSPDeclarations(M);
15030 }
15031 
15032 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15033                                      bool ForCodeSize) const {
15034   if (!VT.isSimple() || !Subtarget.hasVSX())
15035     return false;
15036 
15037   switch(VT.getSimpleVT().SimpleTy) {
15038   default:
15039     // For FP types that are currently not supported by PPC backend, return
15040     // false. Examples: f16, f80.
15041     return false;
15042   case MVT::f32:
15043   case MVT::f64:
15044   case MVT::ppcf128:
15045     return Imm.isPosZero();
15046   }
15047 }
15048 
15049 // For vector shift operation op, fold
15050 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15051 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15052                                   SelectionDAG &DAG) {
15053   SDValue N0 = N->getOperand(0);
15054   SDValue N1 = N->getOperand(1);
15055   EVT VT = N0.getValueType();
15056   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15057   unsigned Opcode = N->getOpcode();
15058   unsigned TargetOpcode;
15059 
15060   switch (Opcode) {
15061   default:
15062     llvm_unreachable("Unexpected shift operation");
15063   case ISD::SHL:
15064     TargetOpcode = PPCISD::SHL;
15065     break;
15066   case ISD::SRL:
15067     TargetOpcode = PPCISD::SRL;
15068     break;
15069   case ISD::SRA:
15070     TargetOpcode = PPCISD::SRA;
15071     break;
15072   }
15073 
15074   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15075       N1->getOpcode() == ISD::AND)
15076     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15077       if (Mask->getZExtValue() == OpSizeInBits - 1)
15078         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15079 
15080   return SDValue();
15081 }
15082 
15083 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15084   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15085     return Value;
15086 
15087   SDValue N0 = N->getOperand(0);
15088   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15089   if (!Subtarget.isISA3_0() ||
15090       N0.getOpcode() != ISD::SIGN_EXTEND ||
15091       N0.getOperand(0).getValueType() != MVT::i32 ||
15092       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15093     return SDValue();
15094 
15095   // We can't save an operation here if the value is already extended, and
15096   // the existing shift is easier to combine.
15097   SDValue ExtsSrc = N0.getOperand(0);
15098   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15099       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15100     return SDValue();
15101 
15102   SDLoc DL(N0);
15103   SDValue ShiftBy = SDValue(CN1, 0);
15104   // We want the shift amount to be i32 on the extswli, but the shift could
15105   // have an i64.
15106   if (ShiftBy.getValueType() == MVT::i64)
15107     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15108 
15109   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15110                          ShiftBy);
15111 }
15112 
15113 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15114   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15115     return Value;
15116 
15117   return SDValue();
15118 }
15119 
15120 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15121   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15122     return Value;
15123 
15124   return SDValue();
15125 }
15126 
15127 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15128 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15129 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15130 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15131 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15132                                  const PPCSubtarget &Subtarget) {
15133   if (!Subtarget.isPPC64())
15134     return SDValue();
15135 
15136   SDValue LHS = N->getOperand(0);
15137   SDValue RHS = N->getOperand(1);
15138 
15139   auto isZextOfCompareWithConstant = [](SDValue Op) {
15140     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15141         Op.getValueType() != MVT::i64)
15142       return false;
15143 
15144     SDValue Cmp = Op.getOperand(0);
15145     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15146         Cmp.getOperand(0).getValueType() != MVT::i64)
15147       return false;
15148 
15149     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15150       int64_t NegConstant = 0 - Constant->getSExtValue();
15151       // Due to the limitations of the addi instruction,
15152       // -C is required to be [-32768, 32767].
15153       return isInt<16>(NegConstant);
15154     }
15155 
15156     return false;
15157   };
15158 
15159   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15160   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15161 
15162   // If there is a pattern, canonicalize a zext operand to the RHS.
15163   if (LHSHasPattern && !RHSHasPattern)
15164     std::swap(LHS, RHS);
15165   else if (!LHSHasPattern && !RHSHasPattern)
15166     return SDValue();
15167 
15168   SDLoc DL(N);
15169   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15170   SDValue Cmp = RHS.getOperand(0);
15171   SDValue Z = Cmp.getOperand(0);
15172   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15173 
15174   assert(Constant && "Constant Should not be a null pointer.");
15175   int64_t NegConstant = 0 - Constant->getSExtValue();
15176 
15177   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15178   default: break;
15179   case ISD::SETNE: {
15180     //                                 when C == 0
15181     //                             --> addze X, (addic Z, -1).carry
15182     //                            /
15183     // add X, (zext(setne Z, C))--
15184     //                            \    when -32768 <= -C <= 32767 && C != 0
15185     //                             --> addze X, (addic (addi Z, -C), -1).carry
15186     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15187                               DAG.getConstant(NegConstant, DL, MVT::i64));
15188     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15189     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15190                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15191     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15192                        SDValue(Addc.getNode(), 1));
15193     }
15194   case ISD::SETEQ: {
15195     //                                 when C == 0
15196     //                             --> addze X, (subfic Z, 0).carry
15197     //                            /
15198     // add X, (zext(sete  Z, C))--
15199     //                            \    when -32768 <= -C <= 32767 && C != 0
15200     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15201     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15202                               DAG.getConstant(NegConstant, DL, MVT::i64));
15203     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15204     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15205                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15206     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15207                        SDValue(Subc.getNode(), 1));
15208     }
15209   }
15210 
15211   return SDValue();
15212 }
15213 
15214 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
15215   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
15216     return Value;
15217 
15218   return SDValue();
15219 }
15220 
15221 // Detect TRUNCATE operations on bitcasts of float128 values.
15222 // What we are looking for here is the situtation where we extract a subset
15223 // of bits from a 128 bit float.
15224 // This can be of two forms:
15225 // 1) BITCAST of f128 feeding TRUNCATE
15226 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
15227 // The reason this is required is because we do not have a legal i128 type
15228 // and so we want to prevent having to store the f128 and then reload part
15229 // of it.
15230 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
15231                                            DAGCombinerInfo &DCI) const {
15232   // If we are using CRBits then try that first.
15233   if (Subtarget.useCRBits()) {
15234     // Check if CRBits did anything and return that if it did.
15235     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
15236       return CRTruncValue;
15237   }
15238 
15239   SDLoc dl(N);
15240   SDValue Op0 = N->getOperand(0);
15241 
15242   // Looking for a truncate of i128 to i64.
15243   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
15244     return SDValue();
15245 
15246   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
15247 
15248   // SRL feeding TRUNCATE.
15249   if (Op0.getOpcode() == ISD::SRL) {
15250     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
15251     // The right shift has to be by 64 bits.
15252     if (!ConstNode || ConstNode->getZExtValue() != 64)
15253       return SDValue();
15254 
15255     // Switch the element number to extract.
15256     EltToExtract = EltToExtract ? 0 : 1;
15257     // Update Op0 past the SRL.
15258     Op0 = Op0.getOperand(0);
15259   }
15260 
15261   // BITCAST feeding a TRUNCATE possibly via SRL.
15262   if (Op0.getOpcode() == ISD::BITCAST &&
15263       Op0.getValueType() == MVT::i128 &&
15264       Op0.getOperand(0).getValueType() == MVT::f128) {
15265     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
15266     return DCI.DAG.getNode(
15267         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
15268         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
15269   }
15270   return SDValue();
15271 }
15272 
15273 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
15274   SelectionDAG &DAG = DCI.DAG;
15275 
15276   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
15277   if (!ConstOpOrElement)
15278     return SDValue();
15279 
15280   // An imul is usually smaller than the alternative sequence for legal type.
15281   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
15282       isOperationLegal(ISD::MUL, N->getValueType(0)))
15283     return SDValue();
15284 
15285   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
15286     switch (this->Subtarget.getDarwinDirective()) {
15287     default:
15288       // TODO: enhance the condition for subtarget before pwr8
15289       return false;
15290     case PPC::DIR_PWR8:
15291       //  type        mul     add    shl
15292       // scalar        4       1      1
15293       // vector        7       2      2
15294       return true;
15295     case PPC::DIR_PWR9:
15296       //  type        mul     add    shl
15297       // scalar        5       2      2
15298       // vector        7       2      2
15299 
15300       // The cycle RATIO of related operations are showed as a table above.
15301       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
15302       // scalar and vector type. For 2 instrs patterns, add/sub + shl
15303       // are 4, it is always profitable; but for 3 instrs patterns
15304       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
15305       // So we should only do it for vector type.
15306       return IsAddOne && IsNeg ? VT.isVector() : true;
15307     }
15308   };
15309 
15310   EVT VT = N->getValueType(0);
15311   SDLoc DL(N);
15312 
15313   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
15314   bool IsNeg = MulAmt.isNegative();
15315   APInt MulAmtAbs = MulAmt.abs();
15316 
15317   if ((MulAmtAbs - 1).isPowerOf2()) {
15318     // (mul x, 2^N + 1) => (add (shl x, N), x)
15319     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
15320 
15321     if (!IsProfitable(IsNeg, true, VT))
15322       return SDValue();
15323 
15324     SDValue Op0 = N->getOperand(0);
15325     SDValue Op1 =
15326         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15327                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
15328     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
15329 
15330     if (!IsNeg)
15331       return Res;
15332 
15333     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
15334   } else if ((MulAmtAbs + 1).isPowerOf2()) {
15335     // (mul x, 2^N - 1) => (sub (shl x, N), x)
15336     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
15337 
15338     if (!IsProfitable(IsNeg, false, VT))
15339       return SDValue();
15340 
15341     SDValue Op0 = N->getOperand(0);
15342     SDValue Op1 =
15343         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15344                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
15345 
15346     if (!IsNeg)
15347       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
15348     else
15349       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
15350 
15351   } else {
15352     return SDValue();
15353   }
15354 }
15355 
15356 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
15357   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
15358   if (!Subtarget.is64BitELFABI())
15359     return false;
15360 
15361   // If not a tail call then no need to proceed.
15362   if (!CI->isTailCall())
15363     return false;
15364 
15365   // If tail calls are disabled for the caller then we are done.
15366   const Function *Caller = CI->getParent()->getParent();
15367   auto Attr = Caller->getFnAttribute("disable-tail-calls");
15368   if (Attr.getValueAsString() == "true")
15369     return false;
15370 
15371   // If sibling calls have been disabled and tail-calls aren't guaranteed
15372   // there is no reason to duplicate.
15373   auto &TM = getTargetMachine();
15374   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
15375     return false;
15376 
15377   // Can't tail call a function called indirectly, or if it has variadic args.
15378   const Function *Callee = CI->getCalledFunction();
15379   if (!Callee || Callee->isVarArg())
15380     return false;
15381 
15382   // Make sure the callee and caller calling conventions are eligible for tco.
15383   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
15384                                            CI->getCallingConv()))
15385       return false;
15386 
15387   // If the function is local then we have a good chance at tail-calling it
15388   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
15389 }
15390 
15391 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
15392   if (!Subtarget.hasVSX())
15393     return false;
15394   if (Subtarget.hasP9Vector() && VT == MVT::f128)
15395     return true;
15396   return VT == MVT::f32 || VT == MVT::f64 ||
15397     VT == MVT::v4f32 || VT == MVT::v2f64;
15398 }
15399 
15400 bool PPCTargetLowering::
15401 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
15402   const Value *Mask = AndI.getOperand(1);
15403   // If the mask is suitable for andi. or andis. we should sink the and.
15404   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
15405     // Can't handle constants wider than 64-bits.
15406     if (CI->getBitWidth() > 64)
15407       return false;
15408     int64_t ConstVal = CI->getZExtValue();
15409     return isUInt<16>(ConstVal) ||
15410       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
15411   }
15412 
15413   // For non-constant masks, we can always use the record-form and.
15414   return true;
15415 }
15416 
15417 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
15418 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
15419 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
15420 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
15421 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
15422 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
15423   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
15424   assert(Subtarget.hasP9Altivec() &&
15425          "Only combine this when P9 altivec supported!");
15426   EVT VT = N->getValueType(0);
15427   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15428     return SDValue();
15429 
15430   SelectionDAG &DAG = DCI.DAG;
15431   SDLoc dl(N);
15432   if (N->getOperand(0).getOpcode() == ISD::SUB) {
15433     // Even for signed integers, if it's known to be positive (as signed
15434     // integer) due to zero-extended inputs.
15435     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
15436     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
15437     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
15438          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
15439         (SubOpcd1 == ISD::ZERO_EXTEND ||
15440          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
15441       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15442                          N->getOperand(0)->getOperand(0),
15443                          N->getOperand(0)->getOperand(1),
15444                          DAG.getTargetConstant(0, dl, MVT::i32));
15445     }
15446 
15447     // For type v4i32, it can be optimized with xvnegsp + vabsduw
15448     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
15449         N->getOperand(0).hasOneUse()) {
15450       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15451                          N->getOperand(0)->getOperand(0),
15452                          N->getOperand(0)->getOperand(1),
15453                          DAG.getTargetConstant(1, dl, MVT::i32));
15454     }
15455   }
15456 
15457   return SDValue();
15458 }
15459 
15460 // For type v4i32/v8ii16/v16i8, transform
15461 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
15462 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
15463 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
15464 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
15465 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
15466                                           DAGCombinerInfo &DCI) const {
15467   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
15468   assert(Subtarget.hasP9Altivec() &&
15469          "Only combine this when P9 altivec supported!");
15470 
15471   SelectionDAG &DAG = DCI.DAG;
15472   SDLoc dl(N);
15473   SDValue Cond = N->getOperand(0);
15474   SDValue TrueOpnd = N->getOperand(1);
15475   SDValue FalseOpnd = N->getOperand(2);
15476   EVT VT = N->getOperand(1).getValueType();
15477 
15478   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
15479       FalseOpnd.getOpcode() != ISD::SUB)
15480     return SDValue();
15481 
15482   // ABSD only available for type v4i32/v8i16/v16i8
15483   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15484     return SDValue();
15485 
15486   // At least to save one more dependent computation
15487   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
15488     return SDValue();
15489 
15490   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15491 
15492   // Can only handle unsigned comparison here
15493   switch (CC) {
15494   default:
15495     return SDValue();
15496   case ISD::SETUGT:
15497   case ISD::SETUGE:
15498     break;
15499   case ISD::SETULT:
15500   case ISD::SETULE:
15501     std::swap(TrueOpnd, FalseOpnd);
15502     break;
15503   }
15504 
15505   SDValue CmpOpnd1 = Cond.getOperand(0);
15506   SDValue CmpOpnd2 = Cond.getOperand(1);
15507 
15508   // SETCC CmpOpnd1 CmpOpnd2 cond
15509   // TrueOpnd = CmpOpnd1 - CmpOpnd2
15510   // FalseOpnd = CmpOpnd2 - CmpOpnd1
15511   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
15512       TrueOpnd.getOperand(1) == CmpOpnd2 &&
15513       FalseOpnd.getOperand(0) == CmpOpnd2 &&
15514       FalseOpnd.getOperand(1) == CmpOpnd1) {
15515     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
15516                        CmpOpnd1, CmpOpnd2,
15517                        DAG.getTargetConstant(0, dl, MVT::i32));
15518   }
15519 
15520   return SDValue();
15521 }
15522