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/TargetLoweringObjectFileImpl.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.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/IntrinsicsPowerPC.h"
70 #include "llvm/IR/Module.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/Use.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/MC/MCContext.h"
75 #include "llvm/MC/MCExpr.h"
76 #include "llvm/MC/MCRegisterInfo.h"
77 #include "llvm/MC/MCSymbolXCOFF.h"
78 #include "llvm/Support/AtomicOrdering.h"
79 #include "llvm/Support/BranchProbability.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/CodeGen.h"
82 #include "llvm/Support/CommandLine.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/Debug.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/KnownBits.h"
88 #include "llvm/Support/MachineValueType.h"
89 #include "llvm/Support/MathExtras.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include "llvm/Target/TargetMachine.h"
92 #include "llvm/Target/TargetOptions.h"
93 #include <algorithm>
94 #include <cassert>
95 #include <cstdint>
96 #include <iterator>
97 #include <list>
98 #include <utility>
99 #include <vector>
100 
101 using namespace llvm;
102 
103 #define DEBUG_TYPE "ppc-lowering"
104 
105 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
106 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
107 
108 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
109 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
110 
111 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
112 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
113 
114 static cl::opt<bool> DisableSCO("disable-ppc-sco",
115 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
116 
117 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
118 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
119 
120 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
121 cl::desc("enable quad precision float support on ppc"), cl::Hidden);
122 
123 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
124 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
125 
126 STATISTIC(NumTailCalls, "Number of tail calls");
127 STATISTIC(NumSiblingCalls, "Number of sibling calls");
128 
129 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
130 
131 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
132 
133 // FIXME: Remove this once the bug has been fixed!
134 extern cl::opt<bool> ANDIGlueBug;
135 
136 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
137                                      const PPCSubtarget &STI)
138     : TargetLowering(TM), Subtarget(STI) {
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   if (Subtarget.isISA3_0()) {
170     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
171     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
172     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
173     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
174   } else {
175     // No extending loads from f16 or HW conversions back and forth.
176     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
177     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
178     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
179     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
180     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
181     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
182     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
183     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
184   }
185 
186   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
187 
188   // PowerPC has pre-inc load and store's.
189   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
190   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
191   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
192   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
193   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
194   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
195   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
196   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
197   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
198   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
199   if (!Subtarget.hasSPE()) {
200     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
201     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
202     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
203     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
204   }
205 
206   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
207   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
208   for (MVT VT : ScalarIntVTs) {
209     setOperationAction(ISD::ADDC, VT, Legal);
210     setOperationAction(ISD::ADDE, VT, Legal);
211     setOperationAction(ISD::SUBC, VT, Legal);
212     setOperationAction(ISD::SUBE, VT, Legal);
213   }
214 
215   if (Subtarget.useCRBits()) {
216     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
217 
218     if (isPPC64 || Subtarget.hasFPCVT()) {
219       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
220       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
221                          isPPC64 ? MVT::i64 : MVT::i32);
222       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
223       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
224                         isPPC64 ? MVT::i64 : MVT::i32);
225     } else {
226       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
227       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
228     }
229 
230     // PowerPC does not support direct load/store of condition registers.
231     setOperationAction(ISD::LOAD, MVT::i1, Custom);
232     setOperationAction(ISD::STORE, MVT::i1, Custom);
233 
234     // FIXME: Remove this once the ANDI glue bug is fixed:
235     if (ANDIGlueBug)
236       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
237 
238     for (MVT VT : MVT::integer_valuetypes()) {
239       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
240       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
241       setTruncStoreAction(VT, MVT::i1, Expand);
242     }
243 
244     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
245   }
246 
247   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
248   // PPC (the libcall is not available).
249   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
250   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
251 
252   // We do not currently implement these libm ops for PowerPC.
253   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
254   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
255   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
256   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
257   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
258   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
259 
260   // PowerPC has no SREM/UREM instructions unless we are on P9
261   // On P9 we may use a hardware instruction to compute the remainder.
262   // The instructions are not legalized directly because in the cases where the
263   // result of both the remainder and the division is required it is more
264   // efficient to compute the remainder from the result of the division rather
265   // than use the remainder instruction.
266   if (Subtarget.isISA3_0()) {
267     setOperationAction(ISD::SREM, MVT::i32, Custom);
268     setOperationAction(ISD::UREM, MVT::i32, Custom);
269     setOperationAction(ISD::SREM, MVT::i64, Custom);
270     setOperationAction(ISD::UREM, MVT::i64, Custom);
271   } else {
272     setOperationAction(ISD::SREM, MVT::i32, Expand);
273     setOperationAction(ISD::UREM, MVT::i32, Expand);
274     setOperationAction(ISD::SREM, MVT::i64, Expand);
275     setOperationAction(ISD::UREM, MVT::i64, Expand);
276   }
277 
278   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
279   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
280   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
281   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
282   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
283   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
284   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
285   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
286   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
287 
288   // Handle constrained floating-point operations of scalar.
289   // TODO: Handle SPE specific operation.
290   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
291   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
292   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
293   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
294   setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
295   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
296 
297   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
298   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
299   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
300   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
301   setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
302   if (Subtarget.hasVSX())
303     setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f64, Legal);
304 
305   if (Subtarget.hasFSQRT()) {
306     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
307     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
308   }
309 
310   if (Subtarget.hasFPRND()) {
311     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
312     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
313     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
314     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
315 
316     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
317     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
318     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
319     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
320   }
321 
322   // We don't support sin/cos/sqrt/fmod/pow
323   setOperationAction(ISD::FSIN , MVT::f64, Expand);
324   setOperationAction(ISD::FCOS , MVT::f64, Expand);
325   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
326   setOperationAction(ISD::FREM , MVT::f64, Expand);
327   setOperationAction(ISD::FPOW , MVT::f64, Expand);
328   setOperationAction(ISD::FSIN , MVT::f32, Expand);
329   setOperationAction(ISD::FCOS , MVT::f32, Expand);
330   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
331   setOperationAction(ISD::FREM , MVT::f32, Expand);
332   setOperationAction(ISD::FPOW , MVT::f32, Expand);
333   if (Subtarget.hasSPE()) {
334     setOperationAction(ISD::FMA  , MVT::f64, Expand);
335     setOperationAction(ISD::FMA  , MVT::f32, Expand);
336   } else {
337     setOperationAction(ISD::FMA  , MVT::f64, Legal);
338     setOperationAction(ISD::FMA  , MVT::f32, Legal);
339   }
340 
341   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
342 
343   // If we're enabling GP optimizations, use hardware square root
344   if (!Subtarget.hasFSQRT() &&
345       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
346         Subtarget.hasFRE()))
347     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
348 
349   if (!Subtarget.hasFSQRT() &&
350       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
351         Subtarget.hasFRES()))
352     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
353 
354   if (Subtarget.hasFCPSGN()) {
355     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
356     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
357   } else {
358     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
359     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
360   }
361 
362   if (Subtarget.hasFPRND()) {
363     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
364     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
365     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
366     setOperationAction(ISD::FROUND, MVT::f64, Legal);
367 
368     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
369     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
370     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
371     setOperationAction(ISD::FROUND, MVT::f32, Legal);
372   }
373 
374   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
375   // to speed up scalar BSWAP64.
376   // CTPOP or CTTZ were introduced in P8/P9 respectively
377   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
378   if (Subtarget.hasP9Vector())
379     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
380   else
381     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
382   if (Subtarget.isISA3_0()) {
383     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
384     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
385   } else {
386     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
387     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
388   }
389 
390   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
391     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
392     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
393   } else {
394     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
395     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
396   }
397 
398   // PowerPC does not have ROTR
399   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
400   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
401 
402   if (!Subtarget.useCRBits()) {
403     // PowerPC does not have Select
404     setOperationAction(ISD::SELECT, MVT::i32, Expand);
405     setOperationAction(ISD::SELECT, MVT::i64, Expand);
406     setOperationAction(ISD::SELECT, MVT::f32, Expand);
407     setOperationAction(ISD::SELECT, MVT::f64, Expand);
408   }
409 
410   // PowerPC wants to turn select_cc of FP into fsel when possible.
411   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
412   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
413 
414   // PowerPC wants to optimize integer setcc a bit
415   if (!Subtarget.useCRBits())
416     setOperationAction(ISD::SETCC, MVT::i32, Custom);
417 
418   // PowerPC does not have BRCOND which requires SetCC
419   if (!Subtarget.useCRBits())
420     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
421 
422   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
423 
424   if (Subtarget.hasSPE()) {
425     // SPE has built-in conversions
426     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
427     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
428     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
429   } else {
430     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
431     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
432 
433     // PowerPC does not have [U|S]INT_TO_FP
434     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
435     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
436   }
437 
438   if (Subtarget.hasDirectMove() && isPPC64) {
439     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
440     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
441     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
442     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
443     if (TM.Options.UnsafeFPMath) {
444       setOperationAction(ISD::LRINT, MVT::f64, Legal);
445       setOperationAction(ISD::LRINT, MVT::f32, Legal);
446       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
447       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
448       setOperationAction(ISD::LROUND, MVT::f64, Legal);
449       setOperationAction(ISD::LROUND, MVT::f32, Legal);
450       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
451       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
452     }
453   } else {
454     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
455     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
456     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
457     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
458   }
459 
460   // We cannot sextinreg(i1).  Expand to shifts.
461   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
462 
463   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
464   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
465   // support continuation, user-level threading, and etc.. As a result, no
466   // other SjLj exception interfaces are implemented and please don't build
467   // your own exception handling based on them.
468   // LLVM/Clang supports zero-cost DWARF exception handling.
469   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
470   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
471 
472   // We want to legalize GlobalAddress and ConstantPool nodes into the
473   // appropriate instructions to materialize the address.
474   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
475   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
476   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
477   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
478   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
479   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
480   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
481   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
482   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
483   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
484 
485   // TRAP is legal.
486   setOperationAction(ISD::TRAP, MVT::Other, Legal);
487 
488   // TRAMPOLINE is custom lowered.
489   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
490   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
491 
492   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
493   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
494 
495   if (Subtarget.is64BitELFABI()) {
496     // VAARG always uses double-word chunks, so promote anything smaller.
497     setOperationAction(ISD::VAARG, MVT::i1, Promote);
498     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
499     setOperationAction(ISD::VAARG, MVT::i8, Promote);
500     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
501     setOperationAction(ISD::VAARG, MVT::i16, Promote);
502     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
503     setOperationAction(ISD::VAARG, MVT::i32, Promote);
504     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
505     setOperationAction(ISD::VAARG, MVT::Other, Expand);
506   } else if (Subtarget.is32BitELFABI()) {
507     // VAARG is custom lowered with the 32-bit SVR4 ABI.
508     setOperationAction(ISD::VAARG, MVT::Other, Custom);
509     setOperationAction(ISD::VAARG, MVT::i64, Custom);
510   } else
511     setOperationAction(ISD::VAARG, MVT::Other, Expand);
512 
513   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
514   if (Subtarget.is32BitELFABI())
515     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
516   else
517     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
518 
519   // Use the default implementation.
520   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
521   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
522   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
523   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
524   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
525   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
526   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
527   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
528   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
529 
530   // We want to custom lower some of our intrinsics.
531   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
532 
533   // To handle counter-based loop conditions.
534   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
535 
536   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
537   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
538   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
539   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
540 
541   // Comparisons that require checking two conditions.
542   if (Subtarget.hasSPE()) {
543     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
544     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
545     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
546     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
547   }
548   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
549   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
550   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
551   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
552   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
553   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
554   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
555   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
556   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
557   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
558   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
559   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
560 
561   if (Subtarget.has64BitSupport()) {
562     // They also have instructions for converting between i64 and fp.
563     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
564     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
565     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
566     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
567     // This is just the low 32 bits of a (signed) fp->i64 conversion.
568     // We cannot do this with Promote because i64 is not a legal type.
569     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
570 
571     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
572       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
573   } else {
574     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
575     if (Subtarget.hasSPE())
576       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
577     else
578       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
579   }
580 
581   // With the instructions enabled under FPCVT, we can do everything.
582   if (Subtarget.hasFPCVT()) {
583     if (Subtarget.has64BitSupport()) {
584       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
585       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
586       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
587       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
588     }
589 
590     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
591     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
592     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
593     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
594   }
595 
596   if (Subtarget.use64BitRegs()) {
597     // 64-bit PowerPC implementations can support i64 types directly
598     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
599     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
600     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
601     // 64-bit PowerPC wants to expand i128 shifts itself.
602     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
603     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
604     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
605   } else {
606     // 32-bit PowerPC wants to expand i64 shifts itself.
607     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
608     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
609     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
610   }
611 
612   if (Subtarget.hasVSX()) {
613     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
614     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
615     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
616     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
617   }
618 
619   if (Subtarget.hasAltivec()) {
620     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
621       setOperationAction(ISD::SADDSAT, VT, Legal);
622       setOperationAction(ISD::SSUBSAT, VT, Legal);
623       setOperationAction(ISD::UADDSAT, VT, Legal);
624       setOperationAction(ISD::USUBSAT, VT, Legal);
625     }
626     // First set operation action for all vector types to expand. Then we
627     // will selectively turn on ones that can be effectively codegen'd.
628     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
629       // add/sub are legal for all supported vector VT's.
630       setOperationAction(ISD::ADD, VT, Legal);
631       setOperationAction(ISD::SUB, VT, Legal);
632 
633       // For v2i64, these are only valid with P8Vector. This is corrected after
634       // the loop.
635       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
636         setOperationAction(ISD::SMAX, VT, Legal);
637         setOperationAction(ISD::SMIN, VT, Legal);
638         setOperationAction(ISD::UMAX, VT, Legal);
639         setOperationAction(ISD::UMIN, VT, Legal);
640       }
641       else {
642         setOperationAction(ISD::SMAX, VT, Expand);
643         setOperationAction(ISD::SMIN, VT, Expand);
644         setOperationAction(ISD::UMAX, VT, Expand);
645         setOperationAction(ISD::UMIN, VT, Expand);
646       }
647 
648       if (Subtarget.hasVSX()) {
649         setOperationAction(ISD::FMAXNUM, VT, Legal);
650         setOperationAction(ISD::FMINNUM, VT, Legal);
651       }
652 
653       // Vector instructions introduced in P8
654       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
655         setOperationAction(ISD::CTPOP, VT, Legal);
656         setOperationAction(ISD::CTLZ, VT, Legal);
657       }
658       else {
659         setOperationAction(ISD::CTPOP, VT, Expand);
660         setOperationAction(ISD::CTLZ, VT, Expand);
661       }
662 
663       // Vector instructions introduced in P9
664       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
665         setOperationAction(ISD::CTTZ, VT, Legal);
666       else
667         setOperationAction(ISD::CTTZ, VT, Expand);
668 
669       // We promote all shuffles to v16i8.
670       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
671       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
672 
673       // We promote all non-typed operations to v4i32.
674       setOperationAction(ISD::AND   , VT, Promote);
675       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
676       setOperationAction(ISD::OR    , VT, Promote);
677       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
678       setOperationAction(ISD::XOR   , VT, Promote);
679       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
680       setOperationAction(ISD::LOAD  , VT, Promote);
681       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
682       setOperationAction(ISD::SELECT, VT, Promote);
683       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
684       setOperationAction(ISD::VSELECT, VT, Legal);
685       setOperationAction(ISD::SELECT_CC, VT, Promote);
686       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
687       setOperationAction(ISD::STORE, VT, Promote);
688       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
689 
690       // No other operations are legal.
691       setOperationAction(ISD::MUL , VT, Expand);
692       setOperationAction(ISD::SDIV, VT, Expand);
693       setOperationAction(ISD::SREM, VT, Expand);
694       setOperationAction(ISD::UDIV, VT, Expand);
695       setOperationAction(ISD::UREM, VT, Expand);
696       setOperationAction(ISD::FDIV, VT, Expand);
697       setOperationAction(ISD::FREM, VT, Expand);
698       setOperationAction(ISD::FNEG, VT, Expand);
699       setOperationAction(ISD::FSQRT, VT, Expand);
700       setOperationAction(ISD::FLOG, VT, Expand);
701       setOperationAction(ISD::FLOG10, VT, Expand);
702       setOperationAction(ISD::FLOG2, VT, Expand);
703       setOperationAction(ISD::FEXP, VT, Expand);
704       setOperationAction(ISD::FEXP2, VT, Expand);
705       setOperationAction(ISD::FSIN, VT, Expand);
706       setOperationAction(ISD::FCOS, VT, Expand);
707       setOperationAction(ISD::FABS, VT, Expand);
708       setOperationAction(ISD::FFLOOR, VT, Expand);
709       setOperationAction(ISD::FCEIL,  VT, Expand);
710       setOperationAction(ISD::FTRUNC, VT, Expand);
711       setOperationAction(ISD::FRINT,  VT, Expand);
712       setOperationAction(ISD::FNEARBYINT, VT, Expand);
713       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
714       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
715       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
716       setOperationAction(ISD::MULHU, VT, Expand);
717       setOperationAction(ISD::MULHS, VT, Expand);
718       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
719       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
720       setOperationAction(ISD::UDIVREM, VT, Expand);
721       setOperationAction(ISD::SDIVREM, VT, Expand);
722       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
723       setOperationAction(ISD::FPOW, VT, Expand);
724       setOperationAction(ISD::BSWAP, VT, Expand);
725       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
726       setOperationAction(ISD::ROTL, VT, Expand);
727       setOperationAction(ISD::ROTR, VT, Expand);
728 
729       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
730         setTruncStoreAction(VT, InnerVT, Expand);
731         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
732         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
733         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
734       }
735     }
736     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
737     if (!Subtarget.hasP8Vector()) {
738       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
739       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
740       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
741       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
742     }
743 
744     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
745       setOperationAction(ISD::ABS, VT, Custom);
746 
747     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
748     // with merges, splats, etc.
749     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
750 
751     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
752     // are cheap, so handle them before they get expanded to scalar.
753     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
754     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
755     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
756     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
757     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
758 
759     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
760     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
761     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
762     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
763     setOperationAction(ISD::SELECT, MVT::v4i32,
764                        Subtarget.useCRBits() ? Legal : Expand);
765     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
766     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
767     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
768     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
769     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
770     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
771     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
772     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
773     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
774 
775     // Without hasP8Altivec set, v2i64 SMAX isn't available.
776     // But ABS custom lowering requires SMAX support.
777     if (!Subtarget.hasP8Altivec())
778       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
779 
780     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
781     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
782     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
783     if (Subtarget.hasAltivec())
784       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
785         setOperationAction(ISD::ROTL, VT, Legal);
786     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
787     if (Subtarget.hasP8Altivec())
788       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
789 
790     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
791     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
792     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
793     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
794 
795     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
796     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
797 
798     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
799       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
800       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
801     }
802 
803     if (Subtarget.hasP8Altivec())
804       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
805     else
806       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
807 
808     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
809     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
810 
811     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
812     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
813 
814     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
815     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
816     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
817     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
818 
819     // Altivec does not contain unordered floating-point compare instructions
820     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
821     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
822     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
823     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
824 
825     if (Subtarget.hasVSX()) {
826       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
827       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
828       if (Subtarget.hasP8Vector()) {
829         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
830         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
831       }
832       if (Subtarget.hasDirectMove() && isPPC64) {
833         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
834         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
835         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
836         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
837         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
838         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
839         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
840         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
841       }
842       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
843 
844       // The nearbyint variants are not allowed to raise the inexact exception
845       // so we can only code-gen them with unsafe math.
846       if (TM.Options.UnsafeFPMath) {
847         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
848         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
849       }
850 
851       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
852       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
853       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
854       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
855       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
856       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
857       setOperationAction(ISD::FROUND, MVT::f64, Legal);
858       setOperationAction(ISD::FRINT, MVT::f64, Legal);
859 
860       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
861       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
862       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
863       setOperationAction(ISD::FROUND, MVT::f32, Legal);
864       setOperationAction(ISD::FRINT, MVT::f32, Legal);
865 
866       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
867       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
868 
869       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
870       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
871 
872       // Share the Altivec comparison restrictions.
873       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
874       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
875       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
876       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
877 
878       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
879       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
880 
881       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
882 
883       if (Subtarget.hasP8Vector())
884         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
885 
886       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
887 
888       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
889       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
890       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
891 
892       if (Subtarget.hasP8Altivec()) {
893         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
894         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
895         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
896 
897         // 128 bit shifts can be accomplished via 3 instructions for SHL and
898         // SRL, but not for SRA because of the instructions available:
899         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
900         // doing
901         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
902         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
903         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
904 
905         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
906       }
907       else {
908         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
909         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
910         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
911 
912         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
913 
914         // VSX v2i64 only supports non-arithmetic operations.
915         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
916         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
917       }
918 
919       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
920       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
921       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
922       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
923 
924       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
925 
926       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
927       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
928       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
929       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
930 
931       // Custom handling for partial vectors of integers converted to
932       // floating point. We already have optimal handling for v2i32 through
933       // the DAG combine, so those aren't necessary.
934       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
935       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
936       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
937       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
938       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
939       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
940       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
941       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
942 
943       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
944       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
945       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
946       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
947       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
948       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
949 
950       if (Subtarget.hasDirectMove())
951         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
952       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
953 
954       // Handle constrained floating-point operations of vector.
955       // The predictor is `hasVSX` because altivec instruction has
956       // no exception but VSX vector instruction has.
957       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
958       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
959       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
960       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
961       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
962       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
963       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
964       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
965       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal);
966       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
967       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
968       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
969       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
970 
971       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
972       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
973       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
974       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
975       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
976       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
977       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
978       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
979       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal);
980       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
981       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
982       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
983       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
984 
985       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
986     }
987 
988     if (Subtarget.hasP8Altivec()) {
989       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
990       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
991     }
992 
993     if (Subtarget.hasP9Vector()) {
994       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
995       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
996 
997       // 128 bit shifts can be accomplished via 3 instructions for SHL and
998       // SRL, but not for SRA because of the instructions available:
999       // VS{RL} and VS{RL}O.
1000       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1001       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1002       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1003 
1004       if (EnableQuadPrecision) {
1005         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1006         setOperationAction(ISD::FADD, MVT::f128, Legal);
1007         setOperationAction(ISD::FSUB, MVT::f128, Legal);
1008         setOperationAction(ISD::FDIV, MVT::f128, Legal);
1009         setOperationAction(ISD::FMUL, MVT::f128, Legal);
1010         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1011         // No extending loads to f128 on PPC.
1012         for (MVT FPT : MVT::fp_valuetypes())
1013           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1014         setOperationAction(ISD::FMA, MVT::f128, Legal);
1015         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1016         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1017         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1018         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1019         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1020         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1021 
1022         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1023         setOperationAction(ISD::FRINT, MVT::f128, Legal);
1024         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1025         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1026         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1027         setOperationAction(ISD::FROUND, MVT::f128, Legal);
1028 
1029         setOperationAction(ISD::SELECT, MVT::f128, Expand);
1030         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1031         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1032         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1033         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1034         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1035         // No implementation for these ops for PowerPC.
1036         setOperationAction(ISD::FSIN , MVT::f128, Expand);
1037         setOperationAction(ISD::FCOS , MVT::f128, Expand);
1038         setOperationAction(ISD::FPOW, MVT::f128, Expand);
1039         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1040         setOperationAction(ISD::FREM, MVT::f128, Expand);
1041 
1042         // Handle constrained floating-point operations of fp128
1043         setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1044         setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1045         setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1046         setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1047         setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1048         setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1049         setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1050         setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1051         setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1052         setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1053         setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1054         setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1055         setOperationAction(ISD::STRICT_FCEIL,  MVT::f128, Legal);
1056         setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1057         setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1058       }
1059       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1060       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1061       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1062       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1063       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1064     }
1065 
1066     if (Subtarget.hasP9Altivec()) {
1067       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1068       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1069 
1070       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1071       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1072       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1073       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1074       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1075       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1076       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1077     }
1078   }
1079 
1080   if (Subtarget.hasQPX()) {
1081     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1082     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1083     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1084     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
1085 
1086     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
1087     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
1088 
1089     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
1090     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
1091 
1092     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
1093     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
1094 
1095     if (!Subtarget.useCRBits())
1096       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
1097     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1098 
1099     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
1100     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
1101     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
1102     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
1103     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
1104     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
1105     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
1106 
1107     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
1108     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
1109 
1110     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
1111     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
1112 
1113     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
1114     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
1115     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
1116     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
1117     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
1118     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
1119     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
1120     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
1121     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
1122     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
1123 
1124     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
1125     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
1126 
1127     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
1128     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
1129 
1130     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
1131 
1132     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
1133     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
1134     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
1135     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
1136 
1137     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1138     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
1139 
1140     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
1141     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
1142 
1143     if (!Subtarget.useCRBits())
1144       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
1145     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1146 
1147     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
1148     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
1149     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
1150     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
1151     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
1152     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
1153     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
1154 
1155     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
1156     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
1157 
1158     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
1159     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
1160     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
1161     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
1162     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
1163     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
1164     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
1165     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
1166     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
1167     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1168 
1169     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1170     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1171 
1172     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1173     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1174 
1175     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1176 
1177     setOperationAction(ISD::AND , MVT::v4i1, Legal);
1178     setOperationAction(ISD::OR , MVT::v4i1, Legal);
1179     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1180 
1181     if (!Subtarget.useCRBits())
1182       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1183     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1184 
1185     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
1186     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1187 
1188     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1189     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1190     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1191     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1192     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1193     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1194     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1195 
1196     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1197     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1198 
1199     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1200 
1201     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1202     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1203     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1204     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1205 
1206     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1207     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1208     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1209     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1210 
1211     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1212     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1213 
1214     // These need to set FE_INEXACT, and so cannot be vectorized here.
1215     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1216     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1217 
1218     if (TM.Options.UnsafeFPMath) {
1219       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1220       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1221 
1222       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1223       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1224     } else {
1225       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1226       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1227 
1228       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1229       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1230     }
1231 
1232     // TODO: Handle constrained floating-point operations of v4f64
1233   }
1234 
1235   if (Subtarget.has64BitSupport())
1236     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1237 
1238   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1239 
1240   if (!isPPC64) {
1241     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1242     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1243   }
1244 
1245   setBooleanContents(ZeroOrOneBooleanContent);
1246 
1247   if (Subtarget.hasAltivec()) {
1248     // Altivec instructions set fields to all zeros or all ones.
1249     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1250   }
1251 
1252   if (!isPPC64) {
1253     // These libcalls are not available in 32-bit.
1254     setLibcallName(RTLIB::SHL_I128, nullptr);
1255     setLibcallName(RTLIB::SRL_I128, nullptr);
1256     setLibcallName(RTLIB::SRA_I128, nullptr);
1257   }
1258 
1259   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1260 
1261   // We have target-specific dag combine patterns for the following nodes:
1262   setTargetDAGCombine(ISD::ADD);
1263   setTargetDAGCombine(ISD::SHL);
1264   setTargetDAGCombine(ISD::SRA);
1265   setTargetDAGCombine(ISD::SRL);
1266   setTargetDAGCombine(ISD::MUL);
1267   setTargetDAGCombine(ISD::FMA);
1268   setTargetDAGCombine(ISD::SINT_TO_FP);
1269   setTargetDAGCombine(ISD::BUILD_VECTOR);
1270   if (Subtarget.hasFPCVT())
1271     setTargetDAGCombine(ISD::UINT_TO_FP);
1272   setTargetDAGCombine(ISD::LOAD);
1273   setTargetDAGCombine(ISD::STORE);
1274   setTargetDAGCombine(ISD::BR_CC);
1275   if (Subtarget.useCRBits())
1276     setTargetDAGCombine(ISD::BRCOND);
1277   setTargetDAGCombine(ISD::BSWAP);
1278   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1279   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1280   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1281 
1282   setTargetDAGCombine(ISD::SIGN_EXTEND);
1283   setTargetDAGCombine(ISD::ZERO_EXTEND);
1284   setTargetDAGCombine(ISD::ANY_EXTEND);
1285 
1286   setTargetDAGCombine(ISD::TRUNCATE);
1287   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1288 
1289 
1290   if (Subtarget.useCRBits()) {
1291     setTargetDAGCombine(ISD::TRUNCATE);
1292     setTargetDAGCombine(ISD::SETCC);
1293     setTargetDAGCombine(ISD::SELECT_CC);
1294   }
1295 
1296   // Use reciprocal estimates.
1297   if (TM.Options.UnsafeFPMath) {
1298     setTargetDAGCombine(ISD::FDIV);
1299     setTargetDAGCombine(ISD::FSQRT);
1300   }
1301 
1302   if (Subtarget.hasP9Altivec()) {
1303     setTargetDAGCombine(ISD::ABS);
1304     setTargetDAGCombine(ISD::VSELECT);
1305   }
1306 
1307   if (EnableQuadPrecision) {
1308     setLibcallName(RTLIB::LOG_F128, "logf128");
1309     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1310     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1311     setLibcallName(RTLIB::EXP_F128, "expf128");
1312     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1313     setLibcallName(RTLIB::SIN_F128, "sinf128");
1314     setLibcallName(RTLIB::COS_F128, "cosf128");
1315     setLibcallName(RTLIB::POW_F128, "powf128");
1316     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1317     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1318     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1319     setLibcallName(RTLIB::REM_F128, "fmodf128");
1320   }
1321 
1322   // With 32 condition bits, we don't need to sink (and duplicate) compares
1323   // aggressively in CodeGenPrep.
1324   if (Subtarget.useCRBits()) {
1325     setHasMultipleConditionRegisters();
1326     setJumpIsExpensive();
1327   }
1328 
1329   setMinFunctionAlignment(Align(4));
1330 
1331   switch (Subtarget.getCPUDirective()) {
1332   default: break;
1333   case PPC::DIR_970:
1334   case PPC::DIR_A2:
1335   case PPC::DIR_E500:
1336   case PPC::DIR_E500mc:
1337   case PPC::DIR_E5500:
1338   case PPC::DIR_PWR4:
1339   case PPC::DIR_PWR5:
1340   case PPC::DIR_PWR5X:
1341   case PPC::DIR_PWR6:
1342   case PPC::DIR_PWR6X:
1343   case PPC::DIR_PWR7:
1344   case PPC::DIR_PWR8:
1345   case PPC::DIR_PWR9:
1346   case PPC::DIR_PWR10:
1347   case PPC::DIR_PWR_FUTURE:
1348     setPrefLoopAlignment(Align(16));
1349     setPrefFunctionAlignment(Align(16));
1350     break;
1351   }
1352 
1353   if (Subtarget.enableMachineScheduler())
1354     setSchedulingPreference(Sched::Source);
1355   else
1356     setSchedulingPreference(Sched::Hybrid);
1357 
1358   computeRegisterProperties(STI.getRegisterInfo());
1359 
1360   // The Freescale cores do better with aggressive inlining of memcpy and
1361   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1362   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1363       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1364     MaxStoresPerMemset = 32;
1365     MaxStoresPerMemsetOptSize = 16;
1366     MaxStoresPerMemcpy = 32;
1367     MaxStoresPerMemcpyOptSize = 8;
1368     MaxStoresPerMemmove = 32;
1369     MaxStoresPerMemmoveOptSize = 8;
1370   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1371     // The A2 also benefits from (very) aggressive inlining of memcpy and
1372     // friends. The overhead of a the function call, even when warm, can be
1373     // over one hundred cycles.
1374     MaxStoresPerMemset = 128;
1375     MaxStoresPerMemcpy = 128;
1376     MaxStoresPerMemmove = 128;
1377     MaxLoadsPerMemcmp = 128;
1378   } else {
1379     MaxLoadsPerMemcmp = 8;
1380     MaxLoadsPerMemcmpOptSize = 4;
1381   }
1382 
1383   // Let the subtarget (CPU) decide if a predictable select is more expensive
1384   // than the corresponding branch. This information is used in CGP to decide
1385   // when to convert selects into branches.
1386   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1387 }
1388 
1389 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1390 /// the desired ByVal argument alignment.
1391 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1392                              unsigned MaxMaxAlign) {
1393   if (MaxAlign == MaxMaxAlign)
1394     return;
1395   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1396     if (MaxMaxAlign >= 32 &&
1397         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1398       MaxAlign = 32;
1399     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1400              MaxAlign < 16)
1401       MaxAlign = 16;
1402   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1403     unsigned EltAlign = 0;
1404     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1405     if (EltAlign > MaxAlign)
1406       MaxAlign = EltAlign;
1407   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1408     for (auto *EltTy : STy->elements()) {
1409       unsigned EltAlign = 0;
1410       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1411       if (EltAlign > MaxAlign)
1412         MaxAlign = EltAlign;
1413       if (MaxAlign == MaxMaxAlign)
1414         break;
1415     }
1416   }
1417 }
1418 
1419 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1420 /// function arguments in the caller parameter area.
1421 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1422                                                   const DataLayout &DL) const {
1423   // 16byte and wider vectors are passed on 16byte boundary.
1424   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1425   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1426   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1427     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1428   return Align;
1429 }
1430 
1431 bool PPCTargetLowering::useSoftFloat() const {
1432   return Subtarget.useSoftFloat();
1433 }
1434 
1435 bool PPCTargetLowering::hasSPE() const {
1436   return Subtarget.hasSPE();
1437 }
1438 
1439 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1440   return VT.isScalarInteger();
1441 }
1442 
1443 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific
1444 /// type is cheaper than a multiply followed by a shift.
1445 /// This is true for words and doublewords on 64-bit PowerPC.
1446 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const {
1447   if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) ||
1448                               isOperationLegal(ISD::MULHU, Type)))
1449     return true;
1450   return TargetLowering::isMulhCheaperThanMulShift(Type);
1451 }
1452 
1453 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1454   switch ((PPCISD::NodeType)Opcode) {
1455   case PPCISD::FIRST_NUMBER:    break;
1456   case PPCISD::FSEL:            return "PPCISD::FSEL";
1457   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1458   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1459   case PPCISD::FCFID:           return "PPCISD::FCFID";
1460   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1461   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1462   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1463   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1464   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1465   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1466   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1467   case PPCISD::FP_TO_UINT_IN_VSR:
1468                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1469   case PPCISD::FP_TO_SINT_IN_VSR:
1470                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1471   case PPCISD::FRE:             return "PPCISD::FRE";
1472   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1473   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1474   case PPCISD::VPERM:           return "PPCISD::VPERM";
1475   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1476   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1477   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1478   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1479   case PPCISD::CMPB:            return "PPCISD::CMPB";
1480   case PPCISD::Hi:              return "PPCISD::Hi";
1481   case PPCISD::Lo:              return "PPCISD::Lo";
1482   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1483   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1484   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1485   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1486   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1487   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1488   case PPCISD::SRL:             return "PPCISD::SRL";
1489   case PPCISD::SRA:             return "PPCISD::SRA";
1490   case PPCISD::SHL:             return "PPCISD::SHL";
1491   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1492   case PPCISD::CALL:            return "PPCISD::CALL";
1493   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1494   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1495   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1496   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1497   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1498   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1499   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1500   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1501   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1502   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1503   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1504   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1505   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1506   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1507   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1508   case PPCISD::ANDI_rec_1_EQ_BIT:
1509     return "PPCISD::ANDI_rec_1_EQ_BIT";
1510   case PPCISD::ANDI_rec_1_GT_BIT:
1511     return "PPCISD::ANDI_rec_1_GT_BIT";
1512   case PPCISD::VCMP:            return "PPCISD::VCMP";
1513   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1514   case PPCISD::LBRX:            return "PPCISD::LBRX";
1515   case PPCISD::STBRX:           return "PPCISD::STBRX";
1516   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1517   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1518   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1519   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1520   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1521   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1522   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1523   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1524   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1525   case PPCISD::ST_VSR_SCAL_INT:
1526                                 return "PPCISD::ST_VSR_SCAL_INT";
1527   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1528   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1529   case PPCISD::BDZ:             return "PPCISD::BDZ";
1530   case PPCISD::MFFS:            return "PPCISD::MFFS";
1531   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1532   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1533   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1534   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1535   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1536   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1537   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1538   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1539   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1540   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1541   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1542   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1543   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1544   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1545   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1546   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1547   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1548   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1549   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1550   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1551   case PPCISD::SC:              return "PPCISD::SC";
1552   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1553   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1554   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1555   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1556   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1557   case PPCISD::VABSD:           return "PPCISD::VABSD";
1558   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1559   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1560   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1561   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1562   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1563   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1564   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1565   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1566   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1567   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1568   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1569   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1570   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1571   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1572   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1573   }
1574   return nullptr;
1575 }
1576 
1577 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1578                                           EVT VT) const {
1579   if (!VT.isVector())
1580     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1581 
1582   if (Subtarget.hasQPX())
1583     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1584 
1585   return VT.changeVectorElementTypeToInteger();
1586 }
1587 
1588 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1589   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1590   return true;
1591 }
1592 
1593 //===----------------------------------------------------------------------===//
1594 // Node matching predicates, for use by the tblgen matching code.
1595 //===----------------------------------------------------------------------===//
1596 
1597 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1598 static bool isFloatingPointZero(SDValue Op) {
1599   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1600     return CFP->getValueAPF().isZero();
1601   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1602     // Maybe this has already been legalized into the constant pool?
1603     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1604       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1605         return CFP->getValueAPF().isZero();
1606   }
1607   return false;
1608 }
1609 
1610 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1611 /// true if Op is undef or if it matches the specified value.
1612 static bool isConstantOrUndef(int Op, int Val) {
1613   return Op < 0 || Op == Val;
1614 }
1615 
1616 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1617 /// VPKUHUM instruction.
1618 /// The ShuffleKind distinguishes between big-endian operations with
1619 /// two different inputs (0), either-endian operations with two identical
1620 /// inputs (1), and little-endian operations with two different inputs (2).
1621 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1622 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1623                                SelectionDAG &DAG) {
1624   bool IsLE = DAG.getDataLayout().isLittleEndian();
1625   if (ShuffleKind == 0) {
1626     if (IsLE)
1627       return false;
1628     for (unsigned i = 0; i != 16; ++i)
1629       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1630         return false;
1631   } else if (ShuffleKind == 2) {
1632     if (!IsLE)
1633       return false;
1634     for (unsigned i = 0; i != 16; ++i)
1635       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1636         return false;
1637   } else if (ShuffleKind == 1) {
1638     unsigned j = IsLE ? 0 : 1;
1639     for (unsigned i = 0; i != 8; ++i)
1640       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1641           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1642         return false;
1643   }
1644   return true;
1645 }
1646 
1647 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1648 /// VPKUWUM instruction.
1649 /// The ShuffleKind distinguishes between big-endian operations with
1650 /// two different inputs (0), either-endian operations with two identical
1651 /// inputs (1), and little-endian operations with two different inputs (2).
1652 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1653 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1654                                SelectionDAG &DAG) {
1655   bool IsLE = DAG.getDataLayout().isLittleEndian();
1656   if (ShuffleKind == 0) {
1657     if (IsLE)
1658       return false;
1659     for (unsigned i = 0; i != 16; i += 2)
1660       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1661           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1662         return false;
1663   } else if (ShuffleKind == 2) {
1664     if (!IsLE)
1665       return false;
1666     for (unsigned i = 0; i != 16; i += 2)
1667       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1668           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1669         return false;
1670   } else if (ShuffleKind == 1) {
1671     unsigned j = IsLE ? 0 : 2;
1672     for (unsigned i = 0; i != 8; i += 2)
1673       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1674           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1675           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1676           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1677         return false;
1678   }
1679   return true;
1680 }
1681 
1682 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1683 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1684 /// current subtarget.
1685 ///
1686 /// The ShuffleKind distinguishes between big-endian operations with
1687 /// two different inputs (0), either-endian operations with two identical
1688 /// inputs (1), and little-endian operations with two different inputs (2).
1689 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1690 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1691                                SelectionDAG &DAG) {
1692   const PPCSubtarget& Subtarget =
1693       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1694   if (!Subtarget.hasP8Vector())
1695     return false;
1696 
1697   bool IsLE = DAG.getDataLayout().isLittleEndian();
1698   if (ShuffleKind == 0) {
1699     if (IsLE)
1700       return false;
1701     for (unsigned i = 0; i != 16; i += 4)
1702       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1703           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1704           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1705           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1706         return false;
1707   } else if (ShuffleKind == 2) {
1708     if (!IsLE)
1709       return false;
1710     for (unsigned i = 0; i != 16; i += 4)
1711       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1712           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1713           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1714           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1715         return false;
1716   } else if (ShuffleKind == 1) {
1717     unsigned j = IsLE ? 0 : 4;
1718     for (unsigned i = 0; i != 8; i += 4)
1719       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1720           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1721           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1722           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1723           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1724           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1725           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1726           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1727         return false;
1728   }
1729   return true;
1730 }
1731 
1732 /// isVMerge - Common function, used to match vmrg* shuffles.
1733 ///
1734 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1735                      unsigned LHSStart, unsigned RHSStart) {
1736   if (N->getValueType(0) != MVT::v16i8)
1737     return false;
1738   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1739          "Unsupported merge size!");
1740 
1741   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1742     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1743       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1744                              LHSStart+j+i*UnitSize) ||
1745           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1746                              RHSStart+j+i*UnitSize))
1747         return false;
1748     }
1749   return true;
1750 }
1751 
1752 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1753 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1754 /// The ShuffleKind distinguishes between big-endian merges with two
1755 /// different inputs (0), either-endian merges with two identical inputs (1),
1756 /// and little-endian merges with two different inputs (2).  For the latter,
1757 /// the input operands are swapped (see PPCInstrAltivec.td).
1758 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1759                              unsigned ShuffleKind, SelectionDAG &DAG) {
1760   if (DAG.getDataLayout().isLittleEndian()) {
1761     if (ShuffleKind == 1) // unary
1762       return isVMerge(N, UnitSize, 0, 0);
1763     else if (ShuffleKind == 2) // swapped
1764       return isVMerge(N, UnitSize, 0, 16);
1765     else
1766       return false;
1767   } else {
1768     if (ShuffleKind == 1) // unary
1769       return isVMerge(N, UnitSize, 8, 8);
1770     else if (ShuffleKind == 0) // normal
1771       return isVMerge(N, UnitSize, 8, 24);
1772     else
1773       return false;
1774   }
1775 }
1776 
1777 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1778 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1779 /// The ShuffleKind distinguishes between big-endian merges with two
1780 /// different inputs (0), either-endian merges with two identical inputs (1),
1781 /// and little-endian merges with two different inputs (2).  For the latter,
1782 /// the input operands are swapped (see PPCInstrAltivec.td).
1783 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1784                              unsigned ShuffleKind, SelectionDAG &DAG) {
1785   if (DAG.getDataLayout().isLittleEndian()) {
1786     if (ShuffleKind == 1) // unary
1787       return isVMerge(N, UnitSize, 8, 8);
1788     else if (ShuffleKind == 2) // swapped
1789       return isVMerge(N, UnitSize, 8, 24);
1790     else
1791       return false;
1792   } else {
1793     if (ShuffleKind == 1) // unary
1794       return isVMerge(N, UnitSize, 0, 0);
1795     else if (ShuffleKind == 0) // normal
1796       return isVMerge(N, UnitSize, 0, 16);
1797     else
1798       return false;
1799   }
1800 }
1801 
1802 /**
1803  * Common function used to match vmrgew and vmrgow shuffles
1804  *
1805  * The indexOffset determines whether to look for even or odd words in
1806  * the shuffle mask. This is based on the of the endianness of the target
1807  * machine.
1808  *   - Little Endian:
1809  *     - Use offset of 0 to check for odd elements
1810  *     - Use offset of 4 to check for even elements
1811  *   - Big Endian:
1812  *     - Use offset of 0 to check for even elements
1813  *     - Use offset of 4 to check for odd elements
1814  * A detailed description of the vector element ordering for little endian and
1815  * big endian can be found at
1816  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1817  * Targeting your applications - what little endian and big endian IBM XL C/C++
1818  * compiler differences mean to you
1819  *
1820  * The mask to the shuffle vector instruction specifies the indices of the
1821  * elements from the two input vectors to place in the result. The elements are
1822  * numbered in array-access order, starting with the first vector. These vectors
1823  * are always of type v16i8, thus each vector will contain 16 elements of size
1824  * 8. More info on the shuffle vector can be found in the
1825  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1826  * Language Reference.
1827  *
1828  * The RHSStartValue indicates whether the same input vectors are used (unary)
1829  * or two different input vectors are used, based on the following:
1830  *   - If the instruction uses the same vector for both inputs, the range of the
1831  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1832  *     be 0.
1833  *   - If the instruction has two different vectors then the range of the
1834  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1835  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1836  *     to 31 specify elements in the second vector).
1837  *
1838  * \param[in] N The shuffle vector SD Node to analyze
1839  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1840  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1841  * vector to the shuffle_vector instruction
1842  * \return true iff this shuffle vector represents an even or odd word merge
1843  */
1844 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1845                      unsigned RHSStartValue) {
1846   if (N->getValueType(0) != MVT::v16i8)
1847     return false;
1848 
1849   for (unsigned i = 0; i < 2; ++i)
1850     for (unsigned j = 0; j < 4; ++j)
1851       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1852                              i*RHSStartValue+j+IndexOffset) ||
1853           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1854                              i*RHSStartValue+j+IndexOffset+8))
1855         return false;
1856   return true;
1857 }
1858 
1859 /**
1860  * Determine if the specified shuffle mask is suitable for the vmrgew or
1861  * vmrgow instructions.
1862  *
1863  * \param[in] N The shuffle vector SD Node to analyze
1864  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1865  * \param[in] ShuffleKind Identify the type of merge:
1866  *   - 0 = big-endian merge with two different inputs;
1867  *   - 1 = either-endian merge with two identical inputs;
1868  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1869  *     little-endian merges).
1870  * \param[in] DAG The current SelectionDAG
1871  * \return true iff this shuffle mask
1872  */
1873 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1874                               unsigned ShuffleKind, SelectionDAG &DAG) {
1875   if (DAG.getDataLayout().isLittleEndian()) {
1876     unsigned indexOffset = CheckEven ? 4 : 0;
1877     if (ShuffleKind == 1) // Unary
1878       return isVMerge(N, indexOffset, 0);
1879     else if (ShuffleKind == 2) // swapped
1880       return isVMerge(N, indexOffset, 16);
1881     else
1882       return false;
1883   }
1884   else {
1885     unsigned indexOffset = CheckEven ? 0 : 4;
1886     if (ShuffleKind == 1) // Unary
1887       return isVMerge(N, indexOffset, 0);
1888     else if (ShuffleKind == 0) // Normal
1889       return isVMerge(N, indexOffset, 16);
1890     else
1891       return false;
1892   }
1893   return false;
1894 }
1895 
1896 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1897 /// amount, otherwise return -1.
1898 /// The ShuffleKind distinguishes between big-endian operations with two
1899 /// different inputs (0), either-endian operations with two identical inputs
1900 /// (1), and little-endian operations with two different inputs (2).  For the
1901 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1902 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1903                              SelectionDAG &DAG) {
1904   if (N->getValueType(0) != MVT::v16i8)
1905     return -1;
1906 
1907   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1908 
1909   // Find the first non-undef value in the shuffle mask.
1910   unsigned i;
1911   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1912     /*search*/;
1913 
1914   if (i == 16) return -1;  // all undef.
1915 
1916   // Otherwise, check to see if the rest of the elements are consecutively
1917   // numbered from this value.
1918   unsigned ShiftAmt = SVOp->getMaskElt(i);
1919   if (ShiftAmt < i) return -1;
1920 
1921   ShiftAmt -= i;
1922   bool isLE = DAG.getDataLayout().isLittleEndian();
1923 
1924   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1925     // Check the rest of the elements to see if they are consecutive.
1926     for (++i; i != 16; ++i)
1927       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1928         return -1;
1929   } else if (ShuffleKind == 1) {
1930     // Check the rest of the elements to see if they are consecutive.
1931     for (++i; i != 16; ++i)
1932       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1933         return -1;
1934   } else
1935     return -1;
1936 
1937   if (isLE)
1938     ShiftAmt = 16 - ShiftAmt;
1939 
1940   return ShiftAmt;
1941 }
1942 
1943 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1944 /// specifies a splat of a single element that is suitable for input to
1945 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1946 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1947   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1948          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1949 
1950   // The consecutive indices need to specify an element, not part of two
1951   // different elements.  So abandon ship early if this isn't the case.
1952   if (N->getMaskElt(0) % EltSize != 0)
1953     return false;
1954 
1955   // This is a splat operation if each element of the permute is the same, and
1956   // if the value doesn't reference the second vector.
1957   unsigned ElementBase = N->getMaskElt(0);
1958 
1959   // FIXME: Handle UNDEF elements too!
1960   if (ElementBase >= 16)
1961     return false;
1962 
1963   // Check that the indices are consecutive, in the case of a multi-byte element
1964   // splatted with a v16i8 mask.
1965   for (unsigned i = 1; i != EltSize; ++i)
1966     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1967       return false;
1968 
1969   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1970     if (N->getMaskElt(i) < 0) continue;
1971     for (unsigned j = 0; j != EltSize; ++j)
1972       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1973         return false;
1974   }
1975   return true;
1976 }
1977 
1978 /// Check that the mask is shuffling N byte elements. Within each N byte
1979 /// element of the mask, the indices could be either in increasing or
1980 /// decreasing order as long as they are consecutive.
1981 /// \param[in] N the shuffle vector SD Node to analyze
1982 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1983 /// Word/DoubleWord/QuadWord).
1984 /// \param[in] StepLen the delta indices number among the N byte element, if
1985 /// the mask is in increasing/decreasing order then it is 1/-1.
1986 /// \return true iff the mask is shuffling N byte elements.
1987 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1988                                    int StepLen) {
1989   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1990          "Unexpected element width.");
1991   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1992 
1993   unsigned NumOfElem = 16 / Width;
1994   unsigned MaskVal[16]; //  Width is never greater than 16
1995   for (unsigned i = 0; i < NumOfElem; ++i) {
1996     MaskVal[0] = N->getMaskElt(i * Width);
1997     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1998       return false;
1999     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2000       return false;
2001     }
2002 
2003     for (unsigned int j = 1; j < Width; ++j) {
2004       MaskVal[j] = N->getMaskElt(i * Width + j);
2005       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2006         return false;
2007       }
2008     }
2009   }
2010 
2011   return true;
2012 }
2013 
2014 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2015                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2016   if (!isNByteElemShuffleMask(N, 4, 1))
2017     return false;
2018 
2019   // Now we look at mask elements 0,4,8,12
2020   unsigned M0 = N->getMaskElt(0) / 4;
2021   unsigned M1 = N->getMaskElt(4) / 4;
2022   unsigned M2 = N->getMaskElt(8) / 4;
2023   unsigned M3 = N->getMaskElt(12) / 4;
2024   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2025   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2026 
2027   // Below, let H and L be arbitrary elements of the shuffle mask
2028   // where H is in the range [4,7] and L is in the range [0,3].
2029   // H, 1, 2, 3 or L, 5, 6, 7
2030   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2031       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2032     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2033     InsertAtByte = IsLE ? 12 : 0;
2034     Swap = M0 < 4;
2035     return true;
2036   }
2037   // 0, H, 2, 3 or 4, L, 6, 7
2038   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2039       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2040     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2041     InsertAtByte = IsLE ? 8 : 4;
2042     Swap = M1 < 4;
2043     return true;
2044   }
2045   // 0, 1, H, 3 or 4, 5, L, 7
2046   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2047       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2048     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2049     InsertAtByte = IsLE ? 4 : 8;
2050     Swap = M2 < 4;
2051     return true;
2052   }
2053   // 0, 1, 2, H or 4, 5, 6, L
2054   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2055       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2056     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2057     InsertAtByte = IsLE ? 0 : 12;
2058     Swap = M3 < 4;
2059     return true;
2060   }
2061 
2062   // If both vector operands for the shuffle are the same vector, the mask will
2063   // contain only elements from the first one and the second one will be undef.
2064   if (N->getOperand(1).isUndef()) {
2065     ShiftElts = 0;
2066     Swap = true;
2067     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2068     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2069       InsertAtByte = IsLE ? 12 : 0;
2070       return true;
2071     }
2072     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2073       InsertAtByte = IsLE ? 8 : 4;
2074       return true;
2075     }
2076     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2077       InsertAtByte = IsLE ? 4 : 8;
2078       return true;
2079     }
2080     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2081       InsertAtByte = IsLE ? 0 : 12;
2082       return true;
2083     }
2084   }
2085 
2086   return false;
2087 }
2088 
2089 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2090                                bool &Swap, bool IsLE) {
2091   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2092   // Ensure each byte index of the word is consecutive.
2093   if (!isNByteElemShuffleMask(N, 4, 1))
2094     return false;
2095 
2096   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2097   unsigned M0 = N->getMaskElt(0) / 4;
2098   unsigned M1 = N->getMaskElt(4) / 4;
2099   unsigned M2 = N->getMaskElt(8) / 4;
2100   unsigned M3 = N->getMaskElt(12) / 4;
2101 
2102   // If both vector operands for the shuffle are the same vector, the mask will
2103   // contain only elements from the first one and the second one will be undef.
2104   if (N->getOperand(1).isUndef()) {
2105     assert(M0 < 4 && "Indexing into an undef vector?");
2106     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2107       return false;
2108 
2109     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2110     Swap = false;
2111     return true;
2112   }
2113 
2114   // Ensure each word index of the ShuffleVector Mask is consecutive.
2115   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2116     return false;
2117 
2118   if (IsLE) {
2119     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2120       // Input vectors don't need to be swapped if the leading element
2121       // of the result is one of the 3 left elements of the second vector
2122       // (or if there is no shift to be done at all).
2123       Swap = false;
2124       ShiftElts = (8 - M0) % 8;
2125     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2126       // Input vectors need to be swapped if the leading element
2127       // of the result is one of the 3 left elements of the first vector
2128       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2129       Swap = true;
2130       ShiftElts = (4 - M0) % 4;
2131     }
2132 
2133     return true;
2134   } else {                                          // BE
2135     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2136       // Input vectors don't need to be swapped if the leading element
2137       // of the result is one of the 4 elements of the first vector.
2138       Swap = false;
2139       ShiftElts = M0;
2140     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2141       // Input vectors need to be swapped if the leading element
2142       // of the result is one of the 4 elements of the right vector.
2143       Swap = true;
2144       ShiftElts = M0 - 4;
2145     }
2146 
2147     return true;
2148   }
2149 }
2150 
2151 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2152   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2153 
2154   if (!isNByteElemShuffleMask(N, Width, -1))
2155     return false;
2156 
2157   for (int i = 0; i < 16; i += Width)
2158     if (N->getMaskElt(i) != i + Width - 1)
2159       return false;
2160 
2161   return true;
2162 }
2163 
2164 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2165   return isXXBRShuffleMaskHelper(N, 2);
2166 }
2167 
2168 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2169   return isXXBRShuffleMaskHelper(N, 4);
2170 }
2171 
2172 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2173   return isXXBRShuffleMaskHelper(N, 8);
2174 }
2175 
2176 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2177   return isXXBRShuffleMaskHelper(N, 16);
2178 }
2179 
2180 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2181 /// if the inputs to the instruction should be swapped and set \p DM to the
2182 /// value for the immediate.
2183 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2184 /// AND element 0 of the result comes from the first input (LE) or second input
2185 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2186 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2187 /// mask.
2188 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2189                                bool &Swap, bool IsLE) {
2190   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2191 
2192   // Ensure each byte index of the double word is consecutive.
2193   if (!isNByteElemShuffleMask(N, 8, 1))
2194     return false;
2195 
2196   unsigned M0 = N->getMaskElt(0) / 8;
2197   unsigned M1 = N->getMaskElt(8) / 8;
2198   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2199 
2200   // If both vector operands for the shuffle are the same vector, the mask will
2201   // contain only elements from the first one and the second one will be undef.
2202   if (N->getOperand(1).isUndef()) {
2203     if ((M0 | M1) < 2) {
2204       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2205       Swap = false;
2206       return true;
2207     } else
2208       return false;
2209   }
2210 
2211   if (IsLE) {
2212     if (M0 > 1 && M1 < 2) {
2213       Swap = false;
2214     } else if (M0 < 2 && M1 > 1) {
2215       M0 = (M0 + 2) % 4;
2216       M1 = (M1 + 2) % 4;
2217       Swap = true;
2218     } else
2219       return false;
2220 
2221     // Note: if control flow comes here that means Swap is already set above
2222     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2223     return true;
2224   } else { // BE
2225     if (M0 < 2 && M1 > 1) {
2226       Swap = false;
2227     } else if (M0 > 1 && M1 < 2) {
2228       M0 = (M0 + 2) % 4;
2229       M1 = (M1 + 2) % 4;
2230       Swap = true;
2231     } else
2232       return false;
2233 
2234     // Note: if control flow comes here that means Swap is already set above
2235     DM = (M0 << 1) + (M1 & 1);
2236     return true;
2237   }
2238 }
2239 
2240 
2241 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2242 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2243 /// elements are counted from the left of the vector register).
2244 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2245                                          SelectionDAG &DAG) {
2246   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2247   assert(isSplatShuffleMask(SVOp, EltSize));
2248   if (DAG.getDataLayout().isLittleEndian())
2249     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2250   else
2251     return SVOp->getMaskElt(0) / EltSize;
2252 }
2253 
2254 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2255 /// by using a vspltis[bhw] instruction of the specified element size, return
2256 /// the constant being splatted.  The ByteSize field indicates the number of
2257 /// bytes of each element [124] -> [bhw].
2258 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2259   SDValue OpVal(nullptr, 0);
2260 
2261   // If ByteSize of the splat is bigger than the element size of the
2262   // build_vector, then we have a case where we are checking for a splat where
2263   // multiple elements of the buildvector are folded together into a single
2264   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2265   unsigned EltSize = 16/N->getNumOperands();
2266   if (EltSize < ByteSize) {
2267     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2268     SDValue UniquedVals[4];
2269     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2270 
2271     // See if all of the elements in the buildvector agree across.
2272     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2273       if (N->getOperand(i).isUndef()) continue;
2274       // If the element isn't a constant, bail fully out.
2275       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2276 
2277       if (!UniquedVals[i&(Multiple-1)].getNode())
2278         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2279       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2280         return SDValue();  // no match.
2281     }
2282 
2283     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2284     // either constant or undef values that are identical for each chunk.  See
2285     // if these chunks can form into a larger vspltis*.
2286 
2287     // Check to see if all of the leading entries are either 0 or -1.  If
2288     // neither, then this won't fit into the immediate field.
2289     bool LeadingZero = true;
2290     bool LeadingOnes = true;
2291     for (unsigned i = 0; i != Multiple-1; ++i) {
2292       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2293 
2294       LeadingZero &= isNullConstant(UniquedVals[i]);
2295       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2296     }
2297     // Finally, check the least significant entry.
2298     if (LeadingZero) {
2299       if (!UniquedVals[Multiple-1].getNode())
2300         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2301       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2302       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2303         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2304     }
2305     if (LeadingOnes) {
2306       if (!UniquedVals[Multiple-1].getNode())
2307         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2308       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2309       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2310         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2311     }
2312 
2313     return SDValue();
2314   }
2315 
2316   // Check to see if this buildvec has a single non-undef value in its elements.
2317   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2318     if (N->getOperand(i).isUndef()) continue;
2319     if (!OpVal.getNode())
2320       OpVal = N->getOperand(i);
2321     else if (OpVal != N->getOperand(i))
2322       return SDValue();
2323   }
2324 
2325   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2326 
2327   unsigned ValSizeInBytes = EltSize;
2328   uint64_t Value = 0;
2329   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2330     Value = CN->getZExtValue();
2331   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2332     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2333     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2334   }
2335 
2336   // If the splat value is larger than the element value, then we can never do
2337   // this splat.  The only case that we could fit the replicated bits into our
2338   // immediate field for would be zero, and we prefer to use vxor for it.
2339   if (ValSizeInBytes < ByteSize) return SDValue();
2340 
2341   // If the element value is larger than the splat value, check if it consists
2342   // of a repeated bit pattern of size ByteSize.
2343   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2344     return SDValue();
2345 
2346   // Properly sign extend the value.
2347   int MaskVal = SignExtend32(Value, ByteSize * 8);
2348 
2349   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2350   if (MaskVal == 0) return SDValue();
2351 
2352   // Finally, if this value fits in a 5 bit sext field, return it
2353   if (SignExtend32<5>(MaskVal) == MaskVal)
2354     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2355   return SDValue();
2356 }
2357 
2358 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2359 /// amount, otherwise return -1.
2360 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2361   EVT VT = N->getValueType(0);
2362   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2363     return -1;
2364 
2365   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2366 
2367   // Find the first non-undef value in the shuffle mask.
2368   unsigned i;
2369   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2370     /*search*/;
2371 
2372   if (i == 4) return -1;  // all undef.
2373 
2374   // Otherwise, check to see if the rest of the elements are consecutively
2375   // numbered from this value.
2376   unsigned ShiftAmt = SVOp->getMaskElt(i);
2377   if (ShiftAmt < i) return -1;
2378   ShiftAmt -= i;
2379 
2380   // Check the rest of the elements to see if they are consecutive.
2381   for (++i; i != 4; ++i)
2382     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2383       return -1;
2384 
2385   return ShiftAmt;
2386 }
2387 
2388 //===----------------------------------------------------------------------===//
2389 //  Addressing Mode Selection
2390 //===----------------------------------------------------------------------===//
2391 
2392 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2393 /// or 64-bit immediate, and if the value can be accurately represented as a
2394 /// sign extension from a 16-bit value.  If so, this returns true and the
2395 /// immediate.
2396 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2397   if (!isa<ConstantSDNode>(N))
2398     return false;
2399 
2400   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2401   if (N->getValueType(0) == MVT::i32)
2402     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2403   else
2404     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2405 }
2406 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2407   return isIntS16Immediate(Op.getNode(), Imm);
2408 }
2409 
2410 
2411 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2412 /// be represented as an indexed [r+r] operation.
2413 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2414                                                SDValue &Index,
2415                                                SelectionDAG &DAG) const {
2416   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2417       UI != E; ++UI) {
2418     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2419       if (Memop->getMemoryVT() == MVT::f64) {
2420           Base = N.getOperand(0);
2421           Index = N.getOperand(1);
2422           return true;
2423       }
2424     }
2425   }
2426   return false;
2427 }
2428 
2429 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2430 /// can be represented as an indexed [r+r] operation.  Returns false if it
2431 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2432 /// non-zero and N can be represented by a base register plus a signed 16-bit
2433 /// displacement, make a more precise judgement by checking (displacement % \p
2434 /// EncodingAlignment).
2435 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2436                                             SDValue &Index, SelectionDAG &DAG,
2437                                             unsigned EncodingAlignment) const {
2438   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2439   // a [pc+imm].
2440   if (SelectAddressPCRel(N, Base))
2441     return false;
2442 
2443   int16_t imm = 0;
2444   if (N.getOpcode() == ISD::ADD) {
2445     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2446     // SPE load/store can only handle 8-bit offsets.
2447     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2448         return true;
2449     if (isIntS16Immediate(N.getOperand(1), imm) &&
2450         (!EncodingAlignment || !(imm % EncodingAlignment)))
2451       return false; // r+i
2452     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2453       return false;    // r+i
2454 
2455     Base = N.getOperand(0);
2456     Index = N.getOperand(1);
2457     return true;
2458   } else if (N.getOpcode() == ISD::OR) {
2459     if (isIntS16Immediate(N.getOperand(1), imm) &&
2460         (!EncodingAlignment || !(imm % EncodingAlignment)))
2461       return false; // r+i can fold it if we can.
2462 
2463     // If this is an or of disjoint bitfields, we can codegen this as an add
2464     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2465     // disjoint.
2466     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2467 
2468     if (LHSKnown.Zero.getBoolValue()) {
2469       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2470       // If all of the bits are known zero on the LHS or RHS, the add won't
2471       // carry.
2472       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2473         Base = N.getOperand(0);
2474         Index = N.getOperand(1);
2475         return true;
2476       }
2477     }
2478   }
2479 
2480   return false;
2481 }
2482 
2483 // If we happen to be doing an i64 load or store into a stack slot that has
2484 // less than a 4-byte alignment, then the frame-index elimination may need to
2485 // use an indexed load or store instruction (because the offset may not be a
2486 // multiple of 4). The extra register needed to hold the offset comes from the
2487 // register scavenger, and it is possible that the scavenger will need to use
2488 // an emergency spill slot. As a result, we need to make sure that a spill slot
2489 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2490 // stack slot.
2491 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2492   // FIXME: This does not handle the LWA case.
2493   if (VT != MVT::i64)
2494     return;
2495 
2496   // NOTE: We'll exclude negative FIs here, which come from argument
2497   // lowering, because there are no known test cases triggering this problem
2498   // using packed structures (or similar). We can remove this exclusion if
2499   // we find such a test case. The reason why this is so test-case driven is
2500   // because this entire 'fixup' is only to prevent crashes (from the
2501   // register scavenger) on not-really-valid inputs. For example, if we have:
2502   //   %a = alloca i1
2503   //   %b = bitcast i1* %a to i64*
2504   //   store i64* a, i64 b
2505   // then the store should really be marked as 'align 1', but is not. If it
2506   // were marked as 'align 1' then the indexed form would have been
2507   // instruction-selected initially, and the problem this 'fixup' is preventing
2508   // won't happen regardless.
2509   if (FrameIdx < 0)
2510     return;
2511 
2512   MachineFunction &MF = DAG.getMachineFunction();
2513   MachineFrameInfo &MFI = MF.getFrameInfo();
2514 
2515   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2516     return;
2517 
2518   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2519   FuncInfo->setHasNonRISpills();
2520 }
2521 
2522 /// Returns true if the address N can be represented by a base register plus
2523 /// a signed 16-bit displacement [r+imm], and if it is not better
2524 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2525 /// displacements that are multiples of that value.
2526 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2527                                             SDValue &Base,
2528                                             SelectionDAG &DAG,
2529                                             unsigned EncodingAlignment) const {
2530   // FIXME dl should come from parent load or store, not from address
2531   SDLoc dl(N);
2532 
2533   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2534   // a [pc+imm].
2535   if (SelectAddressPCRel(N, Base))
2536     return false;
2537 
2538   // If this can be more profitably realized as r+r, fail.
2539   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2540     return false;
2541 
2542   if (N.getOpcode() == ISD::ADD) {
2543     int16_t imm = 0;
2544     if (isIntS16Immediate(N.getOperand(1), imm) &&
2545         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2546       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2547       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2548         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2549         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2550       } else {
2551         Base = N.getOperand(0);
2552       }
2553       return true; // [r+i]
2554     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2555       // Match LOAD (ADD (X, Lo(G))).
2556       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2557              && "Cannot handle constant offsets yet!");
2558       Disp = N.getOperand(1).getOperand(0);  // The global address.
2559       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2560              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2561              Disp.getOpcode() == ISD::TargetConstantPool ||
2562              Disp.getOpcode() == ISD::TargetJumpTable);
2563       Base = N.getOperand(0);
2564       return true;  // [&g+r]
2565     }
2566   } else if (N.getOpcode() == ISD::OR) {
2567     int16_t imm = 0;
2568     if (isIntS16Immediate(N.getOperand(1), imm) &&
2569         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2570       // If this is an or of disjoint bitfields, we can codegen this as an add
2571       // (for better address arithmetic) if the LHS and RHS of the OR are
2572       // provably disjoint.
2573       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2574 
2575       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2576         // If all of the bits are known zero on the LHS or RHS, the add won't
2577         // carry.
2578         if (FrameIndexSDNode *FI =
2579               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2580           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2581           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2582         } else {
2583           Base = N.getOperand(0);
2584         }
2585         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2586         return true;
2587       }
2588     }
2589   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2590     // Loading from a constant address.
2591 
2592     // If this address fits entirely in a 16-bit sext immediate field, codegen
2593     // this as "d, 0"
2594     int16_t Imm;
2595     if (isIntS16Immediate(CN, Imm) &&
2596         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2597       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2598       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2599                              CN->getValueType(0));
2600       return true;
2601     }
2602 
2603     // Handle 32-bit sext immediates with LIS + addr mode.
2604     if ((CN->getValueType(0) == MVT::i32 ||
2605          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2606         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2607       int Addr = (int)CN->getZExtValue();
2608 
2609       // Otherwise, break this down into an LIS + disp.
2610       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2611 
2612       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2613                                    MVT::i32);
2614       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2615       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2616       return true;
2617     }
2618   }
2619 
2620   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2621   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2622     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2623     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2624   } else
2625     Base = N;
2626   return true;      // [r+0]
2627 }
2628 
2629 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2630 /// represented as an indexed [r+r] operation.
2631 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2632                                                 SDValue &Index,
2633                                                 SelectionDAG &DAG) const {
2634   // Check to see if we can easily represent this as an [r+r] address.  This
2635   // will fail if it thinks that the address is more profitably represented as
2636   // reg+imm, e.g. where imm = 0.
2637   if (SelectAddressRegReg(N, Base, Index, DAG))
2638     return true;
2639 
2640   // If the address is the result of an add, we will utilize the fact that the
2641   // address calculation includes an implicit add.  However, we can reduce
2642   // register pressure if we do not materialize a constant just for use as the
2643   // index register.  We only get rid of the add if it is not an add of a
2644   // value and a 16-bit signed constant and both have a single use.
2645   int16_t imm = 0;
2646   if (N.getOpcode() == ISD::ADD &&
2647       (!isIntS16Immediate(N.getOperand(1), imm) ||
2648        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2649     Base = N.getOperand(0);
2650     Index = N.getOperand(1);
2651     return true;
2652   }
2653 
2654   // Otherwise, do it the hard way, using R0 as the base register.
2655   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2656                          N.getValueType());
2657   Index = N;
2658   return true;
2659 }
2660 
2661 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2662   Ty *PCRelCand = dyn_cast<Ty>(N);
2663   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2664 }
2665 
2666 /// Returns true if this address is a PC Relative address.
2667 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2668 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2669 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2670   // This is a materialize PC Relative node. Always select this as PC Relative.
2671   Base = N;
2672   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2673     return true;
2674   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2675       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2676       isValidPCRelNode<JumpTableSDNode>(N) ||
2677       isValidPCRelNode<BlockAddressSDNode>(N))
2678     return true;
2679   return false;
2680 }
2681 
2682 /// Returns true if we should use a direct load into vector instruction
2683 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2684 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2685 
2686   // If there are any other uses other than scalar to vector, then we should
2687   // keep it as a scalar load -> direct move pattern to prevent multiple
2688   // loads.
2689   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2690   if (!LD)
2691     return false;
2692 
2693   EVT MemVT = LD->getMemoryVT();
2694   if (!MemVT.isSimple())
2695     return false;
2696   switch(MemVT.getSimpleVT().SimpleTy) {
2697   case MVT::i64:
2698     break;
2699   case MVT::i32:
2700     if (!ST.hasP8Vector())
2701       return false;
2702     break;
2703   case MVT::i16:
2704   case MVT::i8:
2705     if (!ST.hasP9Vector())
2706       return false;
2707     break;
2708   default:
2709     return false;
2710   }
2711 
2712   SDValue LoadedVal(N, 0);
2713   if (!LoadedVal.hasOneUse())
2714     return false;
2715 
2716   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2717        UI != UE; ++UI)
2718     if (UI.getUse().get().getResNo() == 0 &&
2719         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2720       return false;
2721 
2722   return true;
2723 }
2724 
2725 /// getPreIndexedAddressParts - returns true by value, base pointer and
2726 /// offset pointer and addressing mode by reference if the node's address
2727 /// can be legally represented as pre-indexed load / store address.
2728 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2729                                                   SDValue &Offset,
2730                                                   ISD::MemIndexedMode &AM,
2731                                                   SelectionDAG &DAG) const {
2732   if (DisablePPCPreinc) return false;
2733 
2734   bool isLoad = true;
2735   SDValue Ptr;
2736   EVT VT;
2737   unsigned Alignment;
2738   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2739     Ptr = LD->getBasePtr();
2740     VT = LD->getMemoryVT();
2741     Alignment = LD->getAlignment();
2742   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2743     Ptr = ST->getBasePtr();
2744     VT  = ST->getMemoryVT();
2745     Alignment = ST->getAlignment();
2746     isLoad = false;
2747   } else
2748     return false;
2749 
2750   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2751   // instructions because we can fold these into a more efficient instruction
2752   // instead, (such as LXSD).
2753   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2754     return false;
2755   }
2756 
2757   // PowerPC doesn't have preinc load/store instructions for vectors (except
2758   // for QPX, which does have preinc r+r forms).
2759   if (VT.isVector()) {
2760     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2761       return false;
2762     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2763       AM = ISD::PRE_INC;
2764       return true;
2765     }
2766   }
2767 
2768   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2769     // Common code will reject creating a pre-inc form if the base pointer
2770     // is a frame index, or if N is a store and the base pointer is either
2771     // the same as or a predecessor of the value being stored.  Check for
2772     // those situations here, and try with swapped Base/Offset instead.
2773     bool Swap = false;
2774 
2775     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2776       Swap = true;
2777     else if (!isLoad) {
2778       SDValue Val = cast<StoreSDNode>(N)->getValue();
2779       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2780         Swap = true;
2781     }
2782 
2783     if (Swap)
2784       std::swap(Base, Offset);
2785 
2786     AM = ISD::PRE_INC;
2787     return true;
2788   }
2789 
2790   // LDU/STU can only handle immediates that are a multiple of 4.
2791   if (VT != MVT::i64) {
2792     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2793       return false;
2794   } else {
2795     // LDU/STU need an address with at least 4-byte alignment.
2796     if (Alignment < 4)
2797       return false;
2798 
2799     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2800       return false;
2801   }
2802 
2803   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2804     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2805     // sext i32 to i64 when addr mode is r+i.
2806     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2807         LD->getExtensionType() == ISD::SEXTLOAD &&
2808         isa<ConstantSDNode>(Offset))
2809       return false;
2810   }
2811 
2812   AM = ISD::PRE_INC;
2813   return true;
2814 }
2815 
2816 //===----------------------------------------------------------------------===//
2817 //  LowerOperation implementation
2818 //===----------------------------------------------------------------------===//
2819 
2820 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2821 /// and LoOpFlags to the target MO flags.
2822 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2823                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2824                                const GlobalValue *GV = nullptr) {
2825   HiOpFlags = PPCII::MO_HA;
2826   LoOpFlags = PPCII::MO_LO;
2827 
2828   // Don't use the pic base if not in PIC relocation model.
2829   if (IsPIC) {
2830     HiOpFlags |= PPCII::MO_PIC_FLAG;
2831     LoOpFlags |= PPCII::MO_PIC_FLAG;
2832   }
2833 }
2834 
2835 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2836                              SelectionDAG &DAG) {
2837   SDLoc DL(HiPart);
2838   EVT PtrVT = HiPart.getValueType();
2839   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2840 
2841   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2842   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2843 
2844   // With PIC, the first instruction is actually "GR+hi(&G)".
2845   if (isPIC)
2846     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2847                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2848 
2849   // Generate non-pic code that has direct accesses to the constant pool.
2850   // The address of the global is just (hi(&g)+lo(&g)).
2851   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2852 }
2853 
2854 static void setUsesTOCBasePtr(MachineFunction &MF) {
2855   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2856   FuncInfo->setUsesTOCBasePtr();
2857 }
2858 
2859 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2860   setUsesTOCBasePtr(DAG.getMachineFunction());
2861 }
2862 
2863 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2864                                        SDValue GA) const {
2865   const bool Is64Bit = Subtarget.isPPC64();
2866   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2867   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2868                         : Subtarget.isAIXABI()
2869                               ? DAG.getRegister(PPC::R2, VT)
2870                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2871   SDValue Ops[] = { GA, Reg };
2872   return DAG.getMemIntrinsicNode(
2873       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2874       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2875       MachineMemOperand::MOLoad);
2876 }
2877 
2878 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2879                                              SelectionDAG &DAG) const {
2880   EVT PtrVT = Op.getValueType();
2881   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2882   const Constant *C = CP->getConstVal();
2883 
2884   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2885   // The actual address of the GlobalValue is stored in the TOC.
2886   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2887     if (Subtarget.isUsingPCRelativeCalls()) {
2888       SDLoc DL(CP);
2889       EVT Ty = getPointerTy(DAG.getDataLayout());
2890       SDValue ConstPool = DAG.getTargetConstantPool(
2891           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2892       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2893     }
2894     setUsesTOCBasePtr(DAG);
2895     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2896     return getTOCEntry(DAG, SDLoc(CP), GA);
2897   }
2898 
2899   unsigned MOHiFlag, MOLoFlag;
2900   bool IsPIC = isPositionIndependent();
2901   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2902 
2903   if (IsPIC && Subtarget.isSVR4ABI()) {
2904     SDValue GA =
2905         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2906     return getTOCEntry(DAG, SDLoc(CP), GA);
2907   }
2908 
2909   SDValue CPIHi =
2910       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
2911   SDValue CPILo =
2912       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
2913   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2914 }
2915 
2916 // For 64-bit PowerPC, prefer the more compact relative encodings.
2917 // This trades 32 bits per jump table entry for one or two instructions
2918 // on the jump site.
2919 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2920   if (isJumpTableRelative())
2921     return MachineJumpTableInfo::EK_LabelDifference32;
2922 
2923   return TargetLowering::getJumpTableEncoding();
2924 }
2925 
2926 bool PPCTargetLowering::isJumpTableRelative() const {
2927   if (UseAbsoluteJumpTables)
2928     return false;
2929   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2930     return true;
2931   return TargetLowering::isJumpTableRelative();
2932 }
2933 
2934 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2935                                                     SelectionDAG &DAG) const {
2936   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2937     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2938 
2939   switch (getTargetMachine().getCodeModel()) {
2940   case CodeModel::Small:
2941   case CodeModel::Medium:
2942     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2943   default:
2944     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2945                        getPointerTy(DAG.getDataLayout()));
2946   }
2947 }
2948 
2949 const MCExpr *
2950 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2951                                                 unsigned JTI,
2952                                                 MCContext &Ctx) const {
2953   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2954     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2955 
2956   switch (getTargetMachine().getCodeModel()) {
2957   case CodeModel::Small:
2958   case CodeModel::Medium:
2959     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2960   default:
2961     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2962   }
2963 }
2964 
2965 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2966   EVT PtrVT = Op.getValueType();
2967   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2968 
2969   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2970   if (Subtarget.isUsingPCRelativeCalls()) {
2971     SDLoc DL(JT);
2972     EVT Ty = getPointerTy(DAG.getDataLayout());
2973     SDValue GA =
2974         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
2975     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2976     return MatAddr;
2977   }
2978 
2979   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2980   // The actual address of the GlobalValue is stored in the TOC.
2981   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2982     setUsesTOCBasePtr(DAG);
2983     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2984     return getTOCEntry(DAG, SDLoc(JT), GA);
2985   }
2986 
2987   unsigned MOHiFlag, MOLoFlag;
2988   bool IsPIC = isPositionIndependent();
2989   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2990 
2991   if (IsPIC && Subtarget.isSVR4ABI()) {
2992     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2993                                         PPCII::MO_PIC_FLAG);
2994     return getTOCEntry(DAG, SDLoc(GA), GA);
2995   }
2996 
2997   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2998   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2999   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3000 }
3001 
3002 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3003                                              SelectionDAG &DAG) const {
3004   EVT PtrVT = Op.getValueType();
3005   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3006   const BlockAddress *BA = BASDN->getBlockAddress();
3007 
3008   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3009   if (Subtarget.isUsingPCRelativeCalls()) {
3010     SDLoc DL(BASDN);
3011     EVT Ty = getPointerTy(DAG.getDataLayout());
3012     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3013                                            PPCII::MO_PCREL_FLAG);
3014     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3015     return MatAddr;
3016   }
3017 
3018   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3019   // The actual BlockAddress is stored in the TOC.
3020   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3021     setUsesTOCBasePtr(DAG);
3022     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3023     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3024   }
3025 
3026   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3027   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3028     return getTOCEntry(
3029         DAG, SDLoc(BASDN),
3030         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3031 
3032   unsigned MOHiFlag, MOLoFlag;
3033   bool IsPIC = isPositionIndependent();
3034   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3035   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3036   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3037   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3038 }
3039 
3040 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3041                                               SelectionDAG &DAG) const {
3042   // FIXME: TLS addresses currently use medium model code sequences,
3043   // which is the most useful form.  Eventually support for small and
3044   // large models could be added if users need it, at the cost of
3045   // additional complexity.
3046   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3047   if (DAG.getTarget().useEmulatedTLS())
3048     return LowerToTLSEmulatedModel(GA, DAG);
3049 
3050   SDLoc dl(GA);
3051   const GlobalValue *GV = GA->getGlobal();
3052   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3053   bool is64bit = Subtarget.isPPC64();
3054   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3055   PICLevel::Level picLevel = M->getPICLevel();
3056 
3057   const TargetMachine &TM = getTargetMachine();
3058   TLSModel::Model Model = TM.getTLSModel(GV);
3059 
3060   if (Model == TLSModel::LocalExec) {
3061     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3062                                                PPCII::MO_TPREL_HA);
3063     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3064                                                PPCII::MO_TPREL_LO);
3065     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3066                              : DAG.getRegister(PPC::R2, MVT::i32);
3067 
3068     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3069     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3070   }
3071 
3072   if (Model == TLSModel::InitialExec) {
3073     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3074     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3075                                                 PPCII::MO_TLS);
3076     SDValue GOTPtr;
3077     if (is64bit) {
3078       setUsesTOCBasePtr(DAG);
3079       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3080       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
3081                            PtrVT, GOTReg, TGA);
3082     } else {
3083       if (!TM.isPositionIndependent())
3084         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3085       else if (picLevel == PICLevel::SmallPIC)
3086         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3087       else
3088         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3089     }
3090     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
3091                                    PtrVT, TGA, GOTPtr);
3092     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3093   }
3094 
3095   if (Model == TLSModel::GeneralDynamic) {
3096     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3097     SDValue GOTPtr;
3098     if (is64bit) {
3099       setUsesTOCBasePtr(DAG);
3100       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3101       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3102                                    GOTReg, TGA);
3103     } else {
3104       if (picLevel == PICLevel::SmallPIC)
3105         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3106       else
3107         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3108     }
3109     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3110                        GOTPtr, TGA, TGA);
3111   }
3112 
3113   if (Model == TLSModel::LocalDynamic) {
3114     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3115     SDValue GOTPtr;
3116     if (is64bit) {
3117       setUsesTOCBasePtr(DAG);
3118       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3119       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3120                            GOTReg, TGA);
3121     } else {
3122       if (picLevel == PICLevel::SmallPIC)
3123         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3124       else
3125         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3126     }
3127     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3128                                   PtrVT, GOTPtr, TGA, TGA);
3129     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3130                                       PtrVT, TLSAddr, TGA);
3131     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3132   }
3133 
3134   llvm_unreachable("Unknown TLS model!");
3135 }
3136 
3137 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3138                                               SelectionDAG &DAG) const {
3139   EVT PtrVT = Op.getValueType();
3140   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3141   SDLoc DL(GSDN);
3142   const GlobalValue *GV = GSDN->getGlobal();
3143 
3144   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3145   // The actual address of the GlobalValue is stored in the TOC.
3146   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3147     if (Subtarget.isUsingPCRelativeCalls()) {
3148       EVT Ty = getPointerTy(DAG.getDataLayout());
3149       if (isAccessedAsGotIndirect(Op)) {
3150         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3151                                                 PPCII::MO_PCREL_FLAG |
3152                                                     PPCII::MO_GOT_FLAG);
3153         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3154         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3155                                    MachinePointerInfo());
3156         return Load;
3157       } else {
3158         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3159                                                 PPCII::MO_PCREL_FLAG);
3160         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3161       }
3162     }
3163     setUsesTOCBasePtr(DAG);
3164     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3165     return getTOCEntry(DAG, DL, GA);
3166   }
3167 
3168   unsigned MOHiFlag, MOLoFlag;
3169   bool IsPIC = isPositionIndependent();
3170   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3171 
3172   if (IsPIC && Subtarget.isSVR4ABI()) {
3173     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3174                                             GSDN->getOffset(),
3175                                             PPCII::MO_PIC_FLAG);
3176     return getTOCEntry(DAG, DL, GA);
3177   }
3178 
3179   SDValue GAHi =
3180     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3181   SDValue GALo =
3182     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3183 
3184   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3185 }
3186 
3187 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3188   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3189   SDLoc dl(Op);
3190 
3191   if (Op.getValueType() == MVT::v2i64) {
3192     // When the operands themselves are v2i64 values, we need to do something
3193     // special because VSX has no underlying comparison operations for these.
3194     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3195       // Equality can be handled by casting to the legal type for Altivec
3196       // comparisons, everything else needs to be expanded.
3197       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3198         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3199                  DAG.getSetCC(dl, MVT::v4i32,
3200                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3201                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3202                    CC));
3203       }
3204 
3205       return SDValue();
3206     }
3207 
3208     // We handle most of these in the usual way.
3209     return Op;
3210   }
3211 
3212   // If we're comparing for equality to zero, expose the fact that this is
3213   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3214   // fold the new nodes.
3215   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3216     return V;
3217 
3218   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3219     // Leave comparisons against 0 and -1 alone for now, since they're usually
3220     // optimized.  FIXME: revisit this when we can custom lower all setcc
3221     // optimizations.
3222     if (C->isAllOnesValue() || C->isNullValue())
3223       return SDValue();
3224   }
3225 
3226   // If we have an integer seteq/setne, turn it into a compare against zero
3227   // by xor'ing the rhs with the lhs, which is faster than setting a
3228   // condition register, reading it back out, and masking the correct bit.  The
3229   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3230   // the result to other bit-twiddling opportunities.
3231   EVT LHSVT = Op.getOperand(0).getValueType();
3232   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3233     EVT VT = Op.getValueType();
3234     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3235                                 Op.getOperand(1));
3236     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3237   }
3238   return SDValue();
3239 }
3240 
3241 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3242   SDNode *Node = Op.getNode();
3243   EVT VT = Node->getValueType(0);
3244   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3245   SDValue InChain = Node->getOperand(0);
3246   SDValue VAListPtr = Node->getOperand(1);
3247   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3248   SDLoc dl(Node);
3249 
3250   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3251 
3252   // gpr_index
3253   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3254                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3255   InChain = GprIndex.getValue(1);
3256 
3257   if (VT == MVT::i64) {
3258     // Check if GprIndex is even
3259     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3260                                  DAG.getConstant(1, dl, MVT::i32));
3261     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3262                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3263     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3264                                           DAG.getConstant(1, dl, MVT::i32));
3265     // Align GprIndex to be even if it isn't
3266     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3267                            GprIndex);
3268   }
3269 
3270   // fpr index is 1 byte after gpr
3271   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3272                                DAG.getConstant(1, dl, MVT::i32));
3273 
3274   // fpr
3275   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3276                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3277   InChain = FprIndex.getValue(1);
3278 
3279   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3280                                        DAG.getConstant(8, dl, MVT::i32));
3281 
3282   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3283                                         DAG.getConstant(4, dl, MVT::i32));
3284 
3285   // areas
3286   SDValue OverflowArea =
3287       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3288   InChain = OverflowArea.getValue(1);
3289 
3290   SDValue RegSaveArea =
3291       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3292   InChain = RegSaveArea.getValue(1);
3293 
3294   // select overflow_area if index > 8
3295   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3296                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3297 
3298   // adjustment constant gpr_index * 4/8
3299   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3300                                     VT.isInteger() ? GprIndex : FprIndex,
3301                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3302                                                     MVT::i32));
3303 
3304   // OurReg = RegSaveArea + RegConstant
3305   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3306                                RegConstant);
3307 
3308   // Floating types are 32 bytes into RegSaveArea
3309   if (VT.isFloatingPoint())
3310     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3311                          DAG.getConstant(32, dl, MVT::i32));
3312 
3313   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3314   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3315                                    VT.isInteger() ? GprIndex : FprIndex,
3316                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3317                                                    MVT::i32));
3318 
3319   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3320                               VT.isInteger() ? VAListPtr : FprPtr,
3321                               MachinePointerInfo(SV), MVT::i8);
3322 
3323   // determine if we should load from reg_save_area or overflow_area
3324   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3325 
3326   // increase overflow_area by 4/8 if gpr/fpr > 8
3327   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3328                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3329                                           dl, MVT::i32));
3330 
3331   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3332                              OverflowAreaPlusN);
3333 
3334   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3335                               MachinePointerInfo(), MVT::i32);
3336 
3337   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3338 }
3339 
3340 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3341   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3342 
3343   // We have to copy the entire va_list struct:
3344   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3345   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3346                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3347                        false, true, false, MachinePointerInfo(),
3348                        MachinePointerInfo());
3349 }
3350 
3351 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3352                                                   SelectionDAG &DAG) const {
3353   if (Subtarget.isAIXABI())
3354     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3355 
3356   return Op.getOperand(0);
3357 }
3358 
3359 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3360                                                 SelectionDAG &DAG) const {
3361   if (Subtarget.isAIXABI())
3362     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3363 
3364   SDValue Chain = Op.getOperand(0);
3365   SDValue Trmp = Op.getOperand(1); // trampoline
3366   SDValue FPtr = Op.getOperand(2); // nested function
3367   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3368   SDLoc dl(Op);
3369 
3370   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3371   bool isPPC64 = (PtrVT == MVT::i64);
3372   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3373 
3374   TargetLowering::ArgListTy Args;
3375   TargetLowering::ArgListEntry Entry;
3376 
3377   Entry.Ty = IntPtrTy;
3378   Entry.Node = Trmp; Args.push_back(Entry);
3379 
3380   // TrampSize == (isPPC64 ? 48 : 40);
3381   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3382                                isPPC64 ? MVT::i64 : MVT::i32);
3383   Args.push_back(Entry);
3384 
3385   Entry.Node = FPtr; Args.push_back(Entry);
3386   Entry.Node = Nest; Args.push_back(Entry);
3387 
3388   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3389   TargetLowering::CallLoweringInfo CLI(DAG);
3390   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3391       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3392       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3393 
3394   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3395   return CallResult.second;
3396 }
3397 
3398 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3399   MachineFunction &MF = DAG.getMachineFunction();
3400   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3401   EVT PtrVT = getPointerTy(MF.getDataLayout());
3402 
3403   SDLoc dl(Op);
3404 
3405   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3406     // vastart just stores the address of the VarArgsFrameIndex slot into the
3407     // memory location argument.
3408     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3409     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3410     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3411                         MachinePointerInfo(SV));
3412   }
3413 
3414   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3415   // We suppose the given va_list is already allocated.
3416   //
3417   // typedef struct {
3418   //  char gpr;     /* index into the array of 8 GPRs
3419   //                 * stored in the register save area
3420   //                 * gpr=0 corresponds to r3,
3421   //                 * gpr=1 to r4, etc.
3422   //                 */
3423   //  char fpr;     /* index into the array of 8 FPRs
3424   //                 * stored in the register save area
3425   //                 * fpr=0 corresponds to f1,
3426   //                 * fpr=1 to f2, etc.
3427   //                 */
3428   //  char *overflow_arg_area;
3429   //                /* location on stack that holds
3430   //                 * the next overflow argument
3431   //                 */
3432   //  char *reg_save_area;
3433   //               /* where r3:r10 and f1:f8 (if saved)
3434   //                * are stored
3435   //                */
3436   // } va_list[1];
3437 
3438   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3439   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3440   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3441                                             PtrVT);
3442   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3443                                  PtrVT);
3444 
3445   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3446   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3447 
3448   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3449   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3450 
3451   uint64_t FPROffset = 1;
3452   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3453 
3454   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3455 
3456   // Store first byte : number of int regs
3457   SDValue firstStore =
3458       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3459                         MachinePointerInfo(SV), MVT::i8);
3460   uint64_t nextOffset = FPROffset;
3461   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3462                                   ConstFPROffset);
3463 
3464   // Store second byte : number of float regs
3465   SDValue secondStore =
3466       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3467                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3468   nextOffset += StackOffset;
3469   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3470 
3471   // Store second word : arguments given on stack
3472   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3473                                     MachinePointerInfo(SV, nextOffset));
3474   nextOffset += FrameOffset;
3475   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3476 
3477   // Store third word : arguments given in registers
3478   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3479                       MachinePointerInfo(SV, nextOffset));
3480 }
3481 
3482 /// FPR - The set of FP registers that should be allocated for arguments
3483 /// on Darwin and AIX.
3484 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3485                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3486                                 PPC::F11, PPC::F12, PPC::F13};
3487 
3488 /// QFPR - The set of QPX registers that should be allocated for arguments.
3489 static const MCPhysReg QFPR[] = {
3490     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3491     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3492 
3493 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3494 /// the stack.
3495 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3496                                        unsigned PtrByteSize) {
3497   unsigned ArgSize = ArgVT.getStoreSize();
3498   if (Flags.isByVal())
3499     ArgSize = Flags.getByValSize();
3500 
3501   // Round up to multiples of the pointer size, except for array members,
3502   // which are always packed.
3503   if (!Flags.isInConsecutiveRegs())
3504     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3505 
3506   return ArgSize;
3507 }
3508 
3509 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3510 /// on the stack.
3511 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3512                                          ISD::ArgFlagsTy Flags,
3513                                          unsigned PtrByteSize) {
3514   Align Alignment(PtrByteSize);
3515 
3516   // Altivec parameters are padded to a 16 byte boundary.
3517   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3518       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3519       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3520       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3521     Alignment = Align(16);
3522   // QPX vector types stored in double-precision are padded to a 32 byte
3523   // boundary.
3524   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3525     Alignment = Align(32);
3526 
3527   // ByVal parameters are aligned as requested.
3528   if (Flags.isByVal()) {
3529     auto BVAlign = Flags.getNonZeroByValAlign();
3530     if (BVAlign > PtrByteSize) {
3531       if (BVAlign.value() % PtrByteSize != 0)
3532         llvm_unreachable(
3533             "ByVal alignment is not a multiple of the pointer size");
3534 
3535       Alignment = BVAlign;
3536     }
3537   }
3538 
3539   // Array members are always packed to their original alignment.
3540   if (Flags.isInConsecutiveRegs()) {
3541     // If the array member was split into multiple registers, the first
3542     // needs to be aligned to the size of the full type.  (Except for
3543     // ppcf128, which is only aligned as its f64 components.)
3544     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3545       Alignment = Align(OrigVT.getStoreSize());
3546     else
3547       Alignment = Align(ArgVT.getStoreSize());
3548   }
3549 
3550   return Alignment;
3551 }
3552 
3553 /// CalculateStackSlotUsed - Return whether this argument will use its
3554 /// stack slot (instead of being passed in registers).  ArgOffset,
3555 /// AvailableFPRs, and AvailableVRs must hold the current argument
3556 /// position, and will be updated to account for this argument.
3557 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3558                                    ISD::ArgFlagsTy Flags,
3559                                    unsigned PtrByteSize,
3560                                    unsigned LinkageSize,
3561                                    unsigned ParamAreaSize,
3562                                    unsigned &ArgOffset,
3563                                    unsigned &AvailableFPRs,
3564                                    unsigned &AvailableVRs, bool HasQPX) {
3565   bool UseMemory = false;
3566 
3567   // Respect alignment of argument on the stack.
3568   Align Alignment =
3569       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3570   ArgOffset = alignTo(ArgOffset, Alignment);
3571   // If there's no space left in the argument save area, we must
3572   // use memory (this check also catches zero-sized arguments).
3573   if (ArgOffset >= LinkageSize + ParamAreaSize)
3574     UseMemory = true;
3575 
3576   // Allocate argument on the stack.
3577   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3578   if (Flags.isInConsecutiveRegsLast())
3579     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3580   // If we overran the argument save area, we must use memory
3581   // (this check catches arguments passed partially in memory)
3582   if (ArgOffset > LinkageSize + ParamAreaSize)
3583     UseMemory = true;
3584 
3585   // However, if the argument is actually passed in an FPR or a VR,
3586   // we don't use memory after all.
3587   if (!Flags.isByVal()) {
3588     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3589         // QPX registers overlap with the scalar FP registers.
3590         (HasQPX && (ArgVT == MVT::v4f32 ||
3591                     ArgVT == MVT::v4f64 ||
3592                     ArgVT == MVT::v4i1)))
3593       if (AvailableFPRs > 0) {
3594         --AvailableFPRs;
3595         return false;
3596       }
3597     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3598         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3599         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3600         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3601       if (AvailableVRs > 0) {
3602         --AvailableVRs;
3603         return false;
3604       }
3605   }
3606 
3607   return UseMemory;
3608 }
3609 
3610 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3611 /// ensure minimum alignment required for target.
3612 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3613                                      unsigned NumBytes) {
3614   return alignTo(NumBytes, Lowering->getStackAlign());
3615 }
3616 
3617 SDValue PPCTargetLowering::LowerFormalArguments(
3618     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3619     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3620     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3621   if (Subtarget.isAIXABI())
3622     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3623                                     InVals);
3624   if (Subtarget.is64BitELFABI())
3625     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3626                                        InVals);
3627   if (Subtarget.is32BitELFABI())
3628     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3629                                        InVals);
3630 
3631   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3632                                      InVals);
3633 }
3634 
3635 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3636     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3637     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3638     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3639 
3640   // 32-bit SVR4 ABI Stack Frame Layout:
3641   //              +-----------------------------------+
3642   //        +-->  |            Back chain             |
3643   //        |     +-----------------------------------+
3644   //        |     | Floating-point register save area |
3645   //        |     +-----------------------------------+
3646   //        |     |    General register save area     |
3647   //        |     +-----------------------------------+
3648   //        |     |          CR save word             |
3649   //        |     +-----------------------------------+
3650   //        |     |         VRSAVE save word          |
3651   //        |     +-----------------------------------+
3652   //        |     |         Alignment padding         |
3653   //        |     +-----------------------------------+
3654   //        |     |     Vector register save area     |
3655   //        |     +-----------------------------------+
3656   //        |     |       Local variable space        |
3657   //        |     +-----------------------------------+
3658   //        |     |        Parameter list area        |
3659   //        |     +-----------------------------------+
3660   //        |     |           LR save word            |
3661   //        |     +-----------------------------------+
3662   // SP-->  +---  |            Back chain             |
3663   //              +-----------------------------------+
3664   //
3665   // Specifications:
3666   //   System V Application Binary Interface PowerPC Processor Supplement
3667   //   AltiVec Technology Programming Interface Manual
3668 
3669   MachineFunction &MF = DAG.getMachineFunction();
3670   MachineFrameInfo &MFI = MF.getFrameInfo();
3671   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3672 
3673   EVT PtrVT = getPointerTy(MF.getDataLayout());
3674   // Potential tail calls could cause overwriting of argument stack slots.
3675   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3676                        (CallConv == CallingConv::Fast));
3677   const Align PtrAlign(4);
3678 
3679   // Assign locations to all of the incoming arguments.
3680   SmallVector<CCValAssign, 16> ArgLocs;
3681   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3682                  *DAG.getContext());
3683 
3684   // Reserve space for the linkage area on the stack.
3685   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3686   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3687   if (useSoftFloat())
3688     CCInfo.PreAnalyzeFormalArguments(Ins);
3689 
3690   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3691   CCInfo.clearWasPPCF128();
3692 
3693   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3694     CCValAssign &VA = ArgLocs[i];
3695 
3696     // Arguments stored in registers.
3697     if (VA.isRegLoc()) {
3698       const TargetRegisterClass *RC;
3699       EVT ValVT = VA.getValVT();
3700 
3701       switch (ValVT.getSimpleVT().SimpleTy) {
3702         default:
3703           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3704         case MVT::i1:
3705         case MVT::i32:
3706           RC = &PPC::GPRCRegClass;
3707           break;
3708         case MVT::f32:
3709           if (Subtarget.hasP8Vector())
3710             RC = &PPC::VSSRCRegClass;
3711           else if (Subtarget.hasSPE())
3712             RC = &PPC::GPRCRegClass;
3713           else
3714             RC = &PPC::F4RCRegClass;
3715           break;
3716         case MVT::f64:
3717           if (Subtarget.hasVSX())
3718             RC = &PPC::VSFRCRegClass;
3719           else if (Subtarget.hasSPE())
3720             // SPE passes doubles in GPR pairs.
3721             RC = &PPC::GPRCRegClass;
3722           else
3723             RC = &PPC::F8RCRegClass;
3724           break;
3725         case MVT::v16i8:
3726         case MVT::v8i16:
3727         case MVT::v4i32:
3728           RC = &PPC::VRRCRegClass;
3729           break;
3730         case MVT::v4f32:
3731           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3732           break;
3733         case MVT::v2f64:
3734         case MVT::v2i64:
3735           RC = &PPC::VRRCRegClass;
3736           break;
3737         case MVT::v4f64:
3738           RC = &PPC::QFRCRegClass;
3739           break;
3740         case MVT::v4i1:
3741           RC = &PPC::QBRCRegClass;
3742           break;
3743       }
3744 
3745       SDValue ArgValue;
3746       // Transform the arguments stored in physical registers into
3747       // virtual ones.
3748       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3749         assert(i + 1 < e && "No second half of double precision argument");
3750         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3751         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3752         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3753         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3754         if (!Subtarget.isLittleEndian())
3755           std::swap (ArgValueLo, ArgValueHi);
3756         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3757                                ArgValueHi);
3758       } else {
3759         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3760         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3761                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3762         if (ValVT == MVT::i1)
3763           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3764       }
3765 
3766       InVals.push_back(ArgValue);
3767     } else {
3768       // Argument stored in memory.
3769       assert(VA.isMemLoc());
3770 
3771       // Get the extended size of the argument type in stack
3772       unsigned ArgSize = VA.getLocVT().getStoreSize();
3773       // Get the actual size of the argument type
3774       unsigned ObjSize = VA.getValVT().getStoreSize();
3775       unsigned ArgOffset = VA.getLocMemOffset();
3776       // Stack objects in PPC32 are right justified.
3777       ArgOffset += ArgSize - ObjSize;
3778       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3779 
3780       // Create load nodes to retrieve arguments from the stack.
3781       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3782       InVals.push_back(
3783           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3784     }
3785   }
3786 
3787   // Assign locations to all of the incoming aggregate by value arguments.
3788   // Aggregates passed by value are stored in the local variable space of the
3789   // caller's stack frame, right above the parameter list area.
3790   SmallVector<CCValAssign, 16> ByValArgLocs;
3791   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3792                       ByValArgLocs, *DAG.getContext());
3793 
3794   // Reserve stack space for the allocations in CCInfo.
3795   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
3796 
3797   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3798 
3799   // Area that is at least reserved in the caller of this function.
3800   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3801   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3802 
3803   // Set the size that is at least reserved in caller of this function.  Tail
3804   // call optimized function's reserved stack space needs to be aligned so that
3805   // taking the difference between two stack areas will result in an aligned
3806   // stack.
3807   MinReservedArea =
3808       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3809   FuncInfo->setMinReservedArea(MinReservedArea);
3810 
3811   SmallVector<SDValue, 8> MemOps;
3812 
3813   // If the function takes variable number of arguments, make a frame index for
3814   // the start of the first vararg value... for expansion of llvm.va_start.
3815   if (isVarArg) {
3816     static const MCPhysReg GPArgRegs[] = {
3817       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3818       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3819     };
3820     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3821 
3822     static const MCPhysReg FPArgRegs[] = {
3823       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3824       PPC::F8
3825     };
3826     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3827 
3828     if (useSoftFloat() || hasSPE())
3829        NumFPArgRegs = 0;
3830 
3831     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3832     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3833 
3834     // Make room for NumGPArgRegs and NumFPArgRegs.
3835     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3836                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3837 
3838     FuncInfo->setVarArgsStackOffset(
3839       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3840                             CCInfo.getNextStackOffset(), true));
3841 
3842     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3843     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3844 
3845     // The fixed integer arguments of a variadic function are stored to the
3846     // VarArgsFrameIndex on the stack so that they may be loaded by
3847     // dereferencing the result of va_next.
3848     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3849       // Get an existing live-in vreg, or add a new one.
3850       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3851       if (!VReg)
3852         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3853 
3854       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3855       SDValue Store =
3856           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3857       MemOps.push_back(Store);
3858       // Increment the address by four for the next argument to store
3859       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3860       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3861     }
3862 
3863     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3864     // is set.
3865     // The double arguments are stored to the VarArgsFrameIndex
3866     // on the stack.
3867     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3868       // Get an existing live-in vreg, or add a new one.
3869       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3870       if (!VReg)
3871         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3872 
3873       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3874       SDValue Store =
3875           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3876       MemOps.push_back(Store);
3877       // Increment the address by eight for the next argument to store
3878       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3879                                          PtrVT);
3880       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3881     }
3882   }
3883 
3884   if (!MemOps.empty())
3885     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3886 
3887   return Chain;
3888 }
3889 
3890 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3891 // value to MVT::i64 and then truncate to the correct register size.
3892 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3893                                              EVT ObjectVT, SelectionDAG &DAG,
3894                                              SDValue ArgVal,
3895                                              const SDLoc &dl) const {
3896   if (Flags.isSExt())
3897     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3898                          DAG.getValueType(ObjectVT));
3899   else if (Flags.isZExt())
3900     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3901                          DAG.getValueType(ObjectVT));
3902 
3903   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3904 }
3905 
3906 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3907     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3908     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3909     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3910   // TODO: add description of PPC stack frame format, or at least some docs.
3911   //
3912   bool isELFv2ABI = Subtarget.isELFv2ABI();
3913   bool isLittleEndian = Subtarget.isLittleEndian();
3914   MachineFunction &MF = DAG.getMachineFunction();
3915   MachineFrameInfo &MFI = MF.getFrameInfo();
3916   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3917 
3918   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3919          "fastcc not supported on varargs functions");
3920 
3921   EVT PtrVT = getPointerTy(MF.getDataLayout());
3922   // Potential tail calls could cause overwriting of argument stack slots.
3923   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3924                        (CallConv == CallingConv::Fast));
3925   unsigned PtrByteSize = 8;
3926   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3927 
3928   static const MCPhysReg GPR[] = {
3929     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3930     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3931   };
3932   static const MCPhysReg VR[] = {
3933     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3934     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3935   };
3936 
3937   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3938   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3939   const unsigned Num_VR_Regs  = array_lengthof(VR);
3940   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3941 
3942   // Do a first pass over the arguments to determine whether the ABI
3943   // guarantees that our caller has allocated the parameter save area
3944   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3945   // in the ELFv2 ABI, it is true if this is a vararg function or if
3946   // any parameter is located in a stack slot.
3947 
3948   bool HasParameterArea = !isELFv2ABI || isVarArg;
3949   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3950   unsigned NumBytes = LinkageSize;
3951   unsigned AvailableFPRs = Num_FPR_Regs;
3952   unsigned AvailableVRs = Num_VR_Regs;
3953   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3954     if (Ins[i].Flags.isNest())
3955       continue;
3956 
3957     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3958                                PtrByteSize, LinkageSize, ParamAreaSize,
3959                                NumBytes, AvailableFPRs, AvailableVRs,
3960                                Subtarget.hasQPX()))
3961       HasParameterArea = true;
3962   }
3963 
3964   // Add DAG nodes to load the arguments or copy them out of registers.  On
3965   // entry to a function on PPC, the arguments start after the linkage area,
3966   // although the first ones are often in registers.
3967 
3968   unsigned ArgOffset = LinkageSize;
3969   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3970   unsigned &QFPR_idx = FPR_idx;
3971   SmallVector<SDValue, 8> MemOps;
3972   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3973   unsigned CurArgIdx = 0;
3974   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3975     SDValue ArgVal;
3976     bool needsLoad = false;
3977     EVT ObjectVT = Ins[ArgNo].VT;
3978     EVT OrigVT = Ins[ArgNo].ArgVT;
3979     unsigned ObjSize = ObjectVT.getStoreSize();
3980     unsigned ArgSize = ObjSize;
3981     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3982     if (Ins[ArgNo].isOrigArg()) {
3983       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3984       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3985     }
3986     // We re-align the argument offset for each argument, except when using the
3987     // fast calling convention, when we need to make sure we do that only when
3988     // we'll actually use a stack slot.
3989     unsigned CurArgOffset;
3990     Align Alignment;
3991     auto ComputeArgOffset = [&]() {
3992       /* Respect alignment of argument on the stack.  */
3993       Alignment =
3994           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3995       ArgOffset = alignTo(ArgOffset, Alignment);
3996       CurArgOffset = ArgOffset;
3997     };
3998 
3999     if (CallConv != CallingConv::Fast) {
4000       ComputeArgOffset();
4001 
4002       /* Compute GPR index associated with argument offset.  */
4003       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4004       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4005     }
4006 
4007     // FIXME the codegen can be much improved in some cases.
4008     // We do not have to keep everything in memory.
4009     if (Flags.isByVal()) {
4010       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4011 
4012       if (CallConv == CallingConv::Fast)
4013         ComputeArgOffset();
4014 
4015       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4016       ObjSize = Flags.getByValSize();
4017       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4018       // Empty aggregate parameters do not take up registers.  Examples:
4019       //   struct { } a;
4020       //   union  { } b;
4021       //   int c[0];
4022       // etc.  However, we have to provide a place-holder in InVals, so
4023       // pretend we have an 8-byte item at the current address for that
4024       // purpose.
4025       if (!ObjSize) {
4026         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4027         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4028         InVals.push_back(FIN);
4029         continue;
4030       }
4031 
4032       // Create a stack object covering all stack doublewords occupied
4033       // by the argument.  If the argument is (fully or partially) on
4034       // the stack, or if the argument is fully in registers but the
4035       // caller has allocated the parameter save anyway, we can refer
4036       // directly to the caller's stack frame.  Otherwise, create a
4037       // local copy in our own frame.
4038       int FI;
4039       if (HasParameterArea ||
4040           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4041         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4042       else
4043         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4044       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4045 
4046       // Handle aggregates smaller than 8 bytes.
4047       if (ObjSize < PtrByteSize) {
4048         // The value of the object is its address, which differs from the
4049         // address of the enclosing doubleword on big-endian systems.
4050         SDValue Arg = FIN;
4051         if (!isLittleEndian) {
4052           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4053           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4054         }
4055         InVals.push_back(Arg);
4056 
4057         if (GPR_idx != Num_GPR_Regs) {
4058           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4059           FuncInfo->addLiveInAttr(VReg, Flags);
4060           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4061           SDValue Store;
4062 
4063           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
4064             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
4065                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
4066             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4067                                       MachinePointerInfo(&*FuncArg), ObjType);
4068           } else {
4069             // For sizes that don't fit a truncating store (3, 5, 6, 7),
4070             // store the whole register as-is to the parameter save area
4071             // slot.
4072             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4073                                  MachinePointerInfo(&*FuncArg));
4074           }
4075 
4076           MemOps.push_back(Store);
4077         }
4078         // Whether we copied from a register or not, advance the offset
4079         // into the parameter save area by a full doubleword.
4080         ArgOffset += PtrByteSize;
4081         continue;
4082       }
4083 
4084       // The value of the object is its address, which is the address of
4085       // its first stack doubleword.
4086       InVals.push_back(FIN);
4087 
4088       // Store whatever pieces of the object are in registers to memory.
4089       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4090         if (GPR_idx == Num_GPR_Regs)
4091           break;
4092 
4093         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4094         FuncInfo->addLiveInAttr(VReg, Flags);
4095         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4096         SDValue Addr = FIN;
4097         if (j) {
4098           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4099           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4100         }
4101         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4102                                      MachinePointerInfo(&*FuncArg, j));
4103         MemOps.push_back(Store);
4104         ++GPR_idx;
4105       }
4106       ArgOffset += ArgSize;
4107       continue;
4108     }
4109 
4110     switch (ObjectVT.getSimpleVT().SimpleTy) {
4111     default: llvm_unreachable("Unhandled argument type!");
4112     case MVT::i1:
4113     case MVT::i32:
4114     case MVT::i64:
4115       if (Flags.isNest()) {
4116         // The 'nest' parameter, if any, is passed in R11.
4117         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4118         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4119 
4120         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4121           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4122 
4123         break;
4124       }
4125 
4126       // These can be scalar arguments or elements of an integer array type
4127       // passed directly.  Clang may use those instead of "byval" aggregate
4128       // types to avoid forcing arguments to memory unnecessarily.
4129       if (GPR_idx != Num_GPR_Regs) {
4130         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4131         FuncInfo->addLiveInAttr(VReg, Flags);
4132         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4133 
4134         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4135           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4136           // value to MVT::i64 and then truncate to the correct register size.
4137           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4138       } else {
4139         if (CallConv == CallingConv::Fast)
4140           ComputeArgOffset();
4141 
4142         needsLoad = true;
4143         ArgSize = PtrByteSize;
4144       }
4145       if (CallConv != CallingConv::Fast || needsLoad)
4146         ArgOffset += 8;
4147       break;
4148 
4149     case MVT::f32:
4150     case MVT::f64:
4151       // These can be scalar arguments or elements of a float array type
4152       // passed directly.  The latter are used to implement ELFv2 homogenous
4153       // float aggregates.
4154       if (FPR_idx != Num_FPR_Regs) {
4155         unsigned VReg;
4156 
4157         if (ObjectVT == MVT::f32)
4158           VReg = MF.addLiveIn(FPR[FPR_idx],
4159                               Subtarget.hasP8Vector()
4160                                   ? &PPC::VSSRCRegClass
4161                                   : &PPC::F4RCRegClass);
4162         else
4163           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4164                                                 ? &PPC::VSFRCRegClass
4165                                                 : &PPC::F8RCRegClass);
4166 
4167         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4168         ++FPR_idx;
4169       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4170         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4171         // once we support fp <-> gpr moves.
4172 
4173         // This can only ever happen in the presence of f32 array types,
4174         // since otherwise we never run out of FPRs before running out
4175         // of GPRs.
4176         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4177         FuncInfo->addLiveInAttr(VReg, Flags);
4178         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4179 
4180         if (ObjectVT == MVT::f32) {
4181           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4182             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4183                                  DAG.getConstant(32, dl, MVT::i32));
4184           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4185         }
4186 
4187         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4188       } else {
4189         if (CallConv == CallingConv::Fast)
4190           ComputeArgOffset();
4191 
4192         needsLoad = true;
4193       }
4194 
4195       // When passing an array of floats, the array occupies consecutive
4196       // space in the argument area; only round up to the next doubleword
4197       // at the end of the array.  Otherwise, each float takes 8 bytes.
4198       if (CallConv != CallingConv::Fast || needsLoad) {
4199         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4200         ArgOffset += ArgSize;
4201         if (Flags.isInConsecutiveRegsLast())
4202           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4203       }
4204       break;
4205     case MVT::v4f32:
4206     case MVT::v4i32:
4207     case MVT::v8i16:
4208     case MVT::v16i8:
4209     case MVT::v2f64:
4210     case MVT::v2i64:
4211     case MVT::v1i128:
4212     case MVT::f128:
4213       if (!Subtarget.hasQPX()) {
4214         // These can be scalar arguments or elements of a vector array type
4215         // passed directly.  The latter are used to implement ELFv2 homogenous
4216         // vector aggregates.
4217         if (VR_idx != Num_VR_Regs) {
4218           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4219           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4220           ++VR_idx;
4221         } else {
4222           if (CallConv == CallingConv::Fast)
4223             ComputeArgOffset();
4224           needsLoad = true;
4225         }
4226         if (CallConv != CallingConv::Fast || needsLoad)
4227           ArgOffset += 16;
4228         break;
4229       } // not QPX
4230 
4231       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
4232              "Invalid QPX parameter type");
4233       LLVM_FALLTHROUGH;
4234 
4235     case MVT::v4f64:
4236     case MVT::v4i1:
4237       // QPX vectors are treated like their scalar floating-point subregisters
4238       // (except that they're larger).
4239       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4240       if (QFPR_idx != Num_QFPR_Regs) {
4241         const TargetRegisterClass *RC;
4242         switch (ObjectVT.getSimpleVT().SimpleTy) {
4243         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4244         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4245         default:         RC = &PPC::QBRCRegClass; break;
4246         }
4247 
4248         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4249         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4250         ++QFPR_idx;
4251       } else {
4252         if (CallConv == CallingConv::Fast)
4253           ComputeArgOffset();
4254         needsLoad = true;
4255       }
4256       if (CallConv != CallingConv::Fast || needsLoad)
4257         ArgOffset += Sz;
4258       break;
4259     }
4260 
4261     // We need to load the argument to a virtual register if we determined
4262     // above that we ran out of physical registers of the appropriate type.
4263     if (needsLoad) {
4264       if (ObjSize < ArgSize && !isLittleEndian)
4265         CurArgOffset += ArgSize - ObjSize;
4266       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4267       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4268       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4269     }
4270 
4271     InVals.push_back(ArgVal);
4272   }
4273 
4274   // Area that is at least reserved in the caller of this function.
4275   unsigned MinReservedArea;
4276   if (HasParameterArea)
4277     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4278   else
4279     MinReservedArea = LinkageSize;
4280 
4281   // Set the size that is at least reserved in caller of this function.  Tail
4282   // call optimized functions' reserved stack space needs to be aligned so that
4283   // taking the difference between two stack areas will result in an aligned
4284   // stack.
4285   MinReservedArea =
4286       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4287   FuncInfo->setMinReservedArea(MinReservedArea);
4288 
4289   // If the function takes variable number of arguments, make a frame index for
4290   // the start of the first vararg value... for expansion of llvm.va_start.
4291   if (isVarArg) {
4292     int Depth = ArgOffset;
4293 
4294     FuncInfo->setVarArgsFrameIndex(
4295       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4296     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4297 
4298     // If this function is vararg, store any remaining integer argument regs
4299     // to their spots on the stack so that they may be loaded by dereferencing
4300     // the result of va_next.
4301     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4302          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4303       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4304       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4305       SDValue Store =
4306           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4307       MemOps.push_back(Store);
4308       // Increment the address by four for the next argument to store
4309       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4310       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4311     }
4312   }
4313 
4314   if (!MemOps.empty())
4315     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4316 
4317   return Chain;
4318 }
4319 
4320 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4321     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4322     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4323     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4324   // TODO: add description of PPC stack frame format, or at least some docs.
4325   //
4326   MachineFunction &MF = DAG.getMachineFunction();
4327   MachineFrameInfo &MFI = MF.getFrameInfo();
4328   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4329 
4330   EVT PtrVT = getPointerTy(MF.getDataLayout());
4331   bool isPPC64 = PtrVT == MVT::i64;
4332   // Potential tail calls could cause overwriting of argument stack slots.
4333   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4334                        (CallConv == CallingConv::Fast));
4335   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4336   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4337   unsigned ArgOffset = LinkageSize;
4338   // Area that is at least reserved in caller of this function.
4339   unsigned MinReservedArea = ArgOffset;
4340 
4341   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4342     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4343     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4344   };
4345   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4346     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4347     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4348   };
4349   static const MCPhysReg VR[] = {
4350     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4351     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4352   };
4353 
4354   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4355   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4356   const unsigned Num_VR_Regs  = array_lengthof( VR);
4357 
4358   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4359 
4360   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4361 
4362   // In 32-bit non-varargs functions, the stack space for vectors is after the
4363   // stack space for non-vectors.  We do not use this space unless we have
4364   // too many vectors to fit in registers, something that only occurs in
4365   // constructed examples:), but we have to walk the arglist to figure
4366   // that out...for the pathological case, compute VecArgOffset as the
4367   // start of the vector parameter area.  Computing VecArgOffset is the
4368   // entire point of the following loop.
4369   unsigned VecArgOffset = ArgOffset;
4370   if (!isVarArg && !isPPC64) {
4371     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4372          ++ArgNo) {
4373       EVT ObjectVT = Ins[ArgNo].VT;
4374       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4375 
4376       if (Flags.isByVal()) {
4377         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4378         unsigned ObjSize = Flags.getByValSize();
4379         unsigned ArgSize =
4380                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4381         VecArgOffset += ArgSize;
4382         continue;
4383       }
4384 
4385       switch(ObjectVT.getSimpleVT().SimpleTy) {
4386       default: llvm_unreachable("Unhandled argument type!");
4387       case MVT::i1:
4388       case MVT::i32:
4389       case MVT::f32:
4390         VecArgOffset += 4;
4391         break;
4392       case MVT::i64:  // PPC64
4393       case MVT::f64:
4394         // FIXME: We are guaranteed to be !isPPC64 at this point.
4395         // Does MVT::i64 apply?
4396         VecArgOffset += 8;
4397         break;
4398       case MVT::v4f32:
4399       case MVT::v4i32:
4400       case MVT::v8i16:
4401       case MVT::v16i8:
4402         // Nothing to do, we're only looking at Nonvector args here.
4403         break;
4404       }
4405     }
4406   }
4407   // We've found where the vector parameter area in memory is.  Skip the
4408   // first 12 parameters; these don't use that memory.
4409   VecArgOffset = ((VecArgOffset+15)/16)*16;
4410   VecArgOffset += 12*16;
4411 
4412   // Add DAG nodes to load the arguments or copy them out of registers.  On
4413   // entry to a function on PPC, the arguments start after the linkage area,
4414   // although the first ones are often in registers.
4415 
4416   SmallVector<SDValue, 8> MemOps;
4417   unsigned nAltivecParamsAtEnd = 0;
4418   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4419   unsigned CurArgIdx = 0;
4420   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4421     SDValue ArgVal;
4422     bool needsLoad = false;
4423     EVT ObjectVT = Ins[ArgNo].VT;
4424     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4425     unsigned ArgSize = ObjSize;
4426     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4427     if (Ins[ArgNo].isOrigArg()) {
4428       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4429       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4430     }
4431     unsigned CurArgOffset = ArgOffset;
4432 
4433     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4434     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4435         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4436       if (isVarArg || isPPC64) {
4437         MinReservedArea = ((MinReservedArea+15)/16)*16;
4438         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4439                                                   Flags,
4440                                                   PtrByteSize);
4441       } else  nAltivecParamsAtEnd++;
4442     } else
4443       // Calculate min reserved area.
4444       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4445                                                 Flags,
4446                                                 PtrByteSize);
4447 
4448     // FIXME the codegen can be much improved in some cases.
4449     // We do not have to keep everything in memory.
4450     if (Flags.isByVal()) {
4451       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4452 
4453       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4454       ObjSize = Flags.getByValSize();
4455       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4456       // Objects of size 1 and 2 are right justified, everything else is
4457       // left justified.  This means the memory address is adjusted forwards.
4458       if (ObjSize==1 || ObjSize==2) {
4459         CurArgOffset = CurArgOffset + (4 - ObjSize);
4460       }
4461       // The value of the object is its address.
4462       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4463       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4464       InVals.push_back(FIN);
4465       if (ObjSize==1 || ObjSize==2) {
4466         if (GPR_idx != Num_GPR_Regs) {
4467           unsigned VReg;
4468           if (isPPC64)
4469             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4470           else
4471             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4472           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4473           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4474           SDValue Store =
4475               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4476                                 MachinePointerInfo(&*FuncArg), ObjType);
4477           MemOps.push_back(Store);
4478           ++GPR_idx;
4479         }
4480 
4481         ArgOffset += PtrByteSize;
4482 
4483         continue;
4484       }
4485       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4486         // Store whatever pieces of the object are in registers
4487         // to memory.  ArgOffset will be the address of the beginning
4488         // of the object.
4489         if (GPR_idx != Num_GPR_Regs) {
4490           unsigned VReg;
4491           if (isPPC64)
4492             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4493           else
4494             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4495           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4496           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4497           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4498           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4499                                        MachinePointerInfo(&*FuncArg, j));
4500           MemOps.push_back(Store);
4501           ++GPR_idx;
4502           ArgOffset += PtrByteSize;
4503         } else {
4504           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4505           break;
4506         }
4507       }
4508       continue;
4509     }
4510 
4511     switch (ObjectVT.getSimpleVT().SimpleTy) {
4512     default: llvm_unreachable("Unhandled argument type!");
4513     case MVT::i1:
4514     case MVT::i32:
4515       if (!isPPC64) {
4516         if (GPR_idx != Num_GPR_Regs) {
4517           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4518           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4519 
4520           if (ObjectVT == MVT::i1)
4521             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4522 
4523           ++GPR_idx;
4524         } else {
4525           needsLoad = true;
4526           ArgSize = PtrByteSize;
4527         }
4528         // All int arguments reserve stack space in the Darwin ABI.
4529         ArgOffset += PtrByteSize;
4530         break;
4531       }
4532       LLVM_FALLTHROUGH;
4533     case MVT::i64:  // PPC64
4534       if (GPR_idx != Num_GPR_Regs) {
4535         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4536         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4537 
4538         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4539           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4540           // value to MVT::i64 and then truncate to the correct register size.
4541           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4542 
4543         ++GPR_idx;
4544       } else {
4545         needsLoad = true;
4546         ArgSize = PtrByteSize;
4547       }
4548       // All int arguments reserve stack space in the Darwin ABI.
4549       ArgOffset += 8;
4550       break;
4551 
4552     case MVT::f32:
4553     case MVT::f64:
4554       // Every 4 bytes of argument space consumes one of the GPRs available for
4555       // argument passing.
4556       if (GPR_idx != Num_GPR_Regs) {
4557         ++GPR_idx;
4558         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4559           ++GPR_idx;
4560       }
4561       if (FPR_idx != Num_FPR_Regs) {
4562         unsigned VReg;
4563 
4564         if (ObjectVT == MVT::f32)
4565           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4566         else
4567           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4568 
4569         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4570         ++FPR_idx;
4571       } else {
4572         needsLoad = true;
4573       }
4574 
4575       // All FP arguments reserve stack space in the Darwin ABI.
4576       ArgOffset += isPPC64 ? 8 : ObjSize;
4577       break;
4578     case MVT::v4f32:
4579     case MVT::v4i32:
4580     case MVT::v8i16:
4581     case MVT::v16i8:
4582       // Note that vector arguments in registers don't reserve stack space,
4583       // except in varargs functions.
4584       if (VR_idx != Num_VR_Regs) {
4585         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4586         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4587         if (isVarArg) {
4588           while ((ArgOffset % 16) != 0) {
4589             ArgOffset += PtrByteSize;
4590             if (GPR_idx != Num_GPR_Regs)
4591               GPR_idx++;
4592           }
4593           ArgOffset += 16;
4594           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4595         }
4596         ++VR_idx;
4597       } else {
4598         if (!isVarArg && !isPPC64) {
4599           // Vectors go after all the nonvectors.
4600           CurArgOffset = VecArgOffset;
4601           VecArgOffset += 16;
4602         } else {
4603           // Vectors are aligned.
4604           ArgOffset = ((ArgOffset+15)/16)*16;
4605           CurArgOffset = ArgOffset;
4606           ArgOffset += 16;
4607         }
4608         needsLoad = true;
4609       }
4610       break;
4611     }
4612 
4613     // We need to load the argument to a virtual register if we determined above
4614     // that we ran out of physical registers of the appropriate type.
4615     if (needsLoad) {
4616       int FI = MFI.CreateFixedObject(ObjSize,
4617                                      CurArgOffset + (ArgSize - ObjSize),
4618                                      isImmutable);
4619       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4620       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4621     }
4622 
4623     InVals.push_back(ArgVal);
4624   }
4625 
4626   // Allow for Altivec parameters at the end, if needed.
4627   if (nAltivecParamsAtEnd) {
4628     MinReservedArea = ((MinReservedArea+15)/16)*16;
4629     MinReservedArea += 16*nAltivecParamsAtEnd;
4630   }
4631 
4632   // Area that is at least reserved in the caller of this function.
4633   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4634 
4635   // Set the size that is at least reserved in caller of this function.  Tail
4636   // call optimized functions' reserved stack space needs to be aligned so that
4637   // taking the difference between two stack areas will result in an aligned
4638   // stack.
4639   MinReservedArea =
4640       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4641   FuncInfo->setMinReservedArea(MinReservedArea);
4642 
4643   // If the function takes variable number of arguments, make a frame index for
4644   // the start of the first vararg value... for expansion of llvm.va_start.
4645   if (isVarArg) {
4646     int Depth = ArgOffset;
4647 
4648     FuncInfo->setVarArgsFrameIndex(
4649       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4650                             Depth, true));
4651     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4652 
4653     // If this function is vararg, store any remaining integer argument regs
4654     // to their spots on the stack so that they may be loaded by dereferencing
4655     // the result of va_next.
4656     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4657       unsigned VReg;
4658 
4659       if (isPPC64)
4660         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4661       else
4662         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4663 
4664       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4665       SDValue Store =
4666           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4667       MemOps.push_back(Store);
4668       // Increment the address by four for the next argument to store
4669       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4670       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4671     }
4672   }
4673 
4674   if (!MemOps.empty())
4675     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4676 
4677   return Chain;
4678 }
4679 
4680 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4681 /// adjusted to accommodate the arguments for the tailcall.
4682 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4683                                    unsigned ParamSize) {
4684 
4685   if (!isTailCall) return 0;
4686 
4687   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4688   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4689   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4690   // Remember only if the new adjustment is bigger.
4691   if (SPDiff < FI->getTailCallSPDelta())
4692     FI->setTailCallSPDelta(SPDiff);
4693 
4694   return SPDiff;
4695 }
4696 
4697 static bool isFunctionGlobalAddress(SDValue Callee);
4698 
4699 static bool
4700 callsShareTOCBase(const Function *Caller, SDValue Callee,
4701                     const TargetMachine &TM) {
4702    // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4703    // don't have enough information to determine if the caller and calle share
4704    // the same  TOC base, so we have to pessimistically assume they don't for
4705    // correctness.
4706    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4707    if (!G)
4708      return false;
4709 
4710    const GlobalValue *GV = G->getGlobal();
4711   // The medium and large code models are expected to provide a sufficiently
4712   // large TOC to provide all data addressing needs of a module with a
4713   // single TOC. Since each module will be addressed with a single TOC then we
4714   // only need to check that caller and callee don't cross dso boundaries.
4715   if (CodeModel::Medium == TM.getCodeModel() ||
4716       CodeModel::Large == TM.getCodeModel())
4717     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4718 
4719   // Otherwise we need to ensure callee and caller are in the same section,
4720   // since the linker may allocate multiple TOCs, and we don't know which
4721   // sections will belong to the same TOC base.
4722 
4723   if (!GV->isStrongDefinitionForLinker())
4724     return false;
4725 
4726   // Any explicitly-specified sections and section prefixes must also match.
4727   // Also, if we're using -ffunction-sections, then each function is always in
4728   // a different section (the same is true for COMDAT functions).
4729   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4730       GV->getSection() != Caller->getSection())
4731     return false;
4732   if (const auto *F = dyn_cast<Function>(GV)) {
4733     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4734       return false;
4735   }
4736 
4737   // If the callee might be interposed, then we can't assume the ultimate call
4738   // target will be in the same section. Even in cases where we can assume that
4739   // interposition won't happen, in any case where the linker might insert a
4740   // stub to allow for interposition, we must generate code as though
4741   // interposition might occur. To understand why this matters, consider a
4742   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4743   // in the same section, but a is in a different module (i.e. has a different
4744   // TOC base pointer). If the linker allows for interposition between b and c,
4745   // then it will generate a stub for the call edge between b and c which will
4746   // save the TOC pointer into the designated stack slot allocated by b. If we
4747   // return true here, and therefore allow a tail call between b and c, that
4748   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4749   // pointer into the stack slot allocated by a (where the a -> b stub saved
4750   // a's TOC base pointer). If we're not considering a tail call, but rather,
4751   // whether a nop is needed after the call instruction in b, because the linker
4752   // will insert a stub, it might complain about a missing nop if we omit it
4753   // (although many don't complain in this case).
4754   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4755     return false;
4756 
4757   return true;
4758 }
4759 
4760 static bool
4761 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4762                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4763   assert(Subtarget.is64BitELFABI());
4764 
4765   const unsigned PtrByteSize = 8;
4766   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4767 
4768   static const MCPhysReg GPR[] = {
4769     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4770     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4771   };
4772   static const MCPhysReg VR[] = {
4773     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4774     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4775   };
4776 
4777   const unsigned NumGPRs = array_lengthof(GPR);
4778   const unsigned NumFPRs = 13;
4779   const unsigned NumVRs = array_lengthof(VR);
4780   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4781 
4782   unsigned NumBytes = LinkageSize;
4783   unsigned AvailableFPRs = NumFPRs;
4784   unsigned AvailableVRs = NumVRs;
4785 
4786   for (const ISD::OutputArg& Param : Outs) {
4787     if (Param.Flags.isNest()) continue;
4788 
4789     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4790                                PtrByteSize, LinkageSize, ParamAreaSize,
4791                                NumBytes, AvailableFPRs, AvailableVRs,
4792                                Subtarget.hasQPX()))
4793       return true;
4794   }
4795   return false;
4796 }
4797 
4798 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4799   if (CB.arg_size() != CallerFn->arg_size())
4800     return false;
4801 
4802   auto CalleeArgIter = CB.arg_begin();
4803   auto CalleeArgEnd = CB.arg_end();
4804   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4805 
4806   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4807     const Value* CalleeArg = *CalleeArgIter;
4808     const Value* CallerArg = &(*CallerArgIter);
4809     if (CalleeArg == CallerArg)
4810       continue;
4811 
4812     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4813     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4814     //      }
4815     // 1st argument of callee is undef and has the same type as caller.
4816     if (CalleeArg->getType() == CallerArg->getType() &&
4817         isa<UndefValue>(CalleeArg))
4818       continue;
4819 
4820     return false;
4821   }
4822 
4823   return true;
4824 }
4825 
4826 // Returns true if TCO is possible between the callers and callees
4827 // calling conventions.
4828 static bool
4829 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4830                                     CallingConv::ID CalleeCC) {
4831   // Tail calls are possible with fastcc and ccc.
4832   auto isTailCallableCC  = [] (CallingConv::ID CC){
4833       return  CC == CallingConv::C || CC == CallingConv::Fast;
4834   };
4835   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4836     return false;
4837 
4838   // We can safely tail call both fastcc and ccc callees from a c calling
4839   // convention caller. If the caller is fastcc, we may have less stack space
4840   // than a non-fastcc caller with the same signature so disable tail-calls in
4841   // that case.
4842   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4843 }
4844 
4845 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4846     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4847     const SmallVectorImpl<ISD::OutputArg> &Outs,
4848     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4849   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4850 
4851   if (DisableSCO && !TailCallOpt) return false;
4852 
4853   // Variadic argument functions are not supported.
4854   if (isVarArg) return false;
4855 
4856   auto &Caller = DAG.getMachineFunction().getFunction();
4857   // Check that the calling conventions are compatible for tco.
4858   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4859     return false;
4860 
4861   // Caller contains any byval parameter is not supported.
4862   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4863     return false;
4864 
4865   // Callee contains any byval parameter is not supported, too.
4866   // Note: This is a quick work around, because in some cases, e.g.
4867   // caller's stack size > callee's stack size, we are still able to apply
4868   // sibling call optimization. For example, gcc is able to do SCO for caller1
4869   // in the following example, but not for caller2.
4870   //   struct test {
4871   //     long int a;
4872   //     char ary[56];
4873   //   } gTest;
4874   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4875   //     b->a = v.a;
4876   //     return 0;
4877   //   }
4878   //   void caller1(struct test a, struct test c, struct test *b) {
4879   //     callee(gTest, b); }
4880   //   void caller2(struct test *b) { callee(gTest, b); }
4881   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4882     return false;
4883 
4884   // If callee and caller use different calling conventions, we cannot pass
4885   // parameters on stack since offsets for the parameter area may be different.
4886   if (Caller.getCallingConv() != CalleeCC &&
4887       needStackSlotPassParameters(Subtarget, Outs))
4888     return false;
4889 
4890   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4891   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4892   // callee potentially have different TOC bases then we cannot tail call since
4893   // we need to restore the TOC pointer after the call.
4894   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4895   // We cannot guarantee this for indirect calls or calls to external functions.
4896   // When PC-Relative addressing is used, the concept of the TOC is no longer
4897   // applicable so this check is not required.
4898   // Check first for indirect calls.
4899   if (!Subtarget.isUsingPCRelativeCalls() &&
4900       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4901     return false;
4902 
4903   // Check if we share the TOC base.
4904   if (!Subtarget.isUsingPCRelativeCalls() &&
4905       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4906     return false;
4907 
4908   // TCO allows altering callee ABI, so we don't have to check further.
4909   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4910     return true;
4911 
4912   if (DisableSCO) return false;
4913 
4914   // If callee use the same argument list that caller is using, then we can
4915   // apply SCO on this case. If it is not, then we need to check if callee needs
4916   // stack for passing arguments.
4917   // PC Relative tail calls may not have a CallBase.
4918   // If there is no CallBase we cannot verify if we have the same argument
4919   // list so assume that we don't have the same argument list.
4920   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4921       needStackSlotPassParameters(Subtarget, Outs))
4922     return false;
4923   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4924     return false;
4925 
4926   return true;
4927 }
4928 
4929 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4930 /// for tail call optimization. Targets which want to do tail call
4931 /// optimization should implement this function.
4932 bool
4933 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4934                                                      CallingConv::ID CalleeCC,
4935                                                      bool isVarArg,
4936                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4937                                                      SelectionDAG& DAG) const {
4938   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4939     return false;
4940 
4941   // Variable argument functions are not supported.
4942   if (isVarArg)
4943     return false;
4944 
4945   MachineFunction &MF = DAG.getMachineFunction();
4946   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4947   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4948     // Functions containing by val parameters are not supported.
4949     for (unsigned i = 0; i != Ins.size(); i++) {
4950        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4951        if (Flags.isByVal()) return false;
4952     }
4953 
4954     // Non-PIC/GOT tail calls are supported.
4955     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4956       return true;
4957 
4958     // At the moment we can only do local tail calls (in same module, hidden
4959     // or protected) if we are generating PIC.
4960     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4961       return G->getGlobal()->hasHiddenVisibility()
4962           || G->getGlobal()->hasProtectedVisibility();
4963   }
4964 
4965   return false;
4966 }
4967 
4968 /// isCallCompatibleAddress - Return the immediate to use if the specified
4969 /// 32-bit value is representable in the immediate field of a BxA instruction.
4970 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4971   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4972   if (!C) return nullptr;
4973 
4974   int Addr = C->getZExtValue();
4975   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4976       SignExtend32<26>(Addr) != Addr)
4977     return nullptr;  // Top 6 bits have to be sext of immediate.
4978 
4979   return DAG
4980       .getConstant(
4981           (int)C->getZExtValue() >> 2, SDLoc(Op),
4982           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4983       .getNode();
4984 }
4985 
4986 namespace {
4987 
4988 struct TailCallArgumentInfo {
4989   SDValue Arg;
4990   SDValue FrameIdxOp;
4991   int FrameIdx = 0;
4992 
4993   TailCallArgumentInfo() = default;
4994 };
4995 
4996 } // end anonymous namespace
4997 
4998 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4999 static void StoreTailCallArgumentsToStackSlot(
5000     SelectionDAG &DAG, SDValue Chain,
5001     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
5002     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
5003   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
5004     SDValue Arg = TailCallArgs[i].Arg;
5005     SDValue FIN = TailCallArgs[i].FrameIdxOp;
5006     int FI = TailCallArgs[i].FrameIdx;
5007     // Store relative to framepointer.
5008     MemOpChains.push_back(DAG.getStore(
5009         Chain, dl, Arg, FIN,
5010         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
5011   }
5012 }
5013 
5014 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
5015 /// the appropriate stack slot for the tail call optimized function call.
5016 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
5017                                              SDValue OldRetAddr, SDValue OldFP,
5018                                              int SPDiff, const SDLoc &dl) {
5019   if (SPDiff) {
5020     // Calculate the new stack slot for the return address.
5021     MachineFunction &MF = DAG.getMachineFunction();
5022     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
5023     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
5024     bool isPPC64 = Subtarget.isPPC64();
5025     int SlotSize = isPPC64 ? 8 : 4;
5026     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
5027     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
5028                                                          NewRetAddrLoc, true);
5029     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5030     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
5031     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
5032                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
5033   }
5034   return Chain;
5035 }
5036 
5037 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5038 /// the position of the argument.
5039 static void
5040 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
5041                          SDValue Arg, int SPDiff, unsigned ArgOffset,
5042                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
5043   int Offset = ArgOffset + SPDiff;
5044   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5045   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5046   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5047   SDValue FIN = DAG.getFrameIndex(FI, VT);
5048   TailCallArgumentInfo Info;
5049   Info.Arg = Arg;
5050   Info.FrameIdxOp = FIN;
5051   Info.FrameIdx = FI;
5052   TailCallArguments.push_back(Info);
5053 }
5054 
5055 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5056 /// stack slot. Returns the chain as result and the loaded frame pointers in
5057 /// LROpOut/FPOpout. Used when tail calling.
5058 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5059     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5060     SDValue &FPOpOut, const SDLoc &dl) const {
5061   if (SPDiff) {
5062     // Load the LR and FP stack slot for later adjusting.
5063     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5064     LROpOut = getReturnAddrFrameIndex(DAG);
5065     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5066     Chain = SDValue(LROpOut.getNode(), 1);
5067   }
5068   return Chain;
5069 }
5070 
5071 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5072 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5073 /// specified by the specific parameter attribute. The copy will be passed as
5074 /// a byval function parameter.
5075 /// Sometimes what we are copying is the end of a larger object, the part that
5076 /// does not fit in registers.
5077 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5078                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5079                                          SelectionDAG &DAG, const SDLoc &dl) {
5080   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5081   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5082                        Flags.getNonZeroByValAlign(), false, false, false,
5083                        MachinePointerInfo(), MachinePointerInfo());
5084 }
5085 
5086 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5087 /// tail calls.
5088 static void LowerMemOpCallTo(
5089     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5090     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5091     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5092     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5093   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5094   if (!isTailCall) {
5095     if (isVector) {
5096       SDValue StackPtr;
5097       if (isPPC64)
5098         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5099       else
5100         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5101       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5102                            DAG.getConstant(ArgOffset, dl, PtrVT));
5103     }
5104     MemOpChains.push_back(
5105         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5106     // Calculate and remember argument location.
5107   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5108                                   TailCallArguments);
5109 }
5110 
5111 static void
5112 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5113                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5114                 SDValue FPOp,
5115                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5116   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5117   // might overwrite each other in case of tail call optimization.
5118   SmallVector<SDValue, 8> MemOpChains2;
5119   // Do not flag preceding copytoreg stuff together with the following stuff.
5120   InFlag = SDValue();
5121   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5122                                     MemOpChains2, dl);
5123   if (!MemOpChains2.empty())
5124     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5125 
5126   // Store the return address to the appropriate stack slot.
5127   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5128 
5129   // Emit callseq_end just before tailcall node.
5130   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5131                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5132   InFlag = Chain.getValue(1);
5133 }
5134 
5135 // Is this global address that of a function that can be called by name? (as
5136 // opposed to something that must hold a descriptor for an indirect call).
5137 static bool isFunctionGlobalAddress(SDValue Callee) {
5138   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5139     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5140         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5141       return false;
5142 
5143     return G->getGlobal()->getValueType()->isFunctionTy();
5144   }
5145 
5146   return false;
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 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5214                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5215   // PatchPoint calls are not indirect.
5216   if (isPatchPoint)
5217     return false;
5218 
5219   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5220     return false;
5221 
5222   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5223   // becuase the immediate function pointer points to a descriptor instead of
5224   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5225   // pointer immediate points to the global entry point, while the BLA would
5226   // need to jump to the local entry point (see rL211174).
5227   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5228       isBLACompatibleAddress(Callee, DAG))
5229     return false;
5230 
5231   return true;
5232 }
5233 
5234 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5235 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5236   return Subtarget.isAIXABI() ||
5237          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5238 }
5239 
5240 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5241                               const Function &Caller,
5242                               const SDValue &Callee,
5243                               const PPCSubtarget &Subtarget,
5244                               const TargetMachine &TM) {
5245   if (CFlags.IsTailCall)
5246     return PPCISD::TC_RETURN;
5247 
5248   // This is a call through a function pointer.
5249   if (CFlags.IsIndirect) {
5250     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5251     // indirect calls. The save of the caller's TOC pointer to the stack will be
5252     // inserted into the DAG as part of call lowering. The restore of the TOC
5253     // pointer is modeled by using a pseudo instruction for the call opcode that
5254     // represents the 2 instruction sequence of an indirect branch and link,
5255     // immediately followed by a load of the TOC pointer from the the stack save
5256     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5257     // as it is not saved or used.
5258     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5259                                                : PPCISD::BCTRL;
5260   }
5261 
5262   if (Subtarget.isUsingPCRelativeCalls()) {
5263     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5264     return PPCISD::CALL_NOTOC;
5265   }
5266 
5267   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5268   // immediately following the call instruction if the caller and callee may
5269   // have different TOC bases. At link time if the linker determines the calls
5270   // may not share a TOC base, the call is redirected to a trampoline inserted
5271   // by the linker. The trampoline will (among other things) save the callers
5272   // TOC pointer at an ABI designated offset in the linkage area and the linker
5273   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5274   // into gpr2.
5275   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5276       return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5277                                                     : PPCISD::CALL_NOP;
5278 
5279   return PPCISD::CALL;
5280 }
5281 
5282 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5283                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5284   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5285     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5286       return SDValue(Dest, 0);
5287 
5288   // Returns true if the callee is local, and false otherwise.
5289   auto isLocalCallee = [&]() {
5290     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5291     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5292     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5293 
5294     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5295            !dyn_cast_or_null<GlobalIFunc>(GV);
5296   };
5297 
5298   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5299   // a static relocation model causes some versions of GNU LD (2.17.50, at
5300   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5301   // built with secure-PLT.
5302   bool UsePlt =
5303       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5304       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5305 
5306   // On AIX, direct function calls reference the symbol for the function's
5307   // entry point, which is named by prepending a "." before the function's
5308   // C-linkage name.
5309   const auto getAIXFuncEntryPointSymbolSDNode =
5310       [&](StringRef FuncName, bool IsDeclaration,
5311           const XCOFF::StorageClass &SC) {
5312         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5313 
5314         MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5315             Context.getOrCreateSymbol(Twine(".") + Twine(FuncName)));
5316 
5317         if (IsDeclaration && !S->hasRepresentedCsectSet()) {
5318           // On AIX, an undefined symbol needs to be associated with a
5319           // MCSectionXCOFF to get the correct storage mapping class.
5320           // In this case, XCOFF::XMC_PR.
5321           MCSectionXCOFF *Sec = Context.getXCOFFSection(
5322               S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC,
5323               SectionKind::getMetadata());
5324           S->setRepresentedCsect(Sec);
5325         }
5326 
5327         MVT PtrVT =
5328             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5329         return DAG.getMCSymbol(S, PtrVT);
5330       };
5331 
5332   if (isFunctionGlobalAddress(Callee)) {
5333     const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5334     const GlobalValue *GV = G->getGlobal();
5335 
5336     if (!Subtarget.isAIXABI())
5337       return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5338                                         UsePlt ? PPCII::MO_PLT : 0);
5339 
5340     assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5341     const GlobalObject *GO = cast<GlobalObject>(GV);
5342     const XCOFF::StorageClass SC =
5343         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5344     return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(),
5345                                             SC);
5346   }
5347 
5348   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5349     const char *SymName = S->getSymbol();
5350     if (!Subtarget.isAIXABI())
5351       return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5352                                          UsePlt ? PPCII::MO_PLT : 0);
5353 
5354     // If there exists a user-declared function whose name is the same as the
5355     // ExternalSymbol's, then we pick up the user-declared version.
5356     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5357     if (const Function *F =
5358             dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) {
5359       const XCOFF::StorageClass SC =
5360           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F);
5361       return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(),
5362                                               SC);
5363     }
5364 
5365     return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT);
5366   }
5367 
5368   // No transformation needed.
5369   assert(Callee.getNode() && "What no callee?");
5370   return Callee;
5371 }
5372 
5373 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5374   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5375          "Expected a CALLSEQ_STARTSDNode.");
5376 
5377   // The last operand is the chain, except when the node has glue. If the node
5378   // has glue, then the last operand is the glue, and the chain is the second
5379   // last operand.
5380   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5381   if (LastValue.getValueType() != MVT::Glue)
5382     return LastValue;
5383 
5384   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5385 }
5386 
5387 // Creates the node that moves a functions address into the count register
5388 // to prepare for an indirect call instruction.
5389 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5390                                 SDValue &Glue, SDValue &Chain,
5391                                 const SDLoc &dl) {
5392   SDValue MTCTROps[] = {Chain, Callee, Glue};
5393   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5394   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5395                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5396   // The glue is the second value produced.
5397   Glue = Chain.getValue(1);
5398 }
5399 
5400 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5401                                           SDValue &Glue, SDValue &Chain,
5402                                           SDValue CallSeqStart,
5403                                           const CallBase *CB, const SDLoc &dl,
5404                                           bool hasNest,
5405                                           const PPCSubtarget &Subtarget) {
5406   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5407   // entry point, but to the function descriptor (the function entry point
5408   // address is part of the function descriptor though).
5409   // The function descriptor is a three doubleword structure with the
5410   // following fields: function entry point, TOC base address and
5411   // environment pointer.
5412   // Thus for a call through a function pointer, the following actions need
5413   // to be performed:
5414   //   1. Save the TOC of the caller in the TOC save area of its stack
5415   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5416   //   2. Load the address of the function entry point from the function
5417   //      descriptor.
5418   //   3. Load the TOC of the callee from the function descriptor into r2.
5419   //   4. Load the environment pointer from the function descriptor into
5420   //      r11.
5421   //   5. Branch to the function entry point address.
5422   //   6. On return of the callee, the TOC of the caller needs to be
5423   //      restored (this is done in FinishCall()).
5424   //
5425   // The loads are scheduled at the beginning of the call sequence, and the
5426   // register copies are flagged together to ensure that no other
5427   // operations can be scheduled in between. E.g. without flagging the
5428   // copies together, a TOC access in the caller could be scheduled between
5429   // the assignment of the callee TOC and the branch to the callee, which leads
5430   // to incorrect code.
5431 
5432   // Start by loading the function address from the descriptor.
5433   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5434   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5435                       ? (MachineMemOperand::MODereferenceable |
5436                          MachineMemOperand::MOInvariant)
5437                       : MachineMemOperand::MONone;
5438 
5439   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5440 
5441   // Registers used in building the DAG.
5442   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5443   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5444 
5445   // Offsets of descriptor members.
5446   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5447   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5448 
5449   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5450   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5451 
5452   // One load for the functions entry point address.
5453   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5454                                     Alignment, MMOFlags);
5455 
5456   // One for loading the TOC anchor for the module that contains the called
5457   // function.
5458   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5459   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5460   SDValue TOCPtr =
5461       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5462                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5463 
5464   // One for loading the environment pointer.
5465   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5466   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5467   SDValue LoadEnvPtr =
5468       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5469                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5470 
5471 
5472   // Then copy the newly loaded TOC anchor to the TOC pointer.
5473   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5474   Chain = TOCVal.getValue(0);
5475   Glue = TOCVal.getValue(1);
5476 
5477   // If the function call has an explicit 'nest' parameter, it takes the
5478   // place of the environment pointer.
5479   assert((!hasNest || !Subtarget.isAIXABI()) &&
5480          "Nest parameter is not supported on AIX.");
5481   if (!hasNest) {
5482     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5483     Chain = EnvVal.getValue(0);
5484     Glue = EnvVal.getValue(1);
5485   }
5486 
5487   // The rest of the indirect call sequence is the same as the non-descriptor
5488   // DAG.
5489   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5490 }
5491 
5492 static void
5493 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5494                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5495                   SelectionDAG &DAG,
5496                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5497                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5498                   const PPCSubtarget &Subtarget) {
5499   const bool IsPPC64 = Subtarget.isPPC64();
5500   // MVT for a general purpose register.
5501   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5502 
5503   // First operand is always the chain.
5504   Ops.push_back(Chain);
5505 
5506   // If it's a direct call pass the callee as the second operand.
5507   if (!CFlags.IsIndirect)
5508     Ops.push_back(Callee);
5509   else {
5510     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5511 
5512     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5513     // on the stack (this would have been done in `LowerCall_64SVR4` or
5514     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5515     // represents both the indirect branch and a load that restores the TOC
5516     // pointer from the linkage area. The operand for the TOC restore is an add
5517     // of the TOC save offset to the stack pointer. This must be the second
5518     // operand: after the chain input but before any other variadic arguments.
5519     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5520     // saved or used.
5521     if (isTOCSaveRestoreRequired(Subtarget)) {
5522       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5523 
5524       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5525       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5526       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5527       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5528       Ops.push_back(AddTOC);
5529     }
5530 
5531     // Add the register used for the environment pointer.
5532     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5533       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5534                                     RegVT));
5535 
5536 
5537     // Add CTR register as callee so a bctr can be emitted later.
5538     if (CFlags.IsTailCall)
5539       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5540   }
5541 
5542   // If this is a tail call add stack pointer delta.
5543   if (CFlags.IsTailCall)
5544     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5545 
5546   // Add argument registers to the end of the list so that they are known live
5547   // into the call.
5548   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5549     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5550                                   RegsToPass[i].second.getValueType()));
5551 
5552   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5553   // no way to mark dependencies as implicit here.
5554   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5555   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5556        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5557     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5558 
5559   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5560   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5561     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5562 
5563   // Add a register mask operand representing the call-preserved registers.
5564   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5565   const uint32_t *Mask =
5566       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5567   assert(Mask && "Missing call preserved mask for calling convention");
5568   Ops.push_back(DAG.getRegisterMask(Mask));
5569 
5570   // If the glue is valid, it is the last operand.
5571   if (Glue.getNode())
5572     Ops.push_back(Glue);
5573 }
5574 
5575 SDValue PPCTargetLowering::FinishCall(
5576     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5577     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5578     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5579     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5580     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5581 
5582   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5583       Subtarget.isAIXABI())
5584     setUsesTOCBasePtr(DAG);
5585 
5586   unsigned CallOpc =
5587       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5588                     Subtarget, DAG.getTarget());
5589 
5590   if (!CFlags.IsIndirect)
5591     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5592   else if (Subtarget.usesFunctionDescriptors())
5593     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5594                                   dl, CFlags.HasNest, Subtarget);
5595   else
5596     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5597 
5598   // Build the operand list for the call instruction.
5599   SmallVector<SDValue, 8> Ops;
5600   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5601                     SPDiff, Subtarget);
5602 
5603   // Emit tail call.
5604   if (CFlags.IsTailCall) {
5605     // Indirect tail call when using PC Relative calls do not have the same
5606     // constraints.
5607     assert(((Callee.getOpcode() == ISD::Register &&
5608              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5609             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5610             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5611             isa<ConstantSDNode>(Callee) ||
5612             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5613            "Expecting a global address, external symbol, absolute value, "
5614            "register or an indirect tail call when PC Relative calls are "
5615            "used.");
5616     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5617     assert(CallOpc == PPCISD::TC_RETURN &&
5618            "Unexpected call opcode for a tail call.");
5619     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5620     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5621   }
5622 
5623   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5624   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5625   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5626   Glue = Chain.getValue(1);
5627 
5628   // When performing tail call optimization the callee pops its arguments off
5629   // the stack. Account for this here so these bytes can be pushed back on in
5630   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5631   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5632                          getTargetMachine().Options.GuaranteedTailCallOpt)
5633                             ? NumBytes
5634                             : 0;
5635 
5636   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5637                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5638                              Glue, dl);
5639   Glue = Chain.getValue(1);
5640 
5641   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5642                          DAG, InVals);
5643 }
5644 
5645 SDValue
5646 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5647                              SmallVectorImpl<SDValue> &InVals) const {
5648   SelectionDAG &DAG                     = CLI.DAG;
5649   SDLoc &dl                             = CLI.DL;
5650   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5651   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5652   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5653   SDValue Chain                         = CLI.Chain;
5654   SDValue Callee                        = CLI.Callee;
5655   bool &isTailCall                      = CLI.IsTailCall;
5656   CallingConv::ID CallConv              = CLI.CallConv;
5657   bool isVarArg                         = CLI.IsVarArg;
5658   bool isPatchPoint                     = CLI.IsPatchPoint;
5659   const CallBase *CB                    = CLI.CB;
5660 
5661   if (isTailCall) {
5662     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5663       isTailCall = false;
5664     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5665       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5666           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5667     else
5668       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5669                                                      Ins, DAG);
5670     if (isTailCall) {
5671       ++NumTailCalls;
5672       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5673         ++NumSiblingCalls;
5674 
5675       // PC Relative calls no longer guarantee that the callee is a Global
5676       // Address Node. The callee could be an indirect tail call in which
5677       // case the SDValue for the callee could be a load (to load the address
5678       // of a function pointer) or it may be a register copy (to move the
5679       // address of the callee from a function parameter into a virtual
5680       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5681       assert((Subtarget.isUsingPCRelativeCalls() ||
5682               isa<GlobalAddressSDNode>(Callee)) &&
5683              "Callee should be an llvm::Function object.");
5684 
5685       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5686                         << "\nTCO callee: ");
5687       LLVM_DEBUG(Callee.dump());
5688     }
5689   }
5690 
5691   if (!isTailCall && CB && CB->isMustTailCall())
5692     report_fatal_error("failed to perform tail call elimination on a call "
5693                        "site marked musttail");
5694 
5695   // When long calls (i.e. indirect calls) are always used, calls are always
5696   // made via function pointer. If we have a function name, first translate it
5697   // into a pointer.
5698   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5699       !isTailCall)
5700     Callee = LowerGlobalAddress(Callee, DAG);
5701 
5702   CallFlags CFlags(
5703       CallConv, isTailCall, isVarArg, isPatchPoint,
5704       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5705       // hasNest
5706       Subtarget.is64BitELFABI() &&
5707           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5708       CLI.NoMerge);
5709 
5710   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5711     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5712                             InVals, CB);
5713 
5714   if (Subtarget.isSVR4ABI())
5715     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5716                             InVals, CB);
5717 
5718   if (Subtarget.isAIXABI())
5719     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5720                          InVals, CB);
5721 
5722   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5723                           InVals, CB);
5724 }
5725 
5726 SDValue PPCTargetLowering::LowerCall_32SVR4(
5727     SDValue Chain, SDValue Callee, CallFlags CFlags,
5728     const SmallVectorImpl<ISD::OutputArg> &Outs,
5729     const SmallVectorImpl<SDValue> &OutVals,
5730     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5731     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5732     const CallBase *CB) const {
5733   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5734   // of the 32-bit SVR4 ABI stack frame layout.
5735 
5736   const CallingConv::ID CallConv = CFlags.CallConv;
5737   const bool IsVarArg = CFlags.IsVarArg;
5738   const bool IsTailCall = CFlags.IsTailCall;
5739 
5740   assert((CallConv == CallingConv::C ||
5741           CallConv == CallingConv::Cold ||
5742           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5743 
5744   const Align PtrAlign(4);
5745 
5746   MachineFunction &MF = DAG.getMachineFunction();
5747 
5748   // Mark this function as potentially containing a function that contains a
5749   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5750   // and restoring the callers stack pointer in this functions epilog. This is
5751   // done because by tail calling the called function might overwrite the value
5752   // in this function's (MF) stack pointer stack slot 0(SP).
5753   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5754       CallConv == CallingConv::Fast)
5755     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5756 
5757   // Count how many bytes are to be pushed on the stack, including the linkage
5758   // area, parameter list area and the part of the local variable space which
5759   // contains copies of aggregates which are passed by value.
5760 
5761   // Assign locations to all of the outgoing arguments.
5762   SmallVector<CCValAssign, 16> ArgLocs;
5763   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5764 
5765   // Reserve space for the linkage area on the stack.
5766   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5767                        PtrAlign);
5768   if (useSoftFloat())
5769     CCInfo.PreAnalyzeCallOperands(Outs);
5770 
5771   if (IsVarArg) {
5772     // Handle fixed and variable vector arguments differently.
5773     // Fixed vector arguments go into registers as long as registers are
5774     // available. Variable vector arguments always go into memory.
5775     unsigned NumArgs = Outs.size();
5776 
5777     for (unsigned i = 0; i != NumArgs; ++i) {
5778       MVT ArgVT = Outs[i].VT;
5779       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5780       bool Result;
5781 
5782       if (Outs[i].IsFixed) {
5783         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5784                                CCInfo);
5785       } else {
5786         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5787                                       ArgFlags, CCInfo);
5788       }
5789 
5790       if (Result) {
5791 #ifndef NDEBUG
5792         errs() << "Call operand #" << i << " has unhandled type "
5793              << EVT(ArgVT).getEVTString() << "\n";
5794 #endif
5795         llvm_unreachable(nullptr);
5796       }
5797     }
5798   } else {
5799     // All arguments are treated the same.
5800     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5801   }
5802   CCInfo.clearWasPPCF128();
5803 
5804   // Assign locations to all of the outgoing aggregate by value arguments.
5805   SmallVector<CCValAssign, 16> ByValArgLocs;
5806   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5807 
5808   // Reserve stack space for the allocations in CCInfo.
5809   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5810 
5811   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5812 
5813   // Size of the linkage area, parameter list area and the part of the local
5814   // space variable where copies of aggregates which are passed by value are
5815   // stored.
5816   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5817 
5818   // Calculate by how many bytes the stack has to be adjusted in case of tail
5819   // call optimization.
5820   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5821 
5822   // Adjust the stack pointer for the new arguments...
5823   // These operations are automatically eliminated by the prolog/epilog pass
5824   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5825   SDValue CallSeqStart = Chain;
5826 
5827   // Load the return address and frame pointer so it can be moved somewhere else
5828   // later.
5829   SDValue LROp, FPOp;
5830   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5831 
5832   // Set up a copy of the stack pointer for use loading and storing any
5833   // arguments that may not fit in the registers available for argument
5834   // passing.
5835   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5836 
5837   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5838   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5839   SmallVector<SDValue, 8> MemOpChains;
5840 
5841   bool seenFloatArg = false;
5842   // Walk the register/memloc assignments, inserting copies/loads.
5843   // i - Tracks the index into the list of registers allocated for the call
5844   // RealArgIdx - Tracks the index into the list of actual function arguments
5845   // j - Tracks the index into the list of byval arguments
5846   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5847        i != e;
5848        ++i, ++RealArgIdx) {
5849     CCValAssign &VA = ArgLocs[i];
5850     SDValue Arg = OutVals[RealArgIdx];
5851     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5852 
5853     if (Flags.isByVal()) {
5854       // Argument is an aggregate which is passed by value, thus we need to
5855       // create a copy of it in the local variable space of the current stack
5856       // frame (which is the stack frame of the caller) and pass the address of
5857       // this copy to the callee.
5858       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5859       CCValAssign &ByValVA = ByValArgLocs[j++];
5860       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5861 
5862       // Memory reserved in the local variable space of the callers stack frame.
5863       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5864 
5865       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5866       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5867                            StackPtr, PtrOff);
5868 
5869       // Create a copy of the argument in the local area of the current
5870       // stack frame.
5871       SDValue MemcpyCall =
5872         CreateCopyOfByValArgument(Arg, PtrOff,
5873                                   CallSeqStart.getNode()->getOperand(0),
5874                                   Flags, DAG, dl);
5875 
5876       // This must go outside the CALLSEQ_START..END.
5877       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5878                                                      SDLoc(MemcpyCall));
5879       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5880                              NewCallSeqStart.getNode());
5881       Chain = CallSeqStart = NewCallSeqStart;
5882 
5883       // Pass the address of the aggregate copy on the stack either in a
5884       // physical register or in the parameter list area of the current stack
5885       // frame to the callee.
5886       Arg = PtrOff;
5887     }
5888 
5889     // When useCRBits() is true, there can be i1 arguments.
5890     // It is because getRegisterType(MVT::i1) => MVT::i1,
5891     // and for other integer types getRegisterType() => MVT::i32.
5892     // Extend i1 and ensure callee will get i32.
5893     if (Arg.getValueType() == MVT::i1)
5894       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5895                         dl, MVT::i32, Arg);
5896 
5897     if (VA.isRegLoc()) {
5898       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5899       // Put argument in a physical register.
5900       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5901         bool IsLE = Subtarget.isLittleEndian();
5902         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5903                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5904         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5905         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5906                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5907         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5908                              SVal.getValue(0)));
5909       } else
5910         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5911     } else {
5912       // Put argument in the parameter list area of the current stack frame.
5913       assert(VA.isMemLoc());
5914       unsigned LocMemOffset = VA.getLocMemOffset();
5915 
5916       if (!IsTailCall) {
5917         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5918         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5919                              StackPtr, PtrOff);
5920 
5921         MemOpChains.push_back(
5922             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5923       } else {
5924         // Calculate and remember argument location.
5925         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5926                                  TailCallArguments);
5927       }
5928     }
5929   }
5930 
5931   if (!MemOpChains.empty())
5932     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5933 
5934   // Build a sequence of copy-to-reg nodes chained together with token chain
5935   // and flag operands which copy the outgoing args into the appropriate regs.
5936   SDValue InFlag;
5937   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5938     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5939                              RegsToPass[i].second, InFlag);
5940     InFlag = Chain.getValue(1);
5941   }
5942 
5943   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5944   // registers.
5945   if (IsVarArg) {
5946     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5947     SDValue Ops[] = { Chain, InFlag };
5948 
5949     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5950                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5951 
5952     InFlag = Chain.getValue(1);
5953   }
5954 
5955   if (IsTailCall)
5956     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5957                     TailCallArguments);
5958 
5959   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5960                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5961 }
5962 
5963 // Copy an argument into memory, being careful to do this outside the
5964 // call sequence for the call to which the argument belongs.
5965 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5966     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5967     SelectionDAG &DAG, const SDLoc &dl) const {
5968   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5969                         CallSeqStart.getNode()->getOperand(0),
5970                         Flags, DAG, dl);
5971   // The MEMCPY must go outside the CALLSEQ_START..END.
5972   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5973   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5974                                                  SDLoc(MemcpyCall));
5975   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5976                          NewCallSeqStart.getNode());
5977   return NewCallSeqStart;
5978 }
5979 
5980 SDValue PPCTargetLowering::LowerCall_64SVR4(
5981     SDValue Chain, SDValue Callee, CallFlags CFlags,
5982     const SmallVectorImpl<ISD::OutputArg> &Outs,
5983     const SmallVectorImpl<SDValue> &OutVals,
5984     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5985     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5986     const CallBase *CB) const {
5987   bool isELFv2ABI = Subtarget.isELFv2ABI();
5988   bool isLittleEndian = Subtarget.isLittleEndian();
5989   unsigned NumOps = Outs.size();
5990   bool IsSibCall = false;
5991   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5992 
5993   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5994   unsigned PtrByteSize = 8;
5995 
5996   MachineFunction &MF = DAG.getMachineFunction();
5997 
5998   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5999     IsSibCall = true;
6000 
6001   // Mark this function as potentially containing a function that contains a
6002   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6003   // and restoring the callers stack pointer in this functions epilog. This is
6004   // done because by tail calling the called function might overwrite the value
6005   // in this function's (MF) stack pointer stack slot 0(SP).
6006   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6007     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6008 
6009   assert(!(IsFastCall && CFlags.IsVarArg) &&
6010          "fastcc not supported on varargs functions");
6011 
6012   // Count how many bytes are to be pushed on the stack, including the linkage
6013   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
6014   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
6015   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
6016   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6017   unsigned NumBytes = LinkageSize;
6018   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6019   unsigned &QFPR_idx = FPR_idx;
6020 
6021   static const MCPhysReg GPR[] = {
6022     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6023     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6024   };
6025   static const MCPhysReg VR[] = {
6026     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6027     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6028   };
6029 
6030   const unsigned NumGPRs = array_lengthof(GPR);
6031   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
6032   const unsigned NumVRs  = array_lengthof(VR);
6033   const unsigned NumQFPRs = NumFPRs;
6034 
6035   // On ELFv2, we can avoid allocating the parameter area if all the arguments
6036   // can be passed to the callee in registers.
6037   // For the fast calling convention, there is another check below.
6038   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6039   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6040   if (!HasParameterArea) {
6041     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6042     unsigned AvailableFPRs = NumFPRs;
6043     unsigned AvailableVRs = NumVRs;
6044     unsigned NumBytesTmp = NumBytes;
6045     for (unsigned i = 0; i != NumOps; ++i) {
6046       if (Outs[i].Flags.isNest()) continue;
6047       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6048                                 PtrByteSize, LinkageSize, ParamAreaSize,
6049                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
6050                                 Subtarget.hasQPX()))
6051         HasParameterArea = true;
6052     }
6053   }
6054 
6055   // When using the fast calling convention, we don't provide backing for
6056   // arguments that will be in registers.
6057   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6058 
6059   // Avoid allocating parameter area for fastcc functions if all the arguments
6060   // can be passed in the registers.
6061   if (IsFastCall)
6062     HasParameterArea = false;
6063 
6064   // Add up all the space actually used.
6065   for (unsigned i = 0; i != NumOps; ++i) {
6066     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6067     EVT ArgVT = Outs[i].VT;
6068     EVT OrigVT = Outs[i].ArgVT;
6069 
6070     if (Flags.isNest())
6071       continue;
6072 
6073     if (IsFastCall) {
6074       if (Flags.isByVal()) {
6075         NumGPRsUsed += (Flags.getByValSize()+7)/8;
6076         if (NumGPRsUsed > NumGPRs)
6077           HasParameterArea = true;
6078       } else {
6079         switch (ArgVT.getSimpleVT().SimpleTy) {
6080         default: llvm_unreachable("Unexpected ValueType for argument!");
6081         case MVT::i1:
6082         case MVT::i32:
6083         case MVT::i64:
6084           if (++NumGPRsUsed <= NumGPRs)
6085             continue;
6086           break;
6087         case MVT::v4i32:
6088         case MVT::v8i16:
6089         case MVT::v16i8:
6090         case MVT::v2f64:
6091         case MVT::v2i64:
6092         case MVT::v1i128:
6093         case MVT::f128:
6094           if (++NumVRsUsed <= NumVRs)
6095             continue;
6096           break;
6097         case MVT::v4f32:
6098           // When using QPX, this is handled like a FP register, otherwise, it
6099           // is an Altivec register.
6100           if (Subtarget.hasQPX()) {
6101             if (++NumFPRsUsed <= NumFPRs)
6102               continue;
6103           } else {
6104             if (++NumVRsUsed <= NumVRs)
6105               continue;
6106           }
6107           break;
6108         case MVT::f32:
6109         case MVT::f64:
6110         case MVT::v4f64: // QPX
6111         case MVT::v4i1:  // QPX
6112           if (++NumFPRsUsed <= NumFPRs)
6113             continue;
6114           break;
6115         }
6116         HasParameterArea = true;
6117       }
6118     }
6119 
6120     /* Respect alignment of argument on the stack.  */
6121     auto Alignement =
6122         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6123     NumBytes = alignTo(NumBytes, Alignement);
6124 
6125     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6126     if (Flags.isInConsecutiveRegsLast())
6127       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6128   }
6129 
6130   unsigned NumBytesActuallyUsed = NumBytes;
6131 
6132   // In the old ELFv1 ABI,
6133   // the prolog code of the callee may store up to 8 GPR argument registers to
6134   // the stack, allowing va_start to index over them in memory if its varargs.
6135   // Because we cannot tell if this is needed on the caller side, we have to
6136   // conservatively assume that it is needed.  As such, make sure we have at
6137   // least enough stack space for the caller to store the 8 GPRs.
6138   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6139   // really requires memory operands, e.g. a vararg function.
6140   if (HasParameterArea)
6141     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6142   else
6143     NumBytes = LinkageSize;
6144 
6145   // Tail call needs the stack to be aligned.
6146   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6147     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6148 
6149   int SPDiff = 0;
6150 
6151   // Calculate by how many bytes the stack has to be adjusted in case of tail
6152   // call optimization.
6153   if (!IsSibCall)
6154     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6155 
6156   // To protect arguments on the stack from being clobbered in a tail call,
6157   // force all the loads to happen before doing any other lowering.
6158   if (CFlags.IsTailCall)
6159     Chain = DAG.getStackArgumentTokenFactor(Chain);
6160 
6161   // Adjust the stack pointer for the new arguments...
6162   // These operations are automatically eliminated by the prolog/epilog pass
6163   if (!IsSibCall)
6164     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6165   SDValue CallSeqStart = Chain;
6166 
6167   // Load the return address and frame pointer so it can be move somewhere else
6168   // later.
6169   SDValue LROp, FPOp;
6170   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6171 
6172   // Set up a copy of the stack pointer for use loading and storing any
6173   // arguments that may not fit in the registers available for argument
6174   // passing.
6175   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6176 
6177   // Figure out which arguments are going to go in registers, and which in
6178   // memory.  Also, if this is a vararg function, floating point operations
6179   // must be stored to our stack, and loaded into integer regs as well, if
6180   // any integer regs are available for argument passing.
6181   unsigned ArgOffset = LinkageSize;
6182 
6183   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6184   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6185 
6186   SmallVector<SDValue, 8> MemOpChains;
6187   for (unsigned i = 0; i != NumOps; ++i) {
6188     SDValue Arg = OutVals[i];
6189     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6190     EVT ArgVT = Outs[i].VT;
6191     EVT OrigVT = Outs[i].ArgVT;
6192 
6193     // PtrOff will be used to store the current argument to the stack if a
6194     // register cannot be found for it.
6195     SDValue PtrOff;
6196 
6197     // We re-align the argument offset for each argument, except when using the
6198     // fast calling convention, when we need to make sure we do that only when
6199     // we'll actually use a stack slot.
6200     auto ComputePtrOff = [&]() {
6201       /* Respect alignment of argument on the stack.  */
6202       auto Alignment =
6203           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6204       ArgOffset = alignTo(ArgOffset, Alignment);
6205 
6206       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6207 
6208       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6209     };
6210 
6211     if (!IsFastCall) {
6212       ComputePtrOff();
6213 
6214       /* Compute GPR index associated with argument offset.  */
6215       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6216       GPR_idx = std::min(GPR_idx, NumGPRs);
6217     }
6218 
6219     // Promote integers to 64-bit values.
6220     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6221       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6222       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6223       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6224     }
6225 
6226     // FIXME memcpy is used way more than necessary.  Correctness first.
6227     // Note: "by value" is code for passing a structure by value, not
6228     // basic types.
6229     if (Flags.isByVal()) {
6230       // Note: Size includes alignment padding, so
6231       //   struct x { short a; char b; }
6232       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6233       // These are the proper values we need for right-justifying the
6234       // aggregate in a parameter register.
6235       unsigned Size = Flags.getByValSize();
6236 
6237       // An empty aggregate parameter takes up no storage and no
6238       // registers.
6239       if (Size == 0)
6240         continue;
6241 
6242       if (IsFastCall)
6243         ComputePtrOff();
6244 
6245       // All aggregates smaller than 8 bytes must be passed right-justified.
6246       if (Size==1 || Size==2 || Size==4) {
6247         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6248         if (GPR_idx != NumGPRs) {
6249           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6250                                         MachinePointerInfo(), VT);
6251           MemOpChains.push_back(Load.getValue(1));
6252           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6253 
6254           ArgOffset += PtrByteSize;
6255           continue;
6256         }
6257       }
6258 
6259       if (GPR_idx == NumGPRs && Size < 8) {
6260         SDValue AddPtr = PtrOff;
6261         if (!isLittleEndian) {
6262           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6263                                           PtrOff.getValueType());
6264           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6265         }
6266         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6267                                                           CallSeqStart,
6268                                                           Flags, DAG, dl);
6269         ArgOffset += PtrByteSize;
6270         continue;
6271       }
6272       // Copy entire object into memory.  There are cases where gcc-generated
6273       // code assumes it is there, even if it could be put entirely into
6274       // registers.  (This is not what the doc says.)
6275 
6276       // FIXME: The above statement is likely due to a misunderstanding of the
6277       // documents.  All arguments must be copied into the parameter area BY
6278       // THE CALLEE in the event that the callee takes the address of any
6279       // formal argument.  That has not yet been implemented.  However, it is
6280       // reasonable to use the stack area as a staging area for the register
6281       // load.
6282 
6283       // Skip this for small aggregates, as we will use the same slot for a
6284       // right-justified copy, below.
6285       if (Size >= 8)
6286         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6287                                                           CallSeqStart,
6288                                                           Flags, DAG, dl);
6289 
6290       // When a register is available, pass a small aggregate right-justified.
6291       if (Size < 8 && GPR_idx != NumGPRs) {
6292         // The easiest way to get this right-justified in a register
6293         // is to copy the structure into the rightmost portion of a
6294         // local variable slot, then load the whole slot into the
6295         // register.
6296         // FIXME: The memcpy seems to produce pretty awful code for
6297         // small aggregates, particularly for packed ones.
6298         // FIXME: It would be preferable to use the slot in the
6299         // parameter save area instead of a new local variable.
6300         SDValue AddPtr = PtrOff;
6301         if (!isLittleEndian) {
6302           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6303           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6304         }
6305         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6306                                                           CallSeqStart,
6307                                                           Flags, DAG, dl);
6308 
6309         // Load the slot into the register.
6310         SDValue Load =
6311             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6312         MemOpChains.push_back(Load.getValue(1));
6313         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6314 
6315         // Done with this argument.
6316         ArgOffset += PtrByteSize;
6317         continue;
6318       }
6319 
6320       // For aggregates larger than PtrByteSize, copy the pieces of the
6321       // object that fit into registers from the parameter save area.
6322       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6323         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6324         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6325         if (GPR_idx != NumGPRs) {
6326           SDValue Load =
6327               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6328           MemOpChains.push_back(Load.getValue(1));
6329           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6330           ArgOffset += PtrByteSize;
6331         } else {
6332           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6333           break;
6334         }
6335       }
6336       continue;
6337     }
6338 
6339     switch (Arg.getSimpleValueType().SimpleTy) {
6340     default: llvm_unreachable("Unexpected ValueType for argument!");
6341     case MVT::i1:
6342     case MVT::i32:
6343     case MVT::i64:
6344       if (Flags.isNest()) {
6345         // The 'nest' parameter, if any, is passed in R11.
6346         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6347         break;
6348       }
6349 
6350       // These can be scalar arguments or elements of an integer array type
6351       // passed directly.  Clang may use those instead of "byval" aggregate
6352       // types to avoid forcing arguments to memory unnecessarily.
6353       if (GPR_idx != NumGPRs) {
6354         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6355       } else {
6356         if (IsFastCall)
6357           ComputePtrOff();
6358 
6359         assert(HasParameterArea &&
6360                "Parameter area must exist to pass an argument in memory.");
6361         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6362                          true, CFlags.IsTailCall, false, MemOpChains,
6363                          TailCallArguments, dl);
6364         if (IsFastCall)
6365           ArgOffset += PtrByteSize;
6366       }
6367       if (!IsFastCall)
6368         ArgOffset += PtrByteSize;
6369       break;
6370     case MVT::f32:
6371     case MVT::f64: {
6372       // These can be scalar arguments or elements of a float array type
6373       // passed directly.  The latter are used to implement ELFv2 homogenous
6374       // float aggregates.
6375 
6376       // Named arguments go into FPRs first, and once they overflow, the
6377       // remaining arguments go into GPRs and then the parameter save area.
6378       // Unnamed arguments for vararg functions always go to GPRs and
6379       // then the parameter save area.  For now, put all arguments to vararg
6380       // routines always in both locations (FPR *and* GPR or stack slot).
6381       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6382       bool NeededLoad = false;
6383 
6384       // First load the argument into the next available FPR.
6385       if (FPR_idx != NumFPRs)
6386         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6387 
6388       // Next, load the argument into GPR or stack slot if needed.
6389       if (!NeedGPROrStack)
6390         ;
6391       else if (GPR_idx != NumGPRs && !IsFastCall) {
6392         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6393         // once we support fp <-> gpr moves.
6394 
6395         // In the non-vararg case, this can only ever happen in the
6396         // presence of f32 array types, since otherwise we never run
6397         // out of FPRs before running out of GPRs.
6398         SDValue ArgVal;
6399 
6400         // Double values are always passed in a single GPR.
6401         if (Arg.getValueType() != MVT::f32) {
6402           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6403 
6404         // Non-array float values are extended and passed in a GPR.
6405         } else if (!Flags.isInConsecutiveRegs()) {
6406           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6407           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6408 
6409         // If we have an array of floats, we collect every odd element
6410         // together with its predecessor into one GPR.
6411         } else if (ArgOffset % PtrByteSize != 0) {
6412           SDValue Lo, Hi;
6413           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6414           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6415           if (!isLittleEndian)
6416             std::swap(Lo, Hi);
6417           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6418 
6419         // The final element, if even, goes into the first half of a GPR.
6420         } else if (Flags.isInConsecutiveRegsLast()) {
6421           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6422           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6423           if (!isLittleEndian)
6424             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6425                                  DAG.getConstant(32, dl, MVT::i32));
6426 
6427         // Non-final even elements are skipped; they will be handled
6428         // together the with subsequent argument on the next go-around.
6429         } else
6430           ArgVal = SDValue();
6431 
6432         if (ArgVal.getNode())
6433           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6434       } else {
6435         if (IsFastCall)
6436           ComputePtrOff();
6437 
6438         // Single-precision floating-point values are mapped to the
6439         // second (rightmost) word of the stack doubleword.
6440         if (Arg.getValueType() == MVT::f32 &&
6441             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6442           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6443           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6444         }
6445 
6446         assert(HasParameterArea &&
6447                "Parameter area must exist to pass an argument in memory.");
6448         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6449                          true, CFlags.IsTailCall, false, MemOpChains,
6450                          TailCallArguments, dl);
6451 
6452         NeededLoad = true;
6453       }
6454       // When passing an array of floats, the array occupies consecutive
6455       // space in the argument area; only round up to the next doubleword
6456       // at the end of the array.  Otherwise, each float takes 8 bytes.
6457       if (!IsFastCall || NeededLoad) {
6458         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6459                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6460         if (Flags.isInConsecutiveRegsLast())
6461           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6462       }
6463       break;
6464     }
6465     case MVT::v4f32:
6466     case MVT::v4i32:
6467     case MVT::v8i16:
6468     case MVT::v16i8:
6469     case MVT::v2f64:
6470     case MVT::v2i64:
6471     case MVT::v1i128:
6472     case MVT::f128:
6473       if (!Subtarget.hasQPX()) {
6474       // These can be scalar arguments or elements of a vector array type
6475       // passed directly.  The latter are used to implement ELFv2 homogenous
6476       // vector aggregates.
6477 
6478       // For a varargs call, named arguments go into VRs or on the stack as
6479       // usual; unnamed arguments always go to the stack or the corresponding
6480       // GPRs when within range.  For now, we always put the value in both
6481       // locations (or even all three).
6482       if (CFlags.IsVarArg) {
6483         assert(HasParameterArea &&
6484                "Parameter area must exist if we have a varargs call.");
6485         // We could elide this store in the case where the object fits
6486         // entirely in R registers.  Maybe later.
6487         SDValue Store =
6488             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6489         MemOpChains.push_back(Store);
6490         if (VR_idx != NumVRs) {
6491           SDValue Load =
6492               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6493           MemOpChains.push_back(Load.getValue(1));
6494           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6495         }
6496         ArgOffset += 16;
6497         for (unsigned i=0; i<16; i+=PtrByteSize) {
6498           if (GPR_idx == NumGPRs)
6499             break;
6500           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6501                                    DAG.getConstant(i, dl, PtrVT));
6502           SDValue Load =
6503               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6504           MemOpChains.push_back(Load.getValue(1));
6505           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6506         }
6507         break;
6508       }
6509 
6510       // Non-varargs Altivec params go into VRs or on the stack.
6511       if (VR_idx != NumVRs) {
6512         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6513       } else {
6514         if (IsFastCall)
6515           ComputePtrOff();
6516 
6517         assert(HasParameterArea &&
6518                "Parameter area must exist to pass an argument in memory.");
6519         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6520                          true, CFlags.IsTailCall, true, MemOpChains,
6521                          TailCallArguments, dl);
6522         if (IsFastCall)
6523           ArgOffset += 16;
6524       }
6525 
6526       if (!IsFastCall)
6527         ArgOffset += 16;
6528       break;
6529       } // not QPX
6530 
6531       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6532              "Invalid QPX parameter type");
6533 
6534       LLVM_FALLTHROUGH;
6535     case MVT::v4f64:
6536     case MVT::v4i1: {
6537       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6538       if (CFlags.IsVarArg) {
6539         assert(HasParameterArea &&
6540                "Parameter area must exist if we have a varargs call.");
6541         // We could elide this store in the case where the object fits
6542         // entirely in R registers.  Maybe later.
6543         SDValue Store =
6544             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6545         MemOpChains.push_back(Store);
6546         if (QFPR_idx != NumQFPRs) {
6547           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6548                                      PtrOff, MachinePointerInfo());
6549           MemOpChains.push_back(Load.getValue(1));
6550           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6551         }
6552         ArgOffset += (IsF32 ? 16 : 32);
6553         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6554           if (GPR_idx == NumGPRs)
6555             break;
6556           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6557                                    DAG.getConstant(i, dl, PtrVT));
6558           SDValue Load =
6559               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6560           MemOpChains.push_back(Load.getValue(1));
6561           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6562         }
6563         break;
6564       }
6565 
6566       // Non-varargs QPX params go into registers or on the stack.
6567       if (QFPR_idx != NumQFPRs) {
6568         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6569       } else {
6570         if (IsFastCall)
6571           ComputePtrOff();
6572 
6573         assert(HasParameterArea &&
6574                "Parameter area must exist to pass an argument in memory.");
6575         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6576                          true, CFlags.IsTailCall, true, MemOpChains,
6577                          TailCallArguments, dl);
6578         if (IsFastCall)
6579           ArgOffset += (IsF32 ? 16 : 32);
6580       }
6581 
6582       if (!IsFastCall)
6583         ArgOffset += (IsF32 ? 16 : 32);
6584       break;
6585       }
6586     }
6587   }
6588 
6589   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6590          "mismatch in size of parameter area");
6591   (void)NumBytesActuallyUsed;
6592 
6593   if (!MemOpChains.empty())
6594     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6595 
6596   // Check if this is an indirect call (MTCTR/BCTRL).
6597   // See prepareDescriptorIndirectCall and buildCallOperands for more
6598   // information about calls through function pointers in the 64-bit SVR4 ABI.
6599   if (CFlags.IsIndirect) {
6600     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6601     // caller in the TOC save area.
6602     if (isTOCSaveRestoreRequired(Subtarget)) {
6603       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6604       // Load r2 into a virtual register and store it to the TOC save area.
6605       setUsesTOCBasePtr(DAG);
6606       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6607       // TOC save area offset.
6608       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6609       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6610       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6611       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6612                            MachinePointerInfo::getStack(
6613                                DAG.getMachineFunction(), TOCSaveOffset));
6614     }
6615     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6616     // This does not mean the MTCTR instruction must use R12; it's easier
6617     // to model this as an extra parameter, so do that.
6618     if (isELFv2ABI && !CFlags.IsPatchPoint)
6619       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6620   }
6621 
6622   // Build a sequence of copy-to-reg nodes chained together with token chain
6623   // and flag operands which copy the outgoing args into the appropriate regs.
6624   SDValue InFlag;
6625   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6626     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6627                              RegsToPass[i].second, InFlag);
6628     InFlag = Chain.getValue(1);
6629   }
6630 
6631   if (CFlags.IsTailCall && !IsSibCall)
6632     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6633                     TailCallArguments);
6634 
6635   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6636                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6637 }
6638 
6639 SDValue PPCTargetLowering::LowerCall_Darwin(
6640     SDValue Chain, SDValue Callee, CallFlags CFlags,
6641     const SmallVectorImpl<ISD::OutputArg> &Outs,
6642     const SmallVectorImpl<SDValue> &OutVals,
6643     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6644     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6645     const CallBase *CB) const {
6646   unsigned NumOps = Outs.size();
6647 
6648   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6649   bool isPPC64 = PtrVT == MVT::i64;
6650   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6651 
6652   MachineFunction &MF = DAG.getMachineFunction();
6653 
6654   // Mark this function as potentially containing a function that contains a
6655   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6656   // and restoring the callers stack pointer in this functions epilog. This is
6657   // done because by tail calling the called function might overwrite the value
6658   // in this function's (MF) stack pointer stack slot 0(SP).
6659   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6660       CFlags.CallConv == CallingConv::Fast)
6661     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6662 
6663   // Count how many bytes are to be pushed on the stack, including the linkage
6664   // area, and parameter passing area.  We start with 24/48 bytes, which is
6665   // prereserved space for [SP][CR][LR][3 x unused].
6666   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6667   unsigned NumBytes = LinkageSize;
6668 
6669   // Add up all the space actually used.
6670   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6671   // they all go in registers, but we must reserve stack space for them for
6672   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6673   // assigned stack space in order, with padding so Altivec parameters are
6674   // 16-byte aligned.
6675   unsigned nAltivecParamsAtEnd = 0;
6676   for (unsigned i = 0; i != NumOps; ++i) {
6677     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6678     EVT ArgVT = Outs[i].VT;
6679     // Varargs Altivec parameters are padded to a 16 byte boundary.
6680     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6681         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6682         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6683       if (!CFlags.IsVarArg && !isPPC64) {
6684         // Non-varargs Altivec parameters go after all the non-Altivec
6685         // parameters; handle those later so we know how much padding we need.
6686         nAltivecParamsAtEnd++;
6687         continue;
6688       }
6689       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6690       NumBytes = ((NumBytes+15)/16)*16;
6691     }
6692     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6693   }
6694 
6695   // Allow for Altivec parameters at the end, if needed.
6696   if (nAltivecParamsAtEnd) {
6697     NumBytes = ((NumBytes+15)/16)*16;
6698     NumBytes += 16*nAltivecParamsAtEnd;
6699   }
6700 
6701   // The prolog code of the callee may store up to 8 GPR argument registers to
6702   // the stack, allowing va_start to index over them in memory if its varargs.
6703   // Because we cannot tell if this is needed on the caller side, we have to
6704   // conservatively assume that it is needed.  As such, make sure we have at
6705   // least enough stack space for the caller to store the 8 GPRs.
6706   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6707 
6708   // Tail call needs the stack to be aligned.
6709   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6710       CFlags.CallConv == CallingConv::Fast)
6711     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6712 
6713   // Calculate by how many bytes the stack has to be adjusted in case of tail
6714   // call optimization.
6715   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6716 
6717   // To protect arguments on the stack from being clobbered in a tail call,
6718   // force all the loads to happen before doing any other lowering.
6719   if (CFlags.IsTailCall)
6720     Chain = DAG.getStackArgumentTokenFactor(Chain);
6721 
6722   // Adjust the stack pointer for the new arguments...
6723   // These operations are automatically eliminated by the prolog/epilog pass
6724   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6725   SDValue CallSeqStart = Chain;
6726 
6727   // Load the return address and frame pointer so it can be move somewhere else
6728   // later.
6729   SDValue LROp, FPOp;
6730   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6731 
6732   // Set up a copy of the stack pointer for use loading and storing any
6733   // arguments that may not fit in the registers available for argument
6734   // passing.
6735   SDValue StackPtr;
6736   if (isPPC64)
6737     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6738   else
6739     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6740 
6741   // Figure out which arguments are going to go in registers, and which in
6742   // memory.  Also, if this is a vararg function, floating point operations
6743   // must be stored to our stack, and loaded into integer regs as well, if
6744   // any integer regs are available for argument passing.
6745   unsigned ArgOffset = LinkageSize;
6746   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6747 
6748   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6749     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6750     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6751   };
6752   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6753     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6754     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6755   };
6756   static const MCPhysReg VR[] = {
6757     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6758     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6759   };
6760   const unsigned NumGPRs = array_lengthof(GPR_32);
6761   const unsigned NumFPRs = 13;
6762   const unsigned NumVRs  = array_lengthof(VR);
6763 
6764   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6765 
6766   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6767   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6768 
6769   SmallVector<SDValue, 8> MemOpChains;
6770   for (unsigned i = 0; i != NumOps; ++i) {
6771     SDValue Arg = OutVals[i];
6772     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6773 
6774     // PtrOff will be used to store the current argument to the stack if a
6775     // register cannot be found for it.
6776     SDValue PtrOff;
6777 
6778     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6779 
6780     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6781 
6782     // On PPC64, promote integers to 64-bit values.
6783     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6784       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6785       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6786       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6787     }
6788 
6789     // FIXME memcpy is used way more than necessary.  Correctness first.
6790     // Note: "by value" is code for passing a structure by value, not
6791     // basic types.
6792     if (Flags.isByVal()) {
6793       unsigned Size = Flags.getByValSize();
6794       // Very small objects are passed right-justified.  Everything else is
6795       // passed left-justified.
6796       if (Size==1 || Size==2) {
6797         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6798         if (GPR_idx != NumGPRs) {
6799           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6800                                         MachinePointerInfo(), VT);
6801           MemOpChains.push_back(Load.getValue(1));
6802           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6803 
6804           ArgOffset += PtrByteSize;
6805         } else {
6806           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6807                                           PtrOff.getValueType());
6808           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6809           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6810                                                             CallSeqStart,
6811                                                             Flags, DAG, dl);
6812           ArgOffset += PtrByteSize;
6813         }
6814         continue;
6815       }
6816       // Copy entire object into memory.  There are cases where gcc-generated
6817       // code assumes it is there, even if it could be put entirely into
6818       // registers.  (This is not what the doc says.)
6819       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6820                                                         CallSeqStart,
6821                                                         Flags, DAG, dl);
6822 
6823       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6824       // copy the pieces of the object that fit into registers from the
6825       // parameter save area.
6826       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6827         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6828         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6829         if (GPR_idx != NumGPRs) {
6830           SDValue Load =
6831               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6832           MemOpChains.push_back(Load.getValue(1));
6833           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6834           ArgOffset += PtrByteSize;
6835         } else {
6836           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6837           break;
6838         }
6839       }
6840       continue;
6841     }
6842 
6843     switch (Arg.getSimpleValueType().SimpleTy) {
6844     default: llvm_unreachable("Unexpected ValueType for argument!");
6845     case MVT::i1:
6846     case MVT::i32:
6847     case MVT::i64:
6848       if (GPR_idx != NumGPRs) {
6849         if (Arg.getValueType() == MVT::i1)
6850           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6851 
6852         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6853       } else {
6854         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6855                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6856                          TailCallArguments, dl);
6857       }
6858       ArgOffset += PtrByteSize;
6859       break;
6860     case MVT::f32:
6861     case MVT::f64:
6862       if (FPR_idx != NumFPRs) {
6863         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6864 
6865         if (CFlags.IsVarArg) {
6866           SDValue Store =
6867               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6868           MemOpChains.push_back(Store);
6869 
6870           // Float varargs are always shadowed in available integer registers
6871           if (GPR_idx != NumGPRs) {
6872             SDValue Load =
6873                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6874             MemOpChains.push_back(Load.getValue(1));
6875             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6876           }
6877           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6878             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6879             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6880             SDValue Load =
6881                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6882             MemOpChains.push_back(Load.getValue(1));
6883             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6884           }
6885         } else {
6886           // If we have any FPRs remaining, we may also have GPRs remaining.
6887           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6888           // GPRs.
6889           if (GPR_idx != NumGPRs)
6890             ++GPR_idx;
6891           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6892               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6893             ++GPR_idx;
6894         }
6895       } else
6896         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6897                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6898                          TailCallArguments, dl);
6899       if (isPPC64)
6900         ArgOffset += 8;
6901       else
6902         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6903       break;
6904     case MVT::v4f32:
6905     case MVT::v4i32:
6906     case MVT::v8i16:
6907     case MVT::v16i8:
6908       if (CFlags.IsVarArg) {
6909         // These go aligned on the stack, or in the corresponding R registers
6910         // when within range.  The Darwin PPC ABI doc claims they also go in
6911         // V registers; in fact gcc does this only for arguments that are
6912         // prototyped, not for those that match the ...  We do it for all
6913         // arguments, seems to work.
6914         while (ArgOffset % 16 !=0) {
6915           ArgOffset += PtrByteSize;
6916           if (GPR_idx != NumGPRs)
6917             GPR_idx++;
6918         }
6919         // We could elide this store in the case where the object fits
6920         // entirely in R registers.  Maybe later.
6921         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6922                              DAG.getConstant(ArgOffset, dl, PtrVT));
6923         SDValue Store =
6924             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6925         MemOpChains.push_back(Store);
6926         if (VR_idx != NumVRs) {
6927           SDValue Load =
6928               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6929           MemOpChains.push_back(Load.getValue(1));
6930           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6931         }
6932         ArgOffset += 16;
6933         for (unsigned i=0; i<16; i+=PtrByteSize) {
6934           if (GPR_idx == NumGPRs)
6935             break;
6936           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6937                                    DAG.getConstant(i, dl, PtrVT));
6938           SDValue Load =
6939               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6940           MemOpChains.push_back(Load.getValue(1));
6941           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6942         }
6943         break;
6944       }
6945 
6946       // Non-varargs Altivec params generally go in registers, but have
6947       // stack space allocated at the end.
6948       if (VR_idx != NumVRs) {
6949         // Doesn't have GPR space allocated.
6950         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6951       } else if (nAltivecParamsAtEnd==0) {
6952         // We are emitting Altivec params in order.
6953         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6954                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6955                          TailCallArguments, dl);
6956         ArgOffset += 16;
6957       }
6958       break;
6959     }
6960   }
6961   // If all Altivec parameters fit in registers, as they usually do,
6962   // they get stack space following the non-Altivec parameters.  We
6963   // don't track this here because nobody below needs it.
6964   // If there are more Altivec parameters than fit in registers emit
6965   // the stores here.
6966   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6967     unsigned j = 0;
6968     // Offset is aligned; skip 1st 12 params which go in V registers.
6969     ArgOffset = ((ArgOffset+15)/16)*16;
6970     ArgOffset += 12*16;
6971     for (unsigned i = 0; i != NumOps; ++i) {
6972       SDValue Arg = OutVals[i];
6973       EVT ArgType = Outs[i].VT;
6974       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6975           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6976         if (++j > NumVRs) {
6977           SDValue PtrOff;
6978           // We are emitting Altivec params in order.
6979           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6980                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6981                            TailCallArguments, dl);
6982           ArgOffset += 16;
6983         }
6984       }
6985     }
6986   }
6987 
6988   if (!MemOpChains.empty())
6989     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6990 
6991   // On Darwin, R12 must contain the address of an indirect callee.  This does
6992   // not mean the MTCTR instruction must use R12; it's easier to model this as
6993   // an extra parameter, so do that.
6994   if (CFlags.IsIndirect) {
6995     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6996     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6997                                                    PPC::R12), Callee));
6998   }
6999 
7000   // Build a sequence of copy-to-reg nodes chained together with token chain
7001   // and flag operands which copy the outgoing args into the appropriate regs.
7002   SDValue InFlag;
7003   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
7004     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
7005                              RegsToPass[i].second, InFlag);
7006     InFlag = Chain.getValue(1);
7007   }
7008 
7009   if (CFlags.IsTailCall)
7010     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
7011                     TailCallArguments);
7012 
7013   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7014                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7015 }
7016 
7017 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
7018                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
7019                    CCState &State) {
7020 
7021   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
7022       State.getMachineFunction().getSubtarget());
7023   const bool IsPPC64 = Subtarget.isPPC64();
7024   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
7025   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
7026 
7027   assert((!ValVT.isInteger() ||
7028           (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) &&
7029          "Integer argument exceeds register size: should have been legalized");
7030 
7031   if (ValVT == MVT::f128)
7032     report_fatal_error("f128 is unimplemented on AIX.");
7033 
7034   if (ArgFlags.isNest())
7035     report_fatal_error("Nest arguments are unimplemented.");
7036 
7037   if (ValVT.isVector() || LocVT.isVector())
7038     report_fatal_error("Vector arguments are unimplemented on AIX.");
7039 
7040   static const MCPhysReg GPR_32[] = {// 32-bit registers.
7041                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7042                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7043   static const MCPhysReg GPR_64[] = {// 64-bit registers.
7044                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7045                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7046 
7047   if (ArgFlags.isByVal()) {
7048     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
7049       report_fatal_error("Pass-by-value arguments with alignment greater than "
7050                          "register width are not supported.");
7051 
7052     const unsigned ByValSize = ArgFlags.getByValSize();
7053 
7054     // An empty aggregate parameter takes up no storage and no registers,
7055     // but needs a MemLoc for a stack slot for the formal arguments side.
7056     if (ByValSize == 0) {
7057       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
7058                                        State.getNextStackOffset(), RegVT,
7059                                        LocInfo));
7060       return false;
7061     }
7062 
7063     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
7064     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
7065     for (const unsigned E = Offset + StackSize; Offset < E;
7066          Offset += PtrAlign.value()) {
7067       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
7068         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7069       else {
7070         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
7071                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
7072                                          LocInfo));
7073         break;
7074       }
7075     }
7076     return false;
7077   }
7078 
7079   // Arguments always reserve parameter save area.
7080   switch (ValVT.SimpleTy) {
7081   default:
7082     report_fatal_error("Unhandled value type for argument.");
7083   case MVT::i64:
7084     // i64 arguments should have been split to i32 for PPC32.
7085     assert(IsPPC64 && "PPC32 should have split i64 values.");
7086     LLVM_FALLTHROUGH;
7087   case MVT::i1:
7088   case MVT::i32: {
7089     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
7090     // AIX integer arguments are always passed in register width.
7091     if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
7092       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
7093                                   : CCValAssign::LocInfo::ZExt;
7094     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
7095       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7096     else
7097       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
7098 
7099     return false;
7100   }
7101   case MVT::f32:
7102   case MVT::f64: {
7103     // Parameter save area (PSA) is reserved even if the float passes in fpr.
7104     const unsigned StoreSize = LocVT.getStoreSize();
7105     // Floats are always 4-byte aligned in the PSA on AIX.
7106     // This includes f64 in 64-bit mode for ABI compatibility.
7107     const unsigned Offset =
7108         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
7109     unsigned FReg = State.AllocateReg(FPR);
7110     if (FReg)
7111       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
7112 
7113     // Reserve and initialize GPRs or initialize the PSA as required.
7114     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
7115       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
7116         assert(FReg && "An FPR should be available when a GPR is reserved.");
7117         if (State.isVarArg()) {
7118           // Successfully reserved GPRs are only initialized for vararg calls.
7119           // Custom handling is required for:
7120           //   f64 in PPC32 needs to be split into 2 GPRs.
7121           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
7122           State.addLoc(
7123               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7124         }
7125       } else {
7126         // If there are insufficient GPRs, the PSA needs to be initialized.
7127         // Initialization occurs even if an FPR was initialized for
7128         // compatibility with the AIX XL compiler. The full memory for the
7129         // argument will be initialized even if a prior word is saved in GPR.
7130         // A custom memLoc is used when the argument also passes in FPR so
7131         // that the callee handling can skip over it easily.
7132         State.addLoc(
7133             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
7134                                              LocInfo)
7135                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7136         break;
7137       }
7138     }
7139 
7140     return false;
7141   }
7142   }
7143   return true;
7144 }
7145 
7146 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
7147                                                     bool IsPPC64) {
7148   assert((IsPPC64 || SVT != MVT::i64) &&
7149          "i64 should have been split for 32-bit codegen.");
7150 
7151   switch (SVT) {
7152   default:
7153     report_fatal_error("Unexpected value type for formal argument");
7154   case MVT::i1:
7155   case MVT::i32:
7156   case MVT::i64:
7157     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7158   case MVT::f32:
7159     return &PPC::F4RCRegClass;
7160   case MVT::f64:
7161     return &PPC::F8RCRegClass;
7162   }
7163 }
7164 
7165 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
7166                                         SelectionDAG &DAG, SDValue ArgValue,
7167                                         MVT LocVT, const SDLoc &dl) {
7168   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7169   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
7170 
7171   if (Flags.isSExt())
7172     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7173                            DAG.getValueType(ValVT));
7174   else if (Flags.isZExt())
7175     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7176                            DAG.getValueType(ValVT));
7177 
7178   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7179 }
7180 
7181 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7182   const unsigned LASize = FL->getLinkageSize();
7183 
7184   if (PPC::GPRCRegClass.contains(Reg)) {
7185     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7186            "Reg must be a valid argument register!");
7187     return LASize + 4 * (Reg - PPC::R3);
7188   }
7189 
7190   if (PPC::G8RCRegClass.contains(Reg)) {
7191     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7192            "Reg must be a valid argument register!");
7193     return LASize + 8 * (Reg - PPC::X3);
7194   }
7195 
7196   llvm_unreachable("Only general purpose registers expected.");
7197 }
7198 
7199 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7200     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7201     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7202     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7203 
7204   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7205           CallConv == CallingConv::Fast) &&
7206          "Unexpected calling convention!");
7207 
7208   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7209     report_fatal_error("Tail call support is unimplemented on AIX.");
7210 
7211   if (useSoftFloat())
7212     report_fatal_error("Soft float support is unimplemented on AIX.");
7213 
7214   const PPCSubtarget &Subtarget =
7215       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7216   if (Subtarget.hasQPX())
7217     report_fatal_error("QPX support is not supported on AIX.");
7218 
7219   const bool IsPPC64 = Subtarget.isPPC64();
7220   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7221 
7222   // Assign locations to all of the incoming arguments.
7223   SmallVector<CCValAssign, 16> ArgLocs;
7224   MachineFunction &MF = DAG.getMachineFunction();
7225   MachineFrameInfo &MFI = MF.getFrameInfo();
7226   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7227 
7228   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7229   // Reserve space for the linkage area on the stack.
7230   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7231   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7232   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7233 
7234   SmallVector<SDValue, 8> MemOps;
7235 
7236   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7237     CCValAssign &VA = ArgLocs[I++];
7238     MVT LocVT = VA.getLocVT();
7239     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7240 
7241     // For compatibility with the AIX XL compiler, the float args in the
7242     // parameter save area are initialized even if the argument is available
7243     // in register.  The caller is required to initialize both the register
7244     // and memory, however, the callee can choose to expect it in either.
7245     // The memloc is dismissed here because the argument is retrieved from
7246     // the register.
7247     if (VA.isMemLoc() && VA.needsCustom())
7248       continue;
7249 
7250     if (Flags.isByVal() && VA.isMemLoc()) {
7251       const unsigned Size =
7252           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7253                   PtrByteSize);
7254       const int FI = MF.getFrameInfo().CreateFixedObject(
7255           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7256           /* IsAliased */ true);
7257       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7258       InVals.push_back(FIN);
7259 
7260       continue;
7261     }
7262 
7263     if (Flags.isByVal()) {
7264       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7265 
7266       const MCPhysReg ArgReg = VA.getLocReg();
7267       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7268 
7269       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7270         report_fatal_error("Over aligned byvals not supported yet.");
7271 
7272       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7273       const int FI = MF.getFrameInfo().CreateFixedObject(
7274           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7275           /* IsAliased */ true);
7276       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7277       InVals.push_back(FIN);
7278 
7279       // Add live ins for all the RegLocs for the same ByVal.
7280       const TargetRegisterClass *RegClass =
7281           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7282 
7283       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7284                                                unsigned Offset) {
7285         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7286         // Since the callers side has left justified the aggregate in the
7287         // register, we can simply store the entire register into the stack
7288         // slot.
7289         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7290         // The store to the fixedstack object is needed becuase accessing a
7291         // field of the ByVal will use a gep and load. Ideally we will optimize
7292         // to extracting the value from the register directly, and elide the
7293         // stores when the arguments address is not taken, but that will need to
7294         // be future work.
7295         SDValue Store =
7296             DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom,
7297                          DAG.getObjectPtrOffset(dl, FIN, Offset),
7298                          MachinePointerInfo::getFixedStack(MF, FI, Offset));
7299 
7300         MemOps.push_back(Store);
7301       };
7302 
7303       unsigned Offset = 0;
7304       HandleRegLoc(VA.getLocReg(), Offset);
7305       Offset += PtrByteSize;
7306       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7307            Offset += PtrByteSize) {
7308         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7309                "RegLocs should be for ByVal argument.");
7310 
7311         const CCValAssign RL = ArgLocs[I++];
7312         HandleRegLoc(RL.getLocReg(), Offset);
7313       }
7314 
7315       if (Offset != StackSize) {
7316         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7317                "Expected MemLoc for remaining bytes.");
7318         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7319         // Consume the MemLoc.The InVal has already been emitted, so nothing
7320         // more needs to be done.
7321         ++I;
7322       }
7323 
7324       continue;
7325     }
7326 
7327     EVT ValVT = VA.getValVT();
7328     if (VA.isRegLoc() && !VA.needsCustom()) {
7329       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7330       unsigned VReg =
7331           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7332       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7333       if (ValVT.isScalarInteger() &&
7334           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7335         ArgValue =
7336             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7337       }
7338       InVals.push_back(ArgValue);
7339       continue;
7340     }
7341     if (VA.isMemLoc()) {
7342       const unsigned LocSize = LocVT.getStoreSize();
7343       const unsigned ValSize = ValVT.getStoreSize();
7344       assert((ValSize <= LocSize) &&
7345              "Object size is larger than size of MemLoc");
7346       int CurArgOffset = VA.getLocMemOffset();
7347       // Objects are right-justified because AIX is big-endian.
7348       if (LocSize > ValSize)
7349         CurArgOffset += LocSize - ValSize;
7350       // Potential tail calls could cause overwriting of argument stack slots.
7351       const bool IsImmutable =
7352           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7353             (CallConv == CallingConv::Fast));
7354       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7355       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7356       SDValue ArgValue =
7357           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7358       InVals.push_back(ArgValue);
7359       continue;
7360     }
7361   }
7362 
7363   // On AIX a minimum of 8 words is saved to the parameter save area.
7364   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7365   // Area that is at least reserved in the caller of this function.
7366   unsigned CallerReservedArea =
7367       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7368 
7369   // Set the size that is at least reserved in caller of this function. Tail
7370   // call optimized function's reserved stack space needs to be aligned so
7371   // that taking the difference between two stack areas will result in an
7372   // aligned stack.
7373   CallerReservedArea =
7374       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7375   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7376   FuncInfo->setMinReservedArea(CallerReservedArea);
7377 
7378   if (isVarArg) {
7379     FuncInfo->setVarArgsFrameIndex(
7380         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7381     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7382 
7383     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7384                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7385 
7386     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7387                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7388     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7389 
7390     // The fixed integer arguments of a variadic function are stored to the
7391     // VarArgsFrameIndex on the stack so that they may be loaded by
7392     // dereferencing the result of va_next.
7393     for (unsigned GPRIndex =
7394              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7395          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7396 
7397       const unsigned VReg =
7398           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7399                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7400 
7401       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7402       SDValue Store =
7403           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7404       MemOps.push_back(Store);
7405       // Increment the address for the next argument to store.
7406       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7407       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7408     }
7409   }
7410 
7411   if (!MemOps.empty())
7412     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7413 
7414   return Chain;
7415 }
7416 
7417 SDValue PPCTargetLowering::LowerCall_AIX(
7418     SDValue Chain, SDValue Callee, CallFlags CFlags,
7419     const SmallVectorImpl<ISD::OutputArg> &Outs,
7420     const SmallVectorImpl<SDValue> &OutVals,
7421     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7422     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7423     const CallBase *CB) const {
7424 
7425   assert((CFlags.CallConv == CallingConv::C ||
7426           CFlags.CallConv == CallingConv::Cold ||
7427           CFlags.CallConv == CallingConv::Fast) &&
7428          "Unexpected calling convention!");
7429 
7430   if (CFlags.IsPatchPoint)
7431     report_fatal_error("This call type is unimplemented on AIX.");
7432 
7433   const PPCSubtarget& Subtarget =
7434       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7435   if (Subtarget.hasQPX())
7436     report_fatal_error("QPX is not supported on AIX.");
7437   if (Subtarget.hasAltivec())
7438     report_fatal_error("Altivec support is unimplemented on AIX.");
7439 
7440   MachineFunction &MF = DAG.getMachineFunction();
7441   SmallVector<CCValAssign, 16> ArgLocs;
7442   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7443                  *DAG.getContext());
7444 
7445   // Reserve space for the linkage save area (LSA) on the stack.
7446   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7447   //   [SP][CR][LR][2 x reserved][TOC].
7448   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7449   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7450   const bool IsPPC64 = Subtarget.isPPC64();
7451   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7452   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7453   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7454   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7455 
7456   // The prolog code of the callee may store up to 8 GPR argument registers to
7457   // the stack, allowing va_start to index over them in memory if the callee
7458   // is variadic.
7459   // Because we cannot tell if this is needed on the caller side, we have to
7460   // conservatively assume that it is needed.  As such, make sure we have at
7461   // least enough stack space for the caller to store the 8 GPRs.
7462   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7463   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7464                                      CCInfo.getNextStackOffset());
7465 
7466   // Adjust the stack pointer for the new arguments...
7467   // These operations are automatically eliminated by the prolog/epilog pass.
7468   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7469   SDValue CallSeqStart = Chain;
7470 
7471   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7472   SmallVector<SDValue, 8> MemOpChains;
7473 
7474   // Set up a copy of the stack pointer for loading and storing any
7475   // arguments that may not fit in the registers available for argument
7476   // passing.
7477   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7478                                    : DAG.getRegister(PPC::R1, MVT::i32);
7479 
7480   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7481     const unsigned ValNo = ArgLocs[I].getValNo();
7482     SDValue Arg = OutVals[ValNo];
7483     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7484 
7485     if (Flags.isByVal()) {
7486       const unsigned ByValSize = Flags.getByValSize();
7487 
7488       // Nothing to do for zero-sized ByVals on the caller side.
7489       if (!ByValSize) {
7490         ++I;
7491         continue;
7492       }
7493 
7494       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7495         return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain,
7496                               (LoadOffset != 0)
7497                                   ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7498                                   : Arg,
7499                               MachinePointerInfo(), VT);
7500       };
7501 
7502       unsigned LoadOffset = 0;
7503 
7504       // Initialize registers, which are fully occupied by the by-val argument.
7505       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7506         SDValue Load = GetLoad(PtrVT, LoadOffset);
7507         MemOpChains.push_back(Load.getValue(1));
7508         LoadOffset += PtrByteSize;
7509         const CCValAssign &ByValVA = ArgLocs[I++];
7510         assert(ByValVA.getValNo() == ValNo &&
7511                "Unexpected location for pass-by-value argument.");
7512         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7513       }
7514 
7515       if (LoadOffset == ByValSize)
7516         continue;
7517 
7518       // There must be one more loc to handle the remainder.
7519       assert(ArgLocs[I].getValNo() == ValNo &&
7520              "Expected additional location for by-value argument.");
7521 
7522       if (ArgLocs[I].isMemLoc()) {
7523         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7524         const CCValAssign &ByValVA = ArgLocs[I++];
7525         ISD::ArgFlagsTy MemcpyFlags = Flags;
7526         // Only memcpy the bytes that don't pass in register.
7527         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7528         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7529             (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7530                               : Arg,
7531             DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()),
7532             CallSeqStart, MemcpyFlags, DAG, dl);
7533         continue;
7534       }
7535 
7536       // Initialize the final register residue.
7537       // Any residue that occupies the final by-val arg register must be
7538       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7539       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7540       // 2 and 1 byte loads.
7541       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7542       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7543              "Unexpected register residue for by-value argument.");
7544       SDValue ResidueVal;
7545       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7546         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7547         const MVT VT =
7548             N == 1 ? MVT::i8
7549                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7550         SDValue Load = GetLoad(VT, LoadOffset);
7551         MemOpChains.push_back(Load.getValue(1));
7552         LoadOffset += N;
7553         Bytes += N;
7554 
7555         // By-val arguments are passed left-justfied in register.
7556         // Every load here needs to be shifted, otherwise a full register load
7557         // should have been used.
7558         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7559                "Unexpected load emitted during handling of pass-by-value "
7560                "argument.");
7561         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7562         EVT ShiftAmountTy =
7563             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7564         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7565         SDValue ShiftedLoad =
7566             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7567         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7568                                               ShiftedLoad)
7569                                 : ShiftedLoad;
7570       }
7571 
7572       const CCValAssign &ByValVA = ArgLocs[I++];
7573       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7574       continue;
7575     }
7576 
7577     CCValAssign &VA = ArgLocs[I++];
7578     const MVT LocVT = VA.getLocVT();
7579     const MVT ValVT = VA.getValVT();
7580 
7581     switch (VA.getLocInfo()) {
7582     default:
7583       report_fatal_error("Unexpected argument extension type.");
7584     case CCValAssign::Full:
7585       break;
7586     case CCValAssign::ZExt:
7587       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7588       break;
7589     case CCValAssign::SExt:
7590       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7591       break;
7592     }
7593 
7594     if (VA.isRegLoc() && !VA.needsCustom()) {
7595       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7596       continue;
7597     }
7598 
7599     if (VA.isMemLoc()) {
7600       SDValue PtrOff =
7601           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7602       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7603       MemOpChains.push_back(
7604           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7605 
7606       continue;
7607     }
7608 
7609     // Custom handling is used for GPR initializations for vararg float
7610     // arguments.
7611     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7612            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7613            "Unexpected register handling for calling convention.");
7614 
7615     SDValue ArgAsInt =
7616         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7617 
7618     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7619       // f32 in 32-bit GPR
7620       // f64 in 64-bit GPR
7621       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7622     else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits())
7623       // f32 in 64-bit GPR.
7624       RegsToPass.push_back(std::make_pair(
7625           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7626     else {
7627       // f64 in two 32-bit GPRs
7628       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7629       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7630              "Unexpected custom register for argument!");
7631       CCValAssign &GPR1 = VA;
7632       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7633                                      DAG.getConstant(32, dl, MVT::i8));
7634       RegsToPass.push_back(std::make_pair(
7635           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7636 
7637       if (I != E) {
7638         // If only 1 GPR was available, there will only be one custom GPR and
7639         // the argument will also pass in memory.
7640         CCValAssign &PeekArg = ArgLocs[I];
7641         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7642           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7643           CCValAssign &GPR2 = ArgLocs[I++];
7644           RegsToPass.push_back(std::make_pair(
7645               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7646         }
7647       }
7648     }
7649   }
7650 
7651   if (!MemOpChains.empty())
7652     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7653 
7654   // For indirect calls, we need to save the TOC base to the stack for
7655   // restoration after the call.
7656   if (CFlags.IsIndirect) {
7657     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7658     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7659     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7660     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7661     const unsigned TOCSaveOffset =
7662         Subtarget.getFrameLowering()->getTOCSaveOffset();
7663 
7664     setUsesTOCBasePtr(DAG);
7665     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7666     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7667     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7668     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7669     Chain = DAG.getStore(
7670         Val.getValue(1), dl, Val, AddPtr,
7671         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7672   }
7673 
7674   // Build a sequence of copy-to-reg nodes chained together with token chain
7675   // and flag operands which copy the outgoing args into the appropriate regs.
7676   SDValue InFlag;
7677   for (auto Reg : RegsToPass) {
7678     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7679     InFlag = Chain.getValue(1);
7680   }
7681 
7682   const int SPDiff = 0;
7683   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7684                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7685 }
7686 
7687 bool
7688 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7689                                   MachineFunction &MF, bool isVarArg,
7690                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7691                                   LLVMContext &Context) const {
7692   SmallVector<CCValAssign, 16> RVLocs;
7693   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7694   return CCInfo.CheckReturn(
7695       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7696                 ? RetCC_PPC_Cold
7697                 : RetCC_PPC);
7698 }
7699 
7700 SDValue
7701 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7702                                bool isVarArg,
7703                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7704                                const SmallVectorImpl<SDValue> &OutVals,
7705                                const SDLoc &dl, SelectionDAG &DAG) const {
7706   SmallVector<CCValAssign, 16> RVLocs;
7707   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7708                  *DAG.getContext());
7709   CCInfo.AnalyzeReturn(Outs,
7710                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7711                            ? RetCC_PPC_Cold
7712                            : RetCC_PPC);
7713 
7714   SDValue Flag;
7715   SmallVector<SDValue, 4> RetOps(1, Chain);
7716 
7717   // Copy the result values into the output registers.
7718   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7719     CCValAssign &VA = RVLocs[i];
7720     assert(VA.isRegLoc() && "Can only return in registers!");
7721 
7722     SDValue Arg = OutVals[RealResIdx];
7723 
7724     switch (VA.getLocInfo()) {
7725     default: llvm_unreachable("Unknown loc info!");
7726     case CCValAssign::Full: break;
7727     case CCValAssign::AExt:
7728       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7729       break;
7730     case CCValAssign::ZExt:
7731       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7732       break;
7733     case CCValAssign::SExt:
7734       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7735       break;
7736     }
7737     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7738       bool isLittleEndian = Subtarget.isLittleEndian();
7739       // Legalize ret f64 -> ret 2 x i32.
7740       SDValue SVal =
7741           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7742                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7743       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7744       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7745       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7746                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7747       Flag = Chain.getValue(1);
7748       VA = RVLocs[++i]; // skip ahead to next loc
7749       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7750     } else
7751       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7752     Flag = Chain.getValue(1);
7753     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7754   }
7755 
7756   RetOps[0] = Chain;  // Update chain.
7757 
7758   // Add the flag if we have it.
7759   if (Flag.getNode())
7760     RetOps.push_back(Flag);
7761 
7762   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7763 }
7764 
7765 SDValue
7766 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7767                                                 SelectionDAG &DAG) const {
7768   SDLoc dl(Op);
7769 
7770   // Get the correct type for integers.
7771   EVT IntVT = Op.getValueType();
7772 
7773   // Get the inputs.
7774   SDValue Chain = Op.getOperand(0);
7775   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7776   // Build a DYNAREAOFFSET node.
7777   SDValue Ops[2] = {Chain, FPSIdx};
7778   SDVTList VTs = DAG.getVTList(IntVT);
7779   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7780 }
7781 
7782 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7783                                              SelectionDAG &DAG) const {
7784   // When we pop the dynamic allocation we need to restore the SP link.
7785   SDLoc dl(Op);
7786 
7787   // Get the correct type for pointers.
7788   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7789 
7790   // Construct the stack pointer operand.
7791   bool isPPC64 = Subtarget.isPPC64();
7792   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7793   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7794 
7795   // Get the operands for the STACKRESTORE.
7796   SDValue Chain = Op.getOperand(0);
7797   SDValue SaveSP = Op.getOperand(1);
7798 
7799   // Load the old link SP.
7800   SDValue LoadLinkSP =
7801       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7802 
7803   // Restore the stack pointer.
7804   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7805 
7806   // Store the old link SP.
7807   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7808 }
7809 
7810 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7811   MachineFunction &MF = DAG.getMachineFunction();
7812   bool isPPC64 = Subtarget.isPPC64();
7813   EVT PtrVT = getPointerTy(MF.getDataLayout());
7814 
7815   // Get current frame pointer save index.  The users of this index will be
7816   // primarily DYNALLOC instructions.
7817   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7818   int RASI = FI->getReturnAddrSaveIndex();
7819 
7820   // If the frame pointer save index hasn't been defined yet.
7821   if (!RASI) {
7822     // Find out what the fix offset of the frame pointer save area.
7823     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7824     // Allocate the frame index for frame pointer save area.
7825     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7826     // Save the result.
7827     FI->setReturnAddrSaveIndex(RASI);
7828   }
7829   return DAG.getFrameIndex(RASI, PtrVT);
7830 }
7831 
7832 SDValue
7833 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7834   MachineFunction &MF = DAG.getMachineFunction();
7835   bool isPPC64 = Subtarget.isPPC64();
7836   EVT PtrVT = getPointerTy(MF.getDataLayout());
7837 
7838   // Get current frame pointer save index.  The users of this index will be
7839   // primarily DYNALLOC instructions.
7840   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7841   int FPSI = FI->getFramePointerSaveIndex();
7842 
7843   // If the frame pointer save index hasn't been defined yet.
7844   if (!FPSI) {
7845     // Find out what the fix offset of the frame pointer save area.
7846     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7847     // Allocate the frame index for frame pointer save area.
7848     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7849     // Save the result.
7850     FI->setFramePointerSaveIndex(FPSI);
7851   }
7852   return DAG.getFrameIndex(FPSI, PtrVT);
7853 }
7854 
7855 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7856                                                    SelectionDAG &DAG) const {
7857   // Get the inputs.
7858   SDValue Chain = Op.getOperand(0);
7859   SDValue Size  = Op.getOperand(1);
7860   SDLoc dl(Op);
7861 
7862   // Get the correct type for pointers.
7863   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7864   // Negate the size.
7865   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7866                                 DAG.getConstant(0, dl, PtrVT), Size);
7867   // Construct a node for the frame pointer save index.
7868   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7869   // Build a DYNALLOC node.
7870   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7871   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7872   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7873 }
7874 
7875 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7876                                                      SelectionDAG &DAG) const {
7877   MachineFunction &MF = DAG.getMachineFunction();
7878 
7879   bool isPPC64 = Subtarget.isPPC64();
7880   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7881 
7882   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7883   return DAG.getFrameIndex(FI, PtrVT);
7884 }
7885 
7886 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7887                                                SelectionDAG &DAG) const {
7888   SDLoc DL(Op);
7889   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7890                      DAG.getVTList(MVT::i32, MVT::Other),
7891                      Op.getOperand(0), Op.getOperand(1));
7892 }
7893 
7894 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7895                                                 SelectionDAG &DAG) const {
7896   SDLoc DL(Op);
7897   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7898                      Op.getOperand(0), Op.getOperand(1));
7899 }
7900 
7901 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7902   if (Op.getValueType().isVector())
7903     return LowerVectorLoad(Op, DAG);
7904 
7905   assert(Op.getValueType() == MVT::i1 &&
7906          "Custom lowering only for i1 loads");
7907 
7908   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7909 
7910   SDLoc dl(Op);
7911   LoadSDNode *LD = cast<LoadSDNode>(Op);
7912 
7913   SDValue Chain = LD->getChain();
7914   SDValue BasePtr = LD->getBasePtr();
7915   MachineMemOperand *MMO = LD->getMemOperand();
7916 
7917   SDValue NewLD =
7918       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7919                      BasePtr, MVT::i8, MMO);
7920   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7921 
7922   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7923   return DAG.getMergeValues(Ops, dl);
7924 }
7925 
7926 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7927   if (Op.getOperand(1).getValueType().isVector())
7928     return LowerVectorStore(Op, DAG);
7929 
7930   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7931          "Custom lowering only for i1 stores");
7932 
7933   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7934 
7935   SDLoc dl(Op);
7936   StoreSDNode *ST = cast<StoreSDNode>(Op);
7937 
7938   SDValue Chain = ST->getChain();
7939   SDValue BasePtr = ST->getBasePtr();
7940   SDValue Value = ST->getValue();
7941   MachineMemOperand *MMO = ST->getMemOperand();
7942 
7943   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7944                       Value);
7945   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7946 }
7947 
7948 // FIXME: Remove this once the ANDI glue bug is fixed:
7949 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7950   assert(Op.getValueType() == MVT::i1 &&
7951          "Custom lowering only for i1 results");
7952 
7953   SDLoc DL(Op);
7954   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7955 }
7956 
7957 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7958                                                SelectionDAG &DAG) const {
7959 
7960   // Implements a vector truncate that fits in a vector register as a shuffle.
7961   // We want to legalize vector truncates down to where the source fits in
7962   // a vector register (and target is therefore smaller than vector register
7963   // size).  At that point legalization will try to custom lower the sub-legal
7964   // result and get here - where we can contain the truncate as a single target
7965   // operation.
7966 
7967   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7968   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7969   //
7970   // We will implement it for big-endian ordering as this (where x denotes
7971   // undefined):
7972   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7973   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7974   //
7975   // The same operation in little-endian ordering will be:
7976   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7977   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7978 
7979   assert(Op.getValueType().isVector() && "Vector type expected.");
7980 
7981   SDLoc DL(Op);
7982   SDValue N1 = Op.getOperand(0);
7983   unsigned SrcSize = N1.getValueType().getSizeInBits();
7984   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7985   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7986 
7987   EVT TrgVT = Op.getValueType();
7988   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7989   EVT EltVT = TrgVT.getVectorElementType();
7990   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7991   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7992 
7993   // First list the elements we want to keep.
7994   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7995   SmallVector<int, 16> ShuffV;
7996   if (Subtarget.isLittleEndian())
7997     for (unsigned i = 0; i < TrgNumElts; ++i)
7998       ShuffV.push_back(i * SizeMult);
7999   else
8000     for (unsigned i = 1; i <= TrgNumElts; ++i)
8001       ShuffV.push_back(i * SizeMult - 1);
8002 
8003   // Populate the remaining elements with undefs.
8004   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
8005     // ShuffV.push_back(i + WideNumElts);
8006     ShuffV.push_back(WideNumElts + 1);
8007 
8008   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
8009   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
8010 }
8011 
8012 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
8013 /// possible.
8014 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
8015   // Not FP? Not a fsel.
8016   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
8017       !Op.getOperand(2).getValueType().isFloatingPoint())
8018     return Op;
8019 
8020   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
8021 
8022   EVT ResVT = Op.getValueType();
8023   EVT CmpVT = Op.getOperand(0).getValueType();
8024   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8025   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
8026   SDLoc dl(Op);
8027   SDNodeFlags Flags = Op.getNode()->getFlags();
8028 
8029   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
8030   // presence of infinities.
8031   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
8032     switch (CC) {
8033     default:
8034       break;
8035     case ISD::SETOGT:
8036     case ISD::SETGT:
8037       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
8038     case ISD::SETOLT:
8039     case ISD::SETLT:
8040       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
8041     }
8042   }
8043 
8044   // We might be able to do better than this under some circumstances, but in
8045   // general, fsel-based lowering of select is a finite-math-only optimization.
8046   // For more information, see section F.3 of the 2.06 ISA specification.
8047   // With ISA 3.0
8048   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
8049       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
8050     return Op;
8051 
8052   // If the RHS of the comparison is a 0.0, we don't need to do the
8053   // subtraction at all.
8054   SDValue Sel1;
8055   if (isFloatingPointZero(RHS))
8056     switch (CC) {
8057     default: break;       // SETUO etc aren't handled by fsel.
8058     case ISD::SETNE:
8059       std::swap(TV, FV);
8060       LLVM_FALLTHROUGH;
8061     case ISD::SETEQ:
8062       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8063         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8064       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8065       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8066         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8067       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8068                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
8069     case ISD::SETULT:
8070     case ISD::SETLT:
8071       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8072       LLVM_FALLTHROUGH;
8073     case ISD::SETOGE:
8074     case ISD::SETGE:
8075       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8076         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8077       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8078     case ISD::SETUGT:
8079     case ISD::SETGT:
8080       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8081       LLVM_FALLTHROUGH;
8082     case ISD::SETOLE:
8083     case ISD::SETLE:
8084       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8085         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8086       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8087                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
8088     }
8089 
8090   SDValue Cmp;
8091   switch (CC) {
8092   default: break;       // SETUO etc aren't handled by fsel.
8093   case ISD::SETNE:
8094     std::swap(TV, FV);
8095     LLVM_FALLTHROUGH;
8096   case ISD::SETEQ:
8097     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8098     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8099       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8100     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8101     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8102       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8103     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8104                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8105   case ISD::SETULT:
8106   case ISD::SETLT:
8107     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8108     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8109       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8110     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8111   case ISD::SETOGE:
8112   case ISD::SETGE:
8113     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8114     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8115       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8116     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8117   case ISD::SETUGT:
8118   case ISD::SETGT:
8119     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8120     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8121       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8122     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8123   case ISD::SETOLE:
8124   case ISD::SETLE:
8125     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8126     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8127       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8128     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8129   }
8130   return Op;
8131 }
8132 
8133 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8134                                                SelectionDAG &DAG,
8135                                                const SDLoc &dl) const {
8136   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8137   SDValue Src = Op.getOperand(0);
8138   if (Src.getValueType() == MVT::f32)
8139     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8140 
8141   SDValue Tmp;
8142   switch (Op.getSimpleValueType().SimpleTy) {
8143   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8144   case MVT::i32:
8145     Tmp = DAG.getNode(
8146         Op.getOpcode() == ISD::FP_TO_SINT
8147             ? PPCISD::FCTIWZ
8148             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8149         dl, MVT::f64, Src);
8150     break;
8151   case MVT::i64:
8152     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8153            "i64 FP_TO_UINT is supported only with FPCVT");
8154     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8155                                                         PPCISD::FCTIDUZ,
8156                       dl, MVT::f64, Src);
8157     break;
8158   }
8159 
8160   // Convert the FP value to an int value through memory.
8161   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8162     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
8163   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8164   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8165   MachinePointerInfo MPI =
8166       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8167 
8168   // Emit a store to the stack slot.
8169   SDValue Chain;
8170   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8171   if (i32Stack) {
8172     MachineFunction &MF = DAG.getMachineFunction();
8173     Alignment = Align(4);
8174     MachineMemOperand *MMO =
8175         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8176     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
8177     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8178               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8179   } else
8180     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment);
8181 
8182   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8183   // add in a bias on big endian.
8184   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8185     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8186                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8187     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8188   }
8189 
8190   RLI.Chain = Chain;
8191   RLI.Ptr = FIPtr;
8192   RLI.MPI = MPI;
8193   RLI.Alignment = Alignment;
8194 }
8195 
8196 /// Custom lowers floating point to integer conversions to use
8197 /// the direct move instructions available in ISA 2.07 to avoid the
8198 /// need for load/store combinations.
8199 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8200                                                     SelectionDAG &DAG,
8201                                                     const SDLoc &dl) const {
8202   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8203   SDValue Src = Op.getOperand(0);
8204 
8205   if (Src.getValueType() == MVT::f32)
8206     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8207 
8208   SDValue Tmp;
8209   switch (Op.getSimpleValueType().SimpleTy) {
8210   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8211   case MVT::i32:
8212     Tmp = DAG.getNode(
8213         Op.getOpcode() == ISD::FP_TO_SINT
8214             ? PPCISD::FCTIWZ
8215             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8216         dl, MVT::f64, Src);
8217     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
8218     break;
8219   case MVT::i64:
8220     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8221            "i64 FP_TO_UINT is supported only with FPCVT");
8222     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8223                                                         PPCISD::FCTIDUZ,
8224                       dl, MVT::f64, Src);
8225     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
8226     break;
8227   }
8228   return Tmp;
8229 }
8230 
8231 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8232                                           const SDLoc &dl) const {
8233 
8234   // FP to INT conversions are legal for f128.
8235   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
8236     return Op;
8237 
8238   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8239   // PPC (the libcall is not available).
8240   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
8241     if (Op.getValueType() == MVT::i32) {
8242       if (Op.getOpcode() == ISD::FP_TO_SINT) {
8243         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8244                                  MVT::f64, Op.getOperand(0),
8245                                  DAG.getIntPtrConstant(0, dl));
8246         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8247                                  MVT::f64, Op.getOperand(0),
8248                                  DAG.getIntPtrConstant(1, dl));
8249 
8250         // Add the two halves of the long double in round-to-zero mode.
8251         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8252 
8253         // Now use a smaller FP_TO_SINT.
8254         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8255       }
8256       if (Op.getOpcode() == ISD::FP_TO_UINT) {
8257         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8258         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8259         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
8260         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8261         // FIXME: generated code sucks.
8262         // TODO: Are there fast-math-flags to propagate to this FSUB?
8263         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
8264                                    Op.getOperand(0), Tmp);
8265         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8266         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
8267                            DAG.getConstant(0x80000000, dl, MVT::i32));
8268         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
8269                                     Op.getOperand(0));
8270         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
8271                                ISD::SETGE);
8272       }
8273     }
8274 
8275     return SDValue();
8276   }
8277 
8278   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8279     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8280 
8281   ReuseLoadInfo RLI;
8282   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8283 
8284   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8285                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8286 }
8287 
8288 // We're trying to insert a regular store, S, and then a load, L. If the
8289 // incoming value, O, is a load, we might just be able to have our load use the
8290 // address used by O. However, we don't know if anything else will store to
8291 // that address before we can load from it. To prevent this situation, we need
8292 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8293 // the same chain operand as O, we create a token factor from the chain results
8294 // of O and L, and we replace all uses of O's chain result with that token
8295 // factor (see spliceIntoChain below for this last part).
8296 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8297                                             ReuseLoadInfo &RLI,
8298                                             SelectionDAG &DAG,
8299                                             ISD::LoadExtType ET) const {
8300   SDLoc dl(Op);
8301   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8302                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8303   if (ET == ISD::NON_EXTLOAD &&
8304       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8305       isOperationLegalOrCustom(Op.getOpcode(),
8306                                Op.getOperand(0).getValueType())) {
8307 
8308     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8309     return true;
8310   }
8311 
8312   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8313   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8314       LD->isNonTemporal())
8315     return false;
8316   if (LD->getMemoryVT() != MemVT)
8317     return false;
8318 
8319   RLI.Ptr = LD->getBasePtr();
8320   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8321     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8322            "Non-pre-inc AM on PPC?");
8323     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8324                           LD->getOffset());
8325   }
8326 
8327   RLI.Chain = LD->getChain();
8328   RLI.MPI = LD->getPointerInfo();
8329   RLI.IsDereferenceable = LD->isDereferenceable();
8330   RLI.IsInvariant = LD->isInvariant();
8331   RLI.Alignment = LD->getAlign();
8332   RLI.AAInfo = LD->getAAInfo();
8333   RLI.Ranges = LD->getRanges();
8334 
8335   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8336   return true;
8337 }
8338 
8339 // Given the head of the old chain, ResChain, insert a token factor containing
8340 // it and NewResChain, and make users of ResChain now be users of that token
8341 // factor.
8342 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8343 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8344                                         SDValue NewResChain,
8345                                         SelectionDAG &DAG) const {
8346   if (!ResChain)
8347     return;
8348 
8349   SDLoc dl(NewResChain);
8350 
8351   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8352                            NewResChain, DAG.getUNDEF(MVT::Other));
8353   assert(TF.getNode() != NewResChain.getNode() &&
8354          "A new TF really is required here");
8355 
8356   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8357   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8358 }
8359 
8360 /// Analyze profitability of direct move
8361 /// prefer float load to int load plus direct move
8362 /// when there is no integer use of int load
8363 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8364   SDNode *Origin = Op.getOperand(0).getNode();
8365   if (Origin->getOpcode() != ISD::LOAD)
8366     return true;
8367 
8368   // If there is no LXSIBZX/LXSIHZX, like Power8,
8369   // prefer direct move if the memory size is 1 or 2 bytes.
8370   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8371   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8372     return true;
8373 
8374   for (SDNode::use_iterator UI = Origin->use_begin(),
8375                             UE = Origin->use_end();
8376        UI != UE; ++UI) {
8377 
8378     // Only look at the users of the loaded value.
8379     if (UI.getUse().get().getResNo() != 0)
8380       continue;
8381 
8382     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8383         UI->getOpcode() != ISD::UINT_TO_FP)
8384       return true;
8385   }
8386 
8387   return false;
8388 }
8389 
8390 /// Custom lowers integer to floating point conversions to use
8391 /// the direct move instructions available in ISA 2.07 to avoid the
8392 /// need for load/store combinations.
8393 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8394                                                     SelectionDAG &DAG,
8395                                                     const SDLoc &dl) const {
8396   assert((Op.getValueType() == MVT::f32 ||
8397           Op.getValueType() == MVT::f64) &&
8398          "Invalid floating point type as target of conversion");
8399   assert(Subtarget.hasFPCVT() &&
8400          "Int to FP conversions with direct moves require FPCVT");
8401   SDValue FP;
8402   SDValue Src = Op.getOperand(0);
8403   bool SinglePrec = Op.getValueType() == MVT::f32;
8404   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8405   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
8406   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
8407                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
8408 
8409   if (WordInt) {
8410     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
8411                      dl, MVT::f64, Src);
8412     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8413   }
8414   else {
8415     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
8416     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8417   }
8418 
8419   return FP;
8420 }
8421 
8422 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8423 
8424   EVT VecVT = Vec.getValueType();
8425   assert(VecVT.isVector() && "Expected a vector type.");
8426   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8427 
8428   EVT EltVT = VecVT.getVectorElementType();
8429   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8430   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8431 
8432   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8433   SmallVector<SDValue, 16> Ops(NumConcat);
8434   Ops[0] = Vec;
8435   SDValue UndefVec = DAG.getUNDEF(VecVT);
8436   for (unsigned i = 1; i < NumConcat; ++i)
8437     Ops[i] = UndefVec;
8438 
8439   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8440 }
8441 
8442 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8443                                                 const SDLoc &dl) const {
8444 
8445   unsigned Opc = Op.getOpcode();
8446   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
8447          "Unexpected conversion type");
8448   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8449          "Supports conversions to v2f64/v4f32 only.");
8450 
8451   bool SignedConv = Opc == ISD::SINT_TO_FP;
8452   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8453 
8454   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
8455   EVT WideVT = Wide.getValueType();
8456   unsigned WideNumElts = WideVT.getVectorNumElements();
8457   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8458 
8459   SmallVector<int, 16> ShuffV;
8460   for (unsigned i = 0; i < WideNumElts; ++i)
8461     ShuffV.push_back(i + WideNumElts);
8462 
8463   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8464   int SaveElts = FourEltRes ? 4 : 2;
8465   if (Subtarget.isLittleEndian())
8466     for (int i = 0; i < SaveElts; i++)
8467       ShuffV[i * Stride] = i;
8468   else
8469     for (int i = 1; i <= SaveElts; i++)
8470       ShuffV[i * Stride - 1] = i - 1;
8471 
8472   SDValue ShuffleSrc2 =
8473       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8474   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8475 
8476   SDValue Extend;
8477   if (SignedConv) {
8478     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8479     EVT ExtVT = Op.getOperand(0).getValueType();
8480     if (Subtarget.hasP9Altivec())
8481       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8482                                IntermediateVT.getVectorNumElements());
8483 
8484     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8485                          DAG.getValueType(ExtVT));
8486   } else
8487     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8488 
8489   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8490 }
8491 
8492 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8493                                           SelectionDAG &DAG) const {
8494   SDLoc dl(Op);
8495 
8496   EVT InVT = Op.getOperand(0).getValueType();
8497   EVT OutVT = Op.getValueType();
8498   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8499       isOperationCustom(Op.getOpcode(), InVT))
8500     return LowerINT_TO_FPVector(Op, DAG, dl);
8501 
8502   // Conversions to f128 are legal.
8503   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
8504     return Op;
8505 
8506   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
8507     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
8508       return SDValue();
8509 
8510     SDValue Value = Op.getOperand(0);
8511     // The values are now known to be -1 (false) or 1 (true). To convert this
8512     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8513     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8514     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8515 
8516     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8517 
8518     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8519 
8520     if (Op.getValueType() != MVT::v4f64)
8521       Value = DAG.getNode(ISD::FP_ROUND, dl,
8522                           Op.getValueType(), Value,
8523                           DAG.getIntPtrConstant(1, dl));
8524     return Value;
8525   }
8526 
8527   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8528   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8529     return SDValue();
8530 
8531   if (Op.getOperand(0).getValueType() == MVT::i1)
8532     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
8533                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8534                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8535 
8536   // If we have direct moves, we can do all the conversion, skip the store/load
8537   // however, without FPCVT we can't do most conversions.
8538   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8539       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8540     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8541 
8542   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8543          "UINT_TO_FP is supported only with FPCVT");
8544 
8545   // If we have FCFIDS, then use it when converting to single-precision.
8546   // Otherwise, convert to double-precision and then round.
8547   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8548                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8549                                                             : PPCISD::FCFIDS)
8550                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8551                                                             : PPCISD::FCFID);
8552   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8553                   ? MVT::f32
8554                   : MVT::f64;
8555 
8556   if (Op.getOperand(0).getValueType() == MVT::i64) {
8557     SDValue SINT = Op.getOperand(0);
8558     // When converting to single-precision, we actually need to convert
8559     // to double-precision first and then round to single-precision.
8560     // To avoid double-rounding effects during that operation, we have
8561     // to prepare the input operand.  Bits that might be truncated when
8562     // converting to double-precision are replaced by a bit that won't
8563     // be lost at this stage, but is below the single-precision rounding
8564     // position.
8565     //
8566     // However, if -enable-unsafe-fp-math is in effect, accept double
8567     // rounding to avoid the extra overhead.
8568     if (Op.getValueType() == MVT::f32 &&
8569         !Subtarget.hasFPCVT() &&
8570         !DAG.getTarget().Options.UnsafeFPMath) {
8571 
8572       // Twiddle input to make sure the low 11 bits are zero.  (If this
8573       // is the case, we are guaranteed the value will fit into the 53 bit
8574       // mantissa of an IEEE double-precision value without rounding.)
8575       // If any of those low 11 bits were not zero originally, make sure
8576       // bit 12 (value 2048) is set instead, so that the final rounding
8577       // to single-precision gets the correct result.
8578       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8579                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8580       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8581                           Round, DAG.getConstant(2047, dl, MVT::i64));
8582       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8583       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8584                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8585 
8586       // However, we cannot use that value unconditionally: if the magnitude
8587       // of the input value is small, the bit-twiddling we did above might
8588       // end up visibly changing the output.  Fortunately, in that case, we
8589       // don't need to twiddle bits since the original input will convert
8590       // exactly to double-precision floating-point already.  Therefore,
8591       // construct a conditional to use the original value if the top 11
8592       // bits are all sign-bit copies, and use the rounded value computed
8593       // above otherwise.
8594       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8595                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8596       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8597                          Cond, DAG.getConstant(1, dl, MVT::i64));
8598       Cond = DAG.getSetCC(
8599           dl,
8600           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8601           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8602 
8603       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8604     }
8605 
8606     ReuseLoadInfo RLI;
8607     SDValue Bits;
8608 
8609     MachineFunction &MF = DAG.getMachineFunction();
8610     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8611       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8612                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8613       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8614     } else if (Subtarget.hasLFIWAX() &&
8615                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8616       MachineMemOperand *MMO =
8617         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8618                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8619       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8620       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8621                                      DAG.getVTList(MVT::f64, MVT::Other),
8622                                      Ops, MVT::i32, MMO);
8623       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8624     } else if (Subtarget.hasFPCVT() &&
8625                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8626       MachineMemOperand *MMO =
8627         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8628                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8629       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8630       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8631                                      DAG.getVTList(MVT::f64, MVT::Other),
8632                                      Ops, MVT::i32, MMO);
8633       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8634     } else if (((Subtarget.hasLFIWAX() &&
8635                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8636                 (Subtarget.hasFPCVT() &&
8637                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8638                SINT.getOperand(0).getValueType() == MVT::i32) {
8639       MachineFrameInfo &MFI = MF.getFrameInfo();
8640       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8641 
8642       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8643       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8644 
8645       SDValue Store =
8646           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8647                        MachinePointerInfo::getFixedStack(
8648                            DAG.getMachineFunction(), FrameIdx));
8649 
8650       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8651              "Expected an i32 store");
8652 
8653       RLI.Ptr = FIdx;
8654       RLI.Chain = Store;
8655       RLI.MPI =
8656           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8657       RLI.Alignment = Align(4);
8658 
8659       MachineMemOperand *MMO =
8660         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8661                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8662       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8663       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8664                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8665                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8666                                      Ops, MVT::i32, MMO);
8667     } else
8668       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8669 
8670     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
8671 
8672     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8673       FP = DAG.getNode(ISD::FP_ROUND, dl,
8674                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8675     return FP;
8676   }
8677 
8678   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
8679          "Unhandled INT_TO_FP type in custom expander!");
8680   // Since we only generate this in 64-bit mode, we can take advantage of
8681   // 64-bit registers.  In particular, sign extend the input value into the
8682   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8683   // then lfd it and fcfid it.
8684   MachineFunction &MF = DAG.getMachineFunction();
8685   MachineFrameInfo &MFI = MF.getFrameInfo();
8686   EVT PtrVT = getPointerTy(MF.getDataLayout());
8687 
8688   SDValue Ld;
8689   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8690     ReuseLoadInfo RLI;
8691     bool ReusingLoad;
8692     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
8693                                             DAG))) {
8694       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8695       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8696 
8697       SDValue Store =
8698           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8699                        MachinePointerInfo::getFixedStack(
8700                            DAG.getMachineFunction(), FrameIdx));
8701 
8702       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8703              "Expected an i32 store");
8704 
8705       RLI.Ptr = FIdx;
8706       RLI.Chain = Store;
8707       RLI.MPI =
8708           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8709       RLI.Alignment = Align(4);
8710     }
8711 
8712     MachineMemOperand *MMO =
8713       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8714                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8715     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8716     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
8717                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
8718                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
8719                                  Ops, MVT::i32, MMO);
8720     if (ReusingLoad)
8721       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8722   } else {
8723     assert(Subtarget.isPPC64() &&
8724            "i32->FP without LFIWAX supported only on PPC64");
8725 
8726     int FrameIdx = MFI.CreateStackObject(8, 8, false);
8727     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8728 
8729     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
8730                                 Op.getOperand(0));
8731 
8732     // STD the extended value into the stack slot.
8733     SDValue Store = DAG.getStore(
8734         DAG.getEntryNode(), dl, Ext64, FIdx,
8735         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8736 
8737     // Load the value as a double.
8738     Ld = DAG.getLoad(
8739         MVT::f64, dl, Store, FIdx,
8740         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8741   }
8742 
8743   // FCFID it and return it.
8744   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
8745   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8746     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8747                      DAG.getIntPtrConstant(0, dl));
8748   return FP;
8749 }
8750 
8751 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8752                                             SelectionDAG &DAG) const {
8753   SDLoc dl(Op);
8754   /*
8755    The rounding mode is in bits 30:31 of FPSR, and has the following
8756    settings:
8757      00 Round to nearest
8758      01 Round to 0
8759      10 Round to +inf
8760      11 Round to -inf
8761 
8762   FLT_ROUNDS, on the other hand, expects the following:
8763     -1 Undefined
8764      0 Round to 0
8765      1 Round to nearest
8766      2 Round to +inf
8767      3 Round to -inf
8768 
8769   To perform the conversion, we do:
8770     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8771   */
8772 
8773   MachineFunction &MF = DAG.getMachineFunction();
8774   EVT VT = Op.getValueType();
8775   EVT PtrVT = getPointerTy(MF.getDataLayout());
8776 
8777   // Save FP Control Word to register
8778   SDValue Chain = Op.getOperand(0);
8779   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8780   Chain = MFFS.getValue(1);
8781 
8782   // Save FP register to stack slot
8783   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
8784   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8785   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8786 
8787   // Load FP Control Word from low 32 bits of stack slot.
8788   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8789   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8790   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8791   Chain = CWD.getValue(1);
8792 
8793   // Transform as necessary
8794   SDValue CWD1 =
8795     DAG.getNode(ISD::AND, dl, MVT::i32,
8796                 CWD, DAG.getConstant(3, dl, MVT::i32));
8797   SDValue CWD2 =
8798     DAG.getNode(ISD::SRL, dl, MVT::i32,
8799                 DAG.getNode(ISD::AND, dl, MVT::i32,
8800                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8801                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8802                             DAG.getConstant(3, dl, MVT::i32)),
8803                 DAG.getConstant(1, dl, MVT::i32));
8804 
8805   SDValue RetVal =
8806     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8807 
8808   RetVal =
8809       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8810                   dl, VT, RetVal);
8811 
8812   return DAG.getMergeValues({RetVal, Chain}, dl);
8813 }
8814 
8815 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8816   EVT VT = Op.getValueType();
8817   unsigned BitWidth = VT.getSizeInBits();
8818   SDLoc dl(Op);
8819   assert(Op.getNumOperands() == 3 &&
8820          VT == Op.getOperand(1).getValueType() &&
8821          "Unexpected SHL!");
8822 
8823   // Expand into a bunch of logical ops.  Note that these ops
8824   // depend on the PPC behavior for oversized shift amounts.
8825   SDValue Lo = Op.getOperand(0);
8826   SDValue Hi = Op.getOperand(1);
8827   SDValue Amt = Op.getOperand(2);
8828   EVT AmtVT = Amt.getValueType();
8829 
8830   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8831                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8832   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8833   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8834   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8835   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8836                              DAG.getConstant(-BitWidth, dl, AmtVT));
8837   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8838   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8839   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8840   SDValue OutOps[] = { OutLo, OutHi };
8841   return DAG.getMergeValues(OutOps, dl);
8842 }
8843 
8844 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8845   EVT VT = Op.getValueType();
8846   SDLoc dl(Op);
8847   unsigned BitWidth = VT.getSizeInBits();
8848   assert(Op.getNumOperands() == 3 &&
8849          VT == Op.getOperand(1).getValueType() &&
8850          "Unexpected SRL!");
8851 
8852   // Expand into a bunch of logical ops.  Note that these ops
8853   // depend on the PPC behavior for oversized shift amounts.
8854   SDValue Lo = Op.getOperand(0);
8855   SDValue Hi = Op.getOperand(1);
8856   SDValue Amt = Op.getOperand(2);
8857   EVT AmtVT = Amt.getValueType();
8858 
8859   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8860                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8861   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8862   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8863   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8864   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8865                              DAG.getConstant(-BitWidth, dl, AmtVT));
8866   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8867   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8868   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8869   SDValue OutOps[] = { OutLo, OutHi };
8870   return DAG.getMergeValues(OutOps, dl);
8871 }
8872 
8873 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8874   SDLoc dl(Op);
8875   EVT VT = Op.getValueType();
8876   unsigned BitWidth = VT.getSizeInBits();
8877   assert(Op.getNumOperands() == 3 &&
8878          VT == Op.getOperand(1).getValueType() &&
8879          "Unexpected SRA!");
8880 
8881   // Expand into a bunch of logical ops, followed by a select_cc.
8882   SDValue Lo = Op.getOperand(0);
8883   SDValue Hi = Op.getOperand(1);
8884   SDValue Amt = Op.getOperand(2);
8885   EVT AmtVT = Amt.getValueType();
8886 
8887   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8888                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8889   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8890   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8891   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8892   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8893                              DAG.getConstant(-BitWidth, dl, AmtVT));
8894   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8895   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8896   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8897                                   Tmp4, Tmp6, ISD::SETLE);
8898   SDValue OutOps[] = { OutLo, OutHi };
8899   return DAG.getMergeValues(OutOps, dl);
8900 }
8901 
8902 //===----------------------------------------------------------------------===//
8903 // Vector related lowering.
8904 //
8905 
8906 /// BuildSplatI - Build a canonical splati of Val with an element size of
8907 /// SplatSize.  Cast the result to VT.
8908 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8909                            SelectionDAG &DAG, const SDLoc &dl) {
8910   static const MVT VTys[] = { // canonical VT to use for each size.
8911     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8912   };
8913 
8914   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8915 
8916   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8917   if (Val == -1)
8918     SplatSize = 1;
8919 
8920   EVT CanonicalVT = VTys[SplatSize-1];
8921 
8922   // Build a canonical splat for this value.
8923   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8924 }
8925 
8926 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8927 /// specified intrinsic ID.
8928 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8929                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8930   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8931   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8932                      DAG.getConstant(IID, dl, MVT::i32), Op);
8933 }
8934 
8935 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8936 /// specified intrinsic ID.
8937 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8938                                 SelectionDAG &DAG, const SDLoc &dl,
8939                                 EVT DestVT = MVT::Other) {
8940   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8941   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8942                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8943 }
8944 
8945 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8946 /// specified intrinsic ID.
8947 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8948                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8949                                 EVT DestVT = MVT::Other) {
8950   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8951   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8952                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8953 }
8954 
8955 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8956 /// amount.  The result has the specified value type.
8957 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8958                            SelectionDAG &DAG, const SDLoc &dl) {
8959   // Force LHS/RHS to be the right type.
8960   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8961   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8962 
8963   int Ops[16];
8964   for (unsigned i = 0; i != 16; ++i)
8965     Ops[i] = i + Amt;
8966   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8967   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8968 }
8969 
8970 /// Do we have an efficient pattern in a .td file for this node?
8971 ///
8972 /// \param V - pointer to the BuildVectorSDNode being matched
8973 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8974 ///
8975 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8976 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8977 /// the opposite is true (expansion is beneficial) are:
8978 /// - The node builds a vector out of integers that are not 32 or 64-bits
8979 /// - The node builds a vector out of constants
8980 /// - The node is a "load-and-splat"
8981 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8982 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8983                                             bool HasDirectMove,
8984                                             bool HasP8Vector) {
8985   EVT VecVT = V->getValueType(0);
8986   bool RightType = VecVT == MVT::v2f64 ||
8987     (HasP8Vector && VecVT == MVT::v4f32) ||
8988     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8989   if (!RightType)
8990     return false;
8991 
8992   bool IsSplat = true;
8993   bool IsLoad = false;
8994   SDValue Op0 = V->getOperand(0);
8995 
8996   // This function is called in a block that confirms the node is not a constant
8997   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8998   // different constants.
8999   if (V->isConstant())
9000     return false;
9001   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9002     if (V->getOperand(i).isUndef())
9003       return false;
9004     // We want to expand nodes that represent load-and-splat even if the
9005     // loaded value is a floating point truncation or conversion to int.
9006     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9007         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9008          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9009         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9010          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9011         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9012          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9013       IsLoad = true;
9014     // If the operands are different or the input is not a load and has more
9015     // uses than just this BV node, then it isn't a splat.
9016     if (V->getOperand(i) != Op0 ||
9017         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9018       IsSplat = false;
9019   }
9020   return !(IsSplat && IsLoad);
9021 }
9022 
9023 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9024 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9025 
9026   SDLoc dl(Op);
9027   SDValue Op0 = Op->getOperand(0);
9028 
9029   if (!EnableQuadPrecision ||
9030       (Op.getValueType() != MVT::f128 ) ||
9031       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9032       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
9033       (Op0.getOperand(1).getValueType() != MVT::i64))
9034     return SDValue();
9035 
9036   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9037                      Op0.getOperand(1));
9038 }
9039 
9040 static const SDValue *getNormalLoadInput(const SDValue &Op) {
9041   const SDValue *InputLoad = &Op;
9042   if (InputLoad->getOpcode() == ISD::BITCAST)
9043     InputLoad = &InputLoad->getOperand(0);
9044   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR)
9045     InputLoad = &InputLoad->getOperand(0);
9046   if (InputLoad->getOpcode() != ISD::LOAD)
9047     return nullptr;
9048   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9049   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9050 }
9051 
9052 // If this is a case we can't handle, return null and let the default
9053 // expansion code take care of it.  If we CAN select this case, and if it
9054 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9055 // this case more efficiently than a constant pool load, lower it to the
9056 // sequence of ops that should be used.
9057 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9058                                              SelectionDAG &DAG) const {
9059   SDLoc dl(Op);
9060   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9061   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9062 
9063   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
9064     // We first build an i32 vector, load it into a QPX register,
9065     // then convert it to a floating-point vector and compare it
9066     // to a zero vector to get the boolean result.
9067     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9068     int FrameIdx = MFI.CreateStackObject(16, 16, false);
9069     MachinePointerInfo PtrInfo =
9070         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9071     EVT PtrVT = getPointerTy(DAG.getDataLayout());
9072     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9073 
9074     assert(BVN->getNumOperands() == 4 &&
9075       "BUILD_VECTOR for v4i1 does not have 4 operands");
9076 
9077     bool IsConst = true;
9078     for (unsigned i = 0; i < 4; ++i) {
9079       if (BVN->getOperand(i).isUndef()) continue;
9080       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
9081         IsConst = false;
9082         break;
9083       }
9084     }
9085 
9086     if (IsConst) {
9087       Constant *One =
9088         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
9089       Constant *NegOne =
9090         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
9091 
9092       Constant *CV[4];
9093       for (unsigned i = 0; i < 4; ++i) {
9094         if (BVN->getOperand(i).isUndef())
9095           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
9096         else if (isNullConstant(BVN->getOperand(i)))
9097           CV[i] = NegOne;
9098         else
9099           CV[i] = One;
9100       }
9101 
9102       Constant *CP = ConstantVector::get(CV);
9103       SDValue CPIdx =
9104           DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), Align(16));
9105 
9106       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
9107       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
9108       return DAG.getMemIntrinsicNode(
9109           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
9110           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
9111     }
9112 
9113     SmallVector<SDValue, 4> Stores;
9114     for (unsigned i = 0; i < 4; ++i) {
9115       if (BVN->getOperand(i).isUndef()) continue;
9116 
9117       unsigned Offset = 4*i;
9118       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9119       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9120 
9121       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
9122       if (StoreSize > 4) {
9123         Stores.push_back(
9124             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
9125                               PtrInfo.getWithOffset(Offset), MVT::i32));
9126       } else {
9127         SDValue StoreValue = BVN->getOperand(i);
9128         if (StoreSize < 4)
9129           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
9130 
9131         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
9132                                       PtrInfo.getWithOffset(Offset)));
9133       }
9134     }
9135 
9136     SDValue StoreChain;
9137     if (!Stores.empty())
9138       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9139     else
9140       StoreChain = DAG.getEntryNode();
9141 
9142     // Now load from v4i32 into the QPX register; this will extend it to
9143     // v4i64 but not yet convert it to a floating point. Nevertheless, this
9144     // is typed as v4f64 because the QPX register integer states are not
9145     // explicitly represented.
9146 
9147     SDValue Ops[] = {StoreChain,
9148                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
9149                      FIdx};
9150     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
9151 
9152     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
9153       dl, VTs, Ops, MVT::v4i32, PtrInfo);
9154     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9155       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
9156       LoadedVect);
9157 
9158     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
9159 
9160     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
9161   }
9162 
9163   // All other QPX vectors are handled by generic code.
9164   if (Subtarget.hasQPX())
9165     return SDValue();
9166 
9167   // Check if this is a splat of a constant value.
9168   APInt APSplatBits, APSplatUndef;
9169   unsigned SplatBitSize;
9170   bool HasAnyUndefs;
9171   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9172                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9173       SplatBitSize > 32) {
9174 
9175     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
9176     // Handle load-and-splat patterns as we have instructions that will do this
9177     // in one go.
9178     if (InputLoad && DAG.isSplatValue(Op, true)) {
9179       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9180 
9181       // We have handling for 4 and 8 byte elements.
9182       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9183 
9184       // Checking for a single use of this load, we have to check for vector
9185       // width (128 bits) / ElementSize uses (since each operand of the
9186       // BUILD_VECTOR is a separate use of the value.
9187       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
9188           ((Subtarget.hasVSX() && ElementSize == 64) ||
9189            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9190         SDValue Ops[] = {
9191           LD->getChain(),    // Chain
9192           LD->getBasePtr(),  // Ptr
9193           DAG.getValueType(Op.getValueType()) // VT
9194         };
9195         return
9196           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
9197                                   DAG.getVTList(Op.getValueType(), MVT::Other),
9198                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
9199       }
9200     }
9201 
9202     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
9203     // lowered to VSX instructions under certain conditions.
9204     // Without VSX, there is no pattern more efficient than expanding the node.
9205     if (Subtarget.hasVSX() &&
9206         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9207                                         Subtarget.hasP8Vector()))
9208       return Op;
9209     return SDValue();
9210   }
9211 
9212   unsigned SplatBits = APSplatBits.getZExtValue();
9213   unsigned SplatUndef = APSplatUndef.getZExtValue();
9214   unsigned SplatSize = SplatBitSize / 8;
9215 
9216   // First, handle single instruction cases.
9217 
9218   // All zeros?
9219   if (SplatBits == 0) {
9220     // Canonicalize all zero vectors to be v4i32.
9221     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9222       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9223       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9224     }
9225     return Op;
9226   }
9227 
9228   // We have XXSPLTIB for constant splats one byte wide
9229   // FIXME: SplatBits is an unsigned int being cast to an int while passing it
9230   // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here.
9231   if (Subtarget.hasP9Vector() && SplatSize == 1)
9232     return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl);
9233 
9234   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9235   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9236                     (32-SplatBitSize));
9237   if (SextVal >= -16 && SextVal <= 15)
9238     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
9239 
9240   // Two instruction sequences.
9241 
9242   // If this value is in the range [-32,30] and is even, use:
9243   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9244   // If this value is in the range [17,31] and is odd, use:
9245   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9246   // If this value is in the range [-31,-17] and is odd, use:
9247   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9248   // Note the last two are three-instruction sequences.
9249   if (SextVal >= -32 && SextVal <= 31) {
9250     // To avoid having these optimizations undone by constant folding,
9251     // we convert to a pseudo that will be expanded later into one of
9252     // the above forms.
9253     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9254     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9255               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9256     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9257     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9258     if (VT == Op.getValueType())
9259       return RetVal;
9260     else
9261       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9262   }
9263 
9264   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9265   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9266   // for fneg/fabs.
9267   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9268     // Make -1 and vspltisw -1:
9269     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
9270 
9271     // Make the VSLW intrinsic, computing 0x8000_0000.
9272     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9273                                    OnesV, DAG, dl);
9274 
9275     // xor by OnesV to invert it.
9276     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9277     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9278   }
9279 
9280   // Check to see if this is a wide variety of vsplti*, binop self cases.
9281   static const signed char SplatCsts[] = {
9282     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9283     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9284   };
9285 
9286   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9287     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9288     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9289     int i = SplatCsts[idx];
9290 
9291     // Figure out what shift amount will be used by altivec if shifted by i in
9292     // this splat size.
9293     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9294 
9295     // vsplti + shl self.
9296     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9297       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9298       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9299         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9300         Intrinsic::ppc_altivec_vslw
9301       };
9302       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9303       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9304     }
9305 
9306     // vsplti + srl self.
9307     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9308       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9309       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9310         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9311         Intrinsic::ppc_altivec_vsrw
9312       };
9313       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9314       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9315     }
9316 
9317     // vsplti + sra self.
9318     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9319       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9320       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9321         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9322         Intrinsic::ppc_altivec_vsraw
9323       };
9324       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9325       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9326     }
9327 
9328     // vsplti + rol self.
9329     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9330                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9331       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9332       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9333         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9334         Intrinsic::ppc_altivec_vrlw
9335       };
9336       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9337       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9338     }
9339 
9340     // t = vsplti c, result = vsldoi t, t, 1
9341     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9342       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9343       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9344       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9345     }
9346     // t = vsplti c, result = vsldoi t, t, 2
9347     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9348       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9349       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9350       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9351     }
9352     // t = vsplti c, result = vsldoi t, t, 3
9353     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9354       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9355       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9356       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9357     }
9358   }
9359 
9360   return SDValue();
9361 }
9362 
9363 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9364 /// the specified operations to build the shuffle.
9365 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9366                                       SDValue RHS, SelectionDAG &DAG,
9367                                       const SDLoc &dl) {
9368   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9369   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9370   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9371 
9372   enum {
9373     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9374     OP_VMRGHW,
9375     OP_VMRGLW,
9376     OP_VSPLTISW0,
9377     OP_VSPLTISW1,
9378     OP_VSPLTISW2,
9379     OP_VSPLTISW3,
9380     OP_VSLDOI4,
9381     OP_VSLDOI8,
9382     OP_VSLDOI12
9383   };
9384 
9385   if (OpNum == OP_COPY) {
9386     if (LHSID == (1*9+2)*9+3) return LHS;
9387     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9388     return RHS;
9389   }
9390 
9391   SDValue OpLHS, OpRHS;
9392   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9393   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9394 
9395   int ShufIdxs[16];
9396   switch (OpNum) {
9397   default: llvm_unreachable("Unknown i32 permute!");
9398   case OP_VMRGHW:
9399     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9400     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9401     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9402     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9403     break;
9404   case OP_VMRGLW:
9405     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9406     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9407     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9408     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9409     break;
9410   case OP_VSPLTISW0:
9411     for (unsigned i = 0; i != 16; ++i)
9412       ShufIdxs[i] = (i&3)+0;
9413     break;
9414   case OP_VSPLTISW1:
9415     for (unsigned i = 0; i != 16; ++i)
9416       ShufIdxs[i] = (i&3)+4;
9417     break;
9418   case OP_VSPLTISW2:
9419     for (unsigned i = 0; i != 16; ++i)
9420       ShufIdxs[i] = (i&3)+8;
9421     break;
9422   case OP_VSPLTISW3:
9423     for (unsigned i = 0; i != 16; ++i)
9424       ShufIdxs[i] = (i&3)+12;
9425     break;
9426   case OP_VSLDOI4:
9427     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9428   case OP_VSLDOI8:
9429     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9430   case OP_VSLDOI12:
9431     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9432   }
9433   EVT VT = OpLHS.getValueType();
9434   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9435   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9436   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9437   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9438 }
9439 
9440 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9441 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9442 /// SDValue.
9443 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9444                                            SelectionDAG &DAG) const {
9445   const unsigned BytesInVector = 16;
9446   bool IsLE = Subtarget.isLittleEndian();
9447   SDLoc dl(N);
9448   SDValue V1 = N->getOperand(0);
9449   SDValue V2 = N->getOperand(1);
9450   unsigned ShiftElts = 0, InsertAtByte = 0;
9451   bool Swap = false;
9452 
9453   // Shifts required to get the byte we want at element 7.
9454   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9455                                    0, 15, 14, 13, 12, 11, 10, 9};
9456   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9457                                 1, 2,  3,  4,  5,  6,  7,  8};
9458 
9459   ArrayRef<int> Mask = N->getMask();
9460   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9461 
9462   // For each mask element, find out if we're just inserting something
9463   // from V2 into V1 or vice versa.
9464   // Possible permutations inserting an element from V2 into V1:
9465   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9466   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9467   //   ...
9468   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9469   // Inserting from V1 into V2 will be similar, except mask range will be
9470   // [16,31].
9471 
9472   bool FoundCandidate = false;
9473   // If both vector operands for the shuffle are the same vector, the mask
9474   // will contain only elements from the first one and the second one will be
9475   // undef.
9476   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9477   // Go through the mask of half-words to find an element that's being moved
9478   // from one vector to the other.
9479   for (unsigned i = 0; i < BytesInVector; ++i) {
9480     unsigned CurrentElement = Mask[i];
9481     // If 2nd operand is undefined, we should only look for element 7 in the
9482     // Mask.
9483     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9484       continue;
9485 
9486     bool OtherElementsInOrder = true;
9487     // Examine the other elements in the Mask to see if they're in original
9488     // order.
9489     for (unsigned j = 0; j < BytesInVector; ++j) {
9490       if (j == i)
9491         continue;
9492       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9493       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9494       // in which we always assume we're always picking from the 1st operand.
9495       int MaskOffset =
9496           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9497       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9498         OtherElementsInOrder = false;
9499         break;
9500       }
9501     }
9502     // If other elements are in original order, we record the number of shifts
9503     // we need to get the element we want into element 7. Also record which byte
9504     // in the vector we should insert into.
9505     if (OtherElementsInOrder) {
9506       // If 2nd operand is undefined, we assume no shifts and no swapping.
9507       if (V2.isUndef()) {
9508         ShiftElts = 0;
9509         Swap = false;
9510       } else {
9511         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9512         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9513                          : BigEndianShifts[CurrentElement & 0xF];
9514         Swap = CurrentElement < BytesInVector;
9515       }
9516       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9517       FoundCandidate = true;
9518       break;
9519     }
9520   }
9521 
9522   if (!FoundCandidate)
9523     return SDValue();
9524 
9525   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9526   // optionally with VECSHL if shift is required.
9527   if (Swap)
9528     std::swap(V1, V2);
9529   if (V2.isUndef())
9530     V2 = V1;
9531   if (ShiftElts) {
9532     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9533                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9534     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9535                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9536   }
9537   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9538                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9539 }
9540 
9541 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9542 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9543 /// SDValue.
9544 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9545                                            SelectionDAG &DAG) const {
9546   const unsigned NumHalfWords = 8;
9547   const unsigned BytesInVector = NumHalfWords * 2;
9548   // Check that the shuffle is on half-words.
9549   if (!isNByteElemShuffleMask(N, 2, 1))
9550     return SDValue();
9551 
9552   bool IsLE = Subtarget.isLittleEndian();
9553   SDLoc dl(N);
9554   SDValue V1 = N->getOperand(0);
9555   SDValue V2 = N->getOperand(1);
9556   unsigned ShiftElts = 0, InsertAtByte = 0;
9557   bool Swap = false;
9558 
9559   // Shifts required to get the half-word we want at element 3.
9560   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9561   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9562 
9563   uint32_t Mask = 0;
9564   uint32_t OriginalOrderLow = 0x1234567;
9565   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9566   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9567   // 32-bit space, only need 4-bit nibbles per element.
9568   for (unsigned i = 0; i < NumHalfWords; ++i) {
9569     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9570     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9571   }
9572 
9573   // For each mask element, find out if we're just inserting something
9574   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9575   // from V2 into V1:
9576   //   X, 1, 2, 3, 4, 5, 6, 7
9577   //   0, X, 2, 3, 4, 5, 6, 7
9578   //   0, 1, X, 3, 4, 5, 6, 7
9579   //   0, 1, 2, X, 4, 5, 6, 7
9580   //   0, 1, 2, 3, X, 5, 6, 7
9581   //   0, 1, 2, 3, 4, X, 6, 7
9582   //   0, 1, 2, 3, 4, 5, X, 7
9583   //   0, 1, 2, 3, 4, 5, 6, X
9584   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9585 
9586   bool FoundCandidate = false;
9587   // Go through the mask of half-words to find an element that's being moved
9588   // from one vector to the other.
9589   for (unsigned i = 0; i < NumHalfWords; ++i) {
9590     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9591     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9592     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9593     uint32_t TargetOrder = 0x0;
9594 
9595     // If both vector operands for the shuffle are the same vector, the mask
9596     // will contain only elements from the first one and the second one will be
9597     // undef.
9598     if (V2.isUndef()) {
9599       ShiftElts = 0;
9600       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9601       TargetOrder = OriginalOrderLow;
9602       Swap = false;
9603       // Skip if not the correct element or mask of other elements don't equal
9604       // to our expected order.
9605       if (MaskOneElt == VINSERTHSrcElem &&
9606           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9607         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9608         FoundCandidate = true;
9609         break;
9610       }
9611     } else { // If both operands are defined.
9612       // Target order is [8,15] if the current mask is between [0,7].
9613       TargetOrder =
9614           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9615       // Skip if mask of other elements don't equal our expected order.
9616       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9617         // We only need the last 3 bits for the number of shifts.
9618         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9619                          : BigEndianShifts[MaskOneElt & 0x7];
9620         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9621         Swap = MaskOneElt < NumHalfWords;
9622         FoundCandidate = true;
9623         break;
9624       }
9625     }
9626   }
9627 
9628   if (!FoundCandidate)
9629     return SDValue();
9630 
9631   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9632   // optionally with VECSHL if shift is required.
9633   if (Swap)
9634     std::swap(V1, V2);
9635   if (V2.isUndef())
9636     V2 = V1;
9637   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9638   if (ShiftElts) {
9639     // Double ShiftElts because we're left shifting on v16i8 type.
9640     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9641                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9642     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9643     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9644                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9645     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9646   }
9647   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9648   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9649                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9650   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9651 }
9652 
9653 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9654 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9655 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9656 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9657 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9658   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9659   assert(Op.getValueType() == MVT::v1i128 &&
9660          "Only set v1i128 as custom, other type shouldn't reach here!");
9661   SDLoc dl(Op);
9662   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9663   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9664   unsigned SHLAmt = N1.getConstantOperandVal(0);
9665   if (SHLAmt % 8 == 0) {
9666     SmallVector<int, 16> Mask(16, 0);
9667     std::iota(Mask.begin(), Mask.end(), 0);
9668     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9669     if (SDValue Shuffle =
9670             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9671                                  DAG.getUNDEF(MVT::v16i8), Mask))
9672       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9673   }
9674   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9675   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9676                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9677   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9678                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9679   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9680   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9681 }
9682 
9683 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9684 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9685 /// return the code it can be lowered into.  Worst case, it can always be
9686 /// lowered into a vperm.
9687 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9688                                                SelectionDAG &DAG) const {
9689   SDLoc dl(Op);
9690   SDValue V1 = Op.getOperand(0);
9691   SDValue V2 = Op.getOperand(1);
9692   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9693   EVT VT = Op.getValueType();
9694   bool isLittleEndian = Subtarget.isLittleEndian();
9695 
9696   unsigned ShiftElts, InsertAtByte;
9697   bool Swap = false;
9698 
9699   // If this is a load-and-splat, we can do that with a single instruction
9700   // in some cases. However if the load has multiple uses, we don't want to
9701   // combine it because that will just produce multiple loads.
9702   const SDValue *InputLoad = getNormalLoadInput(V1);
9703   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9704       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9705       InputLoad->hasOneUse()) {
9706     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9707     int SplatIdx =
9708       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9709 
9710     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9711     // For 4-byte load-and-splat, we need Power9.
9712     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9713       uint64_t Offset = 0;
9714       if (IsFourByte)
9715         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9716       else
9717         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9718       SDValue BasePtr = LD->getBasePtr();
9719       if (Offset != 0)
9720         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9721                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9722       SDValue Ops[] = {
9723         LD->getChain(),    // Chain
9724         BasePtr,           // BasePtr
9725         DAG.getValueType(Op.getValueType()) // VT
9726       };
9727       SDVTList VTL =
9728         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9729       SDValue LdSplt =
9730         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9731                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9732       if (LdSplt.getValueType() != SVOp->getValueType(0))
9733         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9734       return LdSplt;
9735     }
9736   }
9737   if (Subtarget.hasP9Vector() &&
9738       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9739                            isLittleEndian)) {
9740     if (Swap)
9741       std::swap(V1, V2);
9742     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9743     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9744     if (ShiftElts) {
9745       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9746                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9747       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9748                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9749       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9750     }
9751     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9752                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9753     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9754   }
9755 
9756   if (Subtarget.hasP9Altivec()) {
9757     SDValue NewISDNode;
9758     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9759       return NewISDNode;
9760 
9761     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9762       return NewISDNode;
9763   }
9764 
9765   if (Subtarget.hasVSX() &&
9766       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9767     if (Swap)
9768       std::swap(V1, V2);
9769     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9770     SDValue Conv2 =
9771         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9772 
9773     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9774                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9775     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9776   }
9777 
9778   if (Subtarget.hasVSX() &&
9779     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9780     if (Swap)
9781       std::swap(V1, V2);
9782     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9783     SDValue Conv2 =
9784         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9785 
9786     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9787                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9788     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9789   }
9790 
9791   if (Subtarget.hasP9Vector()) {
9792      if (PPC::isXXBRHShuffleMask(SVOp)) {
9793       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9794       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9795       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9796     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9797       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9798       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9799       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9800     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9801       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9802       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9803       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9804     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9805       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9806       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9807       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9808     }
9809   }
9810 
9811   if (Subtarget.hasVSX()) {
9812     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9813       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9814 
9815       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9816       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9817                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9818       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9819     }
9820 
9821     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9822     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9823       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9824       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9825       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9826     }
9827   }
9828 
9829   if (Subtarget.hasQPX()) {
9830     if (VT.getVectorNumElements() != 4)
9831       return SDValue();
9832 
9833     if (V2.isUndef()) V2 = V1;
9834 
9835     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
9836     if (AlignIdx != -1) {
9837       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
9838                          DAG.getConstant(AlignIdx, dl, MVT::i32));
9839     } else if (SVOp->isSplat()) {
9840       int SplatIdx = SVOp->getSplatIndex();
9841       if (SplatIdx >= 4) {
9842         std::swap(V1, V2);
9843         SplatIdx -= 4;
9844       }
9845 
9846       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
9847                          DAG.getConstant(SplatIdx, dl, MVT::i32));
9848     }
9849 
9850     // Lower this into a qvgpci/qvfperm pair.
9851 
9852     // Compute the qvgpci literal
9853     unsigned idx = 0;
9854     for (unsigned i = 0; i < 4; ++i) {
9855       int m = SVOp->getMaskElt(i);
9856       unsigned mm = m >= 0 ? (unsigned) m : i;
9857       idx |= mm << (3-i)*3;
9858     }
9859 
9860     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
9861                              DAG.getConstant(idx, dl, MVT::i32));
9862     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
9863   }
9864 
9865   // Cases that are handled by instructions that take permute immediates
9866   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9867   // selected by the instruction selector.
9868   if (V2.isUndef()) {
9869     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9870         PPC::isSplatShuffleMask(SVOp, 2) ||
9871         PPC::isSplatShuffleMask(SVOp, 4) ||
9872         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9873         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9874         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9875         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9876         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9877         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9878         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9879         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9880         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9881         (Subtarget.hasP8Altivec() && (
9882          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9883          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9884          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9885       return Op;
9886     }
9887   }
9888 
9889   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9890   // and produce a fixed permutation.  If any of these match, do not lower to
9891   // VPERM.
9892   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9893   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9894       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9895       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9896       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9897       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9898       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9899       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9900       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9901       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9902       (Subtarget.hasP8Altivec() && (
9903        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9904        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9905        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9906     return Op;
9907 
9908   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9909   // perfect shuffle table to emit an optimal matching sequence.
9910   ArrayRef<int> PermMask = SVOp->getMask();
9911 
9912   unsigned PFIndexes[4];
9913   bool isFourElementShuffle = true;
9914   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9915     unsigned EltNo = 8;   // Start out undef.
9916     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9917       if (PermMask[i*4+j] < 0)
9918         continue;   // Undef, ignore it.
9919 
9920       unsigned ByteSource = PermMask[i*4+j];
9921       if ((ByteSource & 3) != j) {
9922         isFourElementShuffle = false;
9923         break;
9924       }
9925 
9926       if (EltNo == 8) {
9927         EltNo = ByteSource/4;
9928       } else if (EltNo != ByteSource/4) {
9929         isFourElementShuffle = false;
9930         break;
9931       }
9932     }
9933     PFIndexes[i] = EltNo;
9934   }
9935 
9936   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9937   // perfect shuffle vector to determine if it is cost effective to do this as
9938   // discrete instructions, or whether we should use a vperm.
9939   // For now, we skip this for little endian until such time as we have a
9940   // little-endian perfect shuffle table.
9941   if (isFourElementShuffle && !isLittleEndian) {
9942     // Compute the index in the perfect shuffle table.
9943     unsigned PFTableIndex =
9944       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9945 
9946     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9947     unsigned Cost  = (PFEntry >> 30);
9948 
9949     // Determining when to avoid vperm is tricky.  Many things affect the cost
9950     // of vperm, particularly how many times the perm mask needs to be computed.
9951     // For example, if the perm mask can be hoisted out of a loop or is already
9952     // used (perhaps because there are multiple permutes with the same shuffle
9953     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9954     // the loop requires an extra register.
9955     //
9956     // As a compromise, we only emit discrete instructions if the shuffle can be
9957     // generated in 3 or fewer operations.  When we have loop information
9958     // available, if this block is within a loop, we should avoid using vperm
9959     // for 3-operation perms and use a constant pool load instead.
9960     if (Cost < 3)
9961       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9962   }
9963 
9964   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9965   // vector that will get spilled to the constant pool.
9966   if (V2.isUndef()) V2 = V1;
9967 
9968   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9969   // that it is in input element units, not in bytes.  Convert now.
9970 
9971   // For little endian, the order of the input vectors is reversed, and
9972   // the permutation mask is complemented with respect to 31.  This is
9973   // necessary to produce proper semantics with the big-endian-biased vperm
9974   // instruction.
9975   EVT EltVT = V1.getValueType().getVectorElementType();
9976   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9977 
9978   SmallVector<SDValue, 16> ResultMask;
9979   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9980     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9981 
9982     for (unsigned j = 0; j != BytesPerElement; ++j)
9983       if (isLittleEndian)
9984         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9985                                              dl, MVT::i32));
9986       else
9987         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9988                                              MVT::i32));
9989   }
9990 
9991   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9992   if (isLittleEndian)
9993     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9994                        V2, V1, VPermMask);
9995   else
9996     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9997                        V1, V2, VPermMask);
9998 }
9999 
10000 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10001 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10002 /// information about the intrinsic.
10003 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10004                                  bool &isDot, const PPCSubtarget &Subtarget) {
10005   unsigned IntrinsicID =
10006       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10007   CompareOpc = -1;
10008   isDot = false;
10009   switch (IntrinsicID) {
10010   default:
10011     return false;
10012   // Comparison predicates.
10013   case Intrinsic::ppc_altivec_vcmpbfp_p:
10014     CompareOpc = 966;
10015     isDot = true;
10016     break;
10017   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10018     CompareOpc = 198;
10019     isDot = true;
10020     break;
10021   case Intrinsic::ppc_altivec_vcmpequb_p:
10022     CompareOpc = 6;
10023     isDot = true;
10024     break;
10025   case Intrinsic::ppc_altivec_vcmpequh_p:
10026     CompareOpc = 70;
10027     isDot = true;
10028     break;
10029   case Intrinsic::ppc_altivec_vcmpequw_p:
10030     CompareOpc = 134;
10031     isDot = true;
10032     break;
10033   case Intrinsic::ppc_altivec_vcmpequd_p:
10034     if (Subtarget.hasP8Altivec()) {
10035       CompareOpc = 199;
10036       isDot = true;
10037     } else
10038       return false;
10039     break;
10040   case Intrinsic::ppc_altivec_vcmpneb_p:
10041   case Intrinsic::ppc_altivec_vcmpneh_p:
10042   case Intrinsic::ppc_altivec_vcmpnew_p:
10043   case Intrinsic::ppc_altivec_vcmpnezb_p:
10044   case Intrinsic::ppc_altivec_vcmpnezh_p:
10045   case Intrinsic::ppc_altivec_vcmpnezw_p:
10046     if (Subtarget.hasP9Altivec()) {
10047       switch (IntrinsicID) {
10048       default:
10049         llvm_unreachable("Unknown comparison intrinsic.");
10050       case Intrinsic::ppc_altivec_vcmpneb_p:
10051         CompareOpc = 7;
10052         break;
10053       case Intrinsic::ppc_altivec_vcmpneh_p:
10054         CompareOpc = 71;
10055         break;
10056       case Intrinsic::ppc_altivec_vcmpnew_p:
10057         CompareOpc = 135;
10058         break;
10059       case Intrinsic::ppc_altivec_vcmpnezb_p:
10060         CompareOpc = 263;
10061         break;
10062       case Intrinsic::ppc_altivec_vcmpnezh_p:
10063         CompareOpc = 327;
10064         break;
10065       case Intrinsic::ppc_altivec_vcmpnezw_p:
10066         CompareOpc = 391;
10067         break;
10068       }
10069       isDot = true;
10070     } else
10071       return false;
10072     break;
10073   case Intrinsic::ppc_altivec_vcmpgefp_p:
10074     CompareOpc = 454;
10075     isDot = true;
10076     break;
10077   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10078     CompareOpc = 710;
10079     isDot = true;
10080     break;
10081   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10082     CompareOpc = 774;
10083     isDot = true;
10084     break;
10085   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10086     CompareOpc = 838;
10087     isDot = true;
10088     break;
10089   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10090     CompareOpc = 902;
10091     isDot = true;
10092     break;
10093   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10094     if (Subtarget.hasP8Altivec()) {
10095       CompareOpc = 967;
10096       isDot = true;
10097     } else
10098       return false;
10099     break;
10100   case Intrinsic::ppc_altivec_vcmpgtub_p:
10101     CompareOpc = 518;
10102     isDot = true;
10103     break;
10104   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10105     CompareOpc = 582;
10106     isDot = true;
10107     break;
10108   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10109     CompareOpc = 646;
10110     isDot = true;
10111     break;
10112   case Intrinsic::ppc_altivec_vcmpgtud_p:
10113     if (Subtarget.hasP8Altivec()) {
10114       CompareOpc = 711;
10115       isDot = true;
10116     } else
10117       return false;
10118     break;
10119 
10120   // VSX predicate comparisons use the same infrastructure
10121   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10122   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10123   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10124   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10125   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10126   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10127     if (Subtarget.hasVSX()) {
10128       switch (IntrinsicID) {
10129       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10130         CompareOpc = 99;
10131         break;
10132       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10133         CompareOpc = 115;
10134         break;
10135       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10136         CompareOpc = 107;
10137         break;
10138       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10139         CompareOpc = 67;
10140         break;
10141       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10142         CompareOpc = 83;
10143         break;
10144       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10145         CompareOpc = 75;
10146         break;
10147       }
10148       isDot = true;
10149     } else
10150       return false;
10151     break;
10152 
10153   // Normal Comparisons.
10154   case Intrinsic::ppc_altivec_vcmpbfp:
10155     CompareOpc = 966;
10156     break;
10157   case Intrinsic::ppc_altivec_vcmpeqfp:
10158     CompareOpc = 198;
10159     break;
10160   case Intrinsic::ppc_altivec_vcmpequb:
10161     CompareOpc = 6;
10162     break;
10163   case Intrinsic::ppc_altivec_vcmpequh:
10164     CompareOpc = 70;
10165     break;
10166   case Intrinsic::ppc_altivec_vcmpequw:
10167     CompareOpc = 134;
10168     break;
10169   case Intrinsic::ppc_altivec_vcmpequd:
10170     if (Subtarget.hasP8Altivec())
10171       CompareOpc = 199;
10172     else
10173       return false;
10174     break;
10175   case Intrinsic::ppc_altivec_vcmpneb:
10176   case Intrinsic::ppc_altivec_vcmpneh:
10177   case Intrinsic::ppc_altivec_vcmpnew:
10178   case Intrinsic::ppc_altivec_vcmpnezb:
10179   case Intrinsic::ppc_altivec_vcmpnezh:
10180   case Intrinsic::ppc_altivec_vcmpnezw:
10181     if (Subtarget.hasP9Altivec())
10182       switch (IntrinsicID) {
10183       default:
10184         llvm_unreachable("Unknown comparison intrinsic.");
10185       case Intrinsic::ppc_altivec_vcmpneb:
10186         CompareOpc = 7;
10187         break;
10188       case Intrinsic::ppc_altivec_vcmpneh:
10189         CompareOpc = 71;
10190         break;
10191       case Intrinsic::ppc_altivec_vcmpnew:
10192         CompareOpc = 135;
10193         break;
10194       case Intrinsic::ppc_altivec_vcmpnezb:
10195         CompareOpc = 263;
10196         break;
10197       case Intrinsic::ppc_altivec_vcmpnezh:
10198         CompareOpc = 327;
10199         break;
10200       case Intrinsic::ppc_altivec_vcmpnezw:
10201         CompareOpc = 391;
10202         break;
10203       }
10204     else
10205       return false;
10206     break;
10207   case Intrinsic::ppc_altivec_vcmpgefp:
10208     CompareOpc = 454;
10209     break;
10210   case Intrinsic::ppc_altivec_vcmpgtfp:
10211     CompareOpc = 710;
10212     break;
10213   case Intrinsic::ppc_altivec_vcmpgtsb:
10214     CompareOpc = 774;
10215     break;
10216   case Intrinsic::ppc_altivec_vcmpgtsh:
10217     CompareOpc = 838;
10218     break;
10219   case Intrinsic::ppc_altivec_vcmpgtsw:
10220     CompareOpc = 902;
10221     break;
10222   case Intrinsic::ppc_altivec_vcmpgtsd:
10223     if (Subtarget.hasP8Altivec())
10224       CompareOpc = 967;
10225     else
10226       return false;
10227     break;
10228   case Intrinsic::ppc_altivec_vcmpgtub:
10229     CompareOpc = 518;
10230     break;
10231   case Intrinsic::ppc_altivec_vcmpgtuh:
10232     CompareOpc = 582;
10233     break;
10234   case Intrinsic::ppc_altivec_vcmpgtuw:
10235     CompareOpc = 646;
10236     break;
10237   case Intrinsic::ppc_altivec_vcmpgtud:
10238     if (Subtarget.hasP8Altivec())
10239       CompareOpc = 711;
10240     else
10241       return false;
10242     break;
10243   }
10244   return true;
10245 }
10246 
10247 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10248 /// lower, do it, otherwise return null.
10249 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10250                                                    SelectionDAG &DAG) const {
10251   unsigned IntrinsicID =
10252     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10253 
10254   SDLoc dl(Op);
10255 
10256   if (IntrinsicID == Intrinsic::thread_pointer) {
10257     // Reads the thread pointer register, used for __builtin_thread_pointer.
10258     if (Subtarget.isPPC64())
10259       return DAG.getRegister(PPC::X13, MVT::i64);
10260     return DAG.getRegister(PPC::R2, MVT::i32);
10261   }
10262 
10263   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10264   // opcode number of the comparison.
10265   int CompareOpc;
10266   bool isDot;
10267   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10268     return SDValue();    // Don't custom lower most intrinsics.
10269 
10270   // If this is a non-dot comparison, make the VCMP node and we are done.
10271   if (!isDot) {
10272     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10273                               Op.getOperand(1), Op.getOperand(2),
10274                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10275     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10276   }
10277 
10278   // Create the PPCISD altivec 'dot' comparison node.
10279   SDValue Ops[] = {
10280     Op.getOperand(2),  // LHS
10281     Op.getOperand(3),  // RHS
10282     DAG.getConstant(CompareOpc, dl, MVT::i32)
10283   };
10284   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10285   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10286 
10287   // Now that we have the comparison, emit a copy from the CR to a GPR.
10288   // This is flagged to the above dot comparison.
10289   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10290                                 DAG.getRegister(PPC::CR6, MVT::i32),
10291                                 CompNode.getValue(1));
10292 
10293   // Unpack the result based on how the target uses it.
10294   unsigned BitNo;   // Bit # of CR6.
10295   bool InvertBit;   // Invert result?
10296   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10297   default:  // Can't happen, don't crash on invalid number though.
10298   case 0:   // Return the value of the EQ bit of CR6.
10299     BitNo = 0; InvertBit = false;
10300     break;
10301   case 1:   // Return the inverted value of the EQ bit of CR6.
10302     BitNo = 0; InvertBit = true;
10303     break;
10304   case 2:   // Return the value of the LT bit of CR6.
10305     BitNo = 2; InvertBit = false;
10306     break;
10307   case 3:   // Return the inverted value of the LT bit of CR6.
10308     BitNo = 2; InvertBit = true;
10309     break;
10310   }
10311 
10312   // Shift the bit into the low position.
10313   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10314                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10315   // Isolate the bit.
10316   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10317                       DAG.getConstant(1, dl, MVT::i32));
10318 
10319   // If we are supposed to, toggle the bit.
10320   if (InvertBit)
10321     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10322                         DAG.getConstant(1, dl, MVT::i32));
10323   return Flags;
10324 }
10325 
10326 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10327                                                SelectionDAG &DAG) const {
10328   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10329   // the beginning of the argument list.
10330   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10331   SDLoc DL(Op);
10332   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10333   case Intrinsic::ppc_cfence: {
10334     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10335     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10336     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10337                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10338                                                   Op.getOperand(ArgStart + 1)),
10339                                       Op.getOperand(0)),
10340                    0);
10341   }
10342   default:
10343     break;
10344   }
10345   return SDValue();
10346 }
10347 
10348 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
10349   // Check for a DIV with the same operands as this REM.
10350   for (auto UI : Op.getOperand(1)->uses()) {
10351     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
10352         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
10353       if (UI->getOperand(0) == Op.getOperand(0) &&
10354           UI->getOperand(1) == Op.getOperand(1))
10355         return SDValue();
10356   }
10357   return Op;
10358 }
10359 
10360 // Lower scalar BSWAP64 to xxbrd.
10361 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10362   SDLoc dl(Op);
10363   // MTVSRDD
10364   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10365                    Op.getOperand(0));
10366   // XXBRD
10367   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10368   // MFVSRD
10369   int VectorIndex = 0;
10370   if (Subtarget.isLittleEndian())
10371     VectorIndex = 1;
10372   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10373                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10374   return Op;
10375 }
10376 
10377 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10378 // compared to a value that is atomically loaded (atomic loads zero-extend).
10379 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10380                                                 SelectionDAG &DAG) const {
10381   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10382          "Expecting an atomic compare-and-swap here.");
10383   SDLoc dl(Op);
10384   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10385   EVT MemVT = AtomicNode->getMemoryVT();
10386   if (MemVT.getSizeInBits() >= 32)
10387     return Op;
10388 
10389   SDValue CmpOp = Op.getOperand(2);
10390   // If this is already correctly zero-extended, leave it alone.
10391   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10392   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10393     return Op;
10394 
10395   // Clear the high bits of the compare operand.
10396   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10397   SDValue NewCmpOp =
10398     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10399                 DAG.getConstant(MaskVal, dl, MVT::i32));
10400 
10401   // Replace the existing compare operand with the properly zero-extended one.
10402   SmallVector<SDValue, 4> Ops;
10403   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10404     Ops.push_back(AtomicNode->getOperand(i));
10405   Ops[2] = NewCmpOp;
10406   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10407   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10408   auto NodeTy =
10409     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10410   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10411 }
10412 
10413 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10414                                                  SelectionDAG &DAG) const {
10415   SDLoc dl(Op);
10416   // Create a stack slot that is 16-byte aligned.
10417   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10418   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10419   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10420   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10421 
10422   // Store the input value into Value#0 of the stack slot.
10423   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10424                                MachinePointerInfo());
10425   // Load it out.
10426   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10427 }
10428 
10429 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10430                                                   SelectionDAG &DAG) const {
10431   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10432          "Should only be called for ISD::INSERT_VECTOR_ELT");
10433 
10434   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10435   // We have legal lowering for constant indices but not for variable ones.
10436   if (!C)
10437     return SDValue();
10438 
10439   EVT VT = Op.getValueType();
10440   SDLoc dl(Op);
10441   SDValue V1 = Op.getOperand(0);
10442   SDValue V2 = Op.getOperand(1);
10443   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10444   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10445     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10446     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10447     unsigned InsertAtElement = C->getZExtValue();
10448     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10449     if (Subtarget.isLittleEndian()) {
10450       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10451     }
10452     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10453                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10454   }
10455   return Op;
10456 }
10457 
10458 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10459                                                    SelectionDAG &DAG) const {
10460   SDLoc dl(Op);
10461   SDNode *N = Op.getNode();
10462 
10463   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
10464          "Unknown extract_vector_elt type");
10465 
10466   SDValue Value = N->getOperand(0);
10467 
10468   // The first part of this is like the store lowering except that we don't
10469   // need to track the chain.
10470 
10471   // The values are now known to be -1 (false) or 1 (true). To convert this
10472   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10473   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10474   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10475 
10476   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10477   // understand how to form the extending load.
10478   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10479 
10480   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10481 
10482   // Now convert to an integer and store.
10483   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10484     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10485     Value);
10486 
10487   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10488   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10489   MachinePointerInfo PtrInfo =
10490       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10491   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10492   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10493 
10494   SDValue StoreChain = DAG.getEntryNode();
10495   SDValue Ops[] = {StoreChain,
10496                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10497                    Value, FIdx};
10498   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10499 
10500   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10501     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10502 
10503   // Extract the value requested.
10504   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10505   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10506   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10507 
10508   SDValue IntVal =
10509       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
10510 
10511   if (!Subtarget.useCRBits())
10512     return IntVal;
10513 
10514   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
10515 }
10516 
10517 /// Lowering for QPX v4i1 loads
10518 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10519                                            SelectionDAG &DAG) const {
10520   SDLoc dl(Op);
10521   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10522   SDValue LoadChain = LN->getChain();
10523   SDValue BasePtr = LN->getBasePtr();
10524 
10525   if (Op.getValueType() == MVT::v4f64 ||
10526       Op.getValueType() == MVT::v4f32) {
10527     EVT MemVT = LN->getMemoryVT();
10528     unsigned Alignment = LN->getAlignment();
10529 
10530     // If this load is properly aligned, then it is legal.
10531     if (Alignment >= MemVT.getStoreSize())
10532       return Op;
10533 
10534     EVT ScalarVT = Op.getValueType().getScalarType(),
10535         ScalarMemVT = MemVT.getScalarType();
10536     unsigned Stride = ScalarMemVT.getStoreSize();
10537 
10538     SDValue Vals[4], LoadChains[4];
10539     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10540       SDValue Load;
10541       if (ScalarVT != ScalarMemVT)
10542         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
10543                               BasePtr,
10544                               LN->getPointerInfo().getWithOffset(Idx * Stride),
10545                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10546                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
10547       else
10548         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
10549                            LN->getPointerInfo().getWithOffset(Idx * Stride),
10550                            MinAlign(Alignment, Idx * Stride),
10551                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
10552 
10553       if (Idx == 0 && LN->isIndexed()) {
10554         assert(LN->getAddressingMode() == ISD::PRE_INC &&
10555                "Unknown addressing mode on vector load");
10556         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
10557                                   LN->getAddressingMode());
10558       }
10559 
10560       Vals[Idx] = Load;
10561       LoadChains[Idx] = Load.getValue(1);
10562 
10563       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10564                             DAG.getConstant(Stride, dl,
10565                                             BasePtr.getValueType()));
10566     }
10567 
10568     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10569     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
10570 
10571     if (LN->isIndexed()) {
10572       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
10573       return DAG.getMergeValues(RetOps, dl);
10574     }
10575 
10576     SDValue RetOps[] = { Value, TF };
10577     return DAG.getMergeValues(RetOps, dl);
10578   }
10579 
10580   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
10581   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
10582 
10583   // To lower v4i1 from a byte array, we load the byte elements of the
10584   // vector and then reuse the BUILD_VECTOR logic.
10585 
10586   SDValue VectElmts[4], VectElmtChains[4];
10587   for (unsigned i = 0; i < 4; ++i) {
10588     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10589     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10590 
10591     VectElmts[i] = DAG.getExtLoad(
10592         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
10593         LN->getPointerInfo().getWithOffset(i), MVT::i8,
10594         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
10595     VectElmtChains[i] = VectElmts[i].getValue(1);
10596   }
10597 
10598   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
10599   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
10600 
10601   SDValue RVals[] = { Value, LoadChain };
10602   return DAG.getMergeValues(RVals, dl);
10603 }
10604 
10605 /// Lowering for QPX v4i1 stores
10606 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10607                                             SelectionDAG &DAG) const {
10608   SDLoc dl(Op);
10609   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10610   SDValue StoreChain = SN->getChain();
10611   SDValue BasePtr = SN->getBasePtr();
10612   SDValue Value = SN->getValue();
10613 
10614   if (Value.getValueType() == MVT::v4f64 ||
10615       Value.getValueType() == MVT::v4f32) {
10616     EVT MemVT = SN->getMemoryVT();
10617     unsigned Alignment = SN->getAlignment();
10618 
10619     // If this store is properly aligned, then it is legal.
10620     if (Alignment >= MemVT.getStoreSize())
10621       return Op;
10622 
10623     EVT ScalarVT = Value.getValueType().getScalarType(),
10624         ScalarMemVT = MemVT.getScalarType();
10625     unsigned Stride = ScalarMemVT.getStoreSize();
10626 
10627     SDValue Stores[4];
10628     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10629       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
10630                                DAG.getVectorIdxConstant(Idx, dl));
10631       SDValue Store;
10632       if (ScalarVT != ScalarMemVT)
10633         Store =
10634             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
10635                               SN->getPointerInfo().getWithOffset(Idx * Stride),
10636                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10637                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
10638       else
10639         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
10640                              SN->getPointerInfo().getWithOffset(Idx * Stride),
10641                              MinAlign(Alignment, Idx * Stride),
10642                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
10643 
10644       if (Idx == 0 && SN->isIndexed()) {
10645         assert(SN->getAddressingMode() == ISD::PRE_INC &&
10646                "Unknown addressing mode on vector store");
10647         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
10648                                     SN->getAddressingMode());
10649       }
10650 
10651       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10652                             DAG.getConstant(Stride, dl,
10653                                             BasePtr.getValueType()));
10654       Stores[Idx] = Store;
10655     }
10656 
10657     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10658 
10659     if (SN->isIndexed()) {
10660       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
10661       return DAG.getMergeValues(RetOps, dl);
10662     }
10663 
10664     return TF;
10665   }
10666 
10667   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
10668   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
10669 
10670   // The values are now known to be -1 (false) or 1 (true). To convert this
10671   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10672   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10673   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10674 
10675   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10676   // understand how to form the extending load.
10677   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10678 
10679   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10680 
10681   // Now convert to an integer and store.
10682   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10683     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10684     Value);
10685 
10686   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10687   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10688   MachinePointerInfo PtrInfo =
10689       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10690   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10691   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10692 
10693   SDValue Ops[] = {StoreChain,
10694                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10695                    Value, FIdx};
10696   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10697 
10698   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10699     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10700 
10701   // Move data into the byte array.
10702   SDValue Loads[4], LoadChains[4];
10703   for (unsigned i = 0; i < 4; ++i) {
10704     unsigned Offset = 4*i;
10705     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10706     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10707 
10708     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
10709                            PtrInfo.getWithOffset(Offset));
10710     LoadChains[i] = Loads[i].getValue(1);
10711   }
10712 
10713   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10714 
10715   SDValue Stores[4];
10716   for (unsigned i = 0; i < 4; ++i) {
10717     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10718     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10719 
10720     Stores[i] = DAG.getTruncStore(
10721         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
10722         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
10723         SN->getAAInfo());
10724   }
10725 
10726   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10727 
10728   return StoreChain;
10729 }
10730 
10731 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10732   SDLoc dl(Op);
10733   if (Op.getValueType() == MVT::v4i32) {
10734     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10735 
10736     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
10737     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
10738 
10739     SDValue RHSSwap =   // = vrlw RHS, 16
10740       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10741 
10742     // Shrinkify inputs to v8i16.
10743     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10744     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10745     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10746 
10747     // Low parts multiplied together, generating 32-bit results (we ignore the
10748     // top parts).
10749     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10750                                         LHS, RHS, DAG, dl, MVT::v4i32);
10751 
10752     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10753                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10754     // Shift the high parts up 16 bits.
10755     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10756                               Neg16, DAG, dl);
10757     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10758   } else if (Op.getValueType() == MVT::v16i8) {
10759     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10760     bool isLittleEndian = Subtarget.isLittleEndian();
10761 
10762     // Multiply the even 8-bit parts, producing 16-bit sums.
10763     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10764                                            LHS, RHS, DAG, dl, MVT::v8i16);
10765     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10766 
10767     // Multiply the odd 8-bit parts, producing 16-bit sums.
10768     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10769                                           LHS, RHS, DAG, dl, MVT::v8i16);
10770     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10771 
10772     // Merge the results together.  Because vmuleub and vmuloub are
10773     // instructions with a big-endian bias, we must reverse the
10774     // element numbering and reverse the meaning of "odd" and "even"
10775     // when generating little endian code.
10776     int Ops[16];
10777     for (unsigned i = 0; i != 8; ++i) {
10778       if (isLittleEndian) {
10779         Ops[i*2  ] = 2*i;
10780         Ops[i*2+1] = 2*i+16;
10781       } else {
10782         Ops[i*2  ] = 2*i+1;
10783         Ops[i*2+1] = 2*i+1+16;
10784       }
10785     }
10786     if (isLittleEndian)
10787       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10788     else
10789       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10790   } else {
10791     llvm_unreachable("Unknown mul to lower!");
10792   }
10793 }
10794 
10795 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10796 
10797   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10798 
10799   EVT VT = Op.getValueType();
10800   assert(VT.isVector() &&
10801          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10802   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10803           VT == MVT::v16i8) &&
10804          "Unexpected vector element type!");
10805   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10806          "Current subtarget doesn't support smax v2i64!");
10807 
10808   // For vector abs, it can be lowered to:
10809   // abs x
10810   // ==>
10811   // y = -x
10812   // smax(x, y)
10813 
10814   SDLoc dl(Op);
10815   SDValue X = Op.getOperand(0);
10816   SDValue Zero = DAG.getConstant(0, dl, VT);
10817   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10818 
10819   // SMAX patch https://reviews.llvm.org/D47332
10820   // hasn't landed yet, so use intrinsic first here.
10821   // TODO: Should use SMAX directly once SMAX patch landed
10822   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10823   if (VT == MVT::v2i64)
10824     BifID = Intrinsic::ppc_altivec_vmaxsd;
10825   else if (VT == MVT::v8i16)
10826     BifID = Intrinsic::ppc_altivec_vmaxsh;
10827   else if (VT == MVT::v16i8)
10828     BifID = Intrinsic::ppc_altivec_vmaxsb;
10829 
10830   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10831 }
10832 
10833 // Custom lowering for fpext vf32 to v2f64
10834 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10835 
10836   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10837          "Should only be called for ISD::FP_EXTEND");
10838 
10839   // FIXME: handle extends from half precision float vectors on P9.
10840   // We only want to custom lower an extend from v2f32 to v2f64.
10841   if (Op.getValueType() != MVT::v2f64 ||
10842       Op.getOperand(0).getValueType() != MVT::v2f32)
10843     return SDValue();
10844 
10845   SDLoc dl(Op);
10846   SDValue Op0 = Op.getOperand(0);
10847 
10848   switch (Op0.getOpcode()) {
10849   default:
10850     return SDValue();
10851   case ISD::EXTRACT_SUBVECTOR: {
10852     assert(Op0.getNumOperands() == 2 &&
10853            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10854            "Node should have 2 operands with second one being a constant!");
10855 
10856     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10857       return SDValue();
10858 
10859     // Custom lower is only done for high or low doubleword.
10860     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10861     if (Idx % 2 != 0)
10862       return SDValue();
10863 
10864     // Since input is v4f32, at this point Idx is either 0 or 2.
10865     // Shift to get the doubleword position we want.
10866     int DWord = Idx >> 1;
10867 
10868     // High and low word positions are different on little endian.
10869     if (Subtarget.isLittleEndian())
10870       DWord ^= 0x1;
10871 
10872     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10873                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10874   }
10875   case ISD::FADD:
10876   case ISD::FMUL:
10877   case ISD::FSUB: {
10878     SDValue NewLoad[2];
10879     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10880       // Ensure both input are loads.
10881       SDValue LdOp = Op0.getOperand(i);
10882       if (LdOp.getOpcode() != ISD::LOAD)
10883         return SDValue();
10884       // Generate new load node.
10885       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10886       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10887       NewLoad[i] = DAG.getMemIntrinsicNode(
10888           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10889           LD->getMemoryVT(), LD->getMemOperand());
10890     }
10891     SDValue NewOp =
10892         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10893                     NewLoad[1], Op0.getNode()->getFlags());
10894     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10895                        DAG.getConstant(0, dl, MVT::i32));
10896   }
10897   case ISD::LOAD: {
10898     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10899     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10900     SDValue NewLd = DAG.getMemIntrinsicNode(
10901         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10902         LD->getMemoryVT(), LD->getMemOperand());
10903     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10904                        DAG.getConstant(0, dl, MVT::i32));
10905   }
10906   }
10907   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10908 }
10909 
10910 /// LowerOperation - Provide custom lowering hooks for some operations.
10911 ///
10912 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10913   switch (Op.getOpcode()) {
10914   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10915   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10916   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10917   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10918   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10919   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10920   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10921   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10922   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10923 
10924   // Variable argument lowering.
10925   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10926   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10927   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10928 
10929   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10930   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10931   case ISD::GET_DYNAMIC_AREA_OFFSET:
10932     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10933 
10934   // Exception handling lowering.
10935   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10936   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10937   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10938 
10939   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10940   case ISD::STORE:              return LowerSTORE(Op, DAG);
10941   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10942   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10943   case ISD::FP_TO_UINT:
10944   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10945   case ISD::UINT_TO_FP:
10946   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10947   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10948 
10949   // Lower 64-bit shifts.
10950   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10951   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10952   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10953 
10954   // Vector-related lowering.
10955   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10956   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10957   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10958   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10959   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10960   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10961   case ISD::MUL:                return LowerMUL(Op, DAG);
10962   case ISD::ABS:                return LowerABS(Op, DAG);
10963   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10964   case ISD::ROTL:               return LowerROTL(Op, DAG);
10965 
10966   // For counter-based loop handling.
10967   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10968 
10969   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10970 
10971   // Frame & Return address.
10972   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10973   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10974 
10975   case ISD::INTRINSIC_VOID:
10976     return LowerINTRINSIC_VOID(Op, DAG);
10977   case ISD::SREM:
10978   case ISD::UREM:
10979     return LowerREM(Op, DAG);
10980   case ISD::BSWAP:
10981     return LowerBSWAP(Op, DAG);
10982   case ISD::ATOMIC_CMP_SWAP:
10983     return LowerATOMIC_CMP_SWAP(Op, DAG);
10984   }
10985 }
10986 
10987 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10988                                            SmallVectorImpl<SDValue>&Results,
10989                                            SelectionDAG &DAG) const {
10990   SDLoc dl(N);
10991   switch (N->getOpcode()) {
10992   default:
10993     llvm_unreachable("Do not know how to custom type legalize this operation!");
10994   case ISD::READCYCLECOUNTER: {
10995     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10996     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10997 
10998     Results.push_back(
10999         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
11000     Results.push_back(RTB.getValue(2));
11001     break;
11002   }
11003   case ISD::INTRINSIC_W_CHAIN: {
11004     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
11005         Intrinsic::loop_decrement)
11006       break;
11007 
11008     assert(N->getValueType(0) == MVT::i1 &&
11009            "Unexpected result type for CTR decrement intrinsic");
11010     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11011                                  N->getValueType(0));
11012     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
11013     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
11014                                  N->getOperand(1));
11015 
11016     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
11017     Results.push_back(NewInt.getValue(1));
11018     break;
11019   }
11020   case ISD::VAARG: {
11021     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
11022       return;
11023 
11024     EVT VT = N->getValueType(0);
11025 
11026     if (VT == MVT::i64) {
11027       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
11028 
11029       Results.push_back(NewNode);
11030       Results.push_back(NewNode.getValue(1));
11031     }
11032     return;
11033   }
11034   case ISD::FP_TO_SINT:
11035   case ISD::FP_TO_UINT:
11036     // LowerFP_TO_INT() can only handle f32 and f64.
11037     if (N->getOperand(0).getValueType() == MVT::ppcf128)
11038       return;
11039     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
11040     return;
11041   case ISD::TRUNCATE: {
11042     EVT TrgVT = N->getValueType(0);
11043     EVT OpVT = N->getOperand(0).getValueType();
11044     if (TrgVT.isVector() &&
11045         isOperationCustom(N->getOpcode(), TrgVT) &&
11046         OpVT.getSizeInBits() <= 128 &&
11047         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
11048       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
11049     return;
11050   }
11051   case ISD::BITCAST:
11052     // Don't handle bitcast here.
11053     return;
11054   case ISD::FP_EXTEND:
11055     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
11056     if (Lowered)
11057       Results.push_back(Lowered);
11058     return;
11059   }
11060 }
11061 
11062 //===----------------------------------------------------------------------===//
11063 //  Other Lowering Code
11064 //===----------------------------------------------------------------------===//
11065 
11066 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
11067   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11068   Function *Func = Intrinsic::getDeclaration(M, Id);
11069   return Builder.CreateCall(Func, {});
11070 }
11071 
11072 // The mappings for emitLeading/TrailingFence is taken from
11073 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11074 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11075                                                  Instruction *Inst,
11076                                                  AtomicOrdering Ord) const {
11077   if (Ord == AtomicOrdering::SequentiallyConsistent)
11078     return callIntrinsic(Builder, Intrinsic::ppc_sync);
11079   if (isReleaseOrStronger(Ord))
11080     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11081   return nullptr;
11082 }
11083 
11084 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11085                                                   Instruction *Inst,
11086                                                   AtomicOrdering Ord) const {
11087   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11088     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11089     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11090     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11091     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11092       return Builder.CreateCall(
11093           Intrinsic::getDeclaration(
11094               Builder.GetInsertBlock()->getParent()->getParent(),
11095               Intrinsic::ppc_cfence, {Inst->getType()}),
11096           {Inst});
11097     // FIXME: Can use isync for rmw operation.
11098     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11099   }
11100   return nullptr;
11101 }
11102 
11103 MachineBasicBlock *
11104 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11105                                     unsigned AtomicSize,
11106                                     unsigned BinOpcode,
11107                                     unsigned CmpOpcode,
11108                                     unsigned CmpPred) const {
11109   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11110   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11111 
11112   auto LoadMnemonic = PPC::LDARX;
11113   auto StoreMnemonic = PPC::STDCX;
11114   switch (AtomicSize) {
11115   default:
11116     llvm_unreachable("Unexpected size of atomic entity");
11117   case 1:
11118     LoadMnemonic = PPC::LBARX;
11119     StoreMnemonic = PPC::STBCX;
11120     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11121     break;
11122   case 2:
11123     LoadMnemonic = PPC::LHARX;
11124     StoreMnemonic = PPC::STHCX;
11125     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11126     break;
11127   case 4:
11128     LoadMnemonic = PPC::LWARX;
11129     StoreMnemonic = PPC::STWCX;
11130     break;
11131   case 8:
11132     LoadMnemonic = PPC::LDARX;
11133     StoreMnemonic = PPC::STDCX;
11134     break;
11135   }
11136 
11137   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11138   MachineFunction *F = BB->getParent();
11139   MachineFunction::iterator It = ++BB->getIterator();
11140 
11141   Register dest = MI.getOperand(0).getReg();
11142   Register ptrA = MI.getOperand(1).getReg();
11143   Register ptrB = MI.getOperand(2).getReg();
11144   Register incr = MI.getOperand(3).getReg();
11145   DebugLoc dl = MI.getDebugLoc();
11146 
11147   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11148   MachineBasicBlock *loop2MBB =
11149     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11150   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11151   F->insert(It, loopMBB);
11152   if (CmpOpcode)
11153     F->insert(It, loop2MBB);
11154   F->insert(It, exitMBB);
11155   exitMBB->splice(exitMBB->begin(), BB,
11156                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11157   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11158 
11159   MachineRegisterInfo &RegInfo = F->getRegInfo();
11160   Register TmpReg = (!BinOpcode) ? incr :
11161     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11162                                            : &PPC::GPRCRegClass);
11163 
11164   //  thisMBB:
11165   //   ...
11166   //   fallthrough --> loopMBB
11167   BB->addSuccessor(loopMBB);
11168 
11169   //  loopMBB:
11170   //   l[wd]arx dest, ptr
11171   //   add r0, dest, incr
11172   //   st[wd]cx. r0, ptr
11173   //   bne- loopMBB
11174   //   fallthrough --> exitMBB
11175 
11176   // For max/min...
11177   //  loopMBB:
11178   //   l[wd]arx dest, ptr
11179   //   cmpl?[wd] incr, dest
11180   //   bgt exitMBB
11181   //  loop2MBB:
11182   //   st[wd]cx. dest, ptr
11183   //   bne- loopMBB
11184   //   fallthrough --> exitMBB
11185 
11186   BB = loopMBB;
11187   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11188     .addReg(ptrA).addReg(ptrB);
11189   if (BinOpcode)
11190     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11191   if (CmpOpcode) {
11192     // Signed comparisons of byte or halfword values must be sign-extended.
11193     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11194       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11195       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11196               ExtReg).addReg(dest);
11197       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11198         .addReg(incr).addReg(ExtReg);
11199     } else
11200       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11201         .addReg(incr).addReg(dest);
11202 
11203     BuildMI(BB, dl, TII->get(PPC::BCC))
11204       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11205     BB->addSuccessor(loop2MBB);
11206     BB->addSuccessor(exitMBB);
11207     BB = loop2MBB;
11208   }
11209   BuildMI(BB, dl, TII->get(StoreMnemonic))
11210     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11211   BuildMI(BB, dl, TII->get(PPC::BCC))
11212     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11213   BB->addSuccessor(loopMBB);
11214   BB->addSuccessor(exitMBB);
11215 
11216   //  exitMBB:
11217   //   ...
11218   BB = exitMBB;
11219   return BB;
11220 }
11221 
11222 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11223     MachineInstr &MI, MachineBasicBlock *BB,
11224     bool is8bit, // operation
11225     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11226   // If we support part-word atomic mnemonics, just use them
11227   if (Subtarget.hasPartwordAtomics())
11228     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11229                             CmpPred);
11230 
11231   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11232   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11233   // In 64 bit mode we have to use 64 bits for addresses, even though the
11234   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11235   // registers without caring whether they're 32 or 64, but here we're
11236   // doing actual arithmetic on the addresses.
11237   bool is64bit = Subtarget.isPPC64();
11238   bool isLittleEndian = Subtarget.isLittleEndian();
11239   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11240 
11241   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11242   MachineFunction *F = BB->getParent();
11243   MachineFunction::iterator It = ++BB->getIterator();
11244 
11245   Register dest = MI.getOperand(0).getReg();
11246   Register ptrA = MI.getOperand(1).getReg();
11247   Register ptrB = MI.getOperand(2).getReg();
11248   Register incr = MI.getOperand(3).getReg();
11249   DebugLoc dl = MI.getDebugLoc();
11250 
11251   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11252   MachineBasicBlock *loop2MBB =
11253       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11254   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11255   F->insert(It, loopMBB);
11256   if (CmpOpcode)
11257     F->insert(It, loop2MBB);
11258   F->insert(It, exitMBB);
11259   exitMBB->splice(exitMBB->begin(), BB,
11260                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11261   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11262 
11263   MachineRegisterInfo &RegInfo = F->getRegInfo();
11264   const TargetRegisterClass *RC =
11265       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11266   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11267 
11268   Register PtrReg = RegInfo.createVirtualRegister(RC);
11269   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11270   Register ShiftReg =
11271       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11272   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11273   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11274   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11275   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11276   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11277   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11278   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11279   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11280   Register Ptr1Reg;
11281   Register TmpReg =
11282       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11283 
11284   //  thisMBB:
11285   //   ...
11286   //   fallthrough --> loopMBB
11287   BB->addSuccessor(loopMBB);
11288 
11289   // The 4-byte load must be aligned, while a char or short may be
11290   // anywhere in the word.  Hence all this nasty bookkeeping code.
11291   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11292   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11293   //   xori shift, shift1, 24 [16]
11294   //   rlwinm ptr, ptr1, 0, 0, 29
11295   //   slw incr2, incr, shift
11296   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11297   //   slw mask, mask2, shift
11298   //  loopMBB:
11299   //   lwarx tmpDest, ptr
11300   //   add tmp, tmpDest, incr2
11301   //   andc tmp2, tmpDest, mask
11302   //   and tmp3, tmp, mask
11303   //   or tmp4, tmp3, tmp2
11304   //   stwcx. tmp4, ptr
11305   //   bne- loopMBB
11306   //   fallthrough --> exitMBB
11307   //   srw dest, tmpDest, shift
11308   if (ptrA != ZeroReg) {
11309     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11310     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11311         .addReg(ptrA)
11312         .addReg(ptrB);
11313   } else {
11314     Ptr1Reg = ptrB;
11315   }
11316   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11317   // mode.
11318   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11319       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11320       .addImm(3)
11321       .addImm(27)
11322       .addImm(is8bit ? 28 : 27);
11323   if (!isLittleEndian)
11324     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11325         .addReg(Shift1Reg)
11326         .addImm(is8bit ? 24 : 16);
11327   if (is64bit)
11328     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11329         .addReg(Ptr1Reg)
11330         .addImm(0)
11331         .addImm(61);
11332   else
11333     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11334         .addReg(Ptr1Reg)
11335         .addImm(0)
11336         .addImm(0)
11337         .addImm(29);
11338   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11339   if (is8bit)
11340     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11341   else {
11342     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11343     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11344         .addReg(Mask3Reg)
11345         .addImm(65535);
11346   }
11347   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11348       .addReg(Mask2Reg)
11349       .addReg(ShiftReg);
11350 
11351   BB = loopMBB;
11352   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11353       .addReg(ZeroReg)
11354       .addReg(PtrReg);
11355   if (BinOpcode)
11356     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11357         .addReg(Incr2Reg)
11358         .addReg(TmpDestReg);
11359   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11360       .addReg(TmpDestReg)
11361       .addReg(MaskReg);
11362   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11363   if (CmpOpcode) {
11364     // For unsigned comparisons, we can directly compare the shifted values.
11365     // For signed comparisons we shift and sign extend.
11366     Register SReg = RegInfo.createVirtualRegister(GPRC);
11367     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11368         .addReg(TmpDestReg)
11369         .addReg(MaskReg);
11370     unsigned ValueReg = SReg;
11371     unsigned CmpReg = Incr2Reg;
11372     if (CmpOpcode == PPC::CMPW) {
11373       ValueReg = RegInfo.createVirtualRegister(GPRC);
11374       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11375           .addReg(SReg)
11376           .addReg(ShiftReg);
11377       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11378       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11379           .addReg(ValueReg);
11380       ValueReg = ValueSReg;
11381       CmpReg = incr;
11382     }
11383     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11384         .addReg(CmpReg)
11385         .addReg(ValueReg);
11386     BuildMI(BB, dl, TII->get(PPC::BCC))
11387         .addImm(CmpPred)
11388         .addReg(PPC::CR0)
11389         .addMBB(exitMBB);
11390     BB->addSuccessor(loop2MBB);
11391     BB->addSuccessor(exitMBB);
11392     BB = loop2MBB;
11393   }
11394   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11395   BuildMI(BB, dl, TII->get(PPC::STWCX))
11396       .addReg(Tmp4Reg)
11397       .addReg(ZeroReg)
11398       .addReg(PtrReg);
11399   BuildMI(BB, dl, TII->get(PPC::BCC))
11400       .addImm(PPC::PRED_NE)
11401       .addReg(PPC::CR0)
11402       .addMBB(loopMBB);
11403   BB->addSuccessor(loopMBB);
11404   BB->addSuccessor(exitMBB);
11405 
11406   //  exitMBB:
11407   //   ...
11408   BB = exitMBB;
11409   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11410       .addReg(TmpDestReg)
11411       .addReg(ShiftReg);
11412   return BB;
11413 }
11414 
11415 llvm::MachineBasicBlock *
11416 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11417                                     MachineBasicBlock *MBB) const {
11418   DebugLoc DL = MI.getDebugLoc();
11419   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11420   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11421 
11422   MachineFunction *MF = MBB->getParent();
11423   MachineRegisterInfo &MRI = MF->getRegInfo();
11424 
11425   const BasicBlock *BB = MBB->getBasicBlock();
11426   MachineFunction::iterator I = ++MBB->getIterator();
11427 
11428   Register DstReg = MI.getOperand(0).getReg();
11429   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11430   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11431   Register mainDstReg = MRI.createVirtualRegister(RC);
11432   Register restoreDstReg = MRI.createVirtualRegister(RC);
11433 
11434   MVT PVT = getPointerTy(MF->getDataLayout());
11435   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11436          "Invalid Pointer Size!");
11437   // For v = setjmp(buf), we generate
11438   //
11439   // thisMBB:
11440   //  SjLjSetup mainMBB
11441   //  bl mainMBB
11442   //  v_restore = 1
11443   //  b sinkMBB
11444   //
11445   // mainMBB:
11446   //  buf[LabelOffset] = LR
11447   //  v_main = 0
11448   //
11449   // sinkMBB:
11450   //  v = phi(main, restore)
11451   //
11452 
11453   MachineBasicBlock *thisMBB = MBB;
11454   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11455   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11456   MF->insert(I, mainMBB);
11457   MF->insert(I, sinkMBB);
11458 
11459   MachineInstrBuilder MIB;
11460 
11461   // Transfer the remainder of BB and its successor edges to sinkMBB.
11462   sinkMBB->splice(sinkMBB->begin(), MBB,
11463                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11464   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11465 
11466   // Note that the structure of the jmp_buf used here is not compatible
11467   // with that used by libc, and is not designed to be. Specifically, it
11468   // stores only those 'reserved' registers that LLVM does not otherwise
11469   // understand how to spill. Also, by convention, by the time this
11470   // intrinsic is called, Clang has already stored the frame address in the
11471   // first slot of the buffer and stack address in the third. Following the
11472   // X86 target code, we'll store the jump address in the second slot. We also
11473   // need to save the TOC pointer (R2) to handle jumps between shared
11474   // libraries, and that will be stored in the fourth slot. The thread
11475   // identifier (R13) is not affected.
11476 
11477   // thisMBB:
11478   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11479   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11480   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11481 
11482   // Prepare IP either in reg.
11483   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11484   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11485   Register BufReg = MI.getOperand(1).getReg();
11486 
11487   if (Subtarget.is64BitELFABI()) {
11488     setUsesTOCBasePtr(*MBB->getParent());
11489     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11490               .addReg(PPC::X2)
11491               .addImm(TOCOffset)
11492               .addReg(BufReg)
11493               .cloneMemRefs(MI);
11494   }
11495 
11496   // Naked functions never have a base pointer, and so we use r1. For all
11497   // other functions, this decision must be delayed until during PEI.
11498   unsigned BaseReg;
11499   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11500     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11501   else
11502     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11503 
11504   MIB = BuildMI(*thisMBB, MI, DL,
11505                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11506             .addReg(BaseReg)
11507             .addImm(BPOffset)
11508             .addReg(BufReg)
11509             .cloneMemRefs(MI);
11510 
11511   // Setup
11512   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11513   MIB.addRegMask(TRI->getNoPreservedMask());
11514 
11515   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11516 
11517   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11518           .addMBB(mainMBB);
11519   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11520 
11521   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11522   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11523 
11524   // mainMBB:
11525   //  mainDstReg = 0
11526   MIB =
11527       BuildMI(mainMBB, DL,
11528               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11529 
11530   // Store IP
11531   if (Subtarget.isPPC64()) {
11532     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11533             .addReg(LabelReg)
11534             .addImm(LabelOffset)
11535             .addReg(BufReg);
11536   } else {
11537     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11538             .addReg(LabelReg)
11539             .addImm(LabelOffset)
11540             .addReg(BufReg);
11541   }
11542   MIB.cloneMemRefs(MI);
11543 
11544   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11545   mainMBB->addSuccessor(sinkMBB);
11546 
11547   // sinkMBB:
11548   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11549           TII->get(PPC::PHI), DstReg)
11550     .addReg(mainDstReg).addMBB(mainMBB)
11551     .addReg(restoreDstReg).addMBB(thisMBB);
11552 
11553   MI.eraseFromParent();
11554   return sinkMBB;
11555 }
11556 
11557 MachineBasicBlock *
11558 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11559                                      MachineBasicBlock *MBB) const {
11560   DebugLoc DL = MI.getDebugLoc();
11561   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11562 
11563   MachineFunction *MF = MBB->getParent();
11564   MachineRegisterInfo &MRI = MF->getRegInfo();
11565 
11566   MVT PVT = getPointerTy(MF->getDataLayout());
11567   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11568          "Invalid Pointer Size!");
11569 
11570   const TargetRegisterClass *RC =
11571     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11572   Register Tmp = MRI.createVirtualRegister(RC);
11573   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11574   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11575   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11576   unsigned BP =
11577       (PVT == MVT::i64)
11578           ? PPC::X30
11579           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11580                                                               : PPC::R30);
11581 
11582   MachineInstrBuilder MIB;
11583 
11584   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11585   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11586   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11587   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11588 
11589   Register BufReg = MI.getOperand(0).getReg();
11590 
11591   // Reload FP (the jumped-to function may not have had a
11592   // frame pointer, and if so, then its r31 will be restored
11593   // as necessary).
11594   if (PVT == MVT::i64) {
11595     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11596             .addImm(0)
11597             .addReg(BufReg);
11598   } else {
11599     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11600             .addImm(0)
11601             .addReg(BufReg);
11602   }
11603   MIB.cloneMemRefs(MI);
11604 
11605   // Reload IP
11606   if (PVT == MVT::i64) {
11607     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11608             .addImm(LabelOffset)
11609             .addReg(BufReg);
11610   } else {
11611     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11612             .addImm(LabelOffset)
11613             .addReg(BufReg);
11614   }
11615   MIB.cloneMemRefs(MI);
11616 
11617   // Reload SP
11618   if (PVT == MVT::i64) {
11619     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11620             .addImm(SPOffset)
11621             .addReg(BufReg);
11622   } else {
11623     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11624             .addImm(SPOffset)
11625             .addReg(BufReg);
11626   }
11627   MIB.cloneMemRefs(MI);
11628 
11629   // Reload BP
11630   if (PVT == MVT::i64) {
11631     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11632             .addImm(BPOffset)
11633             .addReg(BufReg);
11634   } else {
11635     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11636             .addImm(BPOffset)
11637             .addReg(BufReg);
11638   }
11639   MIB.cloneMemRefs(MI);
11640 
11641   // Reload TOC
11642   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11643     setUsesTOCBasePtr(*MBB->getParent());
11644     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11645               .addImm(TOCOffset)
11646               .addReg(BufReg)
11647               .cloneMemRefs(MI);
11648   }
11649 
11650   // Jump
11651   BuildMI(*MBB, MI, DL,
11652           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11653   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11654 
11655   MI.eraseFromParent();
11656   return MBB;
11657 }
11658 
11659 MachineBasicBlock *
11660 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11661                                                MachineBasicBlock *BB) const {
11662   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11663       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11664     if (Subtarget.is64BitELFABI() &&
11665         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11666         !Subtarget.isUsingPCRelativeCalls()) {
11667       // Call lowering should have added an r2 operand to indicate a dependence
11668       // on the TOC base pointer value. It can't however, because there is no
11669       // way to mark the dependence as implicit there, and so the stackmap code
11670       // will confuse it with a regular operand. Instead, add the dependence
11671       // here.
11672       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11673     }
11674 
11675     return emitPatchPoint(MI, BB);
11676   }
11677 
11678   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11679       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11680     return emitEHSjLjSetJmp(MI, BB);
11681   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11682              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11683     return emitEHSjLjLongJmp(MI, BB);
11684   }
11685 
11686   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11687 
11688   // To "insert" these instructions we actually have to insert their
11689   // control-flow patterns.
11690   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11691   MachineFunction::iterator It = ++BB->getIterator();
11692 
11693   MachineFunction *F = BB->getParent();
11694 
11695   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11696       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11697       MI.getOpcode() == PPC::SELECT_I8) {
11698     SmallVector<MachineOperand, 2> Cond;
11699     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11700         MI.getOpcode() == PPC::SELECT_CC_I8)
11701       Cond.push_back(MI.getOperand(4));
11702     else
11703       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11704     Cond.push_back(MI.getOperand(1));
11705 
11706     DebugLoc dl = MI.getDebugLoc();
11707     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11708                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11709   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11710              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11711              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11712              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
11713              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
11714              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
11715              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11716              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11717              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11718              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11719              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11720              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11721              MI.getOpcode() == PPC::SELECT_F4 ||
11722              MI.getOpcode() == PPC::SELECT_F8 ||
11723              MI.getOpcode() == PPC::SELECT_F16 ||
11724              MI.getOpcode() == PPC::SELECT_QFRC ||
11725              MI.getOpcode() == PPC::SELECT_QSRC ||
11726              MI.getOpcode() == PPC::SELECT_QBRC ||
11727              MI.getOpcode() == PPC::SELECT_SPE ||
11728              MI.getOpcode() == PPC::SELECT_SPE4 ||
11729              MI.getOpcode() == PPC::SELECT_VRRC ||
11730              MI.getOpcode() == PPC::SELECT_VSFRC ||
11731              MI.getOpcode() == PPC::SELECT_VSSRC ||
11732              MI.getOpcode() == PPC::SELECT_VSRC) {
11733     // The incoming instruction knows the destination vreg to set, the
11734     // condition code register to branch on, the true/false values to
11735     // select between, and a branch opcode to use.
11736 
11737     //  thisMBB:
11738     //  ...
11739     //   TrueVal = ...
11740     //   cmpTY ccX, r1, r2
11741     //   bCC copy1MBB
11742     //   fallthrough --> copy0MBB
11743     MachineBasicBlock *thisMBB = BB;
11744     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11745     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11746     DebugLoc dl = MI.getDebugLoc();
11747     F->insert(It, copy0MBB);
11748     F->insert(It, sinkMBB);
11749 
11750     // Transfer the remainder of BB and its successor edges to sinkMBB.
11751     sinkMBB->splice(sinkMBB->begin(), BB,
11752                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11753     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11754 
11755     // Next, add the true and fallthrough blocks as its successors.
11756     BB->addSuccessor(copy0MBB);
11757     BB->addSuccessor(sinkMBB);
11758 
11759     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11760         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11761         MI.getOpcode() == PPC::SELECT_F16 ||
11762         MI.getOpcode() == PPC::SELECT_SPE4 ||
11763         MI.getOpcode() == PPC::SELECT_SPE ||
11764         MI.getOpcode() == PPC::SELECT_QFRC ||
11765         MI.getOpcode() == PPC::SELECT_QSRC ||
11766         MI.getOpcode() == PPC::SELECT_QBRC ||
11767         MI.getOpcode() == PPC::SELECT_VRRC ||
11768         MI.getOpcode() == PPC::SELECT_VSFRC ||
11769         MI.getOpcode() == PPC::SELECT_VSSRC ||
11770         MI.getOpcode() == PPC::SELECT_VSRC) {
11771       BuildMI(BB, dl, TII->get(PPC::BC))
11772           .addReg(MI.getOperand(1).getReg())
11773           .addMBB(sinkMBB);
11774     } else {
11775       unsigned SelectPred = MI.getOperand(4).getImm();
11776       BuildMI(BB, dl, TII->get(PPC::BCC))
11777           .addImm(SelectPred)
11778           .addReg(MI.getOperand(1).getReg())
11779           .addMBB(sinkMBB);
11780     }
11781 
11782     //  copy0MBB:
11783     //   %FalseValue = ...
11784     //   # fallthrough to sinkMBB
11785     BB = copy0MBB;
11786 
11787     // Update machine-CFG edges
11788     BB->addSuccessor(sinkMBB);
11789 
11790     //  sinkMBB:
11791     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11792     //  ...
11793     BB = sinkMBB;
11794     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11795         .addReg(MI.getOperand(3).getReg())
11796         .addMBB(copy0MBB)
11797         .addReg(MI.getOperand(2).getReg())
11798         .addMBB(thisMBB);
11799   } else if (MI.getOpcode() == PPC::ReadTB) {
11800     // To read the 64-bit time-base register on a 32-bit target, we read the
11801     // two halves. Should the counter have wrapped while it was being read, we
11802     // need to try again.
11803     // ...
11804     // readLoop:
11805     // mfspr Rx,TBU # load from TBU
11806     // mfspr Ry,TB  # load from TB
11807     // mfspr Rz,TBU # load from TBU
11808     // cmpw crX,Rx,Rz # check if 'old'='new'
11809     // bne readLoop   # branch if they're not equal
11810     // ...
11811 
11812     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11813     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11814     DebugLoc dl = MI.getDebugLoc();
11815     F->insert(It, readMBB);
11816     F->insert(It, sinkMBB);
11817 
11818     // Transfer the remainder of BB and its successor edges to sinkMBB.
11819     sinkMBB->splice(sinkMBB->begin(), BB,
11820                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11821     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11822 
11823     BB->addSuccessor(readMBB);
11824     BB = readMBB;
11825 
11826     MachineRegisterInfo &RegInfo = F->getRegInfo();
11827     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11828     Register LoReg = MI.getOperand(0).getReg();
11829     Register HiReg = MI.getOperand(1).getReg();
11830 
11831     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11832     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11833     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11834 
11835     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11836 
11837     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11838         .addReg(HiReg)
11839         .addReg(ReadAgainReg);
11840     BuildMI(BB, dl, TII->get(PPC::BCC))
11841         .addImm(PPC::PRED_NE)
11842         .addReg(CmpReg)
11843         .addMBB(readMBB);
11844 
11845     BB->addSuccessor(readMBB);
11846     BB->addSuccessor(sinkMBB);
11847   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11848     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11849   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11850     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11851   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11852     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11853   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11854     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11855 
11856   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11857     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11858   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11859     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11860   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11861     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11862   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11863     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11864 
11865   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11866     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11867   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11868     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11869   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11870     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11871   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11872     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11873 
11874   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11875     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11876   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11877     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11878   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11879     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11880   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11881     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11882 
11883   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11884     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11885   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11886     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11887   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11888     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11889   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11890     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11891 
11892   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11893     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11894   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11895     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11896   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11897     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11898   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11899     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11900 
11901   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11902     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11903   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11904     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11905   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11906     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11907   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11908     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11909 
11910   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11911     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11912   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11913     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11914   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11915     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11916   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11917     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11918 
11919   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11920     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11921   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11922     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11923   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11924     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11925   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11926     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11927 
11928   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11929     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11930   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11931     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11932   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11933     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11934   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11935     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11936 
11937   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11938     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11939   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11940     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11941   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11942     BB = EmitAtomicBinary(MI, BB, 4, 0);
11943   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11944     BB = EmitAtomicBinary(MI, BB, 8, 0);
11945   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11946            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11947            (Subtarget.hasPartwordAtomics() &&
11948             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11949            (Subtarget.hasPartwordAtomics() &&
11950             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11951     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11952 
11953     auto LoadMnemonic = PPC::LDARX;
11954     auto StoreMnemonic = PPC::STDCX;
11955     switch (MI.getOpcode()) {
11956     default:
11957       llvm_unreachable("Compare and swap of unknown size");
11958     case PPC::ATOMIC_CMP_SWAP_I8:
11959       LoadMnemonic = PPC::LBARX;
11960       StoreMnemonic = PPC::STBCX;
11961       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11962       break;
11963     case PPC::ATOMIC_CMP_SWAP_I16:
11964       LoadMnemonic = PPC::LHARX;
11965       StoreMnemonic = PPC::STHCX;
11966       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11967       break;
11968     case PPC::ATOMIC_CMP_SWAP_I32:
11969       LoadMnemonic = PPC::LWARX;
11970       StoreMnemonic = PPC::STWCX;
11971       break;
11972     case PPC::ATOMIC_CMP_SWAP_I64:
11973       LoadMnemonic = PPC::LDARX;
11974       StoreMnemonic = PPC::STDCX;
11975       break;
11976     }
11977     Register dest = MI.getOperand(0).getReg();
11978     Register ptrA = MI.getOperand(1).getReg();
11979     Register ptrB = MI.getOperand(2).getReg();
11980     Register oldval = MI.getOperand(3).getReg();
11981     Register newval = MI.getOperand(4).getReg();
11982     DebugLoc dl = MI.getDebugLoc();
11983 
11984     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11985     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11986     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11987     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11988     F->insert(It, loop1MBB);
11989     F->insert(It, loop2MBB);
11990     F->insert(It, midMBB);
11991     F->insert(It, exitMBB);
11992     exitMBB->splice(exitMBB->begin(), BB,
11993                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11994     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11995 
11996     //  thisMBB:
11997     //   ...
11998     //   fallthrough --> loopMBB
11999     BB->addSuccessor(loop1MBB);
12000 
12001     // loop1MBB:
12002     //   l[bhwd]arx dest, ptr
12003     //   cmp[wd] dest, oldval
12004     //   bne- midMBB
12005     // loop2MBB:
12006     //   st[bhwd]cx. newval, ptr
12007     //   bne- loopMBB
12008     //   b exitBB
12009     // midMBB:
12010     //   st[bhwd]cx. dest, ptr
12011     // exitBB:
12012     BB = loop1MBB;
12013     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12014     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12015         .addReg(oldval)
12016         .addReg(dest);
12017     BuildMI(BB, dl, TII->get(PPC::BCC))
12018         .addImm(PPC::PRED_NE)
12019         .addReg(PPC::CR0)
12020         .addMBB(midMBB);
12021     BB->addSuccessor(loop2MBB);
12022     BB->addSuccessor(midMBB);
12023 
12024     BB = loop2MBB;
12025     BuildMI(BB, dl, TII->get(StoreMnemonic))
12026         .addReg(newval)
12027         .addReg(ptrA)
12028         .addReg(ptrB);
12029     BuildMI(BB, dl, TII->get(PPC::BCC))
12030         .addImm(PPC::PRED_NE)
12031         .addReg(PPC::CR0)
12032         .addMBB(loop1MBB);
12033     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12034     BB->addSuccessor(loop1MBB);
12035     BB->addSuccessor(exitMBB);
12036 
12037     BB = midMBB;
12038     BuildMI(BB, dl, TII->get(StoreMnemonic))
12039         .addReg(dest)
12040         .addReg(ptrA)
12041         .addReg(ptrB);
12042     BB->addSuccessor(exitMBB);
12043 
12044     //  exitMBB:
12045     //   ...
12046     BB = exitMBB;
12047   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12048              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12049     // We must use 64-bit registers for addresses when targeting 64-bit,
12050     // since we're actually doing arithmetic on them.  Other registers
12051     // can be 32-bit.
12052     bool is64bit = Subtarget.isPPC64();
12053     bool isLittleEndian = Subtarget.isLittleEndian();
12054     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12055 
12056     Register dest = MI.getOperand(0).getReg();
12057     Register ptrA = MI.getOperand(1).getReg();
12058     Register ptrB = MI.getOperand(2).getReg();
12059     Register oldval = MI.getOperand(3).getReg();
12060     Register newval = MI.getOperand(4).getReg();
12061     DebugLoc dl = MI.getDebugLoc();
12062 
12063     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12064     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12065     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12066     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12067     F->insert(It, loop1MBB);
12068     F->insert(It, loop2MBB);
12069     F->insert(It, midMBB);
12070     F->insert(It, exitMBB);
12071     exitMBB->splice(exitMBB->begin(), BB,
12072                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12073     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12074 
12075     MachineRegisterInfo &RegInfo = F->getRegInfo();
12076     const TargetRegisterClass *RC =
12077         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12078     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12079 
12080     Register PtrReg = RegInfo.createVirtualRegister(RC);
12081     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12082     Register ShiftReg =
12083         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12084     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12085     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12086     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12087     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12088     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12089     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12090     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12091     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12092     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12093     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12094     Register Ptr1Reg;
12095     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12096     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12097     //  thisMBB:
12098     //   ...
12099     //   fallthrough --> loopMBB
12100     BB->addSuccessor(loop1MBB);
12101 
12102     // The 4-byte load must be aligned, while a char or short may be
12103     // anywhere in the word.  Hence all this nasty bookkeeping code.
12104     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12105     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12106     //   xori shift, shift1, 24 [16]
12107     //   rlwinm ptr, ptr1, 0, 0, 29
12108     //   slw newval2, newval, shift
12109     //   slw oldval2, oldval,shift
12110     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12111     //   slw mask, mask2, shift
12112     //   and newval3, newval2, mask
12113     //   and oldval3, oldval2, mask
12114     // loop1MBB:
12115     //   lwarx tmpDest, ptr
12116     //   and tmp, tmpDest, mask
12117     //   cmpw tmp, oldval3
12118     //   bne- midMBB
12119     // loop2MBB:
12120     //   andc tmp2, tmpDest, mask
12121     //   or tmp4, tmp2, newval3
12122     //   stwcx. tmp4, ptr
12123     //   bne- loop1MBB
12124     //   b exitBB
12125     // midMBB:
12126     //   stwcx. tmpDest, ptr
12127     // exitBB:
12128     //   srw dest, tmpDest, shift
12129     if (ptrA != ZeroReg) {
12130       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12131       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12132           .addReg(ptrA)
12133           .addReg(ptrB);
12134     } else {
12135       Ptr1Reg = ptrB;
12136     }
12137 
12138     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12139     // mode.
12140     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12141         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12142         .addImm(3)
12143         .addImm(27)
12144         .addImm(is8bit ? 28 : 27);
12145     if (!isLittleEndian)
12146       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12147           .addReg(Shift1Reg)
12148           .addImm(is8bit ? 24 : 16);
12149     if (is64bit)
12150       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12151           .addReg(Ptr1Reg)
12152           .addImm(0)
12153           .addImm(61);
12154     else
12155       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12156           .addReg(Ptr1Reg)
12157           .addImm(0)
12158           .addImm(0)
12159           .addImm(29);
12160     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12161         .addReg(newval)
12162         .addReg(ShiftReg);
12163     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12164         .addReg(oldval)
12165         .addReg(ShiftReg);
12166     if (is8bit)
12167       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12168     else {
12169       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12170       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12171           .addReg(Mask3Reg)
12172           .addImm(65535);
12173     }
12174     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12175         .addReg(Mask2Reg)
12176         .addReg(ShiftReg);
12177     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12178         .addReg(NewVal2Reg)
12179         .addReg(MaskReg);
12180     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12181         .addReg(OldVal2Reg)
12182         .addReg(MaskReg);
12183 
12184     BB = loop1MBB;
12185     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12186         .addReg(ZeroReg)
12187         .addReg(PtrReg);
12188     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12189         .addReg(TmpDestReg)
12190         .addReg(MaskReg);
12191     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12192         .addReg(TmpReg)
12193         .addReg(OldVal3Reg);
12194     BuildMI(BB, dl, TII->get(PPC::BCC))
12195         .addImm(PPC::PRED_NE)
12196         .addReg(PPC::CR0)
12197         .addMBB(midMBB);
12198     BB->addSuccessor(loop2MBB);
12199     BB->addSuccessor(midMBB);
12200 
12201     BB = loop2MBB;
12202     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12203         .addReg(TmpDestReg)
12204         .addReg(MaskReg);
12205     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12206         .addReg(Tmp2Reg)
12207         .addReg(NewVal3Reg);
12208     BuildMI(BB, dl, TII->get(PPC::STWCX))
12209         .addReg(Tmp4Reg)
12210         .addReg(ZeroReg)
12211         .addReg(PtrReg);
12212     BuildMI(BB, dl, TII->get(PPC::BCC))
12213         .addImm(PPC::PRED_NE)
12214         .addReg(PPC::CR0)
12215         .addMBB(loop1MBB);
12216     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12217     BB->addSuccessor(loop1MBB);
12218     BB->addSuccessor(exitMBB);
12219 
12220     BB = midMBB;
12221     BuildMI(BB, dl, TII->get(PPC::STWCX))
12222         .addReg(TmpDestReg)
12223         .addReg(ZeroReg)
12224         .addReg(PtrReg);
12225     BB->addSuccessor(exitMBB);
12226 
12227     //  exitMBB:
12228     //   ...
12229     BB = exitMBB;
12230     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12231         .addReg(TmpReg)
12232         .addReg(ShiftReg);
12233   } else if (MI.getOpcode() == PPC::FADDrtz) {
12234     // This pseudo performs an FADD with rounding mode temporarily forced
12235     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12236     // is not modeled at the SelectionDAG level.
12237     Register Dest = MI.getOperand(0).getReg();
12238     Register Src1 = MI.getOperand(1).getReg();
12239     Register Src2 = MI.getOperand(2).getReg();
12240     DebugLoc dl = MI.getDebugLoc();
12241 
12242     MachineRegisterInfo &RegInfo = F->getRegInfo();
12243     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12244 
12245     // Save FPSCR value.
12246     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12247 
12248     // Set rounding mode to round-to-zero.
12249     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
12250     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
12251 
12252     // Perform addition.
12253     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
12254 
12255     // Restore FPSCR value.
12256     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12257   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12258              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12259              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12260              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12261     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12262                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12263                           ? PPC::ANDI8_rec
12264                           : PPC::ANDI_rec;
12265     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12266                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12267 
12268     MachineRegisterInfo &RegInfo = F->getRegInfo();
12269     Register Dest = RegInfo.createVirtualRegister(
12270         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12271 
12272     DebugLoc Dl = MI.getDebugLoc();
12273     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12274         .addReg(MI.getOperand(1).getReg())
12275         .addImm(1);
12276     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12277             MI.getOperand(0).getReg())
12278         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12279   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12280     DebugLoc Dl = MI.getDebugLoc();
12281     MachineRegisterInfo &RegInfo = F->getRegInfo();
12282     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12283     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12284     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12285             MI.getOperand(0).getReg())
12286         .addReg(CRReg);
12287   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12288     DebugLoc Dl = MI.getDebugLoc();
12289     unsigned Imm = MI.getOperand(1).getImm();
12290     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12291     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12292             MI.getOperand(0).getReg())
12293         .addReg(PPC::CR0EQ);
12294   } else if (MI.getOpcode() == PPC::SETRNDi) {
12295     DebugLoc dl = MI.getDebugLoc();
12296     Register OldFPSCRReg = MI.getOperand(0).getReg();
12297 
12298     // Save FPSCR value.
12299     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12300 
12301     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12302     // the following settings:
12303     //   00 Round to nearest
12304     //   01 Round to 0
12305     //   10 Round to +inf
12306     //   11 Round to -inf
12307 
12308     // When the operand is immediate, using the two least significant bits of
12309     // the immediate to set the bits 62:63 of FPSCR.
12310     unsigned Mode = MI.getOperand(1).getImm();
12311     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12312       .addImm(31);
12313 
12314     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12315       .addImm(30);
12316   } else if (MI.getOpcode() == PPC::SETRND) {
12317     DebugLoc dl = MI.getDebugLoc();
12318 
12319     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12320     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12321     // If the target doesn't have DirectMove, we should use stack to do the
12322     // conversion, because the target doesn't have the instructions like mtvsrd
12323     // or mfvsrd to do this conversion directly.
12324     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12325       if (Subtarget.hasDirectMove()) {
12326         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12327           .addReg(SrcReg);
12328       } else {
12329         // Use stack to do the register copy.
12330         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12331         MachineRegisterInfo &RegInfo = F->getRegInfo();
12332         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12333         if (RC == &PPC::F8RCRegClass) {
12334           // Copy register from F8RCRegClass to G8RCRegclass.
12335           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12336                  "Unsupported RegClass.");
12337 
12338           StoreOp = PPC::STFD;
12339           LoadOp = PPC::LD;
12340         } else {
12341           // Copy register from G8RCRegClass to F8RCRegclass.
12342           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12343                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12344                  "Unsupported RegClass.");
12345         }
12346 
12347         MachineFrameInfo &MFI = F->getFrameInfo();
12348         int FrameIdx = MFI.CreateStackObject(8, 8, false);
12349 
12350         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12351             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12352             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12353             MFI.getObjectAlign(FrameIdx));
12354 
12355         // Store the SrcReg into the stack.
12356         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12357           .addReg(SrcReg)
12358           .addImm(0)
12359           .addFrameIndex(FrameIdx)
12360           .addMemOperand(MMOStore);
12361 
12362         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12363             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12364             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12365             MFI.getObjectAlign(FrameIdx));
12366 
12367         // Load from the stack where SrcReg is stored, and save to DestReg,
12368         // so we have done the RegClass conversion from RegClass::SrcReg to
12369         // RegClass::DestReg.
12370         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12371           .addImm(0)
12372           .addFrameIndex(FrameIdx)
12373           .addMemOperand(MMOLoad);
12374       }
12375     };
12376 
12377     Register OldFPSCRReg = MI.getOperand(0).getReg();
12378 
12379     // Save FPSCR value.
12380     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12381 
12382     // When the operand is gprc register, use two least significant bits of the
12383     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12384     //
12385     // copy OldFPSCRTmpReg, OldFPSCRReg
12386     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12387     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12388     // copy NewFPSCRReg, NewFPSCRTmpReg
12389     // mtfsf 255, NewFPSCRReg
12390     MachineOperand SrcOp = MI.getOperand(1);
12391     MachineRegisterInfo &RegInfo = F->getRegInfo();
12392     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12393 
12394     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12395 
12396     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12397     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12398 
12399     // The first operand of INSERT_SUBREG should be a register which has
12400     // subregisters, we only care about its RegClass, so we should use an
12401     // IMPLICIT_DEF register.
12402     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12403     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12404       .addReg(ImDefReg)
12405       .add(SrcOp)
12406       .addImm(1);
12407 
12408     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12409     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12410       .addReg(OldFPSCRTmpReg)
12411       .addReg(ExtSrcReg)
12412       .addImm(0)
12413       .addImm(62);
12414 
12415     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12416     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12417 
12418     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12419     // bits of FPSCR.
12420     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12421       .addImm(255)
12422       .addReg(NewFPSCRReg)
12423       .addImm(0)
12424       .addImm(0);
12425   } else {
12426     llvm_unreachable("Unexpected instr type to insert");
12427   }
12428 
12429   MI.eraseFromParent(); // The pseudo instruction is gone now.
12430   return BB;
12431 }
12432 
12433 //===----------------------------------------------------------------------===//
12434 // Target Optimization Hooks
12435 //===----------------------------------------------------------------------===//
12436 
12437 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12438   // For the estimates, convergence is quadratic, so we essentially double the
12439   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12440   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12441   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12442   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12443   if (VT.getScalarType() == MVT::f64)
12444     RefinementSteps++;
12445   return RefinementSteps;
12446 }
12447 
12448 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12449                                            int Enabled, int &RefinementSteps,
12450                                            bool &UseOneConstNR,
12451                                            bool Reciprocal) const {
12452   EVT VT = Operand.getValueType();
12453   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12454       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12455       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12456       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12457       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12458       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12459     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12460       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12461 
12462     // The Newton-Raphson computation with a single constant does not provide
12463     // enough accuracy on some CPUs.
12464     UseOneConstNR = !Subtarget.needsTwoConstNR();
12465     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12466   }
12467   return SDValue();
12468 }
12469 
12470 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12471                                             int Enabled,
12472                                             int &RefinementSteps) const {
12473   EVT VT = Operand.getValueType();
12474   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12475       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12476       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12477       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12478       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12479       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12480     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12481       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12482     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12483   }
12484   return SDValue();
12485 }
12486 
12487 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12488   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12489   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12490   // enabled for division), this functionality is redundant with the default
12491   // combiner logic (once the division -> reciprocal/multiply transformation
12492   // has taken place). As a result, this matters more for older cores than for
12493   // newer ones.
12494 
12495   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12496   // reciprocal if there are two or more FDIVs (for embedded cores with only
12497   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12498   switch (Subtarget.getCPUDirective()) {
12499   default:
12500     return 3;
12501   case PPC::DIR_440:
12502   case PPC::DIR_A2:
12503   case PPC::DIR_E500:
12504   case PPC::DIR_E500mc:
12505   case PPC::DIR_E5500:
12506     return 2;
12507   }
12508 }
12509 
12510 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12511 // collapsed, and so we need to look through chains of them.
12512 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12513                                      int64_t& Offset, SelectionDAG &DAG) {
12514   if (DAG.isBaseWithConstantOffset(Loc)) {
12515     Base = Loc.getOperand(0);
12516     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12517 
12518     // The base might itself be a base plus an offset, and if so, accumulate
12519     // that as well.
12520     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12521   }
12522 }
12523 
12524 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12525                             unsigned Bytes, int Dist,
12526                             SelectionDAG &DAG) {
12527   if (VT.getSizeInBits() / 8 != Bytes)
12528     return false;
12529 
12530   SDValue BaseLoc = Base->getBasePtr();
12531   if (Loc.getOpcode() == ISD::FrameIndex) {
12532     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12533       return false;
12534     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12535     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12536     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12537     int FS  = MFI.getObjectSize(FI);
12538     int BFS = MFI.getObjectSize(BFI);
12539     if (FS != BFS || FS != (int)Bytes) return false;
12540     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12541   }
12542 
12543   SDValue Base1 = Loc, Base2 = BaseLoc;
12544   int64_t Offset1 = 0, Offset2 = 0;
12545   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12546   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12547   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12548     return true;
12549 
12550   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12551   const GlobalValue *GV1 = nullptr;
12552   const GlobalValue *GV2 = nullptr;
12553   Offset1 = 0;
12554   Offset2 = 0;
12555   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12556   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12557   if (isGA1 && isGA2 && GV1 == GV2)
12558     return Offset1 == (Offset2 + Dist*Bytes);
12559   return false;
12560 }
12561 
12562 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12563 // not enforce equality of the chain operands.
12564 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12565                             unsigned Bytes, int Dist,
12566                             SelectionDAG &DAG) {
12567   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12568     EVT VT = LS->getMemoryVT();
12569     SDValue Loc = LS->getBasePtr();
12570     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12571   }
12572 
12573   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12574     EVT VT;
12575     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12576     default: return false;
12577     case Intrinsic::ppc_qpx_qvlfd:
12578     case Intrinsic::ppc_qpx_qvlfda:
12579       VT = MVT::v4f64;
12580       break;
12581     case Intrinsic::ppc_qpx_qvlfs:
12582     case Intrinsic::ppc_qpx_qvlfsa:
12583       VT = MVT::v4f32;
12584       break;
12585     case Intrinsic::ppc_qpx_qvlfcd:
12586     case Intrinsic::ppc_qpx_qvlfcda:
12587       VT = MVT::v2f64;
12588       break;
12589     case Intrinsic::ppc_qpx_qvlfcs:
12590     case Intrinsic::ppc_qpx_qvlfcsa:
12591       VT = MVT::v2f32;
12592       break;
12593     case Intrinsic::ppc_qpx_qvlfiwa:
12594     case Intrinsic::ppc_qpx_qvlfiwz:
12595     case Intrinsic::ppc_altivec_lvx:
12596     case Intrinsic::ppc_altivec_lvxl:
12597     case Intrinsic::ppc_vsx_lxvw4x:
12598     case Intrinsic::ppc_vsx_lxvw4x_be:
12599       VT = MVT::v4i32;
12600       break;
12601     case Intrinsic::ppc_vsx_lxvd2x:
12602     case Intrinsic::ppc_vsx_lxvd2x_be:
12603       VT = MVT::v2f64;
12604       break;
12605     case Intrinsic::ppc_altivec_lvebx:
12606       VT = MVT::i8;
12607       break;
12608     case Intrinsic::ppc_altivec_lvehx:
12609       VT = MVT::i16;
12610       break;
12611     case Intrinsic::ppc_altivec_lvewx:
12612       VT = MVT::i32;
12613       break;
12614     }
12615 
12616     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12617   }
12618 
12619   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12620     EVT VT;
12621     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12622     default: return false;
12623     case Intrinsic::ppc_qpx_qvstfd:
12624     case Intrinsic::ppc_qpx_qvstfda:
12625       VT = MVT::v4f64;
12626       break;
12627     case Intrinsic::ppc_qpx_qvstfs:
12628     case Intrinsic::ppc_qpx_qvstfsa:
12629       VT = MVT::v4f32;
12630       break;
12631     case Intrinsic::ppc_qpx_qvstfcd:
12632     case Intrinsic::ppc_qpx_qvstfcda:
12633       VT = MVT::v2f64;
12634       break;
12635     case Intrinsic::ppc_qpx_qvstfcs:
12636     case Intrinsic::ppc_qpx_qvstfcsa:
12637       VT = MVT::v2f32;
12638       break;
12639     case Intrinsic::ppc_qpx_qvstfiw:
12640     case Intrinsic::ppc_qpx_qvstfiwa:
12641     case Intrinsic::ppc_altivec_stvx:
12642     case Intrinsic::ppc_altivec_stvxl:
12643     case Intrinsic::ppc_vsx_stxvw4x:
12644       VT = MVT::v4i32;
12645       break;
12646     case Intrinsic::ppc_vsx_stxvd2x:
12647       VT = MVT::v2f64;
12648       break;
12649     case Intrinsic::ppc_vsx_stxvw4x_be:
12650       VT = MVT::v4i32;
12651       break;
12652     case Intrinsic::ppc_vsx_stxvd2x_be:
12653       VT = MVT::v2f64;
12654       break;
12655     case Intrinsic::ppc_altivec_stvebx:
12656       VT = MVT::i8;
12657       break;
12658     case Intrinsic::ppc_altivec_stvehx:
12659       VT = MVT::i16;
12660       break;
12661     case Intrinsic::ppc_altivec_stvewx:
12662       VT = MVT::i32;
12663       break;
12664     }
12665 
12666     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12667   }
12668 
12669   return false;
12670 }
12671 
12672 // Return true is there is a nearyby consecutive load to the one provided
12673 // (regardless of alignment). We search up and down the chain, looking though
12674 // token factors and other loads (but nothing else). As a result, a true result
12675 // indicates that it is safe to create a new consecutive load adjacent to the
12676 // load provided.
12677 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12678   SDValue Chain = LD->getChain();
12679   EVT VT = LD->getMemoryVT();
12680 
12681   SmallSet<SDNode *, 16> LoadRoots;
12682   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12683   SmallSet<SDNode *, 16> Visited;
12684 
12685   // First, search up the chain, branching to follow all token-factor operands.
12686   // If we find a consecutive load, then we're done, otherwise, record all
12687   // nodes just above the top-level loads and token factors.
12688   while (!Queue.empty()) {
12689     SDNode *ChainNext = Queue.pop_back_val();
12690     if (!Visited.insert(ChainNext).second)
12691       continue;
12692 
12693     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12694       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12695         return true;
12696 
12697       if (!Visited.count(ChainLD->getChain().getNode()))
12698         Queue.push_back(ChainLD->getChain().getNode());
12699     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12700       for (const SDUse &O : ChainNext->ops())
12701         if (!Visited.count(O.getNode()))
12702           Queue.push_back(O.getNode());
12703     } else
12704       LoadRoots.insert(ChainNext);
12705   }
12706 
12707   // Second, search down the chain, starting from the top-level nodes recorded
12708   // in the first phase. These top-level nodes are the nodes just above all
12709   // loads and token factors. Starting with their uses, recursively look though
12710   // all loads (just the chain uses) and token factors to find a consecutive
12711   // load.
12712   Visited.clear();
12713   Queue.clear();
12714 
12715   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12716        IE = LoadRoots.end(); I != IE; ++I) {
12717     Queue.push_back(*I);
12718 
12719     while (!Queue.empty()) {
12720       SDNode *LoadRoot = Queue.pop_back_val();
12721       if (!Visited.insert(LoadRoot).second)
12722         continue;
12723 
12724       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12725         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12726           return true;
12727 
12728       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12729            UE = LoadRoot->use_end(); UI != UE; ++UI)
12730         if (((isa<MemSDNode>(*UI) &&
12731             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12732             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12733           Queue.push_back(*UI);
12734     }
12735   }
12736 
12737   return false;
12738 }
12739 
12740 /// This function is called when we have proved that a SETCC node can be replaced
12741 /// by subtraction (and other supporting instructions) so that the result of
12742 /// comparison is kept in a GPR instead of CR. This function is purely for
12743 /// codegen purposes and has some flags to guide the codegen process.
12744 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12745                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12746   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12747 
12748   // Zero extend the operands to the largest legal integer. Originally, they
12749   // must be of a strictly smaller size.
12750   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12751                          DAG.getConstant(Size, DL, MVT::i32));
12752   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12753                          DAG.getConstant(Size, DL, MVT::i32));
12754 
12755   // Swap if needed. Depends on the condition code.
12756   if (Swap)
12757     std::swap(Op0, Op1);
12758 
12759   // Subtract extended integers.
12760   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12761 
12762   // Move the sign bit to the least significant position and zero out the rest.
12763   // Now the least significant bit carries the result of original comparison.
12764   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12765                              DAG.getConstant(Size - 1, DL, MVT::i32));
12766   auto Final = Shifted;
12767 
12768   // Complement the result if needed. Based on the condition code.
12769   if (Complement)
12770     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12771                         DAG.getConstant(1, DL, MVT::i64));
12772 
12773   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12774 }
12775 
12776 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12777                                                   DAGCombinerInfo &DCI) const {
12778   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12779 
12780   SelectionDAG &DAG = DCI.DAG;
12781   SDLoc DL(N);
12782 
12783   // Size of integers being compared has a critical role in the following
12784   // analysis, so we prefer to do this when all types are legal.
12785   if (!DCI.isAfterLegalizeDAG())
12786     return SDValue();
12787 
12788   // If all users of SETCC extend its value to a legal integer type
12789   // then we replace SETCC with a subtraction
12790   for (SDNode::use_iterator UI = N->use_begin(),
12791        UE = N->use_end(); UI != UE; ++UI) {
12792     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12793       return SDValue();
12794   }
12795 
12796   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12797   auto OpSize = N->getOperand(0).getValueSizeInBits();
12798 
12799   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12800 
12801   if (OpSize < Size) {
12802     switch (CC) {
12803     default: break;
12804     case ISD::SETULT:
12805       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12806     case ISD::SETULE:
12807       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12808     case ISD::SETUGT:
12809       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12810     case ISD::SETUGE:
12811       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12812     }
12813   }
12814 
12815   return SDValue();
12816 }
12817 
12818 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12819                                                   DAGCombinerInfo &DCI) const {
12820   SelectionDAG &DAG = DCI.DAG;
12821   SDLoc dl(N);
12822 
12823   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12824   // If we're tracking CR bits, we need to be careful that we don't have:
12825   //   trunc(binary-ops(zext(x), zext(y)))
12826   // or
12827   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12828   // such that we're unnecessarily moving things into GPRs when it would be
12829   // better to keep them in CR bits.
12830 
12831   // Note that trunc here can be an actual i1 trunc, or can be the effective
12832   // truncation that comes from a setcc or select_cc.
12833   if (N->getOpcode() == ISD::TRUNCATE &&
12834       N->getValueType(0) != MVT::i1)
12835     return SDValue();
12836 
12837   if (N->getOperand(0).getValueType() != MVT::i32 &&
12838       N->getOperand(0).getValueType() != MVT::i64)
12839     return SDValue();
12840 
12841   if (N->getOpcode() == ISD::SETCC ||
12842       N->getOpcode() == ISD::SELECT_CC) {
12843     // If we're looking at a comparison, then we need to make sure that the
12844     // high bits (all except for the first) don't matter the result.
12845     ISD::CondCode CC =
12846       cast<CondCodeSDNode>(N->getOperand(
12847         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12848     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12849 
12850     if (ISD::isSignedIntSetCC(CC)) {
12851       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12852           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12853         return SDValue();
12854     } else if (ISD::isUnsignedIntSetCC(CC)) {
12855       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12856                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12857           !DAG.MaskedValueIsZero(N->getOperand(1),
12858                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12859         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12860                                              : SDValue());
12861     } else {
12862       // This is neither a signed nor an unsigned comparison, just make sure
12863       // that the high bits are equal.
12864       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12865       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12866 
12867       // We don't really care about what is known about the first bit (if
12868       // anything), so clear it in all masks prior to comparing them.
12869       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12870       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12871 
12872       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12873         return SDValue();
12874     }
12875   }
12876 
12877   // We now know that the higher-order bits are irrelevant, we just need to
12878   // make sure that all of the intermediate operations are bit operations, and
12879   // all inputs are extensions.
12880   if (N->getOperand(0).getOpcode() != ISD::AND &&
12881       N->getOperand(0).getOpcode() != ISD::OR  &&
12882       N->getOperand(0).getOpcode() != ISD::XOR &&
12883       N->getOperand(0).getOpcode() != ISD::SELECT &&
12884       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12885       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12886       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12887       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12888       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12889     return SDValue();
12890 
12891   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12892       N->getOperand(1).getOpcode() != ISD::AND &&
12893       N->getOperand(1).getOpcode() != ISD::OR  &&
12894       N->getOperand(1).getOpcode() != ISD::XOR &&
12895       N->getOperand(1).getOpcode() != ISD::SELECT &&
12896       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12897       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12898       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12899       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12900       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12901     return SDValue();
12902 
12903   SmallVector<SDValue, 4> Inputs;
12904   SmallVector<SDValue, 8> BinOps, PromOps;
12905   SmallPtrSet<SDNode *, 16> Visited;
12906 
12907   for (unsigned i = 0; i < 2; ++i) {
12908     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12909           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12910           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12911           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12912         isa<ConstantSDNode>(N->getOperand(i)))
12913       Inputs.push_back(N->getOperand(i));
12914     else
12915       BinOps.push_back(N->getOperand(i));
12916 
12917     if (N->getOpcode() == ISD::TRUNCATE)
12918       break;
12919   }
12920 
12921   // Visit all inputs, collect all binary operations (and, or, xor and
12922   // select) that are all fed by extensions.
12923   while (!BinOps.empty()) {
12924     SDValue BinOp = BinOps.back();
12925     BinOps.pop_back();
12926 
12927     if (!Visited.insert(BinOp.getNode()).second)
12928       continue;
12929 
12930     PromOps.push_back(BinOp);
12931 
12932     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12933       // The condition of the select is not promoted.
12934       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12935         continue;
12936       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12937         continue;
12938 
12939       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12940             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12941             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12942            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12943           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12944         Inputs.push_back(BinOp.getOperand(i));
12945       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12946                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12947                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12948                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12949                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12950                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12951                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12952                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12953                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12954         BinOps.push_back(BinOp.getOperand(i));
12955       } else {
12956         // We have an input that is not an extension or another binary
12957         // operation; we'll abort this transformation.
12958         return SDValue();
12959       }
12960     }
12961   }
12962 
12963   // Make sure that this is a self-contained cluster of operations (which
12964   // is not quite the same thing as saying that everything has only one
12965   // use).
12966   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12967     if (isa<ConstantSDNode>(Inputs[i]))
12968       continue;
12969 
12970     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12971                               UE = Inputs[i].getNode()->use_end();
12972          UI != UE; ++UI) {
12973       SDNode *User = *UI;
12974       if (User != N && !Visited.count(User))
12975         return SDValue();
12976 
12977       // Make sure that we're not going to promote the non-output-value
12978       // operand(s) or SELECT or SELECT_CC.
12979       // FIXME: Although we could sometimes handle this, and it does occur in
12980       // practice that one of the condition inputs to the select is also one of
12981       // the outputs, we currently can't deal with this.
12982       if (User->getOpcode() == ISD::SELECT) {
12983         if (User->getOperand(0) == Inputs[i])
12984           return SDValue();
12985       } else if (User->getOpcode() == ISD::SELECT_CC) {
12986         if (User->getOperand(0) == Inputs[i] ||
12987             User->getOperand(1) == Inputs[i])
12988           return SDValue();
12989       }
12990     }
12991   }
12992 
12993   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12994     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12995                               UE = PromOps[i].getNode()->use_end();
12996          UI != UE; ++UI) {
12997       SDNode *User = *UI;
12998       if (User != N && !Visited.count(User))
12999         return SDValue();
13000 
13001       // Make sure that we're not going to promote the non-output-value
13002       // operand(s) or SELECT or SELECT_CC.
13003       // FIXME: Although we could sometimes handle this, and it does occur in
13004       // practice that one of the condition inputs to the select is also one of
13005       // the outputs, we currently can't deal with this.
13006       if (User->getOpcode() == ISD::SELECT) {
13007         if (User->getOperand(0) == PromOps[i])
13008           return SDValue();
13009       } else if (User->getOpcode() == ISD::SELECT_CC) {
13010         if (User->getOperand(0) == PromOps[i] ||
13011             User->getOperand(1) == PromOps[i])
13012           return SDValue();
13013       }
13014     }
13015   }
13016 
13017   // Replace all inputs with the extension operand.
13018   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13019     // Constants may have users outside the cluster of to-be-promoted nodes,
13020     // and so we need to replace those as we do the promotions.
13021     if (isa<ConstantSDNode>(Inputs[i]))
13022       continue;
13023     else
13024       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13025   }
13026 
13027   std::list<HandleSDNode> PromOpHandles;
13028   for (auto &PromOp : PromOps)
13029     PromOpHandles.emplace_back(PromOp);
13030 
13031   // Replace all operations (these are all the same, but have a different
13032   // (i1) return type). DAG.getNode will validate that the types of
13033   // a binary operator match, so go through the list in reverse so that
13034   // we've likely promoted both operands first. Any intermediate truncations or
13035   // extensions disappear.
13036   while (!PromOpHandles.empty()) {
13037     SDValue PromOp = PromOpHandles.back().getValue();
13038     PromOpHandles.pop_back();
13039 
13040     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13041         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13042         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13043         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13044       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13045           PromOp.getOperand(0).getValueType() != MVT::i1) {
13046         // The operand is not yet ready (see comment below).
13047         PromOpHandles.emplace_front(PromOp);
13048         continue;
13049       }
13050 
13051       SDValue RepValue = PromOp.getOperand(0);
13052       if (isa<ConstantSDNode>(RepValue))
13053         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13054 
13055       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13056       continue;
13057     }
13058 
13059     unsigned C;
13060     switch (PromOp.getOpcode()) {
13061     default:             C = 0; break;
13062     case ISD::SELECT:    C = 1; break;
13063     case ISD::SELECT_CC: C = 2; break;
13064     }
13065 
13066     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13067          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13068         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13069          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13070       // The to-be-promoted operands of this node have not yet been
13071       // promoted (this should be rare because we're going through the
13072       // list backward, but if one of the operands has several users in
13073       // this cluster of to-be-promoted nodes, it is possible).
13074       PromOpHandles.emplace_front(PromOp);
13075       continue;
13076     }
13077 
13078     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13079                                 PromOp.getNode()->op_end());
13080 
13081     // If there are any constant inputs, make sure they're replaced now.
13082     for (unsigned i = 0; i < 2; ++i)
13083       if (isa<ConstantSDNode>(Ops[C+i]))
13084         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13085 
13086     DAG.ReplaceAllUsesOfValueWith(PromOp,
13087       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13088   }
13089 
13090   // Now we're left with the initial truncation itself.
13091   if (N->getOpcode() == ISD::TRUNCATE)
13092     return N->getOperand(0);
13093 
13094   // Otherwise, this is a comparison. The operands to be compared have just
13095   // changed type (to i1), but everything else is the same.
13096   return SDValue(N, 0);
13097 }
13098 
13099 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13100                                                   DAGCombinerInfo &DCI) const {
13101   SelectionDAG &DAG = DCI.DAG;
13102   SDLoc dl(N);
13103 
13104   // If we're tracking CR bits, we need to be careful that we don't have:
13105   //   zext(binary-ops(trunc(x), trunc(y)))
13106   // or
13107   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13108   // such that we're unnecessarily moving things into CR bits that can more
13109   // efficiently stay in GPRs. Note that if we're not certain that the high
13110   // bits are set as required by the final extension, we still may need to do
13111   // some masking to get the proper behavior.
13112 
13113   // This same functionality is important on PPC64 when dealing with
13114   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13115   // the return values of functions. Because it is so similar, it is handled
13116   // here as well.
13117 
13118   if (N->getValueType(0) != MVT::i32 &&
13119       N->getValueType(0) != MVT::i64)
13120     return SDValue();
13121 
13122   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13123         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13124     return SDValue();
13125 
13126   if (N->getOperand(0).getOpcode() != ISD::AND &&
13127       N->getOperand(0).getOpcode() != ISD::OR  &&
13128       N->getOperand(0).getOpcode() != ISD::XOR &&
13129       N->getOperand(0).getOpcode() != ISD::SELECT &&
13130       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13131     return SDValue();
13132 
13133   SmallVector<SDValue, 4> Inputs;
13134   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13135   SmallPtrSet<SDNode *, 16> Visited;
13136 
13137   // Visit all inputs, collect all binary operations (and, or, xor and
13138   // select) that are all fed by truncations.
13139   while (!BinOps.empty()) {
13140     SDValue BinOp = BinOps.back();
13141     BinOps.pop_back();
13142 
13143     if (!Visited.insert(BinOp.getNode()).second)
13144       continue;
13145 
13146     PromOps.push_back(BinOp);
13147 
13148     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13149       // The condition of the select is not promoted.
13150       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13151         continue;
13152       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13153         continue;
13154 
13155       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13156           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13157         Inputs.push_back(BinOp.getOperand(i));
13158       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13159                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13160                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13161                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13162                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13163         BinOps.push_back(BinOp.getOperand(i));
13164       } else {
13165         // We have an input that is not a truncation or another binary
13166         // operation; we'll abort this transformation.
13167         return SDValue();
13168       }
13169     }
13170   }
13171 
13172   // The operands of a select that must be truncated when the select is
13173   // promoted because the operand is actually part of the to-be-promoted set.
13174   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13175 
13176   // Make sure that this is a self-contained cluster of operations (which
13177   // is not quite the same thing as saying that everything has only one
13178   // use).
13179   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13180     if (isa<ConstantSDNode>(Inputs[i]))
13181       continue;
13182 
13183     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13184                               UE = Inputs[i].getNode()->use_end();
13185          UI != UE; ++UI) {
13186       SDNode *User = *UI;
13187       if (User != N && !Visited.count(User))
13188         return SDValue();
13189 
13190       // If we're going to promote the non-output-value operand(s) or SELECT or
13191       // SELECT_CC, record them for truncation.
13192       if (User->getOpcode() == ISD::SELECT) {
13193         if (User->getOperand(0) == Inputs[i])
13194           SelectTruncOp[0].insert(std::make_pair(User,
13195                                     User->getOperand(0).getValueType()));
13196       } else if (User->getOpcode() == ISD::SELECT_CC) {
13197         if (User->getOperand(0) == Inputs[i])
13198           SelectTruncOp[0].insert(std::make_pair(User,
13199                                     User->getOperand(0).getValueType()));
13200         if (User->getOperand(1) == Inputs[i])
13201           SelectTruncOp[1].insert(std::make_pair(User,
13202                                     User->getOperand(1).getValueType()));
13203       }
13204     }
13205   }
13206 
13207   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13208     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13209                               UE = PromOps[i].getNode()->use_end();
13210          UI != UE; ++UI) {
13211       SDNode *User = *UI;
13212       if (User != N && !Visited.count(User))
13213         return SDValue();
13214 
13215       // If we're going to promote the non-output-value operand(s) or SELECT or
13216       // SELECT_CC, record them for truncation.
13217       if (User->getOpcode() == ISD::SELECT) {
13218         if (User->getOperand(0) == PromOps[i])
13219           SelectTruncOp[0].insert(std::make_pair(User,
13220                                     User->getOperand(0).getValueType()));
13221       } else if (User->getOpcode() == ISD::SELECT_CC) {
13222         if (User->getOperand(0) == PromOps[i])
13223           SelectTruncOp[0].insert(std::make_pair(User,
13224                                     User->getOperand(0).getValueType()));
13225         if (User->getOperand(1) == PromOps[i])
13226           SelectTruncOp[1].insert(std::make_pair(User,
13227                                     User->getOperand(1).getValueType()));
13228       }
13229     }
13230   }
13231 
13232   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13233   bool ReallyNeedsExt = false;
13234   if (N->getOpcode() != ISD::ANY_EXTEND) {
13235     // If all of the inputs are not already sign/zero extended, then
13236     // we'll still need to do that at the end.
13237     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13238       if (isa<ConstantSDNode>(Inputs[i]))
13239         continue;
13240 
13241       unsigned OpBits =
13242         Inputs[i].getOperand(0).getValueSizeInBits();
13243       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13244 
13245       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13246            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13247                                   APInt::getHighBitsSet(OpBits,
13248                                                         OpBits-PromBits))) ||
13249           (N->getOpcode() == ISD::SIGN_EXTEND &&
13250            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13251              (OpBits-(PromBits-1)))) {
13252         ReallyNeedsExt = true;
13253         break;
13254       }
13255     }
13256   }
13257 
13258   // Replace all inputs, either with the truncation operand, or a
13259   // truncation or extension to the final output type.
13260   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13261     // Constant inputs need to be replaced with the to-be-promoted nodes that
13262     // use them because they might have users outside of the cluster of
13263     // promoted nodes.
13264     if (isa<ConstantSDNode>(Inputs[i]))
13265       continue;
13266 
13267     SDValue InSrc = Inputs[i].getOperand(0);
13268     if (Inputs[i].getValueType() == N->getValueType(0))
13269       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13270     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13271       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13272         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13273     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13274       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13275         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13276     else
13277       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13278         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13279   }
13280 
13281   std::list<HandleSDNode> PromOpHandles;
13282   for (auto &PromOp : PromOps)
13283     PromOpHandles.emplace_back(PromOp);
13284 
13285   // Replace all operations (these are all the same, but have a different
13286   // (promoted) return type). DAG.getNode will validate that the types of
13287   // a binary operator match, so go through the list in reverse so that
13288   // we've likely promoted both operands first.
13289   while (!PromOpHandles.empty()) {
13290     SDValue PromOp = PromOpHandles.back().getValue();
13291     PromOpHandles.pop_back();
13292 
13293     unsigned C;
13294     switch (PromOp.getOpcode()) {
13295     default:             C = 0; break;
13296     case ISD::SELECT:    C = 1; break;
13297     case ISD::SELECT_CC: C = 2; break;
13298     }
13299 
13300     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13301          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13302         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13303          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13304       // The to-be-promoted operands of this node have not yet been
13305       // promoted (this should be rare because we're going through the
13306       // list backward, but if one of the operands has several users in
13307       // this cluster of to-be-promoted nodes, it is possible).
13308       PromOpHandles.emplace_front(PromOp);
13309       continue;
13310     }
13311 
13312     // For SELECT and SELECT_CC nodes, we do a similar check for any
13313     // to-be-promoted comparison inputs.
13314     if (PromOp.getOpcode() == ISD::SELECT ||
13315         PromOp.getOpcode() == ISD::SELECT_CC) {
13316       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13317            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13318           (SelectTruncOp[1].count(PromOp.getNode()) &&
13319            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13320         PromOpHandles.emplace_front(PromOp);
13321         continue;
13322       }
13323     }
13324 
13325     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13326                                 PromOp.getNode()->op_end());
13327 
13328     // If this node has constant inputs, then they'll need to be promoted here.
13329     for (unsigned i = 0; i < 2; ++i) {
13330       if (!isa<ConstantSDNode>(Ops[C+i]))
13331         continue;
13332       if (Ops[C+i].getValueType() == N->getValueType(0))
13333         continue;
13334 
13335       if (N->getOpcode() == ISD::SIGN_EXTEND)
13336         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13337       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13338         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13339       else
13340         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13341     }
13342 
13343     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13344     // truncate them again to the original value type.
13345     if (PromOp.getOpcode() == ISD::SELECT ||
13346         PromOp.getOpcode() == ISD::SELECT_CC) {
13347       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13348       if (SI0 != SelectTruncOp[0].end())
13349         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13350       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13351       if (SI1 != SelectTruncOp[1].end())
13352         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13353     }
13354 
13355     DAG.ReplaceAllUsesOfValueWith(PromOp,
13356       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13357   }
13358 
13359   // Now we're left with the initial extension itself.
13360   if (!ReallyNeedsExt)
13361     return N->getOperand(0);
13362 
13363   // To zero extend, just mask off everything except for the first bit (in the
13364   // i1 case).
13365   if (N->getOpcode() == ISD::ZERO_EXTEND)
13366     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13367                        DAG.getConstant(APInt::getLowBitsSet(
13368                                          N->getValueSizeInBits(0), PromBits),
13369                                        dl, N->getValueType(0)));
13370 
13371   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13372          "Invalid extension type");
13373   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13374   SDValue ShiftCst =
13375       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13376   return DAG.getNode(
13377       ISD::SRA, dl, N->getValueType(0),
13378       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13379       ShiftCst);
13380 }
13381 
13382 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13383                                         DAGCombinerInfo &DCI) const {
13384   assert(N->getOpcode() == ISD::SETCC &&
13385          "Should be called with a SETCC node");
13386 
13387   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13388   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13389     SDValue LHS = N->getOperand(0);
13390     SDValue RHS = N->getOperand(1);
13391 
13392     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13393     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13394         LHS.hasOneUse())
13395       std::swap(LHS, RHS);
13396 
13397     // x == 0-y --> x+y == 0
13398     // x != 0-y --> x+y != 0
13399     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13400         RHS.hasOneUse()) {
13401       SDLoc DL(N);
13402       SelectionDAG &DAG = DCI.DAG;
13403       EVT VT = N->getValueType(0);
13404       EVT OpVT = LHS.getValueType();
13405       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13406       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13407     }
13408   }
13409 
13410   return DAGCombineTruncBoolExt(N, DCI);
13411 }
13412 
13413 // Is this an extending load from an f32 to an f64?
13414 static bool isFPExtLoad(SDValue Op) {
13415   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13416     return LD->getExtensionType() == ISD::EXTLOAD &&
13417       Op.getValueType() == MVT::f64;
13418   return false;
13419 }
13420 
13421 /// Reduces the number of fp-to-int conversion when building a vector.
13422 ///
13423 /// If this vector is built out of floating to integer conversions,
13424 /// transform it to a vector built out of floating point values followed by a
13425 /// single floating to integer conversion of the vector.
13426 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13427 /// becomes (fptosi (build_vector ($A, $B, ...)))
13428 SDValue PPCTargetLowering::
13429 combineElementTruncationToVectorTruncation(SDNode *N,
13430                                            DAGCombinerInfo &DCI) const {
13431   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13432          "Should be called with a BUILD_VECTOR node");
13433 
13434   SelectionDAG &DAG = DCI.DAG;
13435   SDLoc dl(N);
13436 
13437   SDValue FirstInput = N->getOperand(0);
13438   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13439          "The input operand must be an fp-to-int conversion.");
13440 
13441   // This combine happens after legalization so the fp_to_[su]i nodes are
13442   // already converted to PPCSISD nodes.
13443   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13444   if (FirstConversion == PPCISD::FCTIDZ ||
13445       FirstConversion == PPCISD::FCTIDUZ ||
13446       FirstConversion == PPCISD::FCTIWZ ||
13447       FirstConversion == PPCISD::FCTIWUZ) {
13448     bool IsSplat = true;
13449     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13450       FirstConversion == PPCISD::FCTIWUZ;
13451     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13452     SmallVector<SDValue, 4> Ops;
13453     EVT TargetVT = N->getValueType(0);
13454     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13455       SDValue NextOp = N->getOperand(i);
13456       if (NextOp.getOpcode() != PPCISD::MFVSR)
13457         return SDValue();
13458       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13459       if (NextConversion != FirstConversion)
13460         return SDValue();
13461       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13462       // This is not valid if the input was originally double precision. It is
13463       // also not profitable to do unless this is an extending load in which
13464       // case doing this combine will allow us to combine consecutive loads.
13465       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13466         return SDValue();
13467       if (N->getOperand(i) != FirstInput)
13468         IsSplat = false;
13469     }
13470 
13471     // If this is a splat, we leave it as-is since there will be only a single
13472     // fp-to-int conversion followed by a splat of the integer. This is better
13473     // for 32-bit and smaller ints and neutral for 64-bit ints.
13474     if (IsSplat)
13475       return SDValue();
13476 
13477     // Now that we know we have the right type of node, get its operands
13478     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13479       SDValue In = N->getOperand(i).getOperand(0);
13480       if (Is32Bit) {
13481         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13482         // here, we know that all inputs are extending loads so this is safe).
13483         if (In.isUndef())
13484           Ops.push_back(DAG.getUNDEF(SrcVT));
13485         else {
13486           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13487                                       MVT::f32, In.getOperand(0),
13488                                       DAG.getIntPtrConstant(1, dl));
13489           Ops.push_back(Trunc);
13490         }
13491       } else
13492         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13493     }
13494 
13495     unsigned Opcode;
13496     if (FirstConversion == PPCISD::FCTIDZ ||
13497         FirstConversion == PPCISD::FCTIWZ)
13498       Opcode = ISD::FP_TO_SINT;
13499     else
13500       Opcode = ISD::FP_TO_UINT;
13501 
13502     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13503     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13504     return DAG.getNode(Opcode, dl, TargetVT, BV);
13505   }
13506   return SDValue();
13507 }
13508 
13509 /// Reduce the number of loads when building a vector.
13510 ///
13511 /// Building a vector out of multiple loads can be converted to a load
13512 /// of the vector type if the loads are consecutive. If the loads are
13513 /// consecutive but in descending order, a shuffle is added at the end
13514 /// to reorder the vector.
13515 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13516   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13517          "Should be called with a BUILD_VECTOR node");
13518 
13519   SDLoc dl(N);
13520 
13521   // Return early for non byte-sized type, as they can't be consecutive.
13522   if (!N->getValueType(0).getVectorElementType().isByteSized())
13523     return SDValue();
13524 
13525   bool InputsAreConsecutiveLoads = true;
13526   bool InputsAreReverseConsecutive = true;
13527   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13528   SDValue FirstInput = N->getOperand(0);
13529   bool IsRoundOfExtLoad = false;
13530 
13531   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13532       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13533     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13534     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13535   }
13536   // Not a build vector of (possibly fp_rounded) loads.
13537   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13538       N->getNumOperands() == 1)
13539     return SDValue();
13540 
13541   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13542     // If any inputs are fp_round(extload), they all must be.
13543     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13544       return SDValue();
13545 
13546     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13547       N->getOperand(i);
13548     if (NextInput.getOpcode() != ISD::LOAD)
13549       return SDValue();
13550 
13551     SDValue PreviousInput =
13552       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13553     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13554     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13555 
13556     // If any inputs are fp_round(extload), they all must be.
13557     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13558       return SDValue();
13559 
13560     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13561       InputsAreConsecutiveLoads = false;
13562     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13563       InputsAreReverseConsecutive = false;
13564 
13565     // Exit early if the loads are neither consecutive nor reverse consecutive.
13566     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13567       return SDValue();
13568   }
13569 
13570   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13571          "The loads cannot be both consecutive and reverse consecutive.");
13572 
13573   SDValue FirstLoadOp =
13574     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13575   SDValue LastLoadOp =
13576     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13577                        N->getOperand(N->getNumOperands()-1);
13578 
13579   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13580   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13581   if (InputsAreConsecutiveLoads) {
13582     assert(LD1 && "Input needs to be a LoadSDNode.");
13583     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13584                        LD1->getBasePtr(), LD1->getPointerInfo(),
13585                        LD1->getAlignment());
13586   }
13587   if (InputsAreReverseConsecutive) {
13588     assert(LDL && "Input needs to be a LoadSDNode.");
13589     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13590                                LDL->getBasePtr(), LDL->getPointerInfo(),
13591                                LDL->getAlignment());
13592     SmallVector<int, 16> Ops;
13593     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13594       Ops.push_back(i);
13595 
13596     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13597                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13598   }
13599   return SDValue();
13600 }
13601 
13602 // This function adds the required vector_shuffle needed to get
13603 // the elements of the vector extract in the correct position
13604 // as specified by the CorrectElems encoding.
13605 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13606                                       SDValue Input, uint64_t Elems,
13607                                       uint64_t CorrectElems) {
13608   SDLoc dl(N);
13609 
13610   unsigned NumElems = Input.getValueType().getVectorNumElements();
13611   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13612 
13613   // Knowing the element indices being extracted from the original
13614   // vector and the order in which they're being inserted, just put
13615   // them at element indices required for the instruction.
13616   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13617     if (DAG.getDataLayout().isLittleEndian())
13618       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13619     else
13620       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13621     CorrectElems = CorrectElems >> 8;
13622     Elems = Elems >> 8;
13623   }
13624 
13625   SDValue Shuffle =
13626       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13627                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13628 
13629   EVT VT = N->getValueType(0);
13630   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13631 
13632   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13633                                Input.getValueType().getVectorElementType(),
13634                                VT.getVectorNumElements());
13635   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13636                      DAG.getValueType(ExtVT));
13637 }
13638 
13639 // Look for build vector patterns where input operands come from sign
13640 // extended vector_extract elements of specific indices. If the correct indices
13641 // aren't used, add a vector shuffle to fix up the indices and create
13642 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13643 // during instruction selection.
13644 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13645   // This array encodes the indices that the vector sign extend instructions
13646   // extract from when extending from one type to another for both BE and LE.
13647   // The right nibble of each byte corresponds to the LE incides.
13648   // and the left nibble of each byte corresponds to the BE incides.
13649   // For example: 0x3074B8FC  byte->word
13650   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13651   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13652   // For example: 0x000070F8  byte->double word
13653   // For LE: the allowed indices are: 0x0,0x8
13654   // For BE: the allowed indices are: 0x7,0xF
13655   uint64_t TargetElems[] = {
13656       0x3074B8FC, // b->w
13657       0x000070F8, // b->d
13658       0x10325476, // h->w
13659       0x00003074, // h->d
13660       0x00001032, // w->d
13661   };
13662 
13663   uint64_t Elems = 0;
13664   int Index;
13665   SDValue Input;
13666 
13667   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13668     if (!Op)
13669       return false;
13670     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13671         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13672       return false;
13673 
13674     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13675     // of the right width.
13676     SDValue Extract = Op.getOperand(0);
13677     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13678       Extract = Extract.getOperand(0);
13679     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13680       return false;
13681 
13682     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13683     if (!ExtOp)
13684       return false;
13685 
13686     Index = ExtOp->getZExtValue();
13687     if (Input && Input != Extract.getOperand(0))
13688       return false;
13689 
13690     if (!Input)
13691       Input = Extract.getOperand(0);
13692 
13693     Elems = Elems << 8;
13694     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13695     Elems |= Index;
13696 
13697     return true;
13698   };
13699 
13700   // If the build vector operands aren't sign extended vector extracts,
13701   // of the same input vector, then return.
13702   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13703     if (!isSExtOfVecExtract(N->getOperand(i))) {
13704       return SDValue();
13705     }
13706   }
13707 
13708   // If the vector extract indicies are not correct, add the appropriate
13709   // vector_shuffle.
13710   int TgtElemArrayIdx;
13711   int InputSize = Input.getValueType().getScalarSizeInBits();
13712   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13713   if (InputSize + OutputSize == 40)
13714     TgtElemArrayIdx = 0;
13715   else if (InputSize + OutputSize == 72)
13716     TgtElemArrayIdx = 1;
13717   else if (InputSize + OutputSize == 48)
13718     TgtElemArrayIdx = 2;
13719   else if (InputSize + OutputSize == 80)
13720     TgtElemArrayIdx = 3;
13721   else if (InputSize + OutputSize == 96)
13722     TgtElemArrayIdx = 4;
13723   else
13724     return SDValue();
13725 
13726   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13727   CorrectElems = DAG.getDataLayout().isLittleEndian()
13728                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13729                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13730   if (Elems != CorrectElems) {
13731     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13732   }
13733 
13734   // Regular lowering will catch cases where a shuffle is not needed.
13735   return SDValue();
13736 }
13737 
13738 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13739                                                  DAGCombinerInfo &DCI) const {
13740   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13741          "Should be called with a BUILD_VECTOR node");
13742 
13743   SelectionDAG &DAG = DCI.DAG;
13744   SDLoc dl(N);
13745 
13746   if (!Subtarget.hasVSX())
13747     return SDValue();
13748 
13749   // The target independent DAG combiner will leave a build_vector of
13750   // float-to-int conversions intact. We can generate MUCH better code for
13751   // a float-to-int conversion of a vector of floats.
13752   SDValue FirstInput = N->getOperand(0);
13753   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13754     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13755     if (Reduced)
13756       return Reduced;
13757   }
13758 
13759   // If we're building a vector out of consecutive loads, just load that
13760   // vector type.
13761   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13762   if (Reduced)
13763     return Reduced;
13764 
13765   // If we're building a vector out of extended elements from another vector
13766   // we have P9 vector integer extend instructions. The code assumes legal
13767   // input types (i.e. it can't handle things like v4i16) so do not run before
13768   // legalization.
13769   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13770     Reduced = combineBVOfVecSExt(N, DAG);
13771     if (Reduced)
13772       return Reduced;
13773   }
13774 
13775 
13776   if (N->getValueType(0) != MVT::v2f64)
13777     return SDValue();
13778 
13779   // Looking for:
13780   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13781   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13782       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13783     return SDValue();
13784   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13785       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13786     return SDValue();
13787   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13788     return SDValue();
13789 
13790   SDValue Ext1 = FirstInput.getOperand(0);
13791   SDValue Ext2 = N->getOperand(1).getOperand(0);
13792   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13793      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13794     return SDValue();
13795 
13796   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13797   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13798   if (!Ext1Op || !Ext2Op)
13799     return SDValue();
13800   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13801       Ext1.getOperand(0) != Ext2.getOperand(0))
13802     return SDValue();
13803 
13804   int FirstElem = Ext1Op->getZExtValue();
13805   int SecondElem = Ext2Op->getZExtValue();
13806   int SubvecIdx;
13807   if (FirstElem == 0 && SecondElem == 1)
13808     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13809   else if (FirstElem == 2 && SecondElem == 3)
13810     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13811   else
13812     return SDValue();
13813 
13814   SDValue SrcVec = Ext1.getOperand(0);
13815   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13816     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13817   return DAG.getNode(NodeType, dl, MVT::v2f64,
13818                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13819 }
13820 
13821 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13822                                               DAGCombinerInfo &DCI) const {
13823   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13824           N->getOpcode() == ISD::UINT_TO_FP) &&
13825          "Need an int -> FP conversion node here");
13826 
13827   if (useSoftFloat() || !Subtarget.has64BitSupport())
13828     return SDValue();
13829 
13830   SelectionDAG &DAG = DCI.DAG;
13831   SDLoc dl(N);
13832   SDValue Op(N, 0);
13833 
13834   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13835   // from the hardware.
13836   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13837     return SDValue();
13838   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13839       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13840     return SDValue();
13841 
13842   SDValue FirstOperand(Op.getOperand(0));
13843   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13844     (FirstOperand.getValueType() == MVT::i8 ||
13845      FirstOperand.getValueType() == MVT::i16);
13846   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13847     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13848     bool DstDouble = Op.getValueType() == MVT::f64;
13849     unsigned ConvOp = Signed ?
13850       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13851       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13852     SDValue WidthConst =
13853       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13854                             dl, false);
13855     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13856     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13857     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13858                                          DAG.getVTList(MVT::f64, MVT::Other),
13859                                          Ops, MVT::i8, LDN->getMemOperand());
13860 
13861     // For signed conversion, we need to sign-extend the value in the VSR
13862     if (Signed) {
13863       SDValue ExtOps[] = { Ld, WidthConst };
13864       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13865       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13866     } else
13867       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13868   }
13869 
13870 
13871   // For i32 intermediate values, unfortunately, the conversion functions
13872   // leave the upper 32 bits of the value are undefined. Within the set of
13873   // scalar instructions, we have no method for zero- or sign-extending the
13874   // value. Thus, we cannot handle i32 intermediate values here.
13875   if (Op.getOperand(0).getValueType() == MVT::i32)
13876     return SDValue();
13877 
13878   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13879          "UINT_TO_FP is supported only with FPCVT");
13880 
13881   // If we have FCFIDS, then use it when converting to single-precision.
13882   // Otherwise, convert to double-precision and then round.
13883   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13884                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13885                                                             : PPCISD::FCFIDS)
13886                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13887                                                             : PPCISD::FCFID);
13888   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13889                   ? MVT::f32
13890                   : MVT::f64;
13891 
13892   // If we're converting from a float, to an int, and back to a float again,
13893   // then we don't need the store/load pair at all.
13894   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13895        Subtarget.hasFPCVT()) ||
13896       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13897     SDValue Src = Op.getOperand(0).getOperand(0);
13898     if (Src.getValueType() == MVT::f32) {
13899       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13900       DCI.AddToWorklist(Src.getNode());
13901     } else if (Src.getValueType() != MVT::f64) {
13902       // Make sure that we don't pick up a ppc_fp128 source value.
13903       return SDValue();
13904     }
13905 
13906     unsigned FCTOp =
13907       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13908                                                         PPCISD::FCTIDUZ;
13909 
13910     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13911     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13912 
13913     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13914       FP = DAG.getNode(ISD::FP_ROUND, dl,
13915                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13916       DCI.AddToWorklist(FP.getNode());
13917     }
13918 
13919     return FP;
13920   }
13921 
13922   return SDValue();
13923 }
13924 
13925 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13926 // builtins) into loads with swaps.
13927 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13928                                               DAGCombinerInfo &DCI) const {
13929   SelectionDAG &DAG = DCI.DAG;
13930   SDLoc dl(N);
13931   SDValue Chain;
13932   SDValue Base;
13933   MachineMemOperand *MMO;
13934 
13935   switch (N->getOpcode()) {
13936   default:
13937     llvm_unreachable("Unexpected opcode for little endian VSX load");
13938   case ISD::LOAD: {
13939     LoadSDNode *LD = cast<LoadSDNode>(N);
13940     Chain = LD->getChain();
13941     Base = LD->getBasePtr();
13942     MMO = LD->getMemOperand();
13943     // If the MMO suggests this isn't a load of a full vector, leave
13944     // things alone.  For a built-in, we have to make the change for
13945     // correctness, so if there is a size problem that will be a bug.
13946     if (MMO->getSize() < 16)
13947       return SDValue();
13948     break;
13949   }
13950   case ISD::INTRINSIC_W_CHAIN: {
13951     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13952     Chain = Intrin->getChain();
13953     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13954     // us what we want. Get operand 2 instead.
13955     Base = Intrin->getOperand(2);
13956     MMO = Intrin->getMemOperand();
13957     break;
13958   }
13959   }
13960 
13961   MVT VecTy = N->getValueType(0).getSimpleVT();
13962 
13963   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13964   // aligned and the type is a vector with elements up to 4 bytes
13965   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13966       VecTy.getScalarSizeInBits() <= 32) {
13967     return SDValue();
13968   }
13969 
13970   SDValue LoadOps[] = { Chain, Base };
13971   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13972                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13973                                          LoadOps, MVT::v2f64, MMO);
13974 
13975   DCI.AddToWorklist(Load.getNode());
13976   Chain = Load.getValue(1);
13977   SDValue Swap = DAG.getNode(
13978       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13979   DCI.AddToWorklist(Swap.getNode());
13980 
13981   // Add a bitcast if the resulting load type doesn't match v2f64.
13982   if (VecTy != MVT::v2f64) {
13983     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13984     DCI.AddToWorklist(N.getNode());
13985     // Package {bitcast value, swap's chain} to match Load's shape.
13986     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13987                        N, Swap.getValue(1));
13988   }
13989 
13990   return Swap;
13991 }
13992 
13993 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13994 // builtins) into stores with swaps.
13995 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13996                                                DAGCombinerInfo &DCI) const {
13997   SelectionDAG &DAG = DCI.DAG;
13998   SDLoc dl(N);
13999   SDValue Chain;
14000   SDValue Base;
14001   unsigned SrcOpnd;
14002   MachineMemOperand *MMO;
14003 
14004   switch (N->getOpcode()) {
14005   default:
14006     llvm_unreachable("Unexpected opcode for little endian VSX store");
14007   case ISD::STORE: {
14008     StoreSDNode *ST = cast<StoreSDNode>(N);
14009     Chain = ST->getChain();
14010     Base = ST->getBasePtr();
14011     MMO = ST->getMemOperand();
14012     SrcOpnd = 1;
14013     // If the MMO suggests this isn't a store of a full vector, leave
14014     // things alone.  For a built-in, we have to make the change for
14015     // correctness, so if there is a size problem that will be a bug.
14016     if (MMO->getSize() < 16)
14017       return SDValue();
14018     break;
14019   }
14020   case ISD::INTRINSIC_VOID: {
14021     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14022     Chain = Intrin->getChain();
14023     // Intrin->getBasePtr() oddly does not get what we want.
14024     Base = Intrin->getOperand(3);
14025     MMO = Intrin->getMemOperand();
14026     SrcOpnd = 2;
14027     break;
14028   }
14029   }
14030 
14031   SDValue Src = N->getOperand(SrcOpnd);
14032   MVT VecTy = Src.getValueType().getSimpleVT();
14033 
14034   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14035   // aligned and the type is a vector with elements up to 4 bytes
14036   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14037       VecTy.getScalarSizeInBits() <= 32) {
14038     return SDValue();
14039   }
14040 
14041   // All stores are done as v2f64 and possible bit cast.
14042   if (VecTy != MVT::v2f64) {
14043     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14044     DCI.AddToWorklist(Src.getNode());
14045   }
14046 
14047   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14048                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14049   DCI.AddToWorklist(Swap.getNode());
14050   Chain = Swap.getValue(1);
14051   SDValue StoreOps[] = { Chain, Swap, Base };
14052   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14053                                           DAG.getVTList(MVT::Other),
14054                                           StoreOps, VecTy, MMO);
14055   DCI.AddToWorklist(Store.getNode());
14056   return Store;
14057 }
14058 
14059 // Handle DAG combine for STORE (FP_TO_INT F).
14060 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14061                                                DAGCombinerInfo &DCI) const {
14062 
14063   SelectionDAG &DAG = DCI.DAG;
14064   SDLoc dl(N);
14065   unsigned Opcode = N->getOperand(1).getOpcode();
14066 
14067   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14068          && "Not a FP_TO_INT Instruction!");
14069 
14070   SDValue Val = N->getOperand(1).getOperand(0);
14071   EVT Op1VT = N->getOperand(1).getValueType();
14072   EVT ResVT = Val.getValueType();
14073 
14074   // Floating point types smaller than 32 bits are not legal on Power.
14075   if (ResVT.getScalarSizeInBits() < 32)
14076     return SDValue();
14077 
14078   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14079   bool ValidTypeForStoreFltAsInt =
14080         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14081          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14082 
14083   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14084       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14085     return SDValue();
14086 
14087   // Extend f32 values to f64
14088   if (ResVT.getScalarSizeInBits() == 32) {
14089     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14090     DCI.AddToWorklist(Val.getNode());
14091   }
14092 
14093   // Set signed or unsigned conversion opcode.
14094   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14095                           PPCISD::FP_TO_SINT_IN_VSR :
14096                           PPCISD::FP_TO_UINT_IN_VSR;
14097 
14098   Val = DAG.getNode(ConvOpcode,
14099                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14100   DCI.AddToWorklist(Val.getNode());
14101 
14102   // Set number of bytes being converted.
14103   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14104   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14105                     DAG.getIntPtrConstant(ByteSize, dl, false),
14106                     DAG.getValueType(Op1VT) };
14107 
14108   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14109           DAG.getVTList(MVT::Other), Ops,
14110           cast<StoreSDNode>(N)->getMemoryVT(),
14111           cast<StoreSDNode>(N)->getMemOperand());
14112 
14113   DCI.AddToWorklist(Val.getNode());
14114   return Val;
14115 }
14116 
14117 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14118                                                 LSBaseSDNode *LSBase,
14119                                                 DAGCombinerInfo &DCI) const {
14120   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14121         "Not a reverse memop pattern!");
14122 
14123   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14124     auto Mask = SVN->getMask();
14125     int i = 0;
14126     auto I = Mask.rbegin();
14127     auto E = Mask.rend();
14128 
14129     for (; I != E; ++I) {
14130       if (*I != i)
14131         return false;
14132       i++;
14133     }
14134     return true;
14135   };
14136 
14137   SelectionDAG &DAG = DCI.DAG;
14138   EVT VT = SVN->getValueType(0);
14139 
14140   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14141     return SDValue();
14142 
14143   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14144   // See comment in PPCVSXSwapRemoval.cpp.
14145   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14146   if (!Subtarget.hasP9Vector())
14147     return SDValue();
14148 
14149   if(!IsElementReverse(SVN))
14150     return SDValue();
14151 
14152   if (LSBase->getOpcode() == ISD::LOAD) {
14153     SDLoc dl(SVN);
14154     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14155     return DAG.getMemIntrinsicNode(
14156         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14157         LSBase->getMemoryVT(), LSBase->getMemOperand());
14158   }
14159 
14160   if (LSBase->getOpcode() == ISD::STORE) {
14161     SDLoc dl(LSBase);
14162     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14163                           LSBase->getBasePtr()};
14164     return DAG.getMemIntrinsicNode(
14165         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14166         LSBase->getMemoryVT(), LSBase->getMemOperand());
14167   }
14168 
14169   llvm_unreachable("Expected a load or store node here");
14170 }
14171 
14172 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14173                                              DAGCombinerInfo &DCI) const {
14174   SelectionDAG &DAG = DCI.DAG;
14175   SDLoc dl(N);
14176   switch (N->getOpcode()) {
14177   default: break;
14178   case ISD::ADD:
14179     return combineADD(N, DCI);
14180   case ISD::SHL:
14181     return combineSHL(N, DCI);
14182   case ISD::SRA:
14183     return combineSRA(N, DCI);
14184   case ISD::SRL:
14185     return combineSRL(N, DCI);
14186   case ISD::MUL:
14187     return combineMUL(N, DCI);
14188   case ISD::FMA:
14189   case PPCISD::FNMSUB:
14190     return combineFMALike(N, DCI);
14191   case PPCISD::SHL:
14192     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14193         return N->getOperand(0);
14194     break;
14195   case PPCISD::SRL:
14196     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14197         return N->getOperand(0);
14198     break;
14199   case PPCISD::SRA:
14200     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14201       if (C->isNullValue() ||   //  0 >>s V -> 0.
14202           C->isAllOnesValue())    // -1 >>s V -> -1.
14203         return N->getOperand(0);
14204     }
14205     break;
14206   case ISD::SIGN_EXTEND:
14207   case ISD::ZERO_EXTEND:
14208   case ISD::ANY_EXTEND:
14209     return DAGCombineExtBoolTrunc(N, DCI);
14210   case ISD::TRUNCATE:
14211     return combineTRUNCATE(N, DCI);
14212   case ISD::SETCC:
14213     if (SDValue CSCC = combineSetCC(N, DCI))
14214       return CSCC;
14215     LLVM_FALLTHROUGH;
14216   case ISD::SELECT_CC:
14217     return DAGCombineTruncBoolExt(N, DCI);
14218   case ISD::SINT_TO_FP:
14219   case ISD::UINT_TO_FP:
14220     return combineFPToIntToFP(N, DCI);
14221   case ISD::VECTOR_SHUFFLE:
14222     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14223       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14224       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14225     }
14226     break;
14227   case ISD::STORE: {
14228 
14229     EVT Op1VT = N->getOperand(1).getValueType();
14230     unsigned Opcode = N->getOperand(1).getOpcode();
14231 
14232     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14233       SDValue Val= combineStoreFPToInt(N, DCI);
14234       if (Val)
14235         return Val;
14236     }
14237 
14238     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14239       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14240       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14241       if (Val)
14242         return Val;
14243     }
14244 
14245     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14246     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14247         N->getOperand(1).getNode()->hasOneUse() &&
14248         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14249          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14250 
14251       // STBRX can only handle simple types and it makes no sense to store less
14252       // two bytes in byte-reversed order.
14253       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14254       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14255         break;
14256 
14257       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14258       // Do an any-extend to 32-bits if this is a half-word input.
14259       if (BSwapOp.getValueType() == MVT::i16)
14260         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14261 
14262       // If the type of BSWAP operand is wider than stored memory width
14263       // it need to be shifted to the right side before STBRX.
14264       if (Op1VT.bitsGT(mVT)) {
14265         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14266         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14267                               DAG.getConstant(Shift, dl, MVT::i32));
14268         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14269         if (Op1VT == MVT::i64)
14270           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14271       }
14272 
14273       SDValue Ops[] = {
14274         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14275       };
14276       return
14277         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14278                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14279                                 cast<StoreSDNode>(N)->getMemOperand());
14280     }
14281 
14282     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14283     // So it can increase the chance of CSE constant construction.
14284     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14285         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14286       // Need to sign-extended to 64-bits to handle negative values.
14287       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14288       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14289                                     MemVT.getSizeInBits());
14290       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14291 
14292       // DAG.getTruncStore() can't be used here because it doesn't accept
14293       // the general (base + offset) addressing mode.
14294       // So we use UpdateNodeOperands and setTruncatingStore instead.
14295       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14296                              N->getOperand(3));
14297       cast<StoreSDNode>(N)->setTruncatingStore(true);
14298       return SDValue(N, 0);
14299     }
14300 
14301     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14302     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14303     if (Op1VT.isSimple()) {
14304       MVT StoreVT = Op1VT.getSimpleVT();
14305       if (Subtarget.needsSwapsForVSXMemOps() &&
14306           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14307            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14308         return expandVSXStoreForLE(N, DCI);
14309     }
14310     break;
14311   }
14312   case ISD::LOAD: {
14313     LoadSDNode *LD = cast<LoadSDNode>(N);
14314     EVT VT = LD->getValueType(0);
14315 
14316     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14317     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14318     if (VT.isSimple()) {
14319       MVT LoadVT = VT.getSimpleVT();
14320       if (Subtarget.needsSwapsForVSXMemOps() &&
14321           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14322            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14323         return expandVSXLoadForLE(N, DCI);
14324     }
14325 
14326     // We sometimes end up with a 64-bit integer load, from which we extract
14327     // two single-precision floating-point numbers. This happens with
14328     // std::complex<float>, and other similar structures, because of the way we
14329     // canonicalize structure copies. However, if we lack direct moves,
14330     // then the final bitcasts from the extracted integer values to the
14331     // floating-point numbers turn into store/load pairs. Even with direct moves,
14332     // just loading the two floating-point numbers is likely better.
14333     auto ReplaceTwoFloatLoad = [&]() {
14334       if (VT != MVT::i64)
14335         return false;
14336 
14337       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14338           LD->isVolatile())
14339         return false;
14340 
14341       //  We're looking for a sequence like this:
14342       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14343       //      t16: i64 = srl t13, Constant:i32<32>
14344       //    t17: i32 = truncate t16
14345       //  t18: f32 = bitcast t17
14346       //    t19: i32 = truncate t13
14347       //  t20: f32 = bitcast t19
14348 
14349       if (!LD->hasNUsesOfValue(2, 0))
14350         return false;
14351 
14352       auto UI = LD->use_begin();
14353       while (UI.getUse().getResNo() != 0) ++UI;
14354       SDNode *Trunc = *UI++;
14355       while (UI.getUse().getResNo() != 0) ++UI;
14356       SDNode *RightShift = *UI;
14357       if (Trunc->getOpcode() != ISD::TRUNCATE)
14358         std::swap(Trunc, RightShift);
14359 
14360       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14361           Trunc->getValueType(0) != MVT::i32 ||
14362           !Trunc->hasOneUse())
14363         return false;
14364       if (RightShift->getOpcode() != ISD::SRL ||
14365           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14366           RightShift->getConstantOperandVal(1) != 32 ||
14367           !RightShift->hasOneUse())
14368         return false;
14369 
14370       SDNode *Trunc2 = *RightShift->use_begin();
14371       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14372           Trunc2->getValueType(0) != MVT::i32 ||
14373           !Trunc2->hasOneUse())
14374         return false;
14375 
14376       SDNode *Bitcast = *Trunc->use_begin();
14377       SDNode *Bitcast2 = *Trunc2->use_begin();
14378 
14379       if (Bitcast->getOpcode() != ISD::BITCAST ||
14380           Bitcast->getValueType(0) != MVT::f32)
14381         return false;
14382       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14383           Bitcast2->getValueType(0) != MVT::f32)
14384         return false;
14385 
14386       if (Subtarget.isLittleEndian())
14387         std::swap(Bitcast, Bitcast2);
14388 
14389       // Bitcast has the second float (in memory-layout order) and Bitcast2
14390       // has the first one.
14391 
14392       SDValue BasePtr = LD->getBasePtr();
14393       if (LD->isIndexed()) {
14394         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14395                "Non-pre-inc AM on PPC?");
14396         BasePtr =
14397           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14398                       LD->getOffset());
14399       }
14400 
14401       auto MMOFlags =
14402           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14403       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14404                                       LD->getPointerInfo(), LD->getAlignment(),
14405                                       MMOFlags, LD->getAAInfo());
14406       SDValue AddPtr =
14407         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14408                     BasePtr, DAG.getIntPtrConstant(4, dl));
14409       SDValue FloatLoad2 = DAG.getLoad(
14410           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14411           LD->getPointerInfo().getWithOffset(4),
14412           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14413 
14414       if (LD->isIndexed()) {
14415         // Note that DAGCombine should re-form any pre-increment load(s) from
14416         // what is produced here if that makes sense.
14417         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14418       }
14419 
14420       DCI.CombineTo(Bitcast2, FloatLoad);
14421       DCI.CombineTo(Bitcast, FloatLoad2);
14422 
14423       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14424                                     SDValue(FloatLoad2.getNode(), 1));
14425       return true;
14426     };
14427 
14428     if (ReplaceTwoFloatLoad())
14429       return SDValue(N, 0);
14430 
14431     EVT MemVT = LD->getMemoryVT();
14432     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14433     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
14434     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
14435     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
14436     if (LD->isUnindexed() && VT.isVector() &&
14437         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14438           // P8 and later hardware should just use LOAD.
14439           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
14440                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
14441          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
14442           LD->getAlignment() >= ScalarABIAlignment)) &&
14443         LD->getAlignment() < ABIAlignment) {
14444       // This is a type-legal unaligned Altivec or QPX load.
14445       SDValue Chain = LD->getChain();
14446       SDValue Ptr = LD->getBasePtr();
14447       bool isLittleEndian = Subtarget.isLittleEndian();
14448 
14449       // This implements the loading of unaligned vectors as described in
14450       // the venerable Apple Velocity Engine overview. Specifically:
14451       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14452       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14453       //
14454       // The general idea is to expand a sequence of one or more unaligned
14455       // loads into an alignment-based permutation-control instruction (lvsl
14456       // or lvsr), a series of regular vector loads (which always truncate
14457       // their input address to an aligned address), and a series of
14458       // permutations.  The results of these permutations are the requested
14459       // loaded values.  The trick is that the last "extra" load is not taken
14460       // from the address you might suspect (sizeof(vector) bytes after the
14461       // last requested load), but rather sizeof(vector) - 1 bytes after the
14462       // last requested vector. The point of this is to avoid a page fault if
14463       // the base address happened to be aligned. This works because if the
14464       // base address is aligned, then adding less than a full vector length
14465       // will cause the last vector in the sequence to be (re)loaded.
14466       // Otherwise, the next vector will be fetched as you might suspect was
14467       // necessary.
14468 
14469       // We might be able to reuse the permutation generation from
14470       // a different base address offset from this one by an aligned amount.
14471       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14472       // optimization later.
14473       Intrinsic::ID Intr, IntrLD, IntrPerm;
14474       MVT PermCntlTy, PermTy, LDTy;
14475       if (Subtarget.hasAltivec()) {
14476         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
14477                                  Intrinsic::ppc_altivec_lvsl;
14478         IntrLD = Intrinsic::ppc_altivec_lvx;
14479         IntrPerm = Intrinsic::ppc_altivec_vperm;
14480         PermCntlTy = MVT::v16i8;
14481         PermTy = MVT::v4i32;
14482         LDTy = MVT::v4i32;
14483       } else {
14484         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
14485                                        Intrinsic::ppc_qpx_qvlpcls;
14486         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
14487                                        Intrinsic::ppc_qpx_qvlfs;
14488         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
14489         PermCntlTy = MVT::v4f64;
14490         PermTy = MVT::v4f64;
14491         LDTy = MemVT.getSimpleVT();
14492       }
14493 
14494       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14495 
14496       // Create the new MMO for the new base load. It is like the original MMO,
14497       // but represents an area in memory almost twice the vector size centered
14498       // on the original address. If the address is unaligned, we might start
14499       // reading up to (sizeof(vector)-1) bytes below the address of the
14500       // original unaligned load.
14501       MachineFunction &MF = DAG.getMachineFunction();
14502       MachineMemOperand *BaseMMO =
14503         MF.getMachineMemOperand(LD->getMemOperand(),
14504                                 -(long)MemVT.getStoreSize()+1,
14505                                 2*MemVT.getStoreSize()-1);
14506 
14507       // Create the new base load.
14508       SDValue LDXIntID =
14509           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14510       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14511       SDValue BaseLoad =
14512         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14513                                 DAG.getVTList(PermTy, MVT::Other),
14514                                 BaseLoadOps, LDTy, BaseMMO);
14515 
14516       // Note that the value of IncOffset (which is provided to the next
14517       // load's pointer info offset value, and thus used to calculate the
14518       // alignment), and the value of IncValue (which is actually used to
14519       // increment the pointer value) are different! This is because we
14520       // require the next load to appear to be aligned, even though it
14521       // is actually offset from the base pointer by a lesser amount.
14522       int IncOffset = VT.getSizeInBits() / 8;
14523       int IncValue = IncOffset;
14524 
14525       // Walk (both up and down) the chain looking for another load at the real
14526       // (aligned) offset (the alignment of the other load does not matter in
14527       // this case). If found, then do not use the offset reduction trick, as
14528       // that will prevent the loads from being later combined (as they would
14529       // otherwise be duplicates).
14530       if (!findConsecutiveLoad(LD, DAG))
14531         --IncValue;
14532 
14533       SDValue Increment =
14534           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14535       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14536 
14537       MachineMemOperand *ExtraMMO =
14538         MF.getMachineMemOperand(LD->getMemOperand(),
14539                                 1, 2*MemVT.getStoreSize()-1);
14540       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14541       SDValue ExtraLoad =
14542         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14543                                 DAG.getVTList(PermTy, MVT::Other),
14544                                 ExtraLoadOps, LDTy, ExtraMMO);
14545 
14546       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14547         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14548 
14549       // Because vperm has a big-endian bias, we must reverse the order
14550       // of the input vectors and complement the permute control vector
14551       // when generating little endian code.  We have already handled the
14552       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14553       // and ExtraLoad here.
14554       SDValue Perm;
14555       if (isLittleEndian)
14556         Perm = BuildIntrinsicOp(IntrPerm,
14557                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14558       else
14559         Perm = BuildIntrinsicOp(IntrPerm,
14560                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14561 
14562       if (VT != PermTy)
14563         Perm = Subtarget.hasAltivec() ?
14564                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
14565                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
14566                                DAG.getTargetConstant(1, dl, MVT::i64));
14567                                // second argument is 1 because this rounding
14568                                // is always exact.
14569 
14570       // The output of the permutation is our loaded result, the TokenFactor is
14571       // our new chain.
14572       DCI.CombineTo(N, Perm, TF);
14573       return SDValue(N, 0);
14574     }
14575     }
14576     break;
14577     case ISD::INTRINSIC_WO_CHAIN: {
14578       bool isLittleEndian = Subtarget.isLittleEndian();
14579       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14580       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14581                                            : Intrinsic::ppc_altivec_lvsl);
14582       if ((IID == Intr ||
14583            IID == Intrinsic::ppc_qpx_qvlpcld  ||
14584            IID == Intrinsic::ppc_qpx_qvlpcls) &&
14585         N->getOperand(1)->getOpcode() == ISD::ADD) {
14586         SDValue Add = N->getOperand(1);
14587 
14588         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
14589                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
14590 
14591         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14592                                   APInt::getAllOnesValue(Bits /* alignment */)
14593                                       .zext(Add.getScalarValueSizeInBits()))) {
14594           SDNode *BasePtr = Add->getOperand(0).getNode();
14595           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14596                                     UE = BasePtr->use_end();
14597                UI != UE; ++UI) {
14598             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14599                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
14600               // We've found another LVSL/LVSR, and this address is an aligned
14601               // multiple of that one. The results will be the same, so use the
14602               // one we've just found instead.
14603 
14604               return SDValue(*UI, 0);
14605             }
14606           }
14607         }
14608 
14609         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14610           SDNode *BasePtr = Add->getOperand(0).getNode();
14611           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14612                UE = BasePtr->use_end(); UI != UE; ++UI) {
14613             if (UI->getOpcode() == ISD::ADD &&
14614                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14615                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14616                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14617                 (1ULL << Bits) == 0) {
14618               SDNode *OtherAdd = *UI;
14619               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14620                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14621                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14622                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14623                   return SDValue(*VI, 0);
14624                 }
14625               }
14626             }
14627           }
14628         }
14629       }
14630 
14631       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14632       // Expose the vabsduw/h/b opportunity for down stream
14633       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14634           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14635            IID == Intrinsic::ppc_altivec_vmaxsh ||
14636            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14637         SDValue V1 = N->getOperand(1);
14638         SDValue V2 = N->getOperand(2);
14639         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14640              V1.getSimpleValueType() == MVT::v8i16 ||
14641              V1.getSimpleValueType() == MVT::v16i8) &&
14642             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14643           // (0-a, a)
14644           if (V1.getOpcode() == ISD::SUB &&
14645               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14646               V1.getOperand(1) == V2) {
14647             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14648           }
14649           // (a, 0-a)
14650           if (V2.getOpcode() == ISD::SUB &&
14651               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14652               V2.getOperand(1) == V1) {
14653             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14654           }
14655           // (x-y, y-x)
14656           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14657               V1.getOperand(0) == V2.getOperand(1) &&
14658               V1.getOperand(1) == V2.getOperand(0)) {
14659             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14660           }
14661         }
14662       }
14663     }
14664 
14665     break;
14666   case ISD::INTRINSIC_W_CHAIN:
14667     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14668     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14669     if (Subtarget.needsSwapsForVSXMemOps()) {
14670       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14671       default:
14672         break;
14673       case Intrinsic::ppc_vsx_lxvw4x:
14674       case Intrinsic::ppc_vsx_lxvd2x:
14675         return expandVSXLoadForLE(N, DCI);
14676       }
14677     }
14678     break;
14679   case ISD::INTRINSIC_VOID:
14680     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14681     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14682     if (Subtarget.needsSwapsForVSXMemOps()) {
14683       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14684       default:
14685         break;
14686       case Intrinsic::ppc_vsx_stxvw4x:
14687       case Intrinsic::ppc_vsx_stxvd2x:
14688         return expandVSXStoreForLE(N, DCI);
14689       }
14690     }
14691     break;
14692   case ISD::BSWAP:
14693     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14694     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14695         N->getOperand(0).hasOneUse() &&
14696         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14697          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14698           N->getValueType(0) == MVT::i64))) {
14699       SDValue Load = N->getOperand(0);
14700       LoadSDNode *LD = cast<LoadSDNode>(Load);
14701       // Create the byte-swapping load.
14702       SDValue Ops[] = {
14703         LD->getChain(),    // Chain
14704         LD->getBasePtr(),  // Ptr
14705         DAG.getValueType(N->getValueType(0)) // VT
14706       };
14707       SDValue BSLoad =
14708         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14709                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14710                                               MVT::i64 : MVT::i32, MVT::Other),
14711                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14712 
14713       // If this is an i16 load, insert the truncate.
14714       SDValue ResVal = BSLoad;
14715       if (N->getValueType(0) == MVT::i16)
14716         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14717 
14718       // First, combine the bswap away.  This makes the value produced by the
14719       // load dead.
14720       DCI.CombineTo(N, ResVal);
14721 
14722       // Next, combine the load away, we give it a bogus result value but a real
14723       // chain result.  The result value is dead because the bswap is dead.
14724       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14725 
14726       // Return N so it doesn't get rechecked!
14727       return SDValue(N, 0);
14728     }
14729     break;
14730   case PPCISD::VCMP:
14731     // If a VCMPo node already exists with exactly the same operands as this
14732     // node, use its result instead of this node (VCMPo computes both a CR6 and
14733     // a normal output).
14734     //
14735     if (!N->getOperand(0).hasOneUse() &&
14736         !N->getOperand(1).hasOneUse() &&
14737         !N->getOperand(2).hasOneUse()) {
14738 
14739       // Scan all of the users of the LHS, looking for VCMPo's that match.
14740       SDNode *VCMPoNode = nullptr;
14741 
14742       SDNode *LHSN = N->getOperand(0).getNode();
14743       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14744            UI != E; ++UI)
14745         if (UI->getOpcode() == PPCISD::VCMPo &&
14746             UI->getOperand(1) == N->getOperand(1) &&
14747             UI->getOperand(2) == N->getOperand(2) &&
14748             UI->getOperand(0) == N->getOperand(0)) {
14749           VCMPoNode = *UI;
14750           break;
14751         }
14752 
14753       // If there is no VCMPo node, or if the flag value has a single use, don't
14754       // transform this.
14755       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14756         break;
14757 
14758       // Look at the (necessarily single) use of the flag value.  If it has a
14759       // chain, this transformation is more complex.  Note that multiple things
14760       // could use the value result, which we should ignore.
14761       SDNode *FlagUser = nullptr;
14762       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14763            FlagUser == nullptr; ++UI) {
14764         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14765         SDNode *User = *UI;
14766         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14767           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14768             FlagUser = User;
14769             break;
14770           }
14771         }
14772       }
14773 
14774       // If the user is a MFOCRF instruction, we know this is safe.
14775       // Otherwise we give up for right now.
14776       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14777         return SDValue(VCMPoNode, 0);
14778     }
14779     break;
14780   case ISD::BRCOND: {
14781     SDValue Cond = N->getOperand(1);
14782     SDValue Target = N->getOperand(2);
14783 
14784     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14785         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14786           Intrinsic::loop_decrement) {
14787 
14788       // We now need to make the intrinsic dead (it cannot be instruction
14789       // selected).
14790       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14791       assert(Cond.getNode()->hasOneUse() &&
14792              "Counter decrement has more than one use");
14793 
14794       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14795                          N->getOperand(0), Target);
14796     }
14797   }
14798   break;
14799   case ISD::BR_CC: {
14800     // If this is a branch on an altivec predicate comparison, lower this so
14801     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14802     // lowering is done pre-legalize, because the legalizer lowers the predicate
14803     // compare down to code that is difficult to reassemble.
14804     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14805     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14806 
14807     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14808     // value. If so, pass-through the AND to get to the intrinsic.
14809     if (LHS.getOpcode() == ISD::AND &&
14810         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14811         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14812           Intrinsic::loop_decrement &&
14813         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14814         !isNullConstant(LHS.getOperand(1)))
14815       LHS = LHS.getOperand(0);
14816 
14817     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14818         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14819           Intrinsic::loop_decrement &&
14820         isa<ConstantSDNode>(RHS)) {
14821       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14822              "Counter decrement comparison is not EQ or NE");
14823 
14824       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14825       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14826                     (CC == ISD::SETNE && !Val);
14827 
14828       // We now need to make the intrinsic dead (it cannot be instruction
14829       // selected).
14830       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14831       assert(LHS.getNode()->hasOneUse() &&
14832              "Counter decrement has more than one use");
14833 
14834       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14835                          N->getOperand(0), N->getOperand(4));
14836     }
14837 
14838     int CompareOpc;
14839     bool isDot;
14840 
14841     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14842         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14843         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14844       assert(isDot && "Can't compare against a vector result!");
14845 
14846       // If this is a comparison against something other than 0/1, then we know
14847       // that the condition is never/always true.
14848       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14849       if (Val != 0 && Val != 1) {
14850         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14851           return N->getOperand(0);
14852         // Always !=, turn it into an unconditional branch.
14853         return DAG.getNode(ISD::BR, dl, MVT::Other,
14854                            N->getOperand(0), N->getOperand(4));
14855       }
14856 
14857       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14858 
14859       // Create the PPCISD altivec 'dot' comparison node.
14860       SDValue Ops[] = {
14861         LHS.getOperand(2),  // LHS of compare
14862         LHS.getOperand(3),  // RHS of compare
14863         DAG.getConstant(CompareOpc, dl, MVT::i32)
14864       };
14865       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14866       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14867 
14868       // Unpack the result based on how the target uses it.
14869       PPC::Predicate CompOpc;
14870       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14871       default:  // Can't happen, don't crash on invalid number though.
14872       case 0:   // Branch on the value of the EQ bit of CR6.
14873         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14874         break;
14875       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14876         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14877         break;
14878       case 2:   // Branch on the value of the LT bit of CR6.
14879         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14880         break;
14881       case 3:   // Branch on the inverted value of the LT bit of CR6.
14882         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14883         break;
14884       }
14885 
14886       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14887                          DAG.getConstant(CompOpc, dl, MVT::i32),
14888                          DAG.getRegister(PPC::CR6, MVT::i32),
14889                          N->getOperand(4), CompNode.getValue(1));
14890     }
14891     break;
14892   }
14893   case ISD::BUILD_VECTOR:
14894     return DAGCombineBuildVector(N, DCI);
14895   case ISD::ABS:
14896     return combineABS(N, DCI);
14897   case ISD::VSELECT:
14898     return combineVSelect(N, DCI);
14899   }
14900 
14901   return SDValue();
14902 }
14903 
14904 SDValue
14905 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14906                                  SelectionDAG &DAG,
14907                                  SmallVectorImpl<SDNode *> &Created) const {
14908   // fold (sdiv X, pow2)
14909   EVT VT = N->getValueType(0);
14910   if (VT == MVT::i64 && !Subtarget.isPPC64())
14911     return SDValue();
14912   if ((VT != MVT::i32 && VT != MVT::i64) ||
14913       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14914     return SDValue();
14915 
14916   SDLoc DL(N);
14917   SDValue N0 = N->getOperand(0);
14918 
14919   bool IsNegPow2 = (-Divisor).isPowerOf2();
14920   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14921   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14922 
14923   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14924   Created.push_back(Op.getNode());
14925 
14926   if (IsNegPow2) {
14927     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14928     Created.push_back(Op.getNode());
14929   }
14930 
14931   return Op;
14932 }
14933 
14934 //===----------------------------------------------------------------------===//
14935 // Inline Assembly Support
14936 //===----------------------------------------------------------------------===//
14937 
14938 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14939                                                       KnownBits &Known,
14940                                                       const APInt &DemandedElts,
14941                                                       const SelectionDAG &DAG,
14942                                                       unsigned Depth) const {
14943   Known.resetAll();
14944   switch (Op.getOpcode()) {
14945   default: break;
14946   case PPCISD::LBRX: {
14947     // lhbrx is known to have the top bits cleared out.
14948     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14949       Known.Zero = 0xFFFF0000;
14950     break;
14951   }
14952   case ISD::INTRINSIC_WO_CHAIN: {
14953     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14954     default: break;
14955     case Intrinsic::ppc_altivec_vcmpbfp_p:
14956     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14957     case Intrinsic::ppc_altivec_vcmpequb_p:
14958     case Intrinsic::ppc_altivec_vcmpequh_p:
14959     case Intrinsic::ppc_altivec_vcmpequw_p:
14960     case Intrinsic::ppc_altivec_vcmpequd_p:
14961     case Intrinsic::ppc_altivec_vcmpgefp_p:
14962     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14963     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14964     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14965     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14966     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14967     case Intrinsic::ppc_altivec_vcmpgtub_p:
14968     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14969     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14970     case Intrinsic::ppc_altivec_vcmpgtud_p:
14971       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14972       break;
14973     }
14974   }
14975   }
14976 }
14977 
14978 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14979   switch (Subtarget.getCPUDirective()) {
14980   default: break;
14981   case PPC::DIR_970:
14982   case PPC::DIR_PWR4:
14983   case PPC::DIR_PWR5:
14984   case PPC::DIR_PWR5X:
14985   case PPC::DIR_PWR6:
14986   case PPC::DIR_PWR6X:
14987   case PPC::DIR_PWR7:
14988   case PPC::DIR_PWR8:
14989   case PPC::DIR_PWR9:
14990   case PPC::DIR_PWR10:
14991   case PPC::DIR_PWR_FUTURE: {
14992     if (!ML)
14993       break;
14994 
14995     if (!DisableInnermostLoopAlign32) {
14996       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14997       // so that we can decrease cache misses and branch-prediction misses.
14998       // Actual alignment of the loop will depend on the hotness check and other
14999       // logic in alignBlocks.
15000       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15001         return Align(32);
15002     }
15003 
15004     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15005 
15006     // For small loops (between 5 and 8 instructions), align to a 32-byte
15007     // boundary so that the entire loop fits in one instruction-cache line.
15008     uint64_t LoopSize = 0;
15009     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15010       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15011         LoopSize += TII->getInstSizeInBytes(*J);
15012         if (LoopSize > 32)
15013           break;
15014       }
15015 
15016     if (LoopSize > 16 && LoopSize <= 32)
15017       return Align(32);
15018 
15019     break;
15020   }
15021   }
15022 
15023   return TargetLowering::getPrefLoopAlignment(ML);
15024 }
15025 
15026 /// getConstraintType - Given a constraint, return the type of
15027 /// constraint it is for this target.
15028 PPCTargetLowering::ConstraintType
15029 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15030   if (Constraint.size() == 1) {
15031     switch (Constraint[0]) {
15032     default: break;
15033     case 'b':
15034     case 'r':
15035     case 'f':
15036     case 'd':
15037     case 'v':
15038     case 'y':
15039       return C_RegisterClass;
15040     case 'Z':
15041       // FIXME: While Z does indicate a memory constraint, it specifically
15042       // indicates an r+r address (used in conjunction with the 'y' modifier
15043       // in the replacement string). Currently, we're forcing the base
15044       // register to be r0 in the asm printer (which is interpreted as zero)
15045       // and forming the complete address in the second register. This is
15046       // suboptimal.
15047       return C_Memory;
15048     }
15049   } else if (Constraint == "wc") { // individual CR bits.
15050     return C_RegisterClass;
15051   } else if (Constraint == "wa" || Constraint == "wd" ||
15052              Constraint == "wf" || Constraint == "ws" ||
15053              Constraint == "wi" || Constraint == "ww") {
15054     return C_RegisterClass; // VSX registers.
15055   }
15056   return TargetLowering::getConstraintType(Constraint);
15057 }
15058 
15059 /// Examine constraint type and operand type and determine a weight value.
15060 /// This object must already have been set up with the operand type
15061 /// and the current alternative constraint selected.
15062 TargetLowering::ConstraintWeight
15063 PPCTargetLowering::getSingleConstraintMatchWeight(
15064     AsmOperandInfo &info, const char *constraint) const {
15065   ConstraintWeight weight = CW_Invalid;
15066   Value *CallOperandVal = info.CallOperandVal;
15067     // If we don't have a value, we can't do a match,
15068     // but allow it at the lowest weight.
15069   if (!CallOperandVal)
15070     return CW_Default;
15071   Type *type = CallOperandVal->getType();
15072 
15073   // Look at the constraint type.
15074   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15075     return CW_Register; // an individual CR bit.
15076   else if ((StringRef(constraint) == "wa" ||
15077             StringRef(constraint) == "wd" ||
15078             StringRef(constraint) == "wf") &&
15079            type->isVectorTy())
15080     return CW_Register;
15081   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15082     return CW_Register; // just hold 64-bit integers data.
15083   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15084     return CW_Register;
15085   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15086     return CW_Register;
15087 
15088   switch (*constraint) {
15089   default:
15090     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15091     break;
15092   case 'b':
15093     if (type->isIntegerTy())
15094       weight = CW_Register;
15095     break;
15096   case 'f':
15097     if (type->isFloatTy())
15098       weight = CW_Register;
15099     break;
15100   case 'd':
15101     if (type->isDoubleTy())
15102       weight = CW_Register;
15103     break;
15104   case 'v':
15105     if (type->isVectorTy())
15106       weight = CW_Register;
15107     break;
15108   case 'y':
15109     weight = CW_Register;
15110     break;
15111   case 'Z':
15112     weight = CW_Memory;
15113     break;
15114   }
15115   return weight;
15116 }
15117 
15118 std::pair<unsigned, const TargetRegisterClass *>
15119 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15120                                                 StringRef Constraint,
15121                                                 MVT VT) const {
15122   if (Constraint.size() == 1) {
15123     // GCC RS6000 Constraint Letters
15124     switch (Constraint[0]) {
15125     case 'b':   // R1-R31
15126       if (VT == MVT::i64 && Subtarget.isPPC64())
15127         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15128       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15129     case 'r':   // R0-R31
15130       if (VT == MVT::i64 && Subtarget.isPPC64())
15131         return std::make_pair(0U, &PPC::G8RCRegClass);
15132       return std::make_pair(0U, &PPC::GPRCRegClass);
15133     // 'd' and 'f' constraints are both defined to be "the floating point
15134     // registers", where one is for 32-bit and the other for 64-bit. We don't
15135     // really care overly much here so just give them all the same reg classes.
15136     case 'd':
15137     case 'f':
15138       if (Subtarget.hasSPE()) {
15139         if (VT == MVT::f32 || VT == MVT::i32)
15140           return std::make_pair(0U, &PPC::GPRCRegClass);
15141         if (VT == MVT::f64 || VT == MVT::i64)
15142           return std::make_pair(0U, &PPC::SPERCRegClass);
15143       } else {
15144         if (VT == MVT::f32 || VT == MVT::i32)
15145           return std::make_pair(0U, &PPC::F4RCRegClass);
15146         if (VT == MVT::f64 || VT == MVT::i64)
15147           return std::make_pair(0U, &PPC::F8RCRegClass);
15148         if (VT == MVT::v4f64 && Subtarget.hasQPX())
15149           return std::make_pair(0U, &PPC::QFRCRegClass);
15150         if (VT == MVT::v4f32 && Subtarget.hasQPX())
15151           return std::make_pair(0U, &PPC::QSRCRegClass);
15152       }
15153       break;
15154     case 'v':
15155       if (VT == MVT::v4f64 && Subtarget.hasQPX())
15156         return std::make_pair(0U, &PPC::QFRCRegClass);
15157       if (VT == MVT::v4f32 && Subtarget.hasQPX())
15158         return std::make_pair(0U, &PPC::QSRCRegClass);
15159       if (Subtarget.hasAltivec())
15160         return std::make_pair(0U, &PPC::VRRCRegClass);
15161       break;
15162     case 'y':   // crrc
15163       return std::make_pair(0U, &PPC::CRRCRegClass);
15164     }
15165   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15166     // An individual CR bit.
15167     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15168   } else if ((Constraint == "wa" || Constraint == "wd" ||
15169              Constraint == "wf" || Constraint == "wi") &&
15170              Subtarget.hasVSX()) {
15171     return std::make_pair(0U, &PPC::VSRCRegClass);
15172   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15173     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15174       return std::make_pair(0U, &PPC::VSSRCRegClass);
15175     else
15176       return std::make_pair(0U, &PPC::VSFRCRegClass);
15177   }
15178 
15179   // If we name a VSX register, we can't defer to the base class because it
15180   // will not recognize the correct register (their names will be VSL{0-31}
15181   // and V{0-31} so they won't match). So we match them here.
15182   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15183     int VSNum = atoi(Constraint.data() + 3);
15184     assert(VSNum >= 0 && VSNum <= 63 &&
15185            "Attempted to access a vsr out of range");
15186     if (VSNum < 32)
15187       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15188     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15189   }
15190   std::pair<unsigned, const TargetRegisterClass *> R =
15191       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15192 
15193   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15194   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15195   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15196   // register.
15197   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15198   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15199   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15200       PPC::GPRCRegClass.contains(R.first))
15201     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15202                             PPC::sub_32, &PPC::G8RCRegClass),
15203                           &PPC::G8RCRegClass);
15204 
15205   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15206   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15207     R.first = PPC::CR0;
15208     R.second = &PPC::CRRCRegClass;
15209   }
15210 
15211   return R;
15212 }
15213 
15214 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15215 /// vector.  If it is invalid, don't add anything to Ops.
15216 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15217                                                      std::string &Constraint,
15218                                                      std::vector<SDValue>&Ops,
15219                                                      SelectionDAG &DAG) const {
15220   SDValue Result;
15221 
15222   // Only support length 1 constraints.
15223   if (Constraint.length() > 1) return;
15224 
15225   char Letter = Constraint[0];
15226   switch (Letter) {
15227   default: break;
15228   case 'I':
15229   case 'J':
15230   case 'K':
15231   case 'L':
15232   case 'M':
15233   case 'N':
15234   case 'O':
15235   case 'P': {
15236     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15237     if (!CST) return; // Must be an immediate to match.
15238     SDLoc dl(Op);
15239     int64_t Value = CST->getSExtValue();
15240     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15241                          // numbers are printed as such.
15242     switch (Letter) {
15243     default: llvm_unreachable("Unknown constraint letter!");
15244     case 'I':  // "I" is a signed 16-bit constant.
15245       if (isInt<16>(Value))
15246         Result = DAG.getTargetConstant(Value, dl, TCVT);
15247       break;
15248     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15249       if (isShiftedUInt<16, 16>(Value))
15250         Result = DAG.getTargetConstant(Value, dl, TCVT);
15251       break;
15252     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15253       if (isShiftedInt<16, 16>(Value))
15254         Result = DAG.getTargetConstant(Value, dl, TCVT);
15255       break;
15256     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15257       if (isUInt<16>(Value))
15258         Result = DAG.getTargetConstant(Value, dl, TCVT);
15259       break;
15260     case 'M':  // "M" is a constant that is greater than 31.
15261       if (Value > 31)
15262         Result = DAG.getTargetConstant(Value, dl, TCVT);
15263       break;
15264     case 'N':  // "N" is a positive constant that is an exact power of two.
15265       if (Value > 0 && isPowerOf2_64(Value))
15266         Result = DAG.getTargetConstant(Value, dl, TCVT);
15267       break;
15268     case 'O':  // "O" is the constant zero.
15269       if (Value == 0)
15270         Result = DAG.getTargetConstant(Value, dl, TCVT);
15271       break;
15272     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15273       if (isInt<16>(-Value))
15274         Result = DAG.getTargetConstant(Value, dl, TCVT);
15275       break;
15276     }
15277     break;
15278   }
15279   }
15280 
15281   if (Result.getNode()) {
15282     Ops.push_back(Result);
15283     return;
15284   }
15285 
15286   // Handle standard constraint letters.
15287   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15288 }
15289 
15290 // isLegalAddressingMode - Return true if the addressing mode represented
15291 // by AM is legal for this target, for a load/store of the specified type.
15292 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15293                                               const AddrMode &AM, Type *Ty,
15294                                               unsigned AS, Instruction *I) const {
15295   // PPC does not allow r+i addressing modes for vectors!
15296   if (Ty->isVectorTy() && AM.BaseOffs != 0)
15297     return false;
15298 
15299   // PPC allows a sign-extended 16-bit immediate field.
15300   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15301     return false;
15302 
15303   // No global is ever allowed as a base.
15304   if (AM.BaseGV)
15305     return false;
15306 
15307   // PPC only support r+r,
15308   switch (AM.Scale) {
15309   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15310     break;
15311   case 1:
15312     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15313       return false;
15314     // Otherwise we have r+r or r+i.
15315     break;
15316   case 2:
15317     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15318       return false;
15319     // Allow 2*r as r+r.
15320     break;
15321   default:
15322     // No other scales are supported.
15323     return false;
15324   }
15325 
15326   return true;
15327 }
15328 
15329 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15330                                            SelectionDAG &DAG) const {
15331   MachineFunction &MF = DAG.getMachineFunction();
15332   MachineFrameInfo &MFI = MF.getFrameInfo();
15333   MFI.setReturnAddressIsTaken(true);
15334 
15335   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15336     return SDValue();
15337 
15338   SDLoc dl(Op);
15339   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15340 
15341   // Make sure the function does not optimize away the store of the RA to
15342   // the stack.
15343   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15344   FuncInfo->setLRStoreRequired();
15345   bool isPPC64 = Subtarget.isPPC64();
15346   auto PtrVT = getPointerTy(MF.getDataLayout());
15347 
15348   if (Depth > 0) {
15349     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15350     SDValue Offset =
15351         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15352                         isPPC64 ? MVT::i64 : MVT::i32);
15353     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15354                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15355                        MachinePointerInfo());
15356   }
15357 
15358   // Just load the return address off the stack.
15359   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15360   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15361                      MachinePointerInfo());
15362 }
15363 
15364 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15365                                           SelectionDAG &DAG) const {
15366   SDLoc dl(Op);
15367   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15368 
15369   MachineFunction &MF = DAG.getMachineFunction();
15370   MachineFrameInfo &MFI = MF.getFrameInfo();
15371   MFI.setFrameAddressIsTaken(true);
15372 
15373   EVT PtrVT = getPointerTy(MF.getDataLayout());
15374   bool isPPC64 = PtrVT == MVT::i64;
15375 
15376   // Naked functions never have a frame pointer, and so we use r1. For all
15377   // other functions, this decision must be delayed until during PEI.
15378   unsigned FrameReg;
15379   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15380     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15381   else
15382     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15383 
15384   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15385                                          PtrVT);
15386   while (Depth--)
15387     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15388                             FrameAddr, MachinePointerInfo());
15389   return FrameAddr;
15390 }
15391 
15392 // FIXME? Maybe this could be a TableGen attribute on some registers and
15393 // this table could be generated automatically from RegInfo.
15394 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15395                                               const MachineFunction &MF) const {
15396   bool isPPC64 = Subtarget.isPPC64();
15397 
15398   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15399   if (!is64Bit && VT != LLT::scalar(32))
15400     report_fatal_error("Invalid register global variable type");
15401 
15402   Register Reg = StringSwitch<Register>(RegName)
15403                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15404                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15405                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15406                      .Default(Register());
15407 
15408   if (Reg)
15409     return Reg;
15410   report_fatal_error("Invalid register name global variable");
15411 }
15412 
15413 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15414   // 32-bit SVR4 ABI access everything as got-indirect.
15415   if (Subtarget.is32BitELFABI())
15416     return true;
15417 
15418   // AIX accesses everything indirectly through the TOC, which is similar to
15419   // the GOT.
15420   if (Subtarget.isAIXABI())
15421     return true;
15422 
15423   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15424   // If it is small or large code model, module locals are accessed
15425   // indirectly by loading their address from .toc/.got.
15426   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15427     return true;
15428 
15429   // JumpTable and BlockAddress are accessed as got-indirect.
15430   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15431     return true;
15432 
15433   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15434     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15435 
15436   return false;
15437 }
15438 
15439 bool
15440 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15441   // The PowerPC target isn't yet aware of offsets.
15442   return false;
15443 }
15444 
15445 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15446                                            const CallInst &I,
15447                                            MachineFunction &MF,
15448                                            unsigned Intrinsic) const {
15449   switch (Intrinsic) {
15450   case Intrinsic::ppc_qpx_qvlfd:
15451   case Intrinsic::ppc_qpx_qvlfs:
15452   case Intrinsic::ppc_qpx_qvlfcd:
15453   case Intrinsic::ppc_qpx_qvlfcs:
15454   case Intrinsic::ppc_qpx_qvlfiwa:
15455   case Intrinsic::ppc_qpx_qvlfiwz:
15456   case Intrinsic::ppc_altivec_lvx:
15457   case Intrinsic::ppc_altivec_lvxl:
15458   case Intrinsic::ppc_altivec_lvebx:
15459   case Intrinsic::ppc_altivec_lvehx:
15460   case Intrinsic::ppc_altivec_lvewx:
15461   case Intrinsic::ppc_vsx_lxvd2x:
15462   case Intrinsic::ppc_vsx_lxvw4x: {
15463     EVT VT;
15464     switch (Intrinsic) {
15465     case Intrinsic::ppc_altivec_lvebx:
15466       VT = MVT::i8;
15467       break;
15468     case Intrinsic::ppc_altivec_lvehx:
15469       VT = MVT::i16;
15470       break;
15471     case Intrinsic::ppc_altivec_lvewx:
15472       VT = MVT::i32;
15473       break;
15474     case Intrinsic::ppc_vsx_lxvd2x:
15475       VT = MVT::v2f64;
15476       break;
15477     case Intrinsic::ppc_qpx_qvlfd:
15478       VT = MVT::v4f64;
15479       break;
15480     case Intrinsic::ppc_qpx_qvlfs:
15481       VT = MVT::v4f32;
15482       break;
15483     case Intrinsic::ppc_qpx_qvlfcd:
15484       VT = MVT::v2f64;
15485       break;
15486     case Intrinsic::ppc_qpx_qvlfcs:
15487       VT = MVT::v2f32;
15488       break;
15489     default:
15490       VT = MVT::v4i32;
15491       break;
15492     }
15493 
15494     Info.opc = ISD::INTRINSIC_W_CHAIN;
15495     Info.memVT = VT;
15496     Info.ptrVal = I.getArgOperand(0);
15497     Info.offset = -VT.getStoreSize()+1;
15498     Info.size = 2*VT.getStoreSize()-1;
15499     Info.align = Align(1);
15500     Info.flags = MachineMemOperand::MOLoad;
15501     return true;
15502   }
15503   case Intrinsic::ppc_qpx_qvlfda:
15504   case Intrinsic::ppc_qpx_qvlfsa:
15505   case Intrinsic::ppc_qpx_qvlfcda:
15506   case Intrinsic::ppc_qpx_qvlfcsa:
15507   case Intrinsic::ppc_qpx_qvlfiwaa:
15508   case Intrinsic::ppc_qpx_qvlfiwza: {
15509     EVT VT;
15510     switch (Intrinsic) {
15511     case Intrinsic::ppc_qpx_qvlfda:
15512       VT = MVT::v4f64;
15513       break;
15514     case Intrinsic::ppc_qpx_qvlfsa:
15515       VT = MVT::v4f32;
15516       break;
15517     case Intrinsic::ppc_qpx_qvlfcda:
15518       VT = MVT::v2f64;
15519       break;
15520     case Intrinsic::ppc_qpx_qvlfcsa:
15521       VT = MVT::v2f32;
15522       break;
15523     default:
15524       VT = MVT::v4i32;
15525       break;
15526     }
15527 
15528     Info.opc = ISD::INTRINSIC_W_CHAIN;
15529     Info.memVT = VT;
15530     Info.ptrVal = I.getArgOperand(0);
15531     Info.offset = 0;
15532     Info.size = VT.getStoreSize();
15533     Info.align = Align(1);
15534     Info.flags = MachineMemOperand::MOLoad;
15535     return true;
15536   }
15537   case Intrinsic::ppc_qpx_qvstfd:
15538   case Intrinsic::ppc_qpx_qvstfs:
15539   case Intrinsic::ppc_qpx_qvstfcd:
15540   case Intrinsic::ppc_qpx_qvstfcs:
15541   case Intrinsic::ppc_qpx_qvstfiw:
15542   case Intrinsic::ppc_altivec_stvx:
15543   case Intrinsic::ppc_altivec_stvxl:
15544   case Intrinsic::ppc_altivec_stvebx:
15545   case Intrinsic::ppc_altivec_stvehx:
15546   case Intrinsic::ppc_altivec_stvewx:
15547   case Intrinsic::ppc_vsx_stxvd2x:
15548   case Intrinsic::ppc_vsx_stxvw4x: {
15549     EVT VT;
15550     switch (Intrinsic) {
15551     case Intrinsic::ppc_altivec_stvebx:
15552       VT = MVT::i8;
15553       break;
15554     case Intrinsic::ppc_altivec_stvehx:
15555       VT = MVT::i16;
15556       break;
15557     case Intrinsic::ppc_altivec_stvewx:
15558       VT = MVT::i32;
15559       break;
15560     case Intrinsic::ppc_vsx_stxvd2x:
15561       VT = MVT::v2f64;
15562       break;
15563     case Intrinsic::ppc_qpx_qvstfd:
15564       VT = MVT::v4f64;
15565       break;
15566     case Intrinsic::ppc_qpx_qvstfs:
15567       VT = MVT::v4f32;
15568       break;
15569     case Intrinsic::ppc_qpx_qvstfcd:
15570       VT = MVT::v2f64;
15571       break;
15572     case Intrinsic::ppc_qpx_qvstfcs:
15573       VT = MVT::v2f32;
15574       break;
15575     default:
15576       VT = MVT::v4i32;
15577       break;
15578     }
15579 
15580     Info.opc = ISD::INTRINSIC_VOID;
15581     Info.memVT = VT;
15582     Info.ptrVal = I.getArgOperand(1);
15583     Info.offset = -VT.getStoreSize()+1;
15584     Info.size = 2*VT.getStoreSize()-1;
15585     Info.align = Align(1);
15586     Info.flags = MachineMemOperand::MOStore;
15587     return true;
15588   }
15589   case Intrinsic::ppc_qpx_qvstfda:
15590   case Intrinsic::ppc_qpx_qvstfsa:
15591   case Intrinsic::ppc_qpx_qvstfcda:
15592   case Intrinsic::ppc_qpx_qvstfcsa:
15593   case Intrinsic::ppc_qpx_qvstfiwa: {
15594     EVT VT;
15595     switch (Intrinsic) {
15596     case Intrinsic::ppc_qpx_qvstfda:
15597       VT = MVT::v4f64;
15598       break;
15599     case Intrinsic::ppc_qpx_qvstfsa:
15600       VT = MVT::v4f32;
15601       break;
15602     case Intrinsic::ppc_qpx_qvstfcda:
15603       VT = MVT::v2f64;
15604       break;
15605     case Intrinsic::ppc_qpx_qvstfcsa:
15606       VT = MVT::v2f32;
15607       break;
15608     default:
15609       VT = MVT::v4i32;
15610       break;
15611     }
15612 
15613     Info.opc = ISD::INTRINSIC_VOID;
15614     Info.memVT = VT;
15615     Info.ptrVal = I.getArgOperand(1);
15616     Info.offset = 0;
15617     Info.size = VT.getStoreSize();
15618     Info.align = Align(1);
15619     Info.flags = MachineMemOperand::MOStore;
15620     return true;
15621   }
15622   default:
15623     break;
15624   }
15625 
15626   return false;
15627 }
15628 
15629 /// It returns EVT::Other if the type should be determined using generic
15630 /// target-independent logic.
15631 EVT PPCTargetLowering::getOptimalMemOpType(
15632     const MemOp &Op, const AttributeList &FuncAttributes) const {
15633   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15634     // When expanding a memset, require at least two QPX instructions to cover
15635     // the cost of loading the value to be stored from the constant pool.
15636     if (Subtarget.hasQPX() && Op.size() >= 32 &&
15637         (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) &&
15638         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15639       return MVT::v4f64;
15640     }
15641 
15642     // We should use Altivec/VSX loads and stores when available. For unaligned
15643     // addresses, unaligned VSX loads are only fast starting with the P8.
15644     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15645         (Op.isAligned(Align(16)) ||
15646          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15647       return MVT::v4i32;
15648   }
15649 
15650   if (Subtarget.isPPC64()) {
15651     return MVT::i64;
15652   }
15653 
15654   return MVT::i32;
15655 }
15656 
15657 /// Returns true if it is beneficial to convert a load of a constant
15658 /// to just the constant itself.
15659 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15660                                                           Type *Ty) const {
15661   assert(Ty->isIntegerTy());
15662 
15663   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15664   return !(BitSize == 0 || BitSize > 64);
15665 }
15666 
15667 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15668   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15669     return false;
15670   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15671   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15672   return NumBits1 == 64 && NumBits2 == 32;
15673 }
15674 
15675 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15676   if (!VT1.isInteger() || !VT2.isInteger())
15677     return false;
15678   unsigned NumBits1 = VT1.getSizeInBits();
15679   unsigned NumBits2 = VT2.getSizeInBits();
15680   return NumBits1 == 64 && NumBits2 == 32;
15681 }
15682 
15683 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15684   // Generally speaking, zexts are not free, but they are free when they can be
15685   // folded with other operations.
15686   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15687     EVT MemVT = LD->getMemoryVT();
15688     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15689          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15690         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15691          LD->getExtensionType() == ISD::ZEXTLOAD))
15692       return true;
15693   }
15694 
15695   // FIXME: Add other cases...
15696   //  - 32-bit shifts with a zext to i64
15697   //  - zext after ctlz, bswap, etc.
15698   //  - zext after and by a constant mask
15699 
15700   return TargetLowering::isZExtFree(Val, VT2);
15701 }
15702 
15703 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15704   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15705          "invalid fpext types");
15706   // Extending to float128 is not free.
15707   if (DestVT == MVT::f128)
15708     return false;
15709   return true;
15710 }
15711 
15712 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15713   return isInt<16>(Imm) || isUInt<16>(Imm);
15714 }
15715 
15716 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15717   return isInt<16>(Imm) || isUInt<16>(Imm);
15718 }
15719 
15720 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15721                                                        unsigned,
15722                                                        unsigned,
15723                                                        MachineMemOperand::Flags,
15724                                                        bool *Fast) const {
15725   if (DisablePPCUnaligned)
15726     return false;
15727 
15728   // PowerPC supports unaligned memory access for simple non-vector types.
15729   // Although accessing unaligned addresses is not as efficient as accessing
15730   // aligned addresses, it is generally more efficient than manual expansion,
15731   // and generally only traps for software emulation when crossing page
15732   // boundaries.
15733 
15734   if (!VT.isSimple())
15735     return false;
15736 
15737   if (VT.isFloatingPoint() && !VT.isVector() &&
15738       !Subtarget.allowsUnalignedFPAccess())
15739     return false;
15740 
15741   if (VT.getSimpleVT().isVector()) {
15742     if (Subtarget.hasVSX()) {
15743       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15744           VT != MVT::v4f32 && VT != MVT::v4i32)
15745         return false;
15746     } else {
15747       return false;
15748     }
15749   }
15750 
15751   if (VT == MVT::ppcf128)
15752     return false;
15753 
15754   if (Fast)
15755     *Fast = true;
15756 
15757   return true;
15758 }
15759 
15760 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15761                                                    EVT VT) const {
15762   return isFMAFasterThanFMulAndFAdd(
15763       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15764 }
15765 
15766 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15767                                                    Type *Ty) const {
15768   switch (Ty->getScalarType()->getTypeID()) {
15769   case Type::FloatTyID:
15770   case Type::DoubleTyID:
15771     return true;
15772   case Type::FP128TyID:
15773     return EnableQuadPrecision && Subtarget.hasP9Vector();
15774   default:
15775     return false;
15776   }
15777 }
15778 
15779 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist.
15780 // FIXME: add more patterns which are profitable to hoist.
15781 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
15782   if (I->getOpcode() != Instruction::FMul)
15783     return true;
15784 
15785   if (!I->hasOneUse())
15786     return true;
15787 
15788   Instruction *User = I->user_back();
15789   assert(User && "A single use instruction with no uses.");
15790 
15791   if (User->getOpcode() != Instruction::FSub &&
15792       User->getOpcode() != Instruction::FAdd)
15793     return true;
15794 
15795   const TargetOptions &Options = getTargetMachine().Options;
15796   const Function *F = I->getFunction();
15797   const DataLayout &DL = F->getParent()->getDataLayout();
15798   Type *Ty = User->getOperand(0)->getType();
15799 
15800   return !(
15801       isFMAFasterThanFMulAndFAdd(*F, Ty) &&
15802       isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
15803       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
15804 }
15805 
15806 const MCPhysReg *
15807 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15808   // LR is a callee-save register, but we must treat it as clobbered by any call
15809   // site. Hence we include LR in the scratch registers, which are in turn added
15810   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15811   // to CTR, which is used by any indirect call.
15812   static const MCPhysReg ScratchRegs[] = {
15813     PPC::X12, PPC::LR8, PPC::CTR8, 0
15814   };
15815 
15816   return ScratchRegs;
15817 }
15818 
15819 Register PPCTargetLowering::getExceptionPointerRegister(
15820     const Constant *PersonalityFn) const {
15821   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15822 }
15823 
15824 Register PPCTargetLowering::getExceptionSelectorRegister(
15825     const Constant *PersonalityFn) const {
15826   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15827 }
15828 
15829 bool
15830 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15831                      EVT VT , unsigned DefinedValues) const {
15832   if (VT == MVT::v2i64)
15833     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15834 
15835   if (Subtarget.hasVSX() || Subtarget.hasQPX())
15836     return true;
15837 
15838   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15839 }
15840 
15841 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15842   if (DisableILPPref || Subtarget.enableMachineScheduler())
15843     return TargetLowering::getSchedulingPreference(N);
15844 
15845   return Sched::ILP;
15846 }
15847 
15848 // Create a fast isel object.
15849 FastISel *
15850 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15851                                   const TargetLibraryInfo *LibInfo) const {
15852   return PPC::createFastISel(FuncInfo, LibInfo);
15853 }
15854 
15855 // 'Inverted' means the FMA opcode after negating one multiplicand.
15856 // For example, (fma -a b c) = (fnmsub a b c)
15857 static unsigned invertFMAOpcode(unsigned Opc) {
15858   switch (Opc) {
15859   default:
15860     llvm_unreachable("Invalid FMA opcode for PowerPC!");
15861   case ISD::FMA:
15862     return PPCISD::FNMSUB;
15863   case PPCISD::FNMSUB:
15864     return ISD::FMA;
15865   }
15866 }
15867 
15868 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
15869                                                 bool LegalOps, bool OptForSize,
15870                                                 NegatibleCost &Cost,
15871                                                 unsigned Depth) const {
15872   if (Depth > SelectionDAG::MaxRecursionDepth)
15873     return SDValue();
15874 
15875   unsigned Opc = Op.getOpcode();
15876   EVT VT = Op.getValueType();
15877   SDNodeFlags Flags = Op.getNode()->getFlags();
15878 
15879   switch (Opc) {
15880   case PPCISD::FNMSUB:
15881     // TODO: QPX subtarget is deprecated. No transformation here.
15882     if (!Op.hasOneUse() || !isTypeLegal(VT) || Subtarget.hasQPX())
15883       break;
15884 
15885     const TargetOptions &Options = getTargetMachine().Options;
15886     SDValue N0 = Op.getOperand(0);
15887     SDValue N1 = Op.getOperand(1);
15888     SDValue N2 = Op.getOperand(2);
15889     SDLoc Loc(Op);
15890 
15891     NegatibleCost N2Cost = NegatibleCost::Expensive;
15892     SDValue NegN2 =
15893         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
15894 
15895     if (!NegN2)
15896       return SDValue();
15897 
15898     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
15899     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
15900     // These transformations may change sign of zeroes. For example,
15901     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
15902     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
15903       // Try and choose the cheaper one to negate.
15904       NegatibleCost N0Cost = NegatibleCost::Expensive;
15905       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
15906                                            N0Cost, Depth + 1);
15907 
15908       NegatibleCost N1Cost = NegatibleCost::Expensive;
15909       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
15910                                            N1Cost, Depth + 1);
15911 
15912       if (NegN0 && N0Cost <= N1Cost) {
15913         Cost = std::min(N0Cost, N2Cost);
15914         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
15915       } else if (NegN1) {
15916         Cost = std::min(N1Cost, N2Cost);
15917         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
15918       }
15919     }
15920 
15921     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
15922     if (isOperationLegal(ISD::FMA, VT)) {
15923       Cost = N2Cost;
15924       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
15925     }
15926 
15927     break;
15928   }
15929 
15930   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
15931                                               Cost, Depth);
15932 }
15933 
15934 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15935 bool PPCTargetLowering::useLoadStackGuardNode() const {
15936   if (!Subtarget.isTargetLinux())
15937     return TargetLowering::useLoadStackGuardNode();
15938   return true;
15939 }
15940 
15941 // Override to disable global variable loading on Linux.
15942 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15943   if (!Subtarget.isTargetLinux())
15944     return TargetLowering::insertSSPDeclarations(M);
15945 }
15946 
15947 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15948                                      bool ForCodeSize) const {
15949   if (!VT.isSimple() || !Subtarget.hasVSX())
15950     return false;
15951 
15952   switch(VT.getSimpleVT().SimpleTy) {
15953   default:
15954     // For FP types that are currently not supported by PPC backend, return
15955     // false. Examples: f16, f80.
15956     return false;
15957   case MVT::f32:
15958   case MVT::f64:
15959   case MVT::ppcf128:
15960     return Imm.isPosZero();
15961   }
15962 }
15963 
15964 // For vector shift operation op, fold
15965 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15966 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15967                                   SelectionDAG &DAG) {
15968   SDValue N0 = N->getOperand(0);
15969   SDValue N1 = N->getOperand(1);
15970   EVT VT = N0.getValueType();
15971   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15972   unsigned Opcode = N->getOpcode();
15973   unsigned TargetOpcode;
15974 
15975   switch (Opcode) {
15976   default:
15977     llvm_unreachable("Unexpected shift operation");
15978   case ISD::SHL:
15979     TargetOpcode = PPCISD::SHL;
15980     break;
15981   case ISD::SRL:
15982     TargetOpcode = PPCISD::SRL;
15983     break;
15984   case ISD::SRA:
15985     TargetOpcode = PPCISD::SRA;
15986     break;
15987   }
15988 
15989   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15990       N1->getOpcode() == ISD::AND)
15991     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15992       if (Mask->getZExtValue() == OpSizeInBits - 1)
15993         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15994 
15995   return SDValue();
15996 }
15997 
15998 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15999   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16000     return Value;
16001 
16002   SDValue N0 = N->getOperand(0);
16003   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16004   if (!Subtarget.isISA3_0() ||
16005       N0.getOpcode() != ISD::SIGN_EXTEND ||
16006       N0.getOperand(0).getValueType() != MVT::i32 ||
16007       CN1 == nullptr || N->getValueType(0) != MVT::i64)
16008     return SDValue();
16009 
16010   // We can't save an operation here if the value is already extended, and
16011   // the existing shift is easier to combine.
16012   SDValue ExtsSrc = N0.getOperand(0);
16013   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16014       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16015     return SDValue();
16016 
16017   SDLoc DL(N0);
16018   SDValue ShiftBy = SDValue(CN1, 0);
16019   // We want the shift amount to be i32 on the extswli, but the shift could
16020   // have an i64.
16021   if (ShiftBy.getValueType() == MVT::i64)
16022     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16023 
16024   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16025                          ShiftBy);
16026 }
16027 
16028 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16029   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16030     return Value;
16031 
16032   return SDValue();
16033 }
16034 
16035 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16036   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16037     return Value;
16038 
16039   return SDValue();
16040 }
16041 
16042 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16043 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16044 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16045 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16046 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16047                                  const PPCSubtarget &Subtarget) {
16048   if (!Subtarget.isPPC64())
16049     return SDValue();
16050 
16051   SDValue LHS = N->getOperand(0);
16052   SDValue RHS = N->getOperand(1);
16053 
16054   auto isZextOfCompareWithConstant = [](SDValue Op) {
16055     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16056         Op.getValueType() != MVT::i64)
16057       return false;
16058 
16059     SDValue Cmp = Op.getOperand(0);
16060     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16061         Cmp.getOperand(0).getValueType() != MVT::i64)
16062       return false;
16063 
16064     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
16065       int64_t NegConstant = 0 - Constant->getSExtValue();
16066       // Due to the limitations of the addi instruction,
16067       // -C is required to be [-32768, 32767].
16068       return isInt<16>(NegConstant);
16069     }
16070 
16071     return false;
16072   };
16073 
16074   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
16075   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16076 
16077   // If there is a pattern, canonicalize a zext operand to the RHS.
16078   if (LHSHasPattern && !RHSHasPattern)
16079     std::swap(LHS, RHS);
16080   else if (!LHSHasPattern && !RHSHasPattern)
16081     return SDValue();
16082 
16083   SDLoc DL(N);
16084   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16085   SDValue Cmp = RHS.getOperand(0);
16086   SDValue Z = Cmp.getOperand(0);
16087   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
16088 
16089   assert(Constant && "Constant Should not be a null pointer.");
16090   int64_t NegConstant = 0 - Constant->getSExtValue();
16091 
16092   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16093   default: break;
16094   case ISD::SETNE: {
16095     //                                 when C == 0
16096     //                             --> addze X, (addic Z, -1).carry
16097     //                            /
16098     // add X, (zext(setne Z, C))--
16099     //                            \    when -32768 <= -C <= 32767 && C != 0
16100     //                             --> addze X, (addic (addi Z, -C), -1).carry
16101     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16102                               DAG.getConstant(NegConstant, DL, MVT::i64));
16103     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16104     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16105                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16106     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16107                        SDValue(Addc.getNode(), 1));
16108     }
16109   case ISD::SETEQ: {
16110     //                                 when C == 0
16111     //                             --> addze X, (subfic Z, 0).carry
16112     //                            /
16113     // add X, (zext(sete  Z, C))--
16114     //                            \    when -32768 <= -C <= 32767 && C != 0
16115     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16116     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16117                               DAG.getConstant(NegConstant, DL, MVT::i64));
16118     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16119     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16120                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16121     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16122                        SDValue(Subc.getNode(), 1));
16123     }
16124   }
16125 
16126   return SDValue();
16127 }
16128 
16129 // Transform
16130 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16131 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16132 // In this case both C1 and C2 must be known constants.
16133 // C1+C2 must fit into a 34 bit signed integer.
16134 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16135                                           const PPCSubtarget &Subtarget) {
16136   if (!Subtarget.isUsingPCRelativeCalls())
16137     return SDValue();
16138 
16139   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16140   // If we find that node try to cast the Global Address and the Constant.
16141   SDValue LHS = N->getOperand(0);
16142   SDValue RHS = N->getOperand(1);
16143 
16144   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16145     std::swap(LHS, RHS);
16146 
16147   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16148     return SDValue();
16149 
16150   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16151   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16152   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16153 
16154   // Check that both casts succeeded.
16155   if (!GSDN || !ConstNode)
16156     return SDValue();
16157 
16158   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16159   SDLoc DL(GSDN);
16160 
16161   // The signed int offset needs to fit in 34 bits.
16162   if (!isInt<34>(NewOffset))
16163     return SDValue();
16164 
16165   // The new global address is a copy of the old global address except
16166   // that it has the updated Offset.
16167   SDValue GA =
16168       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16169                                  NewOffset, GSDN->getTargetFlags());
16170   SDValue MatPCRel =
16171       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16172   return MatPCRel;
16173 }
16174 
16175 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16176   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16177     return Value;
16178 
16179   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16180     return Value;
16181 
16182   return SDValue();
16183 }
16184 
16185 // Detect TRUNCATE operations on bitcasts of float128 values.
16186 // What we are looking for here is the situtation where we extract a subset
16187 // of bits from a 128 bit float.
16188 // This can be of two forms:
16189 // 1) BITCAST of f128 feeding TRUNCATE
16190 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16191 // The reason this is required is because we do not have a legal i128 type
16192 // and so we want to prevent having to store the f128 and then reload part
16193 // of it.
16194 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16195                                            DAGCombinerInfo &DCI) const {
16196   // If we are using CRBits then try that first.
16197   if (Subtarget.useCRBits()) {
16198     // Check if CRBits did anything and return that if it did.
16199     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16200       return CRTruncValue;
16201   }
16202 
16203   SDLoc dl(N);
16204   SDValue Op0 = N->getOperand(0);
16205 
16206   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
16207   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
16208     EVT VT = N->getValueType(0);
16209     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16210       return SDValue();
16211     SDValue Sub = Op0.getOperand(0);
16212     if (Sub.getOpcode() == ISD::SUB) {
16213       SDValue SubOp0 = Sub.getOperand(0);
16214       SDValue SubOp1 = Sub.getOperand(1);
16215       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16216           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16217         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16218                                SubOp1.getOperand(0),
16219                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16220       }
16221     }
16222   }
16223 
16224   // Looking for a truncate of i128 to i64.
16225   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16226     return SDValue();
16227 
16228   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16229 
16230   // SRL feeding TRUNCATE.
16231   if (Op0.getOpcode() == ISD::SRL) {
16232     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16233     // The right shift has to be by 64 bits.
16234     if (!ConstNode || ConstNode->getZExtValue() != 64)
16235       return SDValue();
16236 
16237     // Switch the element number to extract.
16238     EltToExtract = EltToExtract ? 0 : 1;
16239     // Update Op0 past the SRL.
16240     Op0 = Op0.getOperand(0);
16241   }
16242 
16243   // BITCAST feeding a TRUNCATE possibly via SRL.
16244   if (Op0.getOpcode() == ISD::BITCAST &&
16245       Op0.getValueType() == MVT::i128 &&
16246       Op0.getOperand(0).getValueType() == MVT::f128) {
16247     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16248     return DCI.DAG.getNode(
16249         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16250         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16251   }
16252   return SDValue();
16253 }
16254 
16255 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16256   SelectionDAG &DAG = DCI.DAG;
16257 
16258   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16259   if (!ConstOpOrElement)
16260     return SDValue();
16261 
16262   // An imul is usually smaller than the alternative sequence for legal type.
16263   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16264       isOperationLegal(ISD::MUL, N->getValueType(0)))
16265     return SDValue();
16266 
16267   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16268     switch (this->Subtarget.getCPUDirective()) {
16269     default:
16270       // TODO: enhance the condition for subtarget before pwr8
16271       return false;
16272     case PPC::DIR_PWR8:
16273       //  type        mul     add    shl
16274       // scalar        4       1      1
16275       // vector        7       2      2
16276       return true;
16277     case PPC::DIR_PWR9:
16278     case PPC::DIR_PWR10:
16279     case PPC::DIR_PWR_FUTURE:
16280       //  type        mul     add    shl
16281       // scalar        5       2      2
16282       // vector        7       2      2
16283 
16284       // The cycle RATIO of related operations are showed as a table above.
16285       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16286       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16287       // are 4, it is always profitable; but for 3 instrs patterns
16288       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16289       // So we should only do it for vector type.
16290       return IsAddOne && IsNeg ? VT.isVector() : true;
16291     }
16292   };
16293 
16294   EVT VT = N->getValueType(0);
16295   SDLoc DL(N);
16296 
16297   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16298   bool IsNeg = MulAmt.isNegative();
16299   APInt MulAmtAbs = MulAmt.abs();
16300 
16301   if ((MulAmtAbs - 1).isPowerOf2()) {
16302     // (mul x, 2^N + 1) => (add (shl x, N), x)
16303     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16304 
16305     if (!IsProfitable(IsNeg, true, VT))
16306       return SDValue();
16307 
16308     SDValue Op0 = N->getOperand(0);
16309     SDValue Op1 =
16310         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16311                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16312     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16313 
16314     if (!IsNeg)
16315       return Res;
16316 
16317     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16318   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16319     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16320     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16321 
16322     if (!IsProfitable(IsNeg, false, VT))
16323       return SDValue();
16324 
16325     SDValue Op0 = N->getOperand(0);
16326     SDValue Op1 =
16327         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16328                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16329 
16330     if (!IsNeg)
16331       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16332     else
16333       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16334 
16335   } else {
16336     return SDValue();
16337   }
16338 }
16339 
16340 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16341 // in combiner since we need to check SD flags and other subtarget features.
16342 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16343                                           DAGCombinerInfo &DCI) const {
16344   SDValue N0 = N->getOperand(0);
16345   SDValue N1 = N->getOperand(1);
16346   SDValue N2 = N->getOperand(2);
16347   SDNodeFlags Flags = N->getFlags();
16348   EVT VT = N->getValueType(0);
16349   SelectionDAG &DAG = DCI.DAG;
16350   const TargetOptions &Options = getTargetMachine().Options;
16351   unsigned Opc = N->getOpcode();
16352   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16353   bool LegalOps = !DCI.isBeforeLegalizeOps();
16354   SDLoc Loc(N);
16355 
16356   // TODO: QPX subtarget is deprecated. No transformation here.
16357   if (Subtarget.hasQPX() || !isOperationLegal(ISD::FMA, VT))
16358     return SDValue();
16359 
16360   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16361   // since (fnmsub a b c)=-0 while c-ab=+0.
16362   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16363     return SDValue();
16364 
16365   // (fma (fneg a) b c) => (fnmsub a b c)
16366   // (fnmsub (fneg a) b c) => (fma a b c)
16367   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16368     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16369 
16370   // (fma a (fneg b) c) => (fnmsub a b c)
16371   // (fnmsub a (fneg b) c) => (fma a b c)
16372   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16373     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16374 
16375   return SDValue();
16376 }
16377 
16378 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16379   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16380   if (!Subtarget.is64BitELFABI())
16381     return false;
16382 
16383   // If not a tail call then no need to proceed.
16384   if (!CI->isTailCall())
16385     return false;
16386 
16387   // If sibling calls have been disabled and tail-calls aren't guaranteed
16388   // there is no reason to duplicate.
16389   auto &TM = getTargetMachine();
16390   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16391     return false;
16392 
16393   // Can't tail call a function called indirectly, or if it has variadic args.
16394   const Function *Callee = CI->getCalledFunction();
16395   if (!Callee || Callee->isVarArg())
16396     return false;
16397 
16398   // Make sure the callee and caller calling conventions are eligible for tco.
16399   const Function *Caller = CI->getParent()->getParent();
16400   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16401                                            CI->getCallingConv()))
16402       return false;
16403 
16404   // If the function is local then we have a good chance at tail-calling it
16405   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16406 }
16407 
16408 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16409   if (!Subtarget.hasVSX())
16410     return false;
16411   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16412     return true;
16413   return VT == MVT::f32 || VT == MVT::f64 ||
16414     VT == MVT::v4f32 || VT == MVT::v2f64;
16415 }
16416 
16417 bool PPCTargetLowering::
16418 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16419   const Value *Mask = AndI.getOperand(1);
16420   // If the mask is suitable for andi. or andis. we should sink the and.
16421   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16422     // Can't handle constants wider than 64-bits.
16423     if (CI->getBitWidth() > 64)
16424       return false;
16425     int64_t ConstVal = CI->getZExtValue();
16426     return isUInt<16>(ConstVal) ||
16427       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16428   }
16429 
16430   // For non-constant masks, we can always use the record-form and.
16431   return true;
16432 }
16433 
16434 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16435 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16436 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16437 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16438 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16439 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16440   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16441   assert(Subtarget.hasP9Altivec() &&
16442          "Only combine this when P9 altivec supported!");
16443   EVT VT = N->getValueType(0);
16444   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16445     return SDValue();
16446 
16447   SelectionDAG &DAG = DCI.DAG;
16448   SDLoc dl(N);
16449   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16450     // Even for signed integers, if it's known to be positive (as signed
16451     // integer) due to zero-extended inputs.
16452     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16453     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16454     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16455          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16456         (SubOpcd1 == ISD::ZERO_EXTEND ||
16457          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16458       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16459                          N->getOperand(0)->getOperand(0),
16460                          N->getOperand(0)->getOperand(1),
16461                          DAG.getTargetConstant(0, dl, MVT::i32));
16462     }
16463 
16464     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16465     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16466         N->getOperand(0).hasOneUse()) {
16467       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16468                          N->getOperand(0)->getOperand(0),
16469                          N->getOperand(0)->getOperand(1),
16470                          DAG.getTargetConstant(1, dl, MVT::i32));
16471     }
16472   }
16473 
16474   return SDValue();
16475 }
16476 
16477 // For type v4i32/v8ii16/v16i8, transform
16478 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16479 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16480 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16481 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16482 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16483                                           DAGCombinerInfo &DCI) const {
16484   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16485   assert(Subtarget.hasP9Altivec() &&
16486          "Only combine this when P9 altivec supported!");
16487 
16488   SelectionDAG &DAG = DCI.DAG;
16489   SDLoc dl(N);
16490   SDValue Cond = N->getOperand(0);
16491   SDValue TrueOpnd = N->getOperand(1);
16492   SDValue FalseOpnd = N->getOperand(2);
16493   EVT VT = N->getOperand(1).getValueType();
16494 
16495   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16496       FalseOpnd.getOpcode() != ISD::SUB)
16497     return SDValue();
16498 
16499   // ABSD only available for type v4i32/v8i16/v16i8
16500   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16501     return SDValue();
16502 
16503   // At least to save one more dependent computation
16504   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16505     return SDValue();
16506 
16507   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16508 
16509   // Can only handle unsigned comparison here
16510   switch (CC) {
16511   default:
16512     return SDValue();
16513   case ISD::SETUGT:
16514   case ISD::SETUGE:
16515     break;
16516   case ISD::SETULT:
16517   case ISD::SETULE:
16518     std::swap(TrueOpnd, FalseOpnd);
16519     break;
16520   }
16521 
16522   SDValue CmpOpnd1 = Cond.getOperand(0);
16523   SDValue CmpOpnd2 = Cond.getOperand(1);
16524 
16525   // SETCC CmpOpnd1 CmpOpnd2 cond
16526   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16527   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16528   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16529       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16530       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16531       FalseOpnd.getOperand(1) == CmpOpnd1) {
16532     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16533                        CmpOpnd1, CmpOpnd2,
16534                        DAG.getTargetConstant(0, dl, MVT::i32));
16535   }
16536 
16537   return SDValue();
16538 }
16539