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 
295   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
296   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
297   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
298   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
299 
300   // We don't support sin/cos/sqrt/fmod/pow
301   setOperationAction(ISD::FSIN , MVT::f64, Expand);
302   setOperationAction(ISD::FCOS , MVT::f64, Expand);
303   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
304   setOperationAction(ISD::FREM , MVT::f64, Expand);
305   setOperationAction(ISD::FPOW , MVT::f64, Expand);
306   setOperationAction(ISD::FSIN , MVT::f32, Expand);
307   setOperationAction(ISD::FCOS , MVT::f32, Expand);
308   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
309   setOperationAction(ISD::FREM , MVT::f32, Expand);
310   setOperationAction(ISD::FPOW , MVT::f32, Expand);
311   if (Subtarget.hasSPE()) {
312     setOperationAction(ISD::FMA  , MVT::f64, Expand);
313     setOperationAction(ISD::FMA  , MVT::f32, Expand);
314   } else {
315     setOperationAction(ISD::FMA  , MVT::f64, Legal);
316     setOperationAction(ISD::FMA  , MVT::f32, Legal);
317   }
318 
319   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
320 
321   // If we're enabling GP optimizations, use hardware square root
322   if (!Subtarget.hasFSQRT() &&
323       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
324         Subtarget.hasFRE()))
325     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
326 
327   if (!Subtarget.hasFSQRT() &&
328       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
329         Subtarget.hasFRES()))
330     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
331 
332   if (Subtarget.hasFCPSGN()) {
333     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
334     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
335   } else {
336     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
337     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
338   }
339 
340   if (Subtarget.hasFPRND()) {
341     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
342     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
343     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
344     setOperationAction(ISD::FROUND, MVT::f64, Legal);
345 
346     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
347     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
348     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
349     setOperationAction(ISD::FROUND, MVT::f32, Legal);
350   }
351 
352   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
353   // to speed up scalar BSWAP64.
354   // CTPOP or CTTZ were introduced in P8/P9 respectively
355   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
356   if (Subtarget.hasP9Vector())
357     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
358   else
359     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
360   if (Subtarget.isISA3_0()) {
361     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
362     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
363   } else {
364     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
365     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
366   }
367 
368   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
369     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
370     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
371   } else {
372     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
373     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
374   }
375 
376   // PowerPC does not have ROTR
377   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
378   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
379 
380   if (!Subtarget.useCRBits()) {
381     // PowerPC does not have Select
382     setOperationAction(ISD::SELECT, MVT::i32, Expand);
383     setOperationAction(ISD::SELECT, MVT::i64, Expand);
384     setOperationAction(ISD::SELECT, MVT::f32, Expand);
385     setOperationAction(ISD::SELECT, MVT::f64, Expand);
386   }
387 
388   // PowerPC wants to turn select_cc of FP into fsel when possible.
389   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
390   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
391 
392   // PowerPC wants to optimize integer setcc a bit
393   if (!Subtarget.useCRBits())
394     setOperationAction(ISD::SETCC, MVT::i32, Custom);
395 
396   // PowerPC does not have BRCOND which requires SetCC
397   if (!Subtarget.useCRBits())
398     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
399 
400   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
401 
402   if (Subtarget.hasSPE()) {
403     // SPE has built-in conversions
404     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
405     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
406     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
407   } else {
408     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
409     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
410 
411     // PowerPC does not have [U|S]INT_TO_FP
412     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
413     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
414   }
415 
416   if (Subtarget.hasDirectMove() && isPPC64) {
417     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
418     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
419     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
420     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
421     if (TM.Options.UnsafeFPMath) {
422       setOperationAction(ISD::LRINT, MVT::f64, Legal);
423       setOperationAction(ISD::LRINT, MVT::f32, Legal);
424       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
425       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
426       setOperationAction(ISD::LROUND, MVT::f64, Legal);
427       setOperationAction(ISD::LROUND, MVT::f32, Legal);
428       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
429       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
430     }
431   } else {
432     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
433     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
434     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
435     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
436   }
437 
438   // We cannot sextinreg(i1).  Expand to shifts.
439   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
440 
441   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
442   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
443   // support continuation, user-level threading, and etc.. As a result, no
444   // other SjLj exception interfaces are implemented and please don't build
445   // your own exception handling based on them.
446   // LLVM/Clang supports zero-cost DWARF exception handling.
447   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
448   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
449 
450   // We want to legalize GlobalAddress and ConstantPool nodes into the
451   // appropriate instructions to materialize the address.
452   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
453   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
454   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
455   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
456   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
457   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
458   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
459   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
460   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
461   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
462 
463   // TRAP is legal.
464   setOperationAction(ISD::TRAP, MVT::Other, Legal);
465 
466   // TRAMPOLINE is custom lowered.
467   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
468   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
469 
470   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
471   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
472 
473   if (Subtarget.is64BitELFABI()) {
474     // VAARG always uses double-word chunks, so promote anything smaller.
475     setOperationAction(ISD::VAARG, MVT::i1, Promote);
476     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
477     setOperationAction(ISD::VAARG, MVT::i8, Promote);
478     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
479     setOperationAction(ISD::VAARG, MVT::i16, Promote);
480     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
481     setOperationAction(ISD::VAARG, MVT::i32, Promote);
482     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
483     setOperationAction(ISD::VAARG, MVT::Other, Expand);
484   } else if (Subtarget.is32BitELFABI()) {
485     // VAARG is custom lowered with the 32-bit SVR4 ABI.
486     setOperationAction(ISD::VAARG, MVT::Other, Custom);
487     setOperationAction(ISD::VAARG, MVT::i64, Custom);
488   } else
489     setOperationAction(ISD::VAARG, MVT::Other, Expand);
490 
491   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
492   if (Subtarget.is32BitELFABI())
493     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
494   else
495     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
496 
497   // Use the default implementation.
498   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
499   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
500   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
501   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
502   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
503   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
504   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
505   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
506   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
507 
508   // We want to custom lower some of our intrinsics.
509   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
510 
511   // To handle counter-based loop conditions.
512   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
513 
514   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
515   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
516   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
517   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
518 
519   // Comparisons that require checking two conditions.
520   if (Subtarget.hasSPE()) {
521     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
522     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
523     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
524     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
525   }
526   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
527   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
528   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
529   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
530   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
531   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
532   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
533   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
534   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
535   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
536   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
537   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
538 
539   if (Subtarget.has64BitSupport()) {
540     // They also have instructions for converting between i64 and fp.
541     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
542     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
543     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
544     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
545     // This is just the low 32 bits of a (signed) fp->i64 conversion.
546     // We cannot do this with Promote because i64 is not a legal type.
547     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
548 
549     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
550       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
551   } else {
552     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
553     if (Subtarget.hasSPE())
554       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
555     else
556       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
557   }
558 
559   // With the instructions enabled under FPCVT, we can do everything.
560   if (Subtarget.hasFPCVT()) {
561     if (Subtarget.has64BitSupport()) {
562       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
563       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
564       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
565       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
566     }
567 
568     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
569     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
570     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
571     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
572   }
573 
574   if (Subtarget.use64BitRegs()) {
575     // 64-bit PowerPC implementations can support i64 types directly
576     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
577     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
578     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
579     // 64-bit PowerPC wants to expand i128 shifts itself.
580     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
581     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
582     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
583   } else {
584     // 32-bit PowerPC wants to expand i64 shifts itself.
585     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
586     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
587     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
588   }
589 
590   if (Subtarget.hasVSX()) {
591     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
592     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
593     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
594     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
595   }
596 
597   if (Subtarget.hasAltivec()) {
598     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
599       setOperationAction(ISD::SADDSAT, VT, Legal);
600       setOperationAction(ISD::SSUBSAT, VT, Legal);
601       setOperationAction(ISD::UADDSAT, VT, Legal);
602       setOperationAction(ISD::USUBSAT, VT, Legal);
603     }
604     // First set operation action for all vector types to expand. Then we
605     // will selectively turn on ones that can be effectively codegen'd.
606     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
607       // add/sub are legal for all supported vector VT's.
608       setOperationAction(ISD::ADD, VT, Legal);
609       setOperationAction(ISD::SUB, VT, Legal);
610 
611       // For v2i64, these are only valid with P8Vector. This is corrected after
612       // the loop.
613       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
614         setOperationAction(ISD::SMAX, VT, Legal);
615         setOperationAction(ISD::SMIN, VT, Legal);
616         setOperationAction(ISD::UMAX, VT, Legal);
617         setOperationAction(ISD::UMIN, VT, Legal);
618       }
619       else {
620         setOperationAction(ISD::SMAX, VT, Expand);
621         setOperationAction(ISD::SMIN, VT, Expand);
622         setOperationAction(ISD::UMAX, VT, Expand);
623         setOperationAction(ISD::UMIN, VT, Expand);
624       }
625 
626       if (Subtarget.hasVSX()) {
627         setOperationAction(ISD::FMAXNUM, VT, Legal);
628         setOperationAction(ISD::FMINNUM, VT, Legal);
629       }
630 
631       // Vector instructions introduced in P8
632       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
633         setOperationAction(ISD::CTPOP, VT, Legal);
634         setOperationAction(ISD::CTLZ, VT, Legal);
635       }
636       else {
637         setOperationAction(ISD::CTPOP, VT, Expand);
638         setOperationAction(ISD::CTLZ, VT, Expand);
639       }
640 
641       // Vector instructions introduced in P9
642       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
643         setOperationAction(ISD::CTTZ, VT, Legal);
644       else
645         setOperationAction(ISD::CTTZ, VT, Expand);
646 
647       // We promote all shuffles to v16i8.
648       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
649       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
650 
651       // We promote all non-typed operations to v4i32.
652       setOperationAction(ISD::AND   , VT, Promote);
653       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
654       setOperationAction(ISD::OR    , VT, Promote);
655       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
656       setOperationAction(ISD::XOR   , VT, Promote);
657       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
658       setOperationAction(ISD::LOAD  , VT, Promote);
659       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
660       setOperationAction(ISD::SELECT, VT, Promote);
661       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
662       setOperationAction(ISD::VSELECT, VT, Legal);
663       setOperationAction(ISD::SELECT_CC, VT, Promote);
664       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
665       setOperationAction(ISD::STORE, VT, Promote);
666       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
667 
668       // No other operations are legal.
669       setOperationAction(ISD::MUL , VT, Expand);
670       setOperationAction(ISD::SDIV, VT, Expand);
671       setOperationAction(ISD::SREM, VT, Expand);
672       setOperationAction(ISD::UDIV, VT, Expand);
673       setOperationAction(ISD::UREM, VT, Expand);
674       setOperationAction(ISD::FDIV, VT, Expand);
675       setOperationAction(ISD::FREM, VT, Expand);
676       setOperationAction(ISD::FNEG, VT, Expand);
677       setOperationAction(ISD::FSQRT, VT, Expand);
678       setOperationAction(ISD::FLOG, VT, Expand);
679       setOperationAction(ISD::FLOG10, VT, Expand);
680       setOperationAction(ISD::FLOG2, VT, Expand);
681       setOperationAction(ISD::FEXP, VT, Expand);
682       setOperationAction(ISD::FEXP2, VT, Expand);
683       setOperationAction(ISD::FSIN, VT, Expand);
684       setOperationAction(ISD::FCOS, VT, Expand);
685       setOperationAction(ISD::FABS, VT, Expand);
686       setOperationAction(ISD::FFLOOR, VT, Expand);
687       setOperationAction(ISD::FCEIL,  VT, Expand);
688       setOperationAction(ISD::FTRUNC, VT, Expand);
689       setOperationAction(ISD::FRINT,  VT, Expand);
690       setOperationAction(ISD::FNEARBYINT, VT, Expand);
691       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
692       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
693       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
694       setOperationAction(ISD::MULHU, VT, Expand);
695       setOperationAction(ISD::MULHS, VT, Expand);
696       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
697       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
698       setOperationAction(ISD::UDIVREM, VT, Expand);
699       setOperationAction(ISD::SDIVREM, VT, Expand);
700       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
701       setOperationAction(ISD::FPOW, VT, Expand);
702       setOperationAction(ISD::BSWAP, VT, Expand);
703       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
704       setOperationAction(ISD::ROTL, VT, Expand);
705       setOperationAction(ISD::ROTR, VT, Expand);
706 
707       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
708         setTruncStoreAction(VT, InnerVT, Expand);
709         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
710         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
711         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
712       }
713     }
714     if (!Subtarget.hasP8Vector()) {
715       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
716       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
717       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
718       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
719     }
720 
721     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
722       setOperationAction(ISD::ABS, VT, Custom);
723 
724     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
725     // with merges, splats, etc.
726     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
727 
728     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
729     // are cheap, so handle them before they get expanded to scalar.
730     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
731     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
732     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
733     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
734     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
735 
736     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
737     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
738     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
739     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
740     setOperationAction(ISD::SELECT, MVT::v4i32,
741                        Subtarget.useCRBits() ? Legal : Expand);
742     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
743     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
744     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
745     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
746     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
747     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
748     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
749     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
750     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
751 
752     // Without hasP8Altivec set, v2i64 SMAX isn't available.
753     // But ABS custom lowering requires SMAX support.
754     if (!Subtarget.hasP8Altivec())
755       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
756 
757     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
758     if (Subtarget.hasAltivec())
759       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
760         setOperationAction(ISD::ROTL, VT, Legal);
761     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
762     if (Subtarget.hasP8Altivec())
763       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
764 
765     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
766     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
767     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
768     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
769 
770     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
771     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
772 
773     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
774       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
775       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
776     }
777 
778     if (Subtarget.hasP8Altivec())
779       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
780     else
781       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
782 
783     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
784     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
785 
786     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
787     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
788 
789     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
790     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
791     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
792     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
793 
794     // Altivec does not contain unordered floating-point compare instructions
795     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
796     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
797     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
798     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
799 
800     if (Subtarget.hasVSX()) {
801       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
802       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
803       if (Subtarget.hasP8Vector()) {
804         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
805         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
806       }
807       if (Subtarget.hasDirectMove() && isPPC64) {
808         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
809         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
810         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
811         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
812         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
813         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
814         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
815         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
816       }
817       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
818 
819       // The nearbyint variants are not allowed to raise the inexact exception
820       // so we can only code-gen them with unsafe math.
821       if (TM.Options.UnsafeFPMath) {
822         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
823         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
824       }
825 
826       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
827       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
828       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
829       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
830       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
831       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
832       setOperationAction(ISD::FROUND, MVT::f64, Legal);
833       setOperationAction(ISD::FRINT, MVT::f64, Legal);
834 
835       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
836       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
837       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
838       setOperationAction(ISD::FROUND, MVT::f32, Legal);
839       setOperationAction(ISD::FRINT, MVT::f32, Legal);
840 
841       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
842       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
843 
844       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
845       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
846 
847       // Share the Altivec comparison restrictions.
848       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
849       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
850       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
851       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
852 
853       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
854       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
855 
856       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
857 
858       if (Subtarget.hasP8Vector())
859         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
860 
861       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
862 
863       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
864       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
865       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
866 
867       if (Subtarget.hasP8Altivec()) {
868         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
869         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
870         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
871 
872         // 128 bit shifts can be accomplished via 3 instructions for SHL and
873         // SRL, but not for SRA because of the instructions available:
874         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
875         // doing
876         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
877         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
878         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
879 
880         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
881       }
882       else {
883         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
884         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
885         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
886 
887         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
888 
889         // VSX v2i64 only supports non-arithmetic operations.
890         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
891         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
892       }
893 
894       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
895       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
896       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
897       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
898 
899       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
900 
901       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
902       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
903       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
904       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
905 
906       // Custom handling for partial vectors of integers converted to
907       // floating point. We already have optimal handling for v2i32 through
908       // the DAG combine, so those aren't necessary.
909       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
910       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
911       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
912       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
913       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
914       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
915       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
916       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
917 
918       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
919       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
920       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
921       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
922       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
923       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
924 
925       if (Subtarget.hasDirectMove())
926         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
927       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
928 
929       // Handle constrained floating-point operations of vector.
930       // The predictor is `hasVSX` because altivec instruction has
931       // no exception but VSX vector instruction has.
932       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
933       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
934       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
935       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
936 
937       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
938       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
939       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
940       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
941 
942       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
943     }
944 
945     if (Subtarget.hasP8Altivec()) {
946       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
947       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
948     }
949 
950     if (Subtarget.hasP9Vector()) {
951       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
952       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
953 
954       // 128 bit shifts can be accomplished via 3 instructions for SHL and
955       // SRL, but not for SRA because of the instructions available:
956       // VS{RL} and VS{RL}O.
957       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
958       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
959       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
960 
961       if (EnableQuadPrecision) {
962         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
963         setOperationAction(ISD::FADD, MVT::f128, Legal);
964         setOperationAction(ISD::FSUB, MVT::f128, Legal);
965         setOperationAction(ISD::FDIV, MVT::f128, Legal);
966         setOperationAction(ISD::FMUL, MVT::f128, Legal);
967         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
968         // No extending loads to f128 on PPC.
969         for (MVT FPT : MVT::fp_valuetypes())
970           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
971         setOperationAction(ISD::FMA, MVT::f128, Legal);
972         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
973         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
974         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
975         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
976         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
977         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
978 
979         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
980         setOperationAction(ISD::FRINT, MVT::f128, Legal);
981         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
982         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
983         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
984         setOperationAction(ISD::FROUND, MVT::f128, Legal);
985 
986         setOperationAction(ISD::SELECT, MVT::f128, Expand);
987         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
988         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
989         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
990         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
991         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
992         // No implementation for these ops for PowerPC.
993         setOperationAction(ISD::FSIN , MVT::f128, Expand);
994         setOperationAction(ISD::FCOS , MVT::f128, Expand);
995         setOperationAction(ISD::FPOW, MVT::f128, Expand);
996         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
997         setOperationAction(ISD::FREM, MVT::f128, Expand);
998 
999         // Handle constrained floating-point operations of fp128
1000         setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1001         setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1002         setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1003         setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1004       }
1005       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1006       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1007       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1008       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1009       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1010     }
1011 
1012     if (Subtarget.hasP9Altivec()) {
1013       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1014       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1015 
1016       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1017       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1018       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1019       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1020       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1021       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1022       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1023     }
1024   }
1025 
1026   if (Subtarget.hasQPX()) {
1027     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1028     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1029     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1030     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
1031 
1032     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
1033     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
1034 
1035     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
1036     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
1037 
1038     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
1039     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
1040 
1041     if (!Subtarget.useCRBits())
1042       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
1043     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1044 
1045     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
1046     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
1047     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
1048     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
1049     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
1050     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
1051     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
1052 
1053     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
1054     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
1055 
1056     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
1057     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
1058 
1059     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
1060     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
1061     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
1062     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
1063     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
1064     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
1065     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
1066     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
1067     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
1068     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
1069 
1070     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
1071     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
1072 
1073     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
1074     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
1075 
1076     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
1077 
1078     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
1079     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
1080     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
1081     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
1082 
1083     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1084     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
1085 
1086     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
1087     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
1088 
1089     if (!Subtarget.useCRBits())
1090       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
1091     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1092 
1093     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
1094     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
1095     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
1096     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
1097     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
1098     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
1099     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
1100 
1101     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
1102     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
1103 
1104     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
1105     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
1106     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
1107     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
1108     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
1109     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
1110     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
1111     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
1112     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
1113     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1114 
1115     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1116     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1117 
1118     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1119     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1120 
1121     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1122 
1123     setOperationAction(ISD::AND , MVT::v4i1, Legal);
1124     setOperationAction(ISD::OR , MVT::v4i1, Legal);
1125     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1126 
1127     if (!Subtarget.useCRBits())
1128       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1129     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1130 
1131     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
1132     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1133 
1134     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1135     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1136     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1137     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1138     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1139     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1140     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1141 
1142     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1143     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1144 
1145     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1146 
1147     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1148     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1149     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1150     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1151 
1152     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1153     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1154     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1155     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1156 
1157     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1158     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1159 
1160     // These need to set FE_INEXACT, and so cannot be vectorized here.
1161     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1162     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1163 
1164     if (TM.Options.UnsafeFPMath) {
1165       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1166       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1167 
1168       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1169       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1170     } else {
1171       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1172       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1173 
1174       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1175       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1176     }
1177 
1178     // TODO: Handle constrained floating-point operations of v4f64
1179   }
1180 
1181   if (Subtarget.has64BitSupport())
1182     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1183 
1184   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1185 
1186   if (!isPPC64) {
1187     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1188     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1189   }
1190 
1191   setBooleanContents(ZeroOrOneBooleanContent);
1192 
1193   if (Subtarget.hasAltivec()) {
1194     // Altivec instructions set fields to all zeros or all ones.
1195     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1196   }
1197 
1198   if (!isPPC64) {
1199     // These libcalls are not available in 32-bit.
1200     setLibcallName(RTLIB::SHL_I128, nullptr);
1201     setLibcallName(RTLIB::SRL_I128, nullptr);
1202     setLibcallName(RTLIB::SRA_I128, nullptr);
1203   }
1204 
1205   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1206 
1207   // We have target-specific dag combine patterns for the following nodes:
1208   setTargetDAGCombine(ISD::ADD);
1209   setTargetDAGCombine(ISD::SHL);
1210   setTargetDAGCombine(ISD::SRA);
1211   setTargetDAGCombine(ISD::SRL);
1212   setTargetDAGCombine(ISD::MUL);
1213   setTargetDAGCombine(ISD::SINT_TO_FP);
1214   setTargetDAGCombine(ISD::BUILD_VECTOR);
1215   if (Subtarget.hasFPCVT())
1216     setTargetDAGCombine(ISD::UINT_TO_FP);
1217   setTargetDAGCombine(ISD::LOAD);
1218   setTargetDAGCombine(ISD::STORE);
1219   setTargetDAGCombine(ISD::BR_CC);
1220   if (Subtarget.useCRBits())
1221     setTargetDAGCombine(ISD::BRCOND);
1222   setTargetDAGCombine(ISD::BSWAP);
1223   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1224   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1225   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1226 
1227   setTargetDAGCombine(ISD::SIGN_EXTEND);
1228   setTargetDAGCombine(ISD::ZERO_EXTEND);
1229   setTargetDAGCombine(ISD::ANY_EXTEND);
1230 
1231   setTargetDAGCombine(ISD::TRUNCATE);
1232   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1233 
1234 
1235   if (Subtarget.useCRBits()) {
1236     setTargetDAGCombine(ISD::TRUNCATE);
1237     setTargetDAGCombine(ISD::SETCC);
1238     setTargetDAGCombine(ISD::SELECT_CC);
1239   }
1240 
1241   // Use reciprocal estimates.
1242   if (TM.Options.UnsafeFPMath) {
1243     setTargetDAGCombine(ISD::FDIV);
1244     setTargetDAGCombine(ISD::FSQRT);
1245   }
1246 
1247   if (Subtarget.hasP9Altivec()) {
1248     setTargetDAGCombine(ISD::ABS);
1249     setTargetDAGCombine(ISD::VSELECT);
1250   }
1251 
1252   if (EnableQuadPrecision) {
1253     setLibcallName(RTLIB::LOG_F128, "logf128");
1254     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1255     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1256     setLibcallName(RTLIB::EXP_F128, "expf128");
1257     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1258     setLibcallName(RTLIB::SIN_F128, "sinf128");
1259     setLibcallName(RTLIB::COS_F128, "cosf128");
1260     setLibcallName(RTLIB::POW_F128, "powf128");
1261     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1262     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1263     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1264     setLibcallName(RTLIB::REM_F128, "fmodf128");
1265   }
1266 
1267   // With 32 condition bits, we don't need to sink (and duplicate) compares
1268   // aggressively in CodeGenPrep.
1269   if (Subtarget.useCRBits()) {
1270     setHasMultipleConditionRegisters();
1271     setJumpIsExpensive();
1272   }
1273 
1274   setMinFunctionAlignment(Align(4));
1275 
1276   switch (Subtarget.getCPUDirective()) {
1277   default: break;
1278   case PPC::DIR_970:
1279   case PPC::DIR_A2:
1280   case PPC::DIR_E500:
1281   case PPC::DIR_E500mc:
1282   case PPC::DIR_E5500:
1283   case PPC::DIR_PWR4:
1284   case PPC::DIR_PWR5:
1285   case PPC::DIR_PWR5X:
1286   case PPC::DIR_PWR6:
1287   case PPC::DIR_PWR6X:
1288   case PPC::DIR_PWR7:
1289   case PPC::DIR_PWR8:
1290   case PPC::DIR_PWR9:
1291   case PPC::DIR_PWR_FUTURE:
1292     setPrefLoopAlignment(Align(16));
1293     setPrefFunctionAlignment(Align(16));
1294     break;
1295   }
1296 
1297   if (Subtarget.enableMachineScheduler())
1298     setSchedulingPreference(Sched::Source);
1299   else
1300     setSchedulingPreference(Sched::Hybrid);
1301 
1302   computeRegisterProperties(STI.getRegisterInfo());
1303 
1304   // The Freescale cores do better with aggressive inlining of memcpy and
1305   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1306   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1307       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1308     MaxStoresPerMemset = 32;
1309     MaxStoresPerMemsetOptSize = 16;
1310     MaxStoresPerMemcpy = 32;
1311     MaxStoresPerMemcpyOptSize = 8;
1312     MaxStoresPerMemmove = 32;
1313     MaxStoresPerMemmoveOptSize = 8;
1314   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1315     // The A2 also benefits from (very) aggressive inlining of memcpy and
1316     // friends. The overhead of a the function call, even when warm, can be
1317     // over one hundred cycles.
1318     MaxStoresPerMemset = 128;
1319     MaxStoresPerMemcpy = 128;
1320     MaxStoresPerMemmove = 128;
1321     MaxLoadsPerMemcmp = 128;
1322   } else {
1323     MaxLoadsPerMemcmp = 8;
1324     MaxLoadsPerMemcmpOptSize = 4;
1325   }
1326 }
1327 
1328 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1329 /// the desired ByVal argument alignment.
1330 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1331                              unsigned MaxMaxAlign) {
1332   if (MaxAlign == MaxMaxAlign)
1333     return;
1334   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1335     if (MaxMaxAlign >= 32 &&
1336         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1337       MaxAlign = 32;
1338     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1339              MaxAlign < 16)
1340       MaxAlign = 16;
1341   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1342     unsigned EltAlign = 0;
1343     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1344     if (EltAlign > MaxAlign)
1345       MaxAlign = EltAlign;
1346   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1347     for (auto *EltTy : STy->elements()) {
1348       unsigned EltAlign = 0;
1349       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1350       if (EltAlign > MaxAlign)
1351         MaxAlign = EltAlign;
1352       if (MaxAlign == MaxMaxAlign)
1353         break;
1354     }
1355   }
1356 }
1357 
1358 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1359 /// function arguments in the caller parameter area.
1360 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1361                                                   const DataLayout &DL) const {
1362   // 16byte and wider vectors are passed on 16byte boundary.
1363   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1364   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1365   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1366     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1367   return Align;
1368 }
1369 
1370 bool PPCTargetLowering::useSoftFloat() const {
1371   return Subtarget.useSoftFloat();
1372 }
1373 
1374 bool PPCTargetLowering::hasSPE() const {
1375   return Subtarget.hasSPE();
1376 }
1377 
1378 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1379   return VT.isScalarInteger();
1380 }
1381 
1382 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1383   switch ((PPCISD::NodeType)Opcode) {
1384   case PPCISD::FIRST_NUMBER:    break;
1385   case PPCISD::FSEL:            return "PPCISD::FSEL";
1386   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1387   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1388   case PPCISD::FCFID:           return "PPCISD::FCFID";
1389   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1390   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1391   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1392   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1393   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1394   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1395   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1396   case PPCISD::FP_TO_UINT_IN_VSR:
1397                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1398   case PPCISD::FP_TO_SINT_IN_VSR:
1399                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1400   case PPCISD::FRE:             return "PPCISD::FRE";
1401   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1402   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1403   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1404   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1405   case PPCISD::VPERM:           return "PPCISD::VPERM";
1406   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1407   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1408   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1409   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1410   case PPCISD::CMPB:            return "PPCISD::CMPB";
1411   case PPCISD::Hi:              return "PPCISD::Hi";
1412   case PPCISD::Lo:              return "PPCISD::Lo";
1413   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1414   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1415   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1416   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1417   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1418   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1419   case PPCISD::SRL:             return "PPCISD::SRL";
1420   case PPCISD::SRA:             return "PPCISD::SRA";
1421   case PPCISD::SHL:             return "PPCISD::SHL";
1422   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1423   case PPCISD::CALL:            return "PPCISD::CALL";
1424   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1425   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1426   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1427   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1428   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1429   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1430   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1431   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1432   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1433   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1434   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1435   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1436   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1437   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1438   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1439   case PPCISD::ANDI_rec_1_EQ_BIT:
1440     return "PPCISD::ANDI_rec_1_EQ_BIT";
1441   case PPCISD::ANDI_rec_1_GT_BIT:
1442     return "PPCISD::ANDI_rec_1_GT_BIT";
1443   case PPCISD::VCMP:            return "PPCISD::VCMP";
1444   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1445   case PPCISD::LBRX:            return "PPCISD::LBRX";
1446   case PPCISD::STBRX:           return "PPCISD::STBRX";
1447   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1448   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1449   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1450   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1451   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1452   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1453   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1454   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1455   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1456   case PPCISD::ST_VSR_SCAL_INT:
1457                                 return "PPCISD::ST_VSR_SCAL_INT";
1458   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1459   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1460   case PPCISD::BDZ:             return "PPCISD::BDZ";
1461   case PPCISD::MFFS:            return "PPCISD::MFFS";
1462   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1463   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1464   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1465   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1466   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1467   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1468   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1469   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1470   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1471   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1472   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1473   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1474   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1475   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1476   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1477   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1478   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1479   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1480   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1481   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1482   case PPCISD::SC:              return "PPCISD::SC";
1483   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1484   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1485   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1486   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1487   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1488   case PPCISD::VABSD:           return "PPCISD::VABSD";
1489   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1490   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1491   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1492   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1493   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1494   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1495   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1496   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1497   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1498   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1499   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1500   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1501   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1502   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1503   }
1504   return nullptr;
1505 }
1506 
1507 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1508                                           EVT VT) const {
1509   if (!VT.isVector())
1510     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1511 
1512   if (Subtarget.hasQPX())
1513     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1514 
1515   return VT.changeVectorElementTypeToInteger();
1516 }
1517 
1518 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1519   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1520   return true;
1521 }
1522 
1523 //===----------------------------------------------------------------------===//
1524 // Node matching predicates, for use by the tblgen matching code.
1525 //===----------------------------------------------------------------------===//
1526 
1527 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1528 static bool isFloatingPointZero(SDValue Op) {
1529   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1530     return CFP->getValueAPF().isZero();
1531   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1532     // Maybe this has already been legalized into the constant pool?
1533     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1534       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1535         return CFP->getValueAPF().isZero();
1536   }
1537   return false;
1538 }
1539 
1540 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1541 /// true if Op is undef or if it matches the specified value.
1542 static bool isConstantOrUndef(int Op, int Val) {
1543   return Op < 0 || Op == Val;
1544 }
1545 
1546 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1547 /// VPKUHUM instruction.
1548 /// The ShuffleKind distinguishes between big-endian operations with
1549 /// two different inputs (0), either-endian operations with two identical
1550 /// inputs (1), and little-endian operations with two different inputs (2).
1551 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1552 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1553                                SelectionDAG &DAG) {
1554   bool IsLE = DAG.getDataLayout().isLittleEndian();
1555   if (ShuffleKind == 0) {
1556     if (IsLE)
1557       return false;
1558     for (unsigned i = 0; i != 16; ++i)
1559       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1560         return false;
1561   } else if (ShuffleKind == 2) {
1562     if (!IsLE)
1563       return false;
1564     for (unsigned i = 0; i != 16; ++i)
1565       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1566         return false;
1567   } else if (ShuffleKind == 1) {
1568     unsigned j = IsLE ? 0 : 1;
1569     for (unsigned i = 0; i != 8; ++i)
1570       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1571           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1572         return false;
1573   }
1574   return true;
1575 }
1576 
1577 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1578 /// VPKUWUM instruction.
1579 /// The ShuffleKind distinguishes between big-endian operations with
1580 /// two different inputs (0), either-endian operations with two identical
1581 /// inputs (1), and little-endian operations with two different inputs (2).
1582 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1583 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1584                                SelectionDAG &DAG) {
1585   bool IsLE = DAG.getDataLayout().isLittleEndian();
1586   if (ShuffleKind == 0) {
1587     if (IsLE)
1588       return false;
1589     for (unsigned i = 0; i != 16; i += 2)
1590       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1591           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1592         return false;
1593   } else if (ShuffleKind == 2) {
1594     if (!IsLE)
1595       return false;
1596     for (unsigned i = 0; i != 16; i += 2)
1597       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1598           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1599         return false;
1600   } else if (ShuffleKind == 1) {
1601     unsigned j = IsLE ? 0 : 2;
1602     for (unsigned i = 0; i != 8; i += 2)
1603       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1604           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1605           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1606           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1607         return false;
1608   }
1609   return true;
1610 }
1611 
1612 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1613 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1614 /// current subtarget.
1615 ///
1616 /// The ShuffleKind distinguishes between big-endian operations with
1617 /// two different inputs (0), either-endian operations with two identical
1618 /// inputs (1), and little-endian operations with two different inputs (2).
1619 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1620 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1621                                SelectionDAG &DAG) {
1622   const PPCSubtarget& Subtarget =
1623       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1624   if (!Subtarget.hasP8Vector())
1625     return false;
1626 
1627   bool IsLE = DAG.getDataLayout().isLittleEndian();
1628   if (ShuffleKind == 0) {
1629     if (IsLE)
1630       return false;
1631     for (unsigned i = 0; i != 16; i += 4)
1632       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1633           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1634           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1635           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1636         return false;
1637   } else if (ShuffleKind == 2) {
1638     if (!IsLE)
1639       return false;
1640     for (unsigned i = 0; i != 16; i += 4)
1641       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1642           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1643           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1644           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1645         return false;
1646   } else if (ShuffleKind == 1) {
1647     unsigned j = IsLE ? 0 : 4;
1648     for (unsigned i = 0; i != 8; i += 4)
1649       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1650           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1651           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1652           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1653           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1654           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1655           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1656           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1657         return false;
1658   }
1659   return true;
1660 }
1661 
1662 /// isVMerge - Common function, used to match vmrg* shuffles.
1663 ///
1664 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1665                      unsigned LHSStart, unsigned RHSStart) {
1666   if (N->getValueType(0) != MVT::v16i8)
1667     return false;
1668   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1669          "Unsupported merge size!");
1670 
1671   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1672     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1673       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1674                              LHSStart+j+i*UnitSize) ||
1675           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1676                              RHSStart+j+i*UnitSize))
1677         return false;
1678     }
1679   return true;
1680 }
1681 
1682 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1683 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1684 /// The ShuffleKind distinguishes between big-endian merges with two
1685 /// different inputs (0), either-endian merges with two identical inputs (1),
1686 /// and little-endian merges with two different inputs (2).  For the latter,
1687 /// the input operands are swapped (see PPCInstrAltivec.td).
1688 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1689                              unsigned ShuffleKind, SelectionDAG &DAG) {
1690   if (DAG.getDataLayout().isLittleEndian()) {
1691     if (ShuffleKind == 1) // unary
1692       return isVMerge(N, UnitSize, 0, 0);
1693     else if (ShuffleKind == 2) // swapped
1694       return isVMerge(N, UnitSize, 0, 16);
1695     else
1696       return false;
1697   } else {
1698     if (ShuffleKind == 1) // unary
1699       return isVMerge(N, UnitSize, 8, 8);
1700     else if (ShuffleKind == 0) // normal
1701       return isVMerge(N, UnitSize, 8, 24);
1702     else
1703       return false;
1704   }
1705 }
1706 
1707 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1708 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1709 /// The ShuffleKind distinguishes between big-endian merges with two
1710 /// different inputs (0), either-endian merges with two identical inputs (1),
1711 /// and little-endian merges with two different inputs (2).  For the latter,
1712 /// the input operands are swapped (see PPCInstrAltivec.td).
1713 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1714                              unsigned ShuffleKind, SelectionDAG &DAG) {
1715   if (DAG.getDataLayout().isLittleEndian()) {
1716     if (ShuffleKind == 1) // unary
1717       return isVMerge(N, UnitSize, 8, 8);
1718     else if (ShuffleKind == 2) // swapped
1719       return isVMerge(N, UnitSize, 8, 24);
1720     else
1721       return false;
1722   } else {
1723     if (ShuffleKind == 1) // unary
1724       return isVMerge(N, UnitSize, 0, 0);
1725     else if (ShuffleKind == 0) // normal
1726       return isVMerge(N, UnitSize, 0, 16);
1727     else
1728       return false;
1729   }
1730 }
1731 
1732 /**
1733  * Common function used to match vmrgew and vmrgow shuffles
1734  *
1735  * The indexOffset determines whether to look for even or odd words in
1736  * the shuffle mask. This is based on the of the endianness of the target
1737  * machine.
1738  *   - Little Endian:
1739  *     - Use offset of 0 to check for odd elements
1740  *     - Use offset of 4 to check for even elements
1741  *   - Big Endian:
1742  *     - Use offset of 0 to check for even elements
1743  *     - Use offset of 4 to check for odd elements
1744  * A detailed description of the vector element ordering for little endian and
1745  * big endian can be found at
1746  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1747  * Targeting your applications - what little endian and big endian IBM XL C/C++
1748  * compiler differences mean to you
1749  *
1750  * The mask to the shuffle vector instruction specifies the indices of the
1751  * elements from the two input vectors to place in the result. The elements are
1752  * numbered in array-access order, starting with the first vector. These vectors
1753  * are always of type v16i8, thus each vector will contain 16 elements of size
1754  * 8. More info on the shuffle vector can be found in the
1755  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1756  * Language Reference.
1757  *
1758  * The RHSStartValue indicates whether the same input vectors are used (unary)
1759  * or two different input vectors are used, based on the following:
1760  *   - If the instruction uses the same vector for both inputs, the range of the
1761  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1762  *     be 0.
1763  *   - If the instruction has two different vectors then the range of the
1764  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1765  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1766  *     to 31 specify elements in the second vector).
1767  *
1768  * \param[in] N The shuffle vector SD Node to analyze
1769  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1770  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1771  * vector to the shuffle_vector instruction
1772  * \return true iff this shuffle vector represents an even or odd word merge
1773  */
1774 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1775                      unsigned RHSStartValue) {
1776   if (N->getValueType(0) != MVT::v16i8)
1777     return false;
1778 
1779   for (unsigned i = 0; i < 2; ++i)
1780     for (unsigned j = 0; j < 4; ++j)
1781       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1782                              i*RHSStartValue+j+IndexOffset) ||
1783           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1784                              i*RHSStartValue+j+IndexOffset+8))
1785         return false;
1786   return true;
1787 }
1788 
1789 /**
1790  * Determine if the specified shuffle mask is suitable for the vmrgew or
1791  * vmrgow instructions.
1792  *
1793  * \param[in] N The shuffle vector SD Node to analyze
1794  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1795  * \param[in] ShuffleKind Identify the type of merge:
1796  *   - 0 = big-endian merge with two different inputs;
1797  *   - 1 = either-endian merge with two identical inputs;
1798  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1799  *     little-endian merges).
1800  * \param[in] DAG The current SelectionDAG
1801  * \return true iff this shuffle mask
1802  */
1803 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1804                               unsigned ShuffleKind, SelectionDAG &DAG) {
1805   if (DAG.getDataLayout().isLittleEndian()) {
1806     unsigned indexOffset = CheckEven ? 4 : 0;
1807     if (ShuffleKind == 1) // Unary
1808       return isVMerge(N, indexOffset, 0);
1809     else if (ShuffleKind == 2) // swapped
1810       return isVMerge(N, indexOffset, 16);
1811     else
1812       return false;
1813   }
1814   else {
1815     unsigned indexOffset = CheckEven ? 0 : 4;
1816     if (ShuffleKind == 1) // Unary
1817       return isVMerge(N, indexOffset, 0);
1818     else if (ShuffleKind == 0) // Normal
1819       return isVMerge(N, indexOffset, 16);
1820     else
1821       return false;
1822   }
1823   return false;
1824 }
1825 
1826 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1827 /// amount, otherwise return -1.
1828 /// The ShuffleKind distinguishes between big-endian operations with two
1829 /// different inputs (0), either-endian operations with two identical inputs
1830 /// (1), and little-endian operations with two different inputs (2).  For the
1831 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1832 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1833                              SelectionDAG &DAG) {
1834   if (N->getValueType(0) != MVT::v16i8)
1835     return -1;
1836 
1837   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1838 
1839   // Find the first non-undef value in the shuffle mask.
1840   unsigned i;
1841   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1842     /*search*/;
1843 
1844   if (i == 16) return -1;  // all undef.
1845 
1846   // Otherwise, check to see if the rest of the elements are consecutively
1847   // numbered from this value.
1848   unsigned ShiftAmt = SVOp->getMaskElt(i);
1849   if (ShiftAmt < i) return -1;
1850 
1851   ShiftAmt -= i;
1852   bool isLE = DAG.getDataLayout().isLittleEndian();
1853 
1854   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1855     // Check the rest of the elements to see if they are consecutive.
1856     for (++i; i != 16; ++i)
1857       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1858         return -1;
1859   } else if (ShuffleKind == 1) {
1860     // Check the rest of the elements to see if they are consecutive.
1861     for (++i; i != 16; ++i)
1862       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1863         return -1;
1864   } else
1865     return -1;
1866 
1867   if (isLE)
1868     ShiftAmt = 16 - ShiftAmt;
1869 
1870   return ShiftAmt;
1871 }
1872 
1873 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1874 /// specifies a splat of a single element that is suitable for input to
1875 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1876 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1877   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1878          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1879 
1880   // The consecutive indices need to specify an element, not part of two
1881   // different elements.  So abandon ship early if this isn't the case.
1882   if (N->getMaskElt(0) % EltSize != 0)
1883     return false;
1884 
1885   // This is a splat operation if each element of the permute is the same, and
1886   // if the value doesn't reference the second vector.
1887   unsigned ElementBase = N->getMaskElt(0);
1888 
1889   // FIXME: Handle UNDEF elements too!
1890   if (ElementBase >= 16)
1891     return false;
1892 
1893   // Check that the indices are consecutive, in the case of a multi-byte element
1894   // splatted with a v16i8 mask.
1895   for (unsigned i = 1; i != EltSize; ++i)
1896     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1897       return false;
1898 
1899   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1900     if (N->getMaskElt(i) < 0) continue;
1901     for (unsigned j = 0; j != EltSize; ++j)
1902       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1903         return false;
1904   }
1905   return true;
1906 }
1907 
1908 /// Check that the mask is shuffling N byte elements. Within each N byte
1909 /// element of the mask, the indices could be either in increasing or
1910 /// decreasing order as long as they are consecutive.
1911 /// \param[in] N the shuffle vector SD Node to analyze
1912 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1913 /// Word/DoubleWord/QuadWord).
1914 /// \param[in] StepLen the delta indices number among the N byte element, if
1915 /// the mask is in increasing/decreasing order then it is 1/-1.
1916 /// \return true iff the mask is shuffling N byte elements.
1917 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1918                                    int StepLen) {
1919   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1920          "Unexpected element width.");
1921   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1922 
1923   unsigned NumOfElem = 16 / Width;
1924   unsigned MaskVal[16]; //  Width is never greater than 16
1925   for (unsigned i = 0; i < NumOfElem; ++i) {
1926     MaskVal[0] = N->getMaskElt(i * Width);
1927     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1928       return false;
1929     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1930       return false;
1931     }
1932 
1933     for (unsigned int j = 1; j < Width; ++j) {
1934       MaskVal[j] = N->getMaskElt(i * Width + j);
1935       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1936         return false;
1937       }
1938     }
1939   }
1940 
1941   return true;
1942 }
1943 
1944 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1945                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1946   if (!isNByteElemShuffleMask(N, 4, 1))
1947     return false;
1948 
1949   // Now we look at mask elements 0,4,8,12
1950   unsigned M0 = N->getMaskElt(0) / 4;
1951   unsigned M1 = N->getMaskElt(4) / 4;
1952   unsigned M2 = N->getMaskElt(8) / 4;
1953   unsigned M3 = N->getMaskElt(12) / 4;
1954   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1955   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1956 
1957   // Below, let H and L be arbitrary elements of the shuffle mask
1958   // where H is in the range [4,7] and L is in the range [0,3].
1959   // H, 1, 2, 3 or L, 5, 6, 7
1960   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1961       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1962     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1963     InsertAtByte = IsLE ? 12 : 0;
1964     Swap = M0 < 4;
1965     return true;
1966   }
1967   // 0, H, 2, 3 or 4, L, 6, 7
1968   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1969       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1970     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1971     InsertAtByte = IsLE ? 8 : 4;
1972     Swap = M1 < 4;
1973     return true;
1974   }
1975   // 0, 1, H, 3 or 4, 5, L, 7
1976   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1977       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1978     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1979     InsertAtByte = IsLE ? 4 : 8;
1980     Swap = M2 < 4;
1981     return true;
1982   }
1983   // 0, 1, 2, H or 4, 5, 6, L
1984   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1985       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1986     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1987     InsertAtByte = IsLE ? 0 : 12;
1988     Swap = M3 < 4;
1989     return true;
1990   }
1991 
1992   // If both vector operands for the shuffle are the same vector, the mask will
1993   // contain only elements from the first one and the second one will be undef.
1994   if (N->getOperand(1).isUndef()) {
1995     ShiftElts = 0;
1996     Swap = true;
1997     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1998     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1999       InsertAtByte = IsLE ? 12 : 0;
2000       return true;
2001     }
2002     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2003       InsertAtByte = IsLE ? 8 : 4;
2004       return true;
2005     }
2006     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2007       InsertAtByte = IsLE ? 4 : 8;
2008       return true;
2009     }
2010     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2011       InsertAtByte = IsLE ? 0 : 12;
2012       return true;
2013     }
2014   }
2015 
2016   return false;
2017 }
2018 
2019 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2020                                bool &Swap, bool IsLE) {
2021   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2022   // Ensure each byte index of the word is consecutive.
2023   if (!isNByteElemShuffleMask(N, 4, 1))
2024     return false;
2025 
2026   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2027   unsigned M0 = N->getMaskElt(0) / 4;
2028   unsigned M1 = N->getMaskElt(4) / 4;
2029   unsigned M2 = N->getMaskElt(8) / 4;
2030   unsigned M3 = N->getMaskElt(12) / 4;
2031 
2032   // If both vector operands for the shuffle are the same vector, the mask will
2033   // contain only elements from the first one and the second one will be undef.
2034   if (N->getOperand(1).isUndef()) {
2035     assert(M0 < 4 && "Indexing into an undef vector?");
2036     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2037       return false;
2038 
2039     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2040     Swap = false;
2041     return true;
2042   }
2043 
2044   // Ensure each word index of the ShuffleVector Mask is consecutive.
2045   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2046     return false;
2047 
2048   if (IsLE) {
2049     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2050       // Input vectors don't need to be swapped if the leading element
2051       // of the result is one of the 3 left elements of the second vector
2052       // (or if there is no shift to be done at all).
2053       Swap = false;
2054       ShiftElts = (8 - M0) % 8;
2055     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2056       // Input vectors need to be swapped if the leading element
2057       // of the result is one of the 3 left elements of the first vector
2058       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2059       Swap = true;
2060       ShiftElts = (4 - M0) % 4;
2061     }
2062 
2063     return true;
2064   } else {                                          // BE
2065     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2066       // Input vectors don't need to be swapped if the leading element
2067       // of the result is one of the 4 elements of the first vector.
2068       Swap = false;
2069       ShiftElts = M0;
2070     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2071       // Input vectors need to be swapped if the leading element
2072       // of the result is one of the 4 elements of the right vector.
2073       Swap = true;
2074       ShiftElts = M0 - 4;
2075     }
2076 
2077     return true;
2078   }
2079 }
2080 
2081 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2082   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2083 
2084   if (!isNByteElemShuffleMask(N, Width, -1))
2085     return false;
2086 
2087   for (int i = 0; i < 16; i += Width)
2088     if (N->getMaskElt(i) != i + Width - 1)
2089       return false;
2090 
2091   return true;
2092 }
2093 
2094 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2095   return isXXBRShuffleMaskHelper(N, 2);
2096 }
2097 
2098 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2099   return isXXBRShuffleMaskHelper(N, 4);
2100 }
2101 
2102 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2103   return isXXBRShuffleMaskHelper(N, 8);
2104 }
2105 
2106 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2107   return isXXBRShuffleMaskHelper(N, 16);
2108 }
2109 
2110 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2111 /// if the inputs to the instruction should be swapped and set \p DM to the
2112 /// value for the immediate.
2113 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2114 /// AND element 0 of the result comes from the first input (LE) or second input
2115 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2116 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2117 /// mask.
2118 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2119                                bool &Swap, bool IsLE) {
2120   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2121 
2122   // Ensure each byte index of the double word is consecutive.
2123   if (!isNByteElemShuffleMask(N, 8, 1))
2124     return false;
2125 
2126   unsigned M0 = N->getMaskElt(0) / 8;
2127   unsigned M1 = N->getMaskElt(8) / 8;
2128   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2129 
2130   // If both vector operands for the shuffle are the same vector, the mask will
2131   // contain only elements from the first one and the second one will be undef.
2132   if (N->getOperand(1).isUndef()) {
2133     if ((M0 | M1) < 2) {
2134       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2135       Swap = false;
2136       return true;
2137     } else
2138       return false;
2139   }
2140 
2141   if (IsLE) {
2142     if (M0 > 1 && M1 < 2) {
2143       Swap = false;
2144     } else if (M0 < 2 && M1 > 1) {
2145       M0 = (M0 + 2) % 4;
2146       M1 = (M1 + 2) % 4;
2147       Swap = true;
2148     } else
2149       return false;
2150 
2151     // Note: if control flow comes here that means Swap is already set above
2152     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2153     return true;
2154   } else { // BE
2155     if (M0 < 2 && M1 > 1) {
2156       Swap = false;
2157     } else if (M0 > 1 && M1 < 2) {
2158       M0 = (M0 + 2) % 4;
2159       M1 = (M1 + 2) % 4;
2160       Swap = true;
2161     } else
2162       return false;
2163 
2164     // Note: if control flow comes here that means Swap is already set above
2165     DM = (M0 << 1) + (M1 & 1);
2166     return true;
2167   }
2168 }
2169 
2170 
2171 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2172 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2173 /// elements are counted from the left of the vector register).
2174 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2175                                          SelectionDAG &DAG) {
2176   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2177   assert(isSplatShuffleMask(SVOp, EltSize));
2178   if (DAG.getDataLayout().isLittleEndian())
2179     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2180   else
2181     return SVOp->getMaskElt(0) / EltSize;
2182 }
2183 
2184 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2185 /// by using a vspltis[bhw] instruction of the specified element size, return
2186 /// the constant being splatted.  The ByteSize field indicates the number of
2187 /// bytes of each element [124] -> [bhw].
2188 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2189   SDValue OpVal(nullptr, 0);
2190 
2191   // If ByteSize of the splat is bigger than the element size of the
2192   // build_vector, then we have a case where we are checking for a splat where
2193   // multiple elements of the buildvector are folded together into a single
2194   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2195   unsigned EltSize = 16/N->getNumOperands();
2196   if (EltSize < ByteSize) {
2197     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2198     SDValue UniquedVals[4];
2199     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2200 
2201     // See if all of the elements in the buildvector agree across.
2202     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2203       if (N->getOperand(i).isUndef()) continue;
2204       // If the element isn't a constant, bail fully out.
2205       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2206 
2207       if (!UniquedVals[i&(Multiple-1)].getNode())
2208         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2209       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2210         return SDValue();  // no match.
2211     }
2212 
2213     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2214     // either constant or undef values that are identical for each chunk.  See
2215     // if these chunks can form into a larger vspltis*.
2216 
2217     // Check to see if all of the leading entries are either 0 or -1.  If
2218     // neither, then this won't fit into the immediate field.
2219     bool LeadingZero = true;
2220     bool LeadingOnes = true;
2221     for (unsigned i = 0; i != Multiple-1; ++i) {
2222       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2223 
2224       LeadingZero &= isNullConstant(UniquedVals[i]);
2225       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2226     }
2227     // Finally, check the least significant entry.
2228     if (LeadingZero) {
2229       if (!UniquedVals[Multiple-1].getNode())
2230         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2231       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2232       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2233         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2234     }
2235     if (LeadingOnes) {
2236       if (!UniquedVals[Multiple-1].getNode())
2237         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2238       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2239       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2240         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2241     }
2242 
2243     return SDValue();
2244   }
2245 
2246   // Check to see if this buildvec has a single non-undef value in its elements.
2247   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2248     if (N->getOperand(i).isUndef()) continue;
2249     if (!OpVal.getNode())
2250       OpVal = N->getOperand(i);
2251     else if (OpVal != N->getOperand(i))
2252       return SDValue();
2253   }
2254 
2255   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2256 
2257   unsigned ValSizeInBytes = EltSize;
2258   uint64_t Value = 0;
2259   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2260     Value = CN->getZExtValue();
2261   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2262     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2263     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2264   }
2265 
2266   // If the splat value is larger than the element value, then we can never do
2267   // this splat.  The only case that we could fit the replicated bits into our
2268   // immediate field for would be zero, and we prefer to use vxor for it.
2269   if (ValSizeInBytes < ByteSize) return SDValue();
2270 
2271   // If the element value is larger than the splat value, check if it consists
2272   // of a repeated bit pattern of size ByteSize.
2273   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2274     return SDValue();
2275 
2276   // Properly sign extend the value.
2277   int MaskVal = SignExtend32(Value, ByteSize * 8);
2278 
2279   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2280   if (MaskVal == 0) return SDValue();
2281 
2282   // Finally, if this value fits in a 5 bit sext field, return it
2283   if (SignExtend32<5>(MaskVal) == MaskVal)
2284     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2285   return SDValue();
2286 }
2287 
2288 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2289 /// amount, otherwise return -1.
2290 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2291   EVT VT = N->getValueType(0);
2292   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2293     return -1;
2294 
2295   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2296 
2297   // Find the first non-undef value in the shuffle mask.
2298   unsigned i;
2299   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2300     /*search*/;
2301 
2302   if (i == 4) return -1;  // all undef.
2303 
2304   // Otherwise, check to see if the rest of the elements are consecutively
2305   // numbered from this value.
2306   unsigned ShiftAmt = SVOp->getMaskElt(i);
2307   if (ShiftAmt < i) return -1;
2308   ShiftAmt -= i;
2309 
2310   // Check the rest of the elements to see if they are consecutive.
2311   for (++i; i != 4; ++i)
2312     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2313       return -1;
2314 
2315   return ShiftAmt;
2316 }
2317 
2318 //===----------------------------------------------------------------------===//
2319 //  Addressing Mode Selection
2320 //===----------------------------------------------------------------------===//
2321 
2322 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2323 /// or 64-bit immediate, and if the value can be accurately represented as a
2324 /// sign extension from a 16-bit value.  If so, this returns true and the
2325 /// immediate.
2326 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2327   if (!isa<ConstantSDNode>(N))
2328     return false;
2329 
2330   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2331   if (N->getValueType(0) == MVT::i32)
2332     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2333   else
2334     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2335 }
2336 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2337   return isIntS16Immediate(Op.getNode(), Imm);
2338 }
2339 
2340 
2341 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2342 /// be represented as an indexed [r+r] operation.
2343 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2344                                                SDValue &Index,
2345                                                SelectionDAG &DAG) const {
2346   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2347       UI != E; ++UI) {
2348     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2349       if (Memop->getMemoryVT() == MVT::f64) {
2350           Base = N.getOperand(0);
2351           Index = N.getOperand(1);
2352           return true;
2353       }
2354     }
2355   }
2356   return false;
2357 }
2358 
2359 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2360 /// can be represented as an indexed [r+r] operation.  Returns false if it
2361 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2362 /// non-zero and N can be represented by a base register plus a signed 16-bit
2363 /// displacement, make a more precise judgement by checking (displacement % \p
2364 /// EncodingAlignment).
2365 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2366                                             SDValue &Index, SelectionDAG &DAG,
2367                                             unsigned EncodingAlignment) const {
2368   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2369   // a [pc+imm].
2370   if (SelectAddressPCRel(N, Base))
2371     return false;
2372 
2373   int16_t imm = 0;
2374   if (N.getOpcode() == ISD::ADD) {
2375     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2376     // SPE load/store can only handle 8-bit offsets.
2377     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2378         return true;
2379     if (isIntS16Immediate(N.getOperand(1), imm) &&
2380         (!EncodingAlignment || !(imm % EncodingAlignment)))
2381       return false; // r+i
2382     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2383       return false;    // r+i
2384 
2385     Base = N.getOperand(0);
2386     Index = N.getOperand(1);
2387     return true;
2388   } else if (N.getOpcode() == ISD::OR) {
2389     if (isIntS16Immediate(N.getOperand(1), imm) &&
2390         (!EncodingAlignment || !(imm % EncodingAlignment)))
2391       return false; // r+i can fold it if we can.
2392 
2393     // If this is an or of disjoint bitfields, we can codegen this as an add
2394     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2395     // disjoint.
2396     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2397 
2398     if (LHSKnown.Zero.getBoolValue()) {
2399       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2400       // If all of the bits are known zero on the LHS or RHS, the add won't
2401       // carry.
2402       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2403         Base = N.getOperand(0);
2404         Index = N.getOperand(1);
2405         return true;
2406       }
2407     }
2408   }
2409 
2410   return false;
2411 }
2412 
2413 // If we happen to be doing an i64 load or store into a stack slot that has
2414 // less than a 4-byte alignment, then the frame-index elimination may need to
2415 // use an indexed load or store instruction (because the offset may not be a
2416 // multiple of 4). The extra register needed to hold the offset comes from the
2417 // register scavenger, and it is possible that the scavenger will need to use
2418 // an emergency spill slot. As a result, we need to make sure that a spill slot
2419 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2420 // stack slot.
2421 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2422   // FIXME: This does not handle the LWA case.
2423   if (VT != MVT::i64)
2424     return;
2425 
2426   // NOTE: We'll exclude negative FIs here, which come from argument
2427   // lowering, because there are no known test cases triggering this problem
2428   // using packed structures (or similar). We can remove this exclusion if
2429   // we find such a test case. The reason why this is so test-case driven is
2430   // because this entire 'fixup' is only to prevent crashes (from the
2431   // register scavenger) on not-really-valid inputs. For example, if we have:
2432   //   %a = alloca i1
2433   //   %b = bitcast i1* %a to i64*
2434   //   store i64* a, i64 b
2435   // then the store should really be marked as 'align 1', but is not. If it
2436   // were marked as 'align 1' then the indexed form would have been
2437   // instruction-selected initially, and the problem this 'fixup' is preventing
2438   // won't happen regardless.
2439   if (FrameIdx < 0)
2440     return;
2441 
2442   MachineFunction &MF = DAG.getMachineFunction();
2443   MachineFrameInfo &MFI = MF.getFrameInfo();
2444 
2445   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2446     return;
2447 
2448   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2449   FuncInfo->setHasNonRISpills();
2450 }
2451 
2452 /// Returns true if the address N can be represented by a base register plus
2453 /// a signed 16-bit displacement [r+imm], and if it is not better
2454 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2455 /// displacements that are multiples of that value.
2456 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2457                                             SDValue &Base,
2458                                             SelectionDAG &DAG,
2459                                             unsigned EncodingAlignment) const {
2460   // FIXME dl should come from parent load or store, not from address
2461   SDLoc dl(N);
2462 
2463   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2464   // a [pc+imm].
2465   if (SelectAddressPCRel(N, Base))
2466     return false;
2467 
2468   // If this can be more profitably realized as r+r, fail.
2469   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2470     return false;
2471 
2472   if (N.getOpcode() == ISD::ADD) {
2473     int16_t imm = 0;
2474     if (isIntS16Immediate(N.getOperand(1), imm) &&
2475         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2476       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2477       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2478         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2479         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2480       } else {
2481         Base = N.getOperand(0);
2482       }
2483       return true; // [r+i]
2484     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2485       // Match LOAD (ADD (X, Lo(G))).
2486       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2487              && "Cannot handle constant offsets yet!");
2488       Disp = N.getOperand(1).getOperand(0);  // The global address.
2489       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2490              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2491              Disp.getOpcode() == ISD::TargetConstantPool ||
2492              Disp.getOpcode() == ISD::TargetJumpTable);
2493       Base = N.getOperand(0);
2494       return true;  // [&g+r]
2495     }
2496   } else if (N.getOpcode() == ISD::OR) {
2497     int16_t imm = 0;
2498     if (isIntS16Immediate(N.getOperand(1), imm) &&
2499         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2500       // If this is an or of disjoint bitfields, we can codegen this as an add
2501       // (for better address arithmetic) if the LHS and RHS of the OR are
2502       // provably disjoint.
2503       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2504 
2505       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2506         // If all of the bits are known zero on the LHS or RHS, the add won't
2507         // carry.
2508         if (FrameIndexSDNode *FI =
2509               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2510           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2511           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2512         } else {
2513           Base = N.getOperand(0);
2514         }
2515         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2516         return true;
2517       }
2518     }
2519   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2520     // Loading from a constant address.
2521 
2522     // If this address fits entirely in a 16-bit sext immediate field, codegen
2523     // this as "d, 0"
2524     int16_t Imm;
2525     if (isIntS16Immediate(CN, Imm) &&
2526         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2527       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2528       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2529                              CN->getValueType(0));
2530       return true;
2531     }
2532 
2533     // Handle 32-bit sext immediates with LIS + addr mode.
2534     if ((CN->getValueType(0) == MVT::i32 ||
2535          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2536         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2537       int Addr = (int)CN->getZExtValue();
2538 
2539       // Otherwise, break this down into an LIS + disp.
2540       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2541 
2542       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2543                                    MVT::i32);
2544       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2545       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2546       return true;
2547     }
2548   }
2549 
2550   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2551   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2552     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2553     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2554   } else
2555     Base = N;
2556   return true;      // [r+0]
2557 }
2558 
2559 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2560 /// represented as an indexed [r+r] operation.
2561 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2562                                                 SDValue &Index,
2563                                                 SelectionDAG &DAG) const {
2564   // Check to see if we can easily represent this as an [r+r] address.  This
2565   // will fail if it thinks that the address is more profitably represented as
2566   // reg+imm, e.g. where imm = 0.
2567   if (SelectAddressRegReg(N, Base, Index, DAG))
2568     return true;
2569 
2570   // If the address is the result of an add, we will utilize the fact that the
2571   // address calculation includes an implicit add.  However, we can reduce
2572   // register pressure if we do not materialize a constant just for use as the
2573   // index register.  We only get rid of the add if it is not an add of a
2574   // value and a 16-bit signed constant and both have a single use.
2575   int16_t imm = 0;
2576   if (N.getOpcode() == ISD::ADD &&
2577       (!isIntS16Immediate(N.getOperand(1), imm) ||
2578        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2579     Base = N.getOperand(0);
2580     Index = N.getOperand(1);
2581     return true;
2582   }
2583 
2584   // Otherwise, do it the hard way, using R0 as the base register.
2585   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2586                          N.getValueType());
2587   Index = N;
2588   return true;
2589 }
2590 
2591 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2592   Ty *PCRelCand = dyn_cast<Ty>(N);
2593   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2594 }
2595 
2596 /// Returns true if this address is a PC Relative address.
2597 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2598 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2599 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2600   // This is a materialize PC Relative node. Always select this as PC Relative.
2601   Base = N;
2602   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2603     return true;
2604   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2605       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2606       isValidPCRelNode<JumpTableSDNode>(N) ||
2607       isValidPCRelNode<BlockAddressSDNode>(N))
2608     return true;
2609   return false;
2610 }
2611 
2612 /// Returns true if we should use a direct load into vector instruction
2613 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2614 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2615 
2616   // If there are any other uses other than scalar to vector, then we should
2617   // keep it as a scalar load -> direct move pattern to prevent multiple
2618   // loads.
2619   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2620   if (!LD)
2621     return false;
2622 
2623   EVT MemVT = LD->getMemoryVT();
2624   if (!MemVT.isSimple())
2625     return false;
2626   switch(MemVT.getSimpleVT().SimpleTy) {
2627   case MVT::i64:
2628     break;
2629   case MVT::i32:
2630     if (!ST.hasP8Vector())
2631       return false;
2632     break;
2633   case MVT::i16:
2634   case MVT::i8:
2635     if (!ST.hasP9Vector())
2636       return false;
2637     break;
2638   default:
2639     return false;
2640   }
2641 
2642   SDValue LoadedVal(N, 0);
2643   if (!LoadedVal.hasOneUse())
2644     return false;
2645 
2646   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2647        UI != UE; ++UI)
2648     if (UI.getUse().get().getResNo() == 0 &&
2649         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2650       return false;
2651 
2652   return true;
2653 }
2654 
2655 /// getPreIndexedAddressParts - returns true by value, base pointer and
2656 /// offset pointer and addressing mode by reference if the node's address
2657 /// can be legally represented as pre-indexed load / store address.
2658 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2659                                                   SDValue &Offset,
2660                                                   ISD::MemIndexedMode &AM,
2661                                                   SelectionDAG &DAG) const {
2662   if (DisablePPCPreinc) return false;
2663 
2664   bool isLoad = true;
2665   SDValue Ptr;
2666   EVT VT;
2667   unsigned Alignment;
2668   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2669     Ptr = LD->getBasePtr();
2670     VT = LD->getMemoryVT();
2671     Alignment = LD->getAlignment();
2672   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2673     Ptr = ST->getBasePtr();
2674     VT  = ST->getMemoryVT();
2675     Alignment = ST->getAlignment();
2676     isLoad = false;
2677   } else
2678     return false;
2679 
2680   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2681   // instructions because we can fold these into a more efficient instruction
2682   // instead, (such as LXSD).
2683   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2684     return false;
2685   }
2686 
2687   // PowerPC doesn't have preinc load/store instructions for vectors (except
2688   // for QPX, which does have preinc r+r forms).
2689   if (VT.isVector()) {
2690     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2691       return false;
2692     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2693       AM = ISD::PRE_INC;
2694       return true;
2695     }
2696   }
2697 
2698   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2699     // Common code will reject creating a pre-inc form if the base pointer
2700     // is a frame index, or if N is a store and the base pointer is either
2701     // the same as or a predecessor of the value being stored.  Check for
2702     // those situations here, and try with swapped Base/Offset instead.
2703     bool Swap = false;
2704 
2705     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2706       Swap = true;
2707     else if (!isLoad) {
2708       SDValue Val = cast<StoreSDNode>(N)->getValue();
2709       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2710         Swap = true;
2711     }
2712 
2713     if (Swap)
2714       std::swap(Base, Offset);
2715 
2716     AM = ISD::PRE_INC;
2717     return true;
2718   }
2719 
2720   // LDU/STU can only handle immediates that are a multiple of 4.
2721   if (VT != MVT::i64) {
2722     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2723       return false;
2724   } else {
2725     // LDU/STU need an address with at least 4-byte alignment.
2726     if (Alignment < 4)
2727       return false;
2728 
2729     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2730       return false;
2731   }
2732 
2733   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2734     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2735     // sext i32 to i64 when addr mode is r+i.
2736     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2737         LD->getExtensionType() == ISD::SEXTLOAD &&
2738         isa<ConstantSDNode>(Offset))
2739       return false;
2740   }
2741 
2742   AM = ISD::PRE_INC;
2743   return true;
2744 }
2745 
2746 //===----------------------------------------------------------------------===//
2747 //  LowerOperation implementation
2748 //===----------------------------------------------------------------------===//
2749 
2750 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2751 /// and LoOpFlags to the target MO flags.
2752 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2753                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2754                                const GlobalValue *GV = nullptr) {
2755   HiOpFlags = PPCII::MO_HA;
2756   LoOpFlags = PPCII::MO_LO;
2757 
2758   // Don't use the pic base if not in PIC relocation model.
2759   if (IsPIC) {
2760     HiOpFlags |= PPCII::MO_PIC_FLAG;
2761     LoOpFlags |= PPCII::MO_PIC_FLAG;
2762   }
2763 }
2764 
2765 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2766                              SelectionDAG &DAG) {
2767   SDLoc DL(HiPart);
2768   EVT PtrVT = HiPart.getValueType();
2769   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2770 
2771   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2772   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2773 
2774   // With PIC, the first instruction is actually "GR+hi(&G)".
2775   if (isPIC)
2776     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2777                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2778 
2779   // Generate non-pic code that has direct accesses to the constant pool.
2780   // The address of the global is just (hi(&g)+lo(&g)).
2781   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2782 }
2783 
2784 static void setUsesTOCBasePtr(MachineFunction &MF) {
2785   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2786   FuncInfo->setUsesTOCBasePtr();
2787 }
2788 
2789 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2790   setUsesTOCBasePtr(DAG.getMachineFunction());
2791 }
2792 
2793 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2794                                        SDValue GA) const {
2795   const bool Is64Bit = Subtarget.isPPC64();
2796   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2797   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2798                         : Subtarget.isAIXABI()
2799                               ? DAG.getRegister(PPC::R2, VT)
2800                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2801   SDValue Ops[] = { GA, Reg };
2802   return DAG.getMemIntrinsicNode(
2803       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2804       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2805       MachineMemOperand::MOLoad);
2806 }
2807 
2808 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2809                                              SelectionDAG &DAG) const {
2810   EVT PtrVT = Op.getValueType();
2811   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2812   const Constant *C = CP->getConstVal();
2813 
2814   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2815   // The actual address of the GlobalValue is stored in the TOC.
2816   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2817     if (Subtarget.isUsingPCRelativeCalls()) {
2818       SDLoc DL(CP);
2819       EVT Ty = getPointerTy(DAG.getDataLayout());
2820       SDValue ConstPool = DAG.getTargetConstantPool(C, Ty,
2821                                                     CP->getAlignment(),
2822                                                     CP->getOffset(),
2823                                                     PPCII::MO_PCREL_FLAG);
2824       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2825     }
2826     setUsesTOCBasePtr(DAG);
2827     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2828     return getTOCEntry(DAG, SDLoc(CP), GA);
2829   }
2830 
2831   unsigned MOHiFlag, MOLoFlag;
2832   bool IsPIC = isPositionIndependent();
2833   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2834 
2835   if (IsPIC && Subtarget.isSVR4ABI()) {
2836     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2837                                            PPCII::MO_PIC_FLAG);
2838     return getTOCEntry(DAG, SDLoc(CP), GA);
2839   }
2840 
2841   SDValue CPIHi =
2842     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2843   SDValue CPILo =
2844     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2845   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2846 }
2847 
2848 // For 64-bit PowerPC, prefer the more compact relative encodings.
2849 // This trades 32 bits per jump table entry for one or two instructions
2850 // on the jump site.
2851 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2852   if (isJumpTableRelative())
2853     return MachineJumpTableInfo::EK_LabelDifference32;
2854 
2855   return TargetLowering::getJumpTableEncoding();
2856 }
2857 
2858 bool PPCTargetLowering::isJumpTableRelative() const {
2859   if (UseAbsoluteJumpTables)
2860     return false;
2861   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2862     return true;
2863   return TargetLowering::isJumpTableRelative();
2864 }
2865 
2866 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2867                                                     SelectionDAG &DAG) const {
2868   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2869     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2870 
2871   switch (getTargetMachine().getCodeModel()) {
2872   case CodeModel::Small:
2873   case CodeModel::Medium:
2874     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2875   default:
2876     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2877                        getPointerTy(DAG.getDataLayout()));
2878   }
2879 }
2880 
2881 const MCExpr *
2882 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2883                                                 unsigned JTI,
2884                                                 MCContext &Ctx) const {
2885   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2886     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2887 
2888   switch (getTargetMachine().getCodeModel()) {
2889   case CodeModel::Small:
2890   case CodeModel::Medium:
2891     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2892   default:
2893     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2894   }
2895 }
2896 
2897 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2898   EVT PtrVT = Op.getValueType();
2899   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2900 
2901   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2902   if (Subtarget.isUsingPCRelativeCalls()) {
2903     SDLoc DL(JT);
2904     EVT Ty = getPointerTy(DAG.getDataLayout());
2905     SDValue GA =
2906         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
2907     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2908     return MatAddr;
2909   }
2910 
2911   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2912   // The actual address of the GlobalValue is stored in the TOC.
2913   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2914     setUsesTOCBasePtr(DAG);
2915     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2916     return getTOCEntry(DAG, SDLoc(JT), GA);
2917   }
2918 
2919   unsigned MOHiFlag, MOLoFlag;
2920   bool IsPIC = isPositionIndependent();
2921   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2922 
2923   if (IsPIC && Subtarget.isSVR4ABI()) {
2924     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2925                                         PPCII::MO_PIC_FLAG);
2926     return getTOCEntry(DAG, SDLoc(GA), GA);
2927   }
2928 
2929   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2930   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2931   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2932 }
2933 
2934 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2935                                              SelectionDAG &DAG) const {
2936   EVT PtrVT = Op.getValueType();
2937   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2938   const BlockAddress *BA = BASDN->getBlockAddress();
2939 
2940   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2941   if (Subtarget.isUsingPCRelativeCalls()) {
2942     SDLoc DL(BASDN);
2943     EVT Ty = getPointerTy(DAG.getDataLayout());
2944     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
2945                                            PPCII::MO_PCREL_FLAG);
2946     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2947     return MatAddr;
2948   }
2949 
2950   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2951   // The actual BlockAddress is stored in the TOC.
2952   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2953     setUsesTOCBasePtr(DAG);
2954     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2955     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2956   }
2957 
2958   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2959   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2960     return getTOCEntry(
2961         DAG, SDLoc(BASDN),
2962         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2963 
2964   unsigned MOHiFlag, MOLoFlag;
2965   bool IsPIC = isPositionIndependent();
2966   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2967   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2968   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2969   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2970 }
2971 
2972 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2973                                               SelectionDAG &DAG) const {
2974   // FIXME: TLS addresses currently use medium model code sequences,
2975   // which is the most useful form.  Eventually support for small and
2976   // large models could be added if users need it, at the cost of
2977   // additional complexity.
2978   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2979   if (DAG.getTarget().useEmulatedTLS())
2980     return LowerToTLSEmulatedModel(GA, DAG);
2981 
2982   SDLoc dl(GA);
2983   const GlobalValue *GV = GA->getGlobal();
2984   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2985   bool is64bit = Subtarget.isPPC64();
2986   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2987   PICLevel::Level picLevel = M->getPICLevel();
2988 
2989   const TargetMachine &TM = getTargetMachine();
2990   TLSModel::Model Model = TM.getTLSModel(GV);
2991 
2992   if (Model == TLSModel::LocalExec) {
2993     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2994                                                PPCII::MO_TPREL_HA);
2995     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2996                                                PPCII::MO_TPREL_LO);
2997     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2998                              : DAG.getRegister(PPC::R2, MVT::i32);
2999 
3000     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3001     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3002   }
3003 
3004   if (Model == TLSModel::InitialExec) {
3005     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3006     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3007                                                 PPCII::MO_TLS);
3008     SDValue GOTPtr;
3009     if (is64bit) {
3010       setUsesTOCBasePtr(DAG);
3011       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3012       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
3013                            PtrVT, GOTReg, TGA);
3014     } else {
3015       if (!TM.isPositionIndependent())
3016         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3017       else if (picLevel == PICLevel::SmallPIC)
3018         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3019       else
3020         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3021     }
3022     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
3023                                    PtrVT, TGA, GOTPtr);
3024     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3025   }
3026 
3027   if (Model == TLSModel::GeneralDynamic) {
3028     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3029     SDValue GOTPtr;
3030     if (is64bit) {
3031       setUsesTOCBasePtr(DAG);
3032       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3033       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3034                                    GOTReg, TGA);
3035     } else {
3036       if (picLevel == PICLevel::SmallPIC)
3037         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3038       else
3039         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3040     }
3041     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3042                        GOTPtr, TGA, TGA);
3043   }
3044 
3045   if (Model == TLSModel::LocalDynamic) {
3046     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3047     SDValue GOTPtr;
3048     if (is64bit) {
3049       setUsesTOCBasePtr(DAG);
3050       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3051       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3052                            GOTReg, TGA);
3053     } else {
3054       if (picLevel == PICLevel::SmallPIC)
3055         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3056       else
3057         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3058     }
3059     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3060                                   PtrVT, GOTPtr, TGA, TGA);
3061     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3062                                       PtrVT, TLSAddr, TGA);
3063     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3064   }
3065 
3066   llvm_unreachable("Unknown TLS model!");
3067 }
3068 
3069 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3070                                               SelectionDAG &DAG) const {
3071   EVT PtrVT = Op.getValueType();
3072   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3073   SDLoc DL(GSDN);
3074   const GlobalValue *GV = GSDN->getGlobal();
3075 
3076   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3077   // The actual address of the GlobalValue is stored in the TOC.
3078   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3079     if (Subtarget.isUsingPCRelativeCalls()) {
3080       EVT Ty = getPointerTy(DAG.getDataLayout());
3081       if (isAccessedAsGotIndirect(Op)) {
3082         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3083                                                 PPCII::MO_PCREL_FLAG |
3084                                                     PPCII::MO_GOT_FLAG);
3085         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3086         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3087                                    MachinePointerInfo());
3088         return Load;
3089       } else {
3090         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3091                                                 PPCII::MO_PCREL_FLAG);
3092         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3093       }
3094     }
3095     setUsesTOCBasePtr(DAG);
3096     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3097     return getTOCEntry(DAG, DL, GA);
3098   }
3099 
3100   unsigned MOHiFlag, MOLoFlag;
3101   bool IsPIC = isPositionIndependent();
3102   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3103 
3104   if (IsPIC && Subtarget.isSVR4ABI()) {
3105     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3106                                             GSDN->getOffset(),
3107                                             PPCII::MO_PIC_FLAG);
3108     return getTOCEntry(DAG, DL, GA);
3109   }
3110 
3111   SDValue GAHi =
3112     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3113   SDValue GALo =
3114     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3115 
3116   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3117 }
3118 
3119 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3120   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3121   SDLoc dl(Op);
3122 
3123   if (Op.getValueType() == MVT::v2i64) {
3124     // When the operands themselves are v2i64 values, we need to do something
3125     // special because VSX has no underlying comparison operations for these.
3126     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3127       // Equality can be handled by casting to the legal type for Altivec
3128       // comparisons, everything else needs to be expanded.
3129       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3130         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3131                  DAG.getSetCC(dl, MVT::v4i32,
3132                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3133                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3134                    CC));
3135       }
3136 
3137       return SDValue();
3138     }
3139 
3140     // We handle most of these in the usual way.
3141     return Op;
3142   }
3143 
3144   // If we're comparing for equality to zero, expose the fact that this is
3145   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3146   // fold the new nodes.
3147   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3148     return V;
3149 
3150   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3151     // Leave comparisons against 0 and -1 alone for now, since they're usually
3152     // optimized.  FIXME: revisit this when we can custom lower all setcc
3153     // optimizations.
3154     if (C->isAllOnesValue() || C->isNullValue())
3155       return SDValue();
3156   }
3157 
3158   // If we have an integer seteq/setne, turn it into a compare against zero
3159   // by xor'ing the rhs with the lhs, which is faster than setting a
3160   // condition register, reading it back out, and masking the correct bit.  The
3161   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3162   // the result to other bit-twiddling opportunities.
3163   EVT LHSVT = Op.getOperand(0).getValueType();
3164   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3165     EVT VT = Op.getValueType();
3166     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3167                                 Op.getOperand(1));
3168     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3169   }
3170   return SDValue();
3171 }
3172 
3173 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3174   SDNode *Node = Op.getNode();
3175   EVT VT = Node->getValueType(0);
3176   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3177   SDValue InChain = Node->getOperand(0);
3178   SDValue VAListPtr = Node->getOperand(1);
3179   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3180   SDLoc dl(Node);
3181 
3182   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3183 
3184   // gpr_index
3185   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3186                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3187   InChain = GprIndex.getValue(1);
3188 
3189   if (VT == MVT::i64) {
3190     // Check if GprIndex is even
3191     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3192                                  DAG.getConstant(1, dl, MVT::i32));
3193     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3194                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3195     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3196                                           DAG.getConstant(1, dl, MVT::i32));
3197     // Align GprIndex to be even if it isn't
3198     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3199                            GprIndex);
3200   }
3201 
3202   // fpr index is 1 byte after gpr
3203   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3204                                DAG.getConstant(1, dl, MVT::i32));
3205 
3206   // fpr
3207   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3208                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3209   InChain = FprIndex.getValue(1);
3210 
3211   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3212                                        DAG.getConstant(8, dl, MVT::i32));
3213 
3214   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3215                                         DAG.getConstant(4, dl, MVT::i32));
3216 
3217   // areas
3218   SDValue OverflowArea =
3219       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3220   InChain = OverflowArea.getValue(1);
3221 
3222   SDValue RegSaveArea =
3223       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3224   InChain = RegSaveArea.getValue(1);
3225 
3226   // select overflow_area if index > 8
3227   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3228                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3229 
3230   // adjustment constant gpr_index * 4/8
3231   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3232                                     VT.isInteger() ? GprIndex : FprIndex,
3233                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3234                                                     MVT::i32));
3235 
3236   // OurReg = RegSaveArea + RegConstant
3237   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3238                                RegConstant);
3239 
3240   // Floating types are 32 bytes into RegSaveArea
3241   if (VT.isFloatingPoint())
3242     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3243                          DAG.getConstant(32, dl, MVT::i32));
3244 
3245   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3246   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3247                                    VT.isInteger() ? GprIndex : FprIndex,
3248                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3249                                                    MVT::i32));
3250 
3251   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3252                               VT.isInteger() ? VAListPtr : FprPtr,
3253                               MachinePointerInfo(SV), MVT::i8);
3254 
3255   // determine if we should load from reg_save_area or overflow_area
3256   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3257 
3258   // increase overflow_area by 4/8 if gpr/fpr > 8
3259   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3260                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3261                                           dl, MVT::i32));
3262 
3263   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3264                              OverflowAreaPlusN);
3265 
3266   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3267                               MachinePointerInfo(), MVT::i32);
3268 
3269   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3270 }
3271 
3272 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3273   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3274 
3275   // We have to copy the entire va_list struct:
3276   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3277   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3278                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3279                        false, true, false, MachinePointerInfo(),
3280                        MachinePointerInfo());
3281 }
3282 
3283 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3284                                                   SelectionDAG &DAG) const {
3285   if (Subtarget.isAIXABI())
3286     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3287 
3288   return Op.getOperand(0);
3289 }
3290 
3291 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3292                                                 SelectionDAG &DAG) const {
3293   if (Subtarget.isAIXABI())
3294     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3295 
3296   SDValue Chain = Op.getOperand(0);
3297   SDValue Trmp = Op.getOperand(1); // trampoline
3298   SDValue FPtr = Op.getOperand(2); // nested function
3299   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3300   SDLoc dl(Op);
3301 
3302   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3303   bool isPPC64 = (PtrVT == MVT::i64);
3304   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3305 
3306   TargetLowering::ArgListTy Args;
3307   TargetLowering::ArgListEntry Entry;
3308 
3309   Entry.Ty = IntPtrTy;
3310   Entry.Node = Trmp; Args.push_back(Entry);
3311 
3312   // TrampSize == (isPPC64 ? 48 : 40);
3313   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3314                                isPPC64 ? MVT::i64 : MVT::i32);
3315   Args.push_back(Entry);
3316 
3317   Entry.Node = FPtr; Args.push_back(Entry);
3318   Entry.Node = Nest; Args.push_back(Entry);
3319 
3320   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3321   TargetLowering::CallLoweringInfo CLI(DAG);
3322   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3323       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3324       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3325 
3326   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3327   return CallResult.second;
3328 }
3329 
3330 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3331   MachineFunction &MF = DAG.getMachineFunction();
3332   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3333   EVT PtrVT = getPointerTy(MF.getDataLayout());
3334 
3335   SDLoc dl(Op);
3336 
3337   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3338     // vastart just stores the address of the VarArgsFrameIndex slot into the
3339     // memory location argument.
3340     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3341     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3342     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3343                         MachinePointerInfo(SV));
3344   }
3345 
3346   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3347   // We suppose the given va_list is already allocated.
3348   //
3349   // typedef struct {
3350   //  char gpr;     /* index into the array of 8 GPRs
3351   //                 * stored in the register save area
3352   //                 * gpr=0 corresponds to r3,
3353   //                 * gpr=1 to r4, etc.
3354   //                 */
3355   //  char fpr;     /* index into the array of 8 FPRs
3356   //                 * stored in the register save area
3357   //                 * fpr=0 corresponds to f1,
3358   //                 * fpr=1 to f2, etc.
3359   //                 */
3360   //  char *overflow_arg_area;
3361   //                /* location on stack that holds
3362   //                 * the next overflow argument
3363   //                 */
3364   //  char *reg_save_area;
3365   //               /* where r3:r10 and f1:f8 (if saved)
3366   //                * are stored
3367   //                */
3368   // } va_list[1];
3369 
3370   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3371   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3372   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3373                                             PtrVT);
3374   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3375                                  PtrVT);
3376 
3377   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3378   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3379 
3380   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3381   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3382 
3383   uint64_t FPROffset = 1;
3384   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3385 
3386   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3387 
3388   // Store first byte : number of int regs
3389   SDValue firstStore =
3390       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3391                         MachinePointerInfo(SV), MVT::i8);
3392   uint64_t nextOffset = FPROffset;
3393   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3394                                   ConstFPROffset);
3395 
3396   // Store second byte : number of float regs
3397   SDValue secondStore =
3398       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3399                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3400   nextOffset += StackOffset;
3401   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3402 
3403   // Store second word : arguments given on stack
3404   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3405                                     MachinePointerInfo(SV, nextOffset));
3406   nextOffset += FrameOffset;
3407   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3408 
3409   // Store third word : arguments given in registers
3410   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3411                       MachinePointerInfo(SV, nextOffset));
3412 }
3413 
3414 /// FPR - The set of FP registers that should be allocated for arguments
3415 /// on Darwin and AIX.
3416 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3417                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3418                                 PPC::F11, PPC::F12, PPC::F13};
3419 
3420 /// QFPR - The set of QPX registers that should be allocated for arguments.
3421 static const MCPhysReg QFPR[] = {
3422     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3423     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3424 
3425 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3426 /// the stack.
3427 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3428                                        unsigned PtrByteSize) {
3429   unsigned ArgSize = ArgVT.getStoreSize();
3430   if (Flags.isByVal())
3431     ArgSize = Flags.getByValSize();
3432 
3433   // Round up to multiples of the pointer size, except for array members,
3434   // which are always packed.
3435   if (!Flags.isInConsecutiveRegs())
3436     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3437 
3438   return ArgSize;
3439 }
3440 
3441 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3442 /// on the stack.
3443 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3444                                          ISD::ArgFlagsTy Flags,
3445                                          unsigned PtrByteSize) {
3446   Align Alignment(PtrByteSize);
3447 
3448   // Altivec parameters are padded to a 16 byte boundary.
3449   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3450       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3451       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3452       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3453     Alignment = Align(16);
3454   // QPX vector types stored in double-precision are padded to a 32 byte
3455   // boundary.
3456   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3457     Alignment = Align(32);
3458 
3459   // ByVal parameters are aligned as requested.
3460   if (Flags.isByVal()) {
3461     auto BVAlign = Flags.getNonZeroByValAlign();
3462     if (BVAlign > PtrByteSize) {
3463       if (BVAlign.value() % PtrByteSize != 0)
3464         llvm_unreachable(
3465             "ByVal alignment is not a multiple of the pointer size");
3466 
3467       Alignment = BVAlign;
3468     }
3469   }
3470 
3471   // Array members are always packed to their original alignment.
3472   if (Flags.isInConsecutiveRegs()) {
3473     // If the array member was split into multiple registers, the first
3474     // needs to be aligned to the size of the full type.  (Except for
3475     // ppcf128, which is only aligned as its f64 components.)
3476     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3477       Alignment = Align(OrigVT.getStoreSize());
3478     else
3479       Alignment = Align(ArgVT.getStoreSize());
3480   }
3481 
3482   return Alignment;
3483 }
3484 
3485 /// CalculateStackSlotUsed - Return whether this argument will use its
3486 /// stack slot (instead of being passed in registers).  ArgOffset,
3487 /// AvailableFPRs, and AvailableVRs must hold the current argument
3488 /// position, and will be updated to account for this argument.
3489 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3490                                    ISD::ArgFlagsTy Flags,
3491                                    unsigned PtrByteSize,
3492                                    unsigned LinkageSize,
3493                                    unsigned ParamAreaSize,
3494                                    unsigned &ArgOffset,
3495                                    unsigned &AvailableFPRs,
3496                                    unsigned &AvailableVRs, bool HasQPX) {
3497   bool UseMemory = false;
3498 
3499   // Respect alignment of argument on the stack.
3500   Align Alignment =
3501       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3502   ArgOffset = alignTo(ArgOffset, Alignment);
3503   // If there's no space left in the argument save area, we must
3504   // use memory (this check also catches zero-sized arguments).
3505   if (ArgOffset >= LinkageSize + ParamAreaSize)
3506     UseMemory = true;
3507 
3508   // Allocate argument on the stack.
3509   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3510   if (Flags.isInConsecutiveRegsLast())
3511     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3512   // If we overran the argument save area, we must use memory
3513   // (this check catches arguments passed partially in memory)
3514   if (ArgOffset > LinkageSize + ParamAreaSize)
3515     UseMemory = true;
3516 
3517   // However, if the argument is actually passed in an FPR or a VR,
3518   // we don't use memory after all.
3519   if (!Flags.isByVal()) {
3520     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3521         // QPX registers overlap with the scalar FP registers.
3522         (HasQPX && (ArgVT == MVT::v4f32 ||
3523                     ArgVT == MVT::v4f64 ||
3524                     ArgVT == MVT::v4i1)))
3525       if (AvailableFPRs > 0) {
3526         --AvailableFPRs;
3527         return false;
3528       }
3529     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3530         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3531         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3532         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3533       if (AvailableVRs > 0) {
3534         --AvailableVRs;
3535         return false;
3536       }
3537   }
3538 
3539   return UseMemory;
3540 }
3541 
3542 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3543 /// ensure minimum alignment required for target.
3544 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3545                                      unsigned NumBytes) {
3546   return alignTo(NumBytes, Lowering->getStackAlign());
3547 }
3548 
3549 SDValue PPCTargetLowering::LowerFormalArguments(
3550     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3551     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3552     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3553   if (Subtarget.isAIXABI())
3554     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3555                                     InVals);
3556   if (Subtarget.is64BitELFABI())
3557     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3558                                        InVals);
3559   if (Subtarget.is32BitELFABI())
3560     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3561                                        InVals);
3562 
3563   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3564                                      InVals);
3565 }
3566 
3567 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3568     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3569     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3570     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3571 
3572   // 32-bit SVR4 ABI Stack Frame Layout:
3573   //              +-----------------------------------+
3574   //        +-->  |            Back chain             |
3575   //        |     +-----------------------------------+
3576   //        |     | Floating-point register save area |
3577   //        |     +-----------------------------------+
3578   //        |     |    General register save area     |
3579   //        |     +-----------------------------------+
3580   //        |     |          CR save word             |
3581   //        |     +-----------------------------------+
3582   //        |     |         VRSAVE save word          |
3583   //        |     +-----------------------------------+
3584   //        |     |         Alignment padding         |
3585   //        |     +-----------------------------------+
3586   //        |     |     Vector register save area     |
3587   //        |     +-----------------------------------+
3588   //        |     |       Local variable space        |
3589   //        |     +-----------------------------------+
3590   //        |     |        Parameter list area        |
3591   //        |     +-----------------------------------+
3592   //        |     |           LR save word            |
3593   //        |     +-----------------------------------+
3594   // SP-->  +---  |            Back chain             |
3595   //              +-----------------------------------+
3596   //
3597   // Specifications:
3598   //   System V Application Binary Interface PowerPC Processor Supplement
3599   //   AltiVec Technology Programming Interface Manual
3600 
3601   MachineFunction &MF = DAG.getMachineFunction();
3602   MachineFrameInfo &MFI = MF.getFrameInfo();
3603   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3604 
3605   EVT PtrVT = getPointerTy(MF.getDataLayout());
3606   // Potential tail calls could cause overwriting of argument stack slots.
3607   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3608                        (CallConv == CallingConv::Fast));
3609   unsigned PtrByteSize = 4;
3610 
3611   // Assign locations to all of the incoming arguments.
3612   SmallVector<CCValAssign, 16> ArgLocs;
3613   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3614                  *DAG.getContext());
3615 
3616   // Reserve space for the linkage area on the stack.
3617   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3618   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3619   if (useSoftFloat())
3620     CCInfo.PreAnalyzeFormalArguments(Ins);
3621 
3622   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3623   CCInfo.clearWasPPCF128();
3624 
3625   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3626     CCValAssign &VA = ArgLocs[i];
3627 
3628     // Arguments stored in registers.
3629     if (VA.isRegLoc()) {
3630       const TargetRegisterClass *RC;
3631       EVT ValVT = VA.getValVT();
3632 
3633       switch (ValVT.getSimpleVT().SimpleTy) {
3634         default:
3635           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3636         case MVT::i1:
3637         case MVT::i32:
3638           RC = &PPC::GPRCRegClass;
3639           break;
3640         case MVT::f32:
3641           if (Subtarget.hasP8Vector())
3642             RC = &PPC::VSSRCRegClass;
3643           else if (Subtarget.hasSPE())
3644             RC = &PPC::GPRCRegClass;
3645           else
3646             RC = &PPC::F4RCRegClass;
3647           break;
3648         case MVT::f64:
3649           if (Subtarget.hasVSX())
3650             RC = &PPC::VSFRCRegClass;
3651           else if (Subtarget.hasSPE())
3652             // SPE passes doubles in GPR pairs.
3653             RC = &PPC::GPRCRegClass;
3654           else
3655             RC = &PPC::F8RCRegClass;
3656           break;
3657         case MVT::v16i8:
3658         case MVT::v8i16:
3659         case MVT::v4i32:
3660           RC = &PPC::VRRCRegClass;
3661           break;
3662         case MVT::v4f32:
3663           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3664           break;
3665         case MVT::v2f64:
3666         case MVT::v2i64:
3667           RC = &PPC::VRRCRegClass;
3668           break;
3669         case MVT::v4f64:
3670           RC = &PPC::QFRCRegClass;
3671           break;
3672         case MVT::v4i1:
3673           RC = &PPC::QBRCRegClass;
3674           break;
3675       }
3676 
3677       SDValue ArgValue;
3678       // Transform the arguments stored in physical registers into
3679       // virtual ones.
3680       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3681         assert(i + 1 < e && "No second half of double precision argument");
3682         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3683         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3684         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3685         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3686         if (!Subtarget.isLittleEndian())
3687           std::swap (ArgValueLo, ArgValueHi);
3688         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3689                                ArgValueHi);
3690       } else {
3691         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3692         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3693                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3694         if (ValVT == MVT::i1)
3695           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3696       }
3697 
3698       InVals.push_back(ArgValue);
3699     } else {
3700       // Argument stored in memory.
3701       assert(VA.isMemLoc());
3702 
3703       // Get the extended size of the argument type in stack
3704       unsigned ArgSize = VA.getLocVT().getStoreSize();
3705       // Get the actual size of the argument type
3706       unsigned ObjSize = VA.getValVT().getStoreSize();
3707       unsigned ArgOffset = VA.getLocMemOffset();
3708       // Stack objects in PPC32 are right justified.
3709       ArgOffset += ArgSize - ObjSize;
3710       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3711 
3712       // Create load nodes to retrieve arguments from the stack.
3713       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3714       InVals.push_back(
3715           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3716     }
3717   }
3718 
3719   // Assign locations to all of the incoming aggregate by value arguments.
3720   // Aggregates passed by value are stored in the local variable space of the
3721   // caller's stack frame, right above the parameter list area.
3722   SmallVector<CCValAssign, 16> ByValArgLocs;
3723   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3724                       ByValArgLocs, *DAG.getContext());
3725 
3726   // Reserve stack space for the allocations in CCInfo.
3727   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3728 
3729   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3730 
3731   // Area that is at least reserved in the caller of this function.
3732   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3733   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3734 
3735   // Set the size that is at least reserved in caller of this function.  Tail
3736   // call optimized function's reserved stack space needs to be aligned so that
3737   // taking the difference between two stack areas will result in an aligned
3738   // stack.
3739   MinReservedArea =
3740       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3741   FuncInfo->setMinReservedArea(MinReservedArea);
3742 
3743   SmallVector<SDValue, 8> MemOps;
3744 
3745   // If the function takes variable number of arguments, make a frame index for
3746   // the start of the first vararg value... for expansion of llvm.va_start.
3747   if (isVarArg) {
3748     static const MCPhysReg GPArgRegs[] = {
3749       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3750       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3751     };
3752     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3753 
3754     static const MCPhysReg FPArgRegs[] = {
3755       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3756       PPC::F8
3757     };
3758     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3759 
3760     if (useSoftFloat() || hasSPE())
3761        NumFPArgRegs = 0;
3762 
3763     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3764     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3765 
3766     // Make room for NumGPArgRegs and NumFPArgRegs.
3767     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3768                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3769 
3770     FuncInfo->setVarArgsStackOffset(
3771       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3772                             CCInfo.getNextStackOffset(), true));
3773 
3774     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3775     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3776 
3777     // The fixed integer arguments of a variadic function are stored to the
3778     // VarArgsFrameIndex on the stack so that they may be loaded by
3779     // dereferencing the result of va_next.
3780     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3781       // Get an existing live-in vreg, or add a new one.
3782       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3783       if (!VReg)
3784         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3785 
3786       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3787       SDValue Store =
3788           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3789       MemOps.push_back(Store);
3790       // Increment the address by four for the next argument to store
3791       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3792       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3793     }
3794 
3795     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3796     // is set.
3797     // The double arguments are stored to the VarArgsFrameIndex
3798     // on the stack.
3799     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3800       // Get an existing live-in vreg, or add a new one.
3801       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3802       if (!VReg)
3803         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3804 
3805       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3806       SDValue Store =
3807           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3808       MemOps.push_back(Store);
3809       // Increment the address by eight for the next argument to store
3810       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3811                                          PtrVT);
3812       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3813     }
3814   }
3815 
3816   if (!MemOps.empty())
3817     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3818 
3819   return Chain;
3820 }
3821 
3822 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3823 // value to MVT::i64 and then truncate to the correct register size.
3824 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3825                                              EVT ObjectVT, SelectionDAG &DAG,
3826                                              SDValue ArgVal,
3827                                              const SDLoc &dl) const {
3828   if (Flags.isSExt())
3829     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3830                          DAG.getValueType(ObjectVT));
3831   else if (Flags.isZExt())
3832     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3833                          DAG.getValueType(ObjectVT));
3834 
3835   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3836 }
3837 
3838 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3839     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3840     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3841     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3842   // TODO: add description of PPC stack frame format, or at least some docs.
3843   //
3844   bool isELFv2ABI = Subtarget.isELFv2ABI();
3845   bool isLittleEndian = Subtarget.isLittleEndian();
3846   MachineFunction &MF = DAG.getMachineFunction();
3847   MachineFrameInfo &MFI = MF.getFrameInfo();
3848   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3849 
3850   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3851          "fastcc not supported on varargs functions");
3852 
3853   EVT PtrVT = getPointerTy(MF.getDataLayout());
3854   // Potential tail calls could cause overwriting of argument stack slots.
3855   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3856                        (CallConv == CallingConv::Fast));
3857   unsigned PtrByteSize = 8;
3858   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3859 
3860   static const MCPhysReg GPR[] = {
3861     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3862     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3863   };
3864   static const MCPhysReg VR[] = {
3865     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3866     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3867   };
3868 
3869   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3870   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3871   const unsigned Num_VR_Regs  = array_lengthof(VR);
3872   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3873 
3874   // Do a first pass over the arguments to determine whether the ABI
3875   // guarantees that our caller has allocated the parameter save area
3876   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3877   // in the ELFv2 ABI, it is true if this is a vararg function or if
3878   // any parameter is located in a stack slot.
3879 
3880   bool HasParameterArea = !isELFv2ABI || isVarArg;
3881   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3882   unsigned NumBytes = LinkageSize;
3883   unsigned AvailableFPRs = Num_FPR_Regs;
3884   unsigned AvailableVRs = Num_VR_Regs;
3885   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3886     if (Ins[i].Flags.isNest())
3887       continue;
3888 
3889     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3890                                PtrByteSize, LinkageSize, ParamAreaSize,
3891                                NumBytes, AvailableFPRs, AvailableVRs,
3892                                Subtarget.hasQPX()))
3893       HasParameterArea = true;
3894   }
3895 
3896   // Add DAG nodes to load the arguments or copy them out of registers.  On
3897   // entry to a function on PPC, the arguments start after the linkage area,
3898   // although the first ones are often in registers.
3899 
3900   unsigned ArgOffset = LinkageSize;
3901   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3902   unsigned &QFPR_idx = FPR_idx;
3903   SmallVector<SDValue, 8> MemOps;
3904   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3905   unsigned CurArgIdx = 0;
3906   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3907     SDValue ArgVal;
3908     bool needsLoad = false;
3909     EVT ObjectVT = Ins[ArgNo].VT;
3910     EVT OrigVT = Ins[ArgNo].ArgVT;
3911     unsigned ObjSize = ObjectVT.getStoreSize();
3912     unsigned ArgSize = ObjSize;
3913     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3914     if (Ins[ArgNo].isOrigArg()) {
3915       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3916       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3917     }
3918     // We re-align the argument offset for each argument, except when using the
3919     // fast calling convention, when we need to make sure we do that only when
3920     // we'll actually use a stack slot.
3921     unsigned CurArgOffset;
3922     Align Alignment;
3923     auto ComputeArgOffset = [&]() {
3924       /* Respect alignment of argument on the stack.  */
3925       Alignment =
3926           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3927       ArgOffset = alignTo(ArgOffset, Alignment);
3928       CurArgOffset = ArgOffset;
3929     };
3930 
3931     if (CallConv != CallingConv::Fast) {
3932       ComputeArgOffset();
3933 
3934       /* Compute GPR index associated with argument offset.  */
3935       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3936       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3937     }
3938 
3939     // FIXME the codegen can be much improved in some cases.
3940     // We do not have to keep everything in memory.
3941     if (Flags.isByVal()) {
3942       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3943 
3944       if (CallConv == CallingConv::Fast)
3945         ComputeArgOffset();
3946 
3947       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3948       ObjSize = Flags.getByValSize();
3949       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3950       // Empty aggregate parameters do not take up registers.  Examples:
3951       //   struct { } a;
3952       //   union  { } b;
3953       //   int c[0];
3954       // etc.  However, we have to provide a place-holder in InVals, so
3955       // pretend we have an 8-byte item at the current address for that
3956       // purpose.
3957       if (!ObjSize) {
3958         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3959         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3960         InVals.push_back(FIN);
3961         continue;
3962       }
3963 
3964       // Create a stack object covering all stack doublewords occupied
3965       // by the argument.  If the argument is (fully or partially) on
3966       // the stack, or if the argument is fully in registers but the
3967       // caller has allocated the parameter save anyway, we can refer
3968       // directly to the caller's stack frame.  Otherwise, create a
3969       // local copy in our own frame.
3970       int FI;
3971       if (HasParameterArea ||
3972           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3973         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3974       else
3975         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
3976       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3977 
3978       // Handle aggregates smaller than 8 bytes.
3979       if (ObjSize < PtrByteSize) {
3980         // The value of the object is its address, which differs from the
3981         // address of the enclosing doubleword on big-endian systems.
3982         SDValue Arg = FIN;
3983         if (!isLittleEndian) {
3984           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3985           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3986         }
3987         InVals.push_back(Arg);
3988 
3989         if (GPR_idx != Num_GPR_Regs) {
3990           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3991           FuncInfo->addLiveInAttr(VReg, Flags);
3992           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3993           SDValue Store;
3994 
3995           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3996             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3997                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3998             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3999                                       MachinePointerInfo(&*FuncArg), ObjType);
4000           } else {
4001             // For sizes that don't fit a truncating store (3, 5, 6, 7),
4002             // store the whole register as-is to the parameter save area
4003             // slot.
4004             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4005                                  MachinePointerInfo(&*FuncArg));
4006           }
4007 
4008           MemOps.push_back(Store);
4009         }
4010         // Whether we copied from a register or not, advance the offset
4011         // into the parameter save area by a full doubleword.
4012         ArgOffset += PtrByteSize;
4013         continue;
4014       }
4015 
4016       // The value of the object is its address, which is the address of
4017       // its first stack doubleword.
4018       InVals.push_back(FIN);
4019 
4020       // Store whatever pieces of the object are in registers to memory.
4021       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4022         if (GPR_idx == Num_GPR_Regs)
4023           break;
4024 
4025         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4026         FuncInfo->addLiveInAttr(VReg, Flags);
4027         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4028         SDValue Addr = FIN;
4029         if (j) {
4030           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4031           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4032         }
4033         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4034                                      MachinePointerInfo(&*FuncArg, j));
4035         MemOps.push_back(Store);
4036         ++GPR_idx;
4037       }
4038       ArgOffset += ArgSize;
4039       continue;
4040     }
4041 
4042     switch (ObjectVT.getSimpleVT().SimpleTy) {
4043     default: llvm_unreachable("Unhandled argument type!");
4044     case MVT::i1:
4045     case MVT::i32:
4046     case MVT::i64:
4047       if (Flags.isNest()) {
4048         // The 'nest' parameter, if any, is passed in R11.
4049         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4050         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4051 
4052         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4053           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4054 
4055         break;
4056       }
4057 
4058       // These can be scalar arguments or elements of an integer array type
4059       // passed directly.  Clang may use those instead of "byval" aggregate
4060       // types to avoid forcing arguments to memory unnecessarily.
4061       if (GPR_idx != Num_GPR_Regs) {
4062         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4063         FuncInfo->addLiveInAttr(VReg, Flags);
4064         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4065 
4066         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4067           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4068           // value to MVT::i64 and then truncate to the correct register size.
4069           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4070       } else {
4071         if (CallConv == CallingConv::Fast)
4072           ComputeArgOffset();
4073 
4074         needsLoad = true;
4075         ArgSize = PtrByteSize;
4076       }
4077       if (CallConv != CallingConv::Fast || needsLoad)
4078         ArgOffset += 8;
4079       break;
4080 
4081     case MVT::f32:
4082     case MVT::f64:
4083       // These can be scalar arguments or elements of a float array type
4084       // passed directly.  The latter are used to implement ELFv2 homogenous
4085       // float aggregates.
4086       if (FPR_idx != Num_FPR_Regs) {
4087         unsigned VReg;
4088 
4089         if (ObjectVT == MVT::f32)
4090           VReg = MF.addLiveIn(FPR[FPR_idx],
4091                               Subtarget.hasP8Vector()
4092                                   ? &PPC::VSSRCRegClass
4093                                   : &PPC::F4RCRegClass);
4094         else
4095           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4096                                                 ? &PPC::VSFRCRegClass
4097                                                 : &PPC::F8RCRegClass);
4098 
4099         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4100         ++FPR_idx;
4101       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4102         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4103         // once we support fp <-> gpr moves.
4104 
4105         // This can only ever happen in the presence of f32 array types,
4106         // since otherwise we never run out of FPRs before running out
4107         // of GPRs.
4108         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4109         FuncInfo->addLiveInAttr(VReg, Flags);
4110         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4111 
4112         if (ObjectVT == MVT::f32) {
4113           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4114             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4115                                  DAG.getConstant(32, dl, MVT::i32));
4116           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4117         }
4118 
4119         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4120       } else {
4121         if (CallConv == CallingConv::Fast)
4122           ComputeArgOffset();
4123 
4124         needsLoad = true;
4125       }
4126 
4127       // When passing an array of floats, the array occupies consecutive
4128       // space in the argument area; only round up to the next doubleword
4129       // at the end of the array.  Otherwise, each float takes 8 bytes.
4130       if (CallConv != CallingConv::Fast || needsLoad) {
4131         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4132         ArgOffset += ArgSize;
4133         if (Flags.isInConsecutiveRegsLast())
4134           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4135       }
4136       break;
4137     case MVT::v4f32:
4138     case MVT::v4i32:
4139     case MVT::v8i16:
4140     case MVT::v16i8:
4141     case MVT::v2f64:
4142     case MVT::v2i64:
4143     case MVT::v1i128:
4144     case MVT::f128:
4145       if (!Subtarget.hasQPX()) {
4146         // These can be scalar arguments or elements of a vector array type
4147         // passed directly.  The latter are used to implement ELFv2 homogenous
4148         // vector aggregates.
4149         if (VR_idx != Num_VR_Regs) {
4150           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4151           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4152           ++VR_idx;
4153         } else {
4154           if (CallConv == CallingConv::Fast)
4155             ComputeArgOffset();
4156           needsLoad = true;
4157         }
4158         if (CallConv != CallingConv::Fast || needsLoad)
4159           ArgOffset += 16;
4160         break;
4161       } // not QPX
4162 
4163       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
4164              "Invalid QPX parameter type");
4165       LLVM_FALLTHROUGH;
4166 
4167     case MVT::v4f64:
4168     case MVT::v4i1:
4169       // QPX vectors are treated like their scalar floating-point subregisters
4170       // (except that they're larger).
4171       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4172       if (QFPR_idx != Num_QFPR_Regs) {
4173         const TargetRegisterClass *RC;
4174         switch (ObjectVT.getSimpleVT().SimpleTy) {
4175         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4176         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4177         default:         RC = &PPC::QBRCRegClass; break;
4178         }
4179 
4180         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4181         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4182         ++QFPR_idx;
4183       } else {
4184         if (CallConv == CallingConv::Fast)
4185           ComputeArgOffset();
4186         needsLoad = true;
4187       }
4188       if (CallConv != CallingConv::Fast || needsLoad)
4189         ArgOffset += Sz;
4190       break;
4191     }
4192 
4193     // We need to load the argument to a virtual register if we determined
4194     // above that we ran out of physical registers of the appropriate type.
4195     if (needsLoad) {
4196       if (ObjSize < ArgSize && !isLittleEndian)
4197         CurArgOffset += ArgSize - ObjSize;
4198       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4199       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4200       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4201     }
4202 
4203     InVals.push_back(ArgVal);
4204   }
4205 
4206   // Area that is at least reserved in the caller of this function.
4207   unsigned MinReservedArea;
4208   if (HasParameterArea)
4209     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4210   else
4211     MinReservedArea = LinkageSize;
4212 
4213   // Set the size that is at least reserved in caller of this function.  Tail
4214   // call optimized functions' reserved stack space needs to be aligned so that
4215   // taking the difference between two stack areas will result in an aligned
4216   // stack.
4217   MinReservedArea =
4218       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4219   FuncInfo->setMinReservedArea(MinReservedArea);
4220 
4221   // If the function takes variable number of arguments, make a frame index for
4222   // the start of the first vararg value... for expansion of llvm.va_start.
4223   if (isVarArg) {
4224     int Depth = ArgOffset;
4225 
4226     FuncInfo->setVarArgsFrameIndex(
4227       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4228     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4229 
4230     // If this function is vararg, store any remaining integer argument regs
4231     // to their spots on the stack so that they may be loaded by dereferencing
4232     // the result of va_next.
4233     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4234          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4235       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4236       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4237       SDValue Store =
4238           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4239       MemOps.push_back(Store);
4240       // Increment the address by four for the next argument to store
4241       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4242       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4243     }
4244   }
4245 
4246   if (!MemOps.empty())
4247     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4248 
4249   return Chain;
4250 }
4251 
4252 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4253     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4254     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4255     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4256   // TODO: add description of PPC stack frame format, or at least some docs.
4257   //
4258   MachineFunction &MF = DAG.getMachineFunction();
4259   MachineFrameInfo &MFI = MF.getFrameInfo();
4260   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4261 
4262   EVT PtrVT = getPointerTy(MF.getDataLayout());
4263   bool isPPC64 = PtrVT == MVT::i64;
4264   // Potential tail calls could cause overwriting of argument stack slots.
4265   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4266                        (CallConv == CallingConv::Fast));
4267   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4268   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4269   unsigned ArgOffset = LinkageSize;
4270   // Area that is at least reserved in caller of this function.
4271   unsigned MinReservedArea = ArgOffset;
4272 
4273   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4274     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4275     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4276   };
4277   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4278     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4279     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4280   };
4281   static const MCPhysReg VR[] = {
4282     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4283     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4284   };
4285 
4286   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4287   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4288   const unsigned Num_VR_Regs  = array_lengthof( VR);
4289 
4290   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4291 
4292   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4293 
4294   // In 32-bit non-varargs functions, the stack space for vectors is after the
4295   // stack space for non-vectors.  We do not use this space unless we have
4296   // too many vectors to fit in registers, something that only occurs in
4297   // constructed examples:), but we have to walk the arglist to figure
4298   // that out...for the pathological case, compute VecArgOffset as the
4299   // start of the vector parameter area.  Computing VecArgOffset is the
4300   // entire point of the following loop.
4301   unsigned VecArgOffset = ArgOffset;
4302   if (!isVarArg && !isPPC64) {
4303     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4304          ++ArgNo) {
4305       EVT ObjectVT = Ins[ArgNo].VT;
4306       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4307 
4308       if (Flags.isByVal()) {
4309         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4310         unsigned ObjSize = Flags.getByValSize();
4311         unsigned ArgSize =
4312                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4313         VecArgOffset += ArgSize;
4314         continue;
4315       }
4316 
4317       switch(ObjectVT.getSimpleVT().SimpleTy) {
4318       default: llvm_unreachable("Unhandled argument type!");
4319       case MVT::i1:
4320       case MVT::i32:
4321       case MVT::f32:
4322         VecArgOffset += 4;
4323         break;
4324       case MVT::i64:  // PPC64
4325       case MVT::f64:
4326         // FIXME: We are guaranteed to be !isPPC64 at this point.
4327         // Does MVT::i64 apply?
4328         VecArgOffset += 8;
4329         break;
4330       case MVT::v4f32:
4331       case MVT::v4i32:
4332       case MVT::v8i16:
4333       case MVT::v16i8:
4334         // Nothing to do, we're only looking at Nonvector args here.
4335         break;
4336       }
4337     }
4338   }
4339   // We've found where the vector parameter area in memory is.  Skip the
4340   // first 12 parameters; these don't use that memory.
4341   VecArgOffset = ((VecArgOffset+15)/16)*16;
4342   VecArgOffset += 12*16;
4343 
4344   // Add DAG nodes to load the arguments or copy them out of registers.  On
4345   // entry to a function on PPC, the arguments start after the linkage area,
4346   // although the first ones are often in registers.
4347 
4348   SmallVector<SDValue, 8> MemOps;
4349   unsigned nAltivecParamsAtEnd = 0;
4350   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4351   unsigned CurArgIdx = 0;
4352   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4353     SDValue ArgVal;
4354     bool needsLoad = false;
4355     EVT ObjectVT = Ins[ArgNo].VT;
4356     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4357     unsigned ArgSize = ObjSize;
4358     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4359     if (Ins[ArgNo].isOrigArg()) {
4360       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4361       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4362     }
4363     unsigned CurArgOffset = ArgOffset;
4364 
4365     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4366     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4367         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4368       if (isVarArg || isPPC64) {
4369         MinReservedArea = ((MinReservedArea+15)/16)*16;
4370         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4371                                                   Flags,
4372                                                   PtrByteSize);
4373       } else  nAltivecParamsAtEnd++;
4374     } else
4375       // Calculate min reserved area.
4376       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4377                                                 Flags,
4378                                                 PtrByteSize);
4379 
4380     // FIXME the codegen can be much improved in some cases.
4381     // We do not have to keep everything in memory.
4382     if (Flags.isByVal()) {
4383       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4384 
4385       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4386       ObjSize = Flags.getByValSize();
4387       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4388       // Objects of size 1 and 2 are right justified, everything else is
4389       // left justified.  This means the memory address is adjusted forwards.
4390       if (ObjSize==1 || ObjSize==2) {
4391         CurArgOffset = CurArgOffset + (4 - ObjSize);
4392       }
4393       // The value of the object is its address.
4394       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4395       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4396       InVals.push_back(FIN);
4397       if (ObjSize==1 || ObjSize==2) {
4398         if (GPR_idx != Num_GPR_Regs) {
4399           unsigned VReg;
4400           if (isPPC64)
4401             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4402           else
4403             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4404           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4405           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4406           SDValue Store =
4407               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4408                                 MachinePointerInfo(&*FuncArg), ObjType);
4409           MemOps.push_back(Store);
4410           ++GPR_idx;
4411         }
4412 
4413         ArgOffset += PtrByteSize;
4414 
4415         continue;
4416       }
4417       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4418         // Store whatever pieces of the object are in registers
4419         // to memory.  ArgOffset will be the address of the beginning
4420         // of the object.
4421         if (GPR_idx != Num_GPR_Regs) {
4422           unsigned VReg;
4423           if (isPPC64)
4424             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4425           else
4426             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4427           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4428           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4429           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4430           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4431                                        MachinePointerInfo(&*FuncArg, j));
4432           MemOps.push_back(Store);
4433           ++GPR_idx;
4434           ArgOffset += PtrByteSize;
4435         } else {
4436           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4437           break;
4438         }
4439       }
4440       continue;
4441     }
4442 
4443     switch (ObjectVT.getSimpleVT().SimpleTy) {
4444     default: llvm_unreachable("Unhandled argument type!");
4445     case MVT::i1:
4446     case MVT::i32:
4447       if (!isPPC64) {
4448         if (GPR_idx != Num_GPR_Regs) {
4449           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4450           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4451 
4452           if (ObjectVT == MVT::i1)
4453             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4454 
4455           ++GPR_idx;
4456         } else {
4457           needsLoad = true;
4458           ArgSize = PtrByteSize;
4459         }
4460         // All int arguments reserve stack space in the Darwin ABI.
4461         ArgOffset += PtrByteSize;
4462         break;
4463       }
4464       LLVM_FALLTHROUGH;
4465     case MVT::i64:  // PPC64
4466       if (GPR_idx != Num_GPR_Regs) {
4467         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4468         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4469 
4470         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4471           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4472           // value to MVT::i64 and then truncate to the correct register size.
4473           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4474 
4475         ++GPR_idx;
4476       } else {
4477         needsLoad = true;
4478         ArgSize = PtrByteSize;
4479       }
4480       // All int arguments reserve stack space in the Darwin ABI.
4481       ArgOffset += 8;
4482       break;
4483 
4484     case MVT::f32:
4485     case MVT::f64:
4486       // Every 4 bytes of argument space consumes one of the GPRs available for
4487       // argument passing.
4488       if (GPR_idx != Num_GPR_Regs) {
4489         ++GPR_idx;
4490         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4491           ++GPR_idx;
4492       }
4493       if (FPR_idx != Num_FPR_Regs) {
4494         unsigned VReg;
4495 
4496         if (ObjectVT == MVT::f32)
4497           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4498         else
4499           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4500 
4501         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4502         ++FPR_idx;
4503       } else {
4504         needsLoad = true;
4505       }
4506 
4507       // All FP arguments reserve stack space in the Darwin ABI.
4508       ArgOffset += isPPC64 ? 8 : ObjSize;
4509       break;
4510     case MVT::v4f32:
4511     case MVT::v4i32:
4512     case MVT::v8i16:
4513     case MVT::v16i8:
4514       // Note that vector arguments in registers don't reserve stack space,
4515       // except in varargs functions.
4516       if (VR_idx != Num_VR_Regs) {
4517         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4518         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4519         if (isVarArg) {
4520           while ((ArgOffset % 16) != 0) {
4521             ArgOffset += PtrByteSize;
4522             if (GPR_idx != Num_GPR_Regs)
4523               GPR_idx++;
4524           }
4525           ArgOffset += 16;
4526           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4527         }
4528         ++VR_idx;
4529       } else {
4530         if (!isVarArg && !isPPC64) {
4531           // Vectors go after all the nonvectors.
4532           CurArgOffset = VecArgOffset;
4533           VecArgOffset += 16;
4534         } else {
4535           // Vectors are aligned.
4536           ArgOffset = ((ArgOffset+15)/16)*16;
4537           CurArgOffset = ArgOffset;
4538           ArgOffset += 16;
4539         }
4540         needsLoad = true;
4541       }
4542       break;
4543     }
4544 
4545     // We need to load the argument to a virtual register if we determined above
4546     // that we ran out of physical registers of the appropriate type.
4547     if (needsLoad) {
4548       int FI = MFI.CreateFixedObject(ObjSize,
4549                                      CurArgOffset + (ArgSize - ObjSize),
4550                                      isImmutable);
4551       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4552       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4553     }
4554 
4555     InVals.push_back(ArgVal);
4556   }
4557 
4558   // Allow for Altivec parameters at the end, if needed.
4559   if (nAltivecParamsAtEnd) {
4560     MinReservedArea = ((MinReservedArea+15)/16)*16;
4561     MinReservedArea += 16*nAltivecParamsAtEnd;
4562   }
4563 
4564   // Area that is at least reserved in the caller of this function.
4565   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4566 
4567   // Set the size that is at least reserved in caller of this function.  Tail
4568   // call optimized functions' reserved stack space needs to be aligned so that
4569   // taking the difference between two stack areas will result in an aligned
4570   // stack.
4571   MinReservedArea =
4572       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4573   FuncInfo->setMinReservedArea(MinReservedArea);
4574 
4575   // If the function takes variable number of arguments, make a frame index for
4576   // the start of the first vararg value... for expansion of llvm.va_start.
4577   if (isVarArg) {
4578     int Depth = ArgOffset;
4579 
4580     FuncInfo->setVarArgsFrameIndex(
4581       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4582                             Depth, true));
4583     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4584 
4585     // If this function is vararg, store any remaining integer argument regs
4586     // to their spots on the stack so that they may be loaded by dereferencing
4587     // the result of va_next.
4588     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4589       unsigned VReg;
4590 
4591       if (isPPC64)
4592         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4593       else
4594         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4595 
4596       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4597       SDValue Store =
4598           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4599       MemOps.push_back(Store);
4600       // Increment the address by four for the next argument to store
4601       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4602       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4603     }
4604   }
4605 
4606   if (!MemOps.empty())
4607     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4608 
4609   return Chain;
4610 }
4611 
4612 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4613 /// adjusted to accommodate the arguments for the tailcall.
4614 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4615                                    unsigned ParamSize) {
4616 
4617   if (!isTailCall) return 0;
4618 
4619   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4620   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4621   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4622   // Remember only if the new adjustment is bigger.
4623   if (SPDiff < FI->getTailCallSPDelta())
4624     FI->setTailCallSPDelta(SPDiff);
4625 
4626   return SPDiff;
4627 }
4628 
4629 static bool isFunctionGlobalAddress(SDValue Callee);
4630 
4631 static bool
4632 callsShareTOCBase(const Function *Caller, SDValue Callee,
4633                     const TargetMachine &TM) {
4634    // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4635    // don't have enough information to determine if the caller and calle share
4636    // the same  TOC base, so we have to pessimistically assume they don't for
4637    // correctness.
4638    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4639    if (!G)
4640      return false;
4641 
4642    const GlobalValue *GV = G->getGlobal();
4643   // The medium and large code models are expected to provide a sufficiently
4644   // large TOC to provide all data addressing needs of a module with a
4645   // single TOC. Since each module will be addressed with a single TOC then we
4646   // only need to check that caller and callee don't cross dso boundaries.
4647   if (CodeModel::Medium == TM.getCodeModel() ||
4648       CodeModel::Large == TM.getCodeModel())
4649     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4650 
4651   // Otherwise we need to ensure callee and caller are in the same section,
4652   // since the linker may allocate multiple TOCs, and we don't know which
4653   // sections will belong to the same TOC base.
4654 
4655   if (!GV->isStrongDefinitionForLinker())
4656     return false;
4657 
4658   // Any explicitly-specified sections and section prefixes must also match.
4659   // Also, if we're using -ffunction-sections, then each function is always in
4660   // a different section (the same is true for COMDAT functions).
4661   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4662       GV->getSection() != Caller->getSection())
4663     return false;
4664   if (const auto *F = dyn_cast<Function>(GV)) {
4665     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4666       return false;
4667   }
4668 
4669   // If the callee might be interposed, then we can't assume the ultimate call
4670   // target will be in the same section. Even in cases where we can assume that
4671   // interposition won't happen, in any case where the linker might insert a
4672   // stub to allow for interposition, we must generate code as though
4673   // interposition might occur. To understand why this matters, consider a
4674   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4675   // in the same section, but a is in a different module (i.e. has a different
4676   // TOC base pointer). If the linker allows for interposition between b and c,
4677   // then it will generate a stub for the call edge between b and c which will
4678   // save the TOC pointer into the designated stack slot allocated by b. If we
4679   // return true here, and therefore allow a tail call between b and c, that
4680   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4681   // pointer into the stack slot allocated by a (where the a -> b stub saved
4682   // a's TOC base pointer). If we're not considering a tail call, but rather,
4683   // whether a nop is needed after the call instruction in b, because the linker
4684   // will insert a stub, it might complain about a missing nop if we omit it
4685   // (although many don't complain in this case).
4686   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4687     return false;
4688 
4689   return true;
4690 }
4691 
4692 static bool
4693 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4694                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4695   assert(Subtarget.is64BitELFABI());
4696 
4697   const unsigned PtrByteSize = 8;
4698   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4699 
4700   static const MCPhysReg GPR[] = {
4701     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4702     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4703   };
4704   static const MCPhysReg VR[] = {
4705     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4706     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4707   };
4708 
4709   const unsigned NumGPRs = array_lengthof(GPR);
4710   const unsigned NumFPRs = 13;
4711   const unsigned NumVRs = array_lengthof(VR);
4712   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4713 
4714   unsigned NumBytes = LinkageSize;
4715   unsigned AvailableFPRs = NumFPRs;
4716   unsigned AvailableVRs = NumVRs;
4717 
4718   for (const ISD::OutputArg& Param : Outs) {
4719     if (Param.Flags.isNest()) continue;
4720 
4721     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4722                                PtrByteSize, LinkageSize, ParamAreaSize,
4723                                NumBytes, AvailableFPRs, AvailableVRs,
4724                                Subtarget.hasQPX()))
4725       return true;
4726   }
4727   return false;
4728 }
4729 
4730 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4731   if (CB.arg_size() != CallerFn->arg_size())
4732     return false;
4733 
4734   auto CalleeArgIter = CB.arg_begin();
4735   auto CalleeArgEnd = CB.arg_end();
4736   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4737 
4738   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4739     const Value* CalleeArg = *CalleeArgIter;
4740     const Value* CallerArg = &(*CallerArgIter);
4741     if (CalleeArg == CallerArg)
4742       continue;
4743 
4744     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4745     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4746     //      }
4747     // 1st argument of callee is undef and has the same type as caller.
4748     if (CalleeArg->getType() == CallerArg->getType() &&
4749         isa<UndefValue>(CalleeArg))
4750       continue;
4751 
4752     return false;
4753   }
4754 
4755   return true;
4756 }
4757 
4758 // Returns true if TCO is possible between the callers and callees
4759 // calling conventions.
4760 static bool
4761 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4762                                     CallingConv::ID CalleeCC) {
4763   // Tail calls are possible with fastcc and ccc.
4764   auto isTailCallableCC  = [] (CallingConv::ID CC){
4765       return  CC == CallingConv::C || CC == CallingConv::Fast;
4766   };
4767   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4768     return false;
4769 
4770   // We can safely tail call both fastcc and ccc callees from a c calling
4771   // convention caller. If the caller is fastcc, we may have less stack space
4772   // than a non-fastcc caller with the same signature so disable tail-calls in
4773   // that case.
4774   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4775 }
4776 
4777 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4778     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4779     const SmallVectorImpl<ISD::OutputArg> &Outs,
4780     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4781   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4782 
4783   // FIXME: Tail calls are currently disabled when using PC Relative addressing.
4784   // The issue is that PC Relative is only partially implemented and so there
4785   // is currently a mix of functions that require the TOC and functions that do
4786   // not require it. If we have A calls B calls C and both A and B require the
4787   // TOC and C does not and is marked as clobbering R2 then it is not safe for
4788   // B to tail call C. Since we do not have the information of whether or not
4789   // a funciton needs to use the TOC here in this function we need to be
4790   // conservatively safe and disable all tail calls for now.
4791   if (Subtarget.isUsingPCRelativeCalls()) return false;
4792 
4793   if (DisableSCO && !TailCallOpt) return false;
4794 
4795   // Variadic argument functions are not supported.
4796   if (isVarArg) return false;
4797 
4798   auto &Caller = DAG.getMachineFunction().getFunction();
4799   // Check that the calling conventions are compatible for tco.
4800   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4801     return false;
4802 
4803   // Caller contains any byval parameter is not supported.
4804   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4805     return false;
4806 
4807   // Callee contains any byval parameter is not supported, too.
4808   // Note: This is a quick work around, because in some cases, e.g.
4809   // caller's stack size > callee's stack size, we are still able to apply
4810   // sibling call optimization. For example, gcc is able to do SCO for caller1
4811   // in the following example, but not for caller2.
4812   //   struct test {
4813   //     long int a;
4814   //     char ary[56];
4815   //   } gTest;
4816   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4817   //     b->a = v.a;
4818   //     return 0;
4819   //   }
4820   //   void caller1(struct test a, struct test c, struct test *b) {
4821   //     callee(gTest, b); }
4822   //   void caller2(struct test *b) { callee(gTest, b); }
4823   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4824     return false;
4825 
4826   // If callee and caller use different calling conventions, we cannot pass
4827   // parameters on stack since offsets for the parameter area may be different.
4828   if (Caller.getCallingConv() != CalleeCC &&
4829       needStackSlotPassParameters(Subtarget, Outs))
4830     return false;
4831 
4832   // No TCO/SCO on indirect call because Caller have to restore its TOC
4833   if (!isFunctionGlobalAddress(Callee) &&
4834       !isa<ExternalSymbolSDNode>(Callee))
4835     return false;
4836 
4837   // If the caller and callee potentially have different TOC bases then we
4838   // cannot tail call since we need to restore the TOC pointer after the call.
4839   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4840   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4841     return false;
4842 
4843   // TCO allows altering callee ABI, so we don't have to check further.
4844   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4845     return true;
4846 
4847   if (DisableSCO) return false;
4848 
4849   // If callee use the same argument list that caller is using, then we can
4850   // apply SCO on this case. If it is not, then we need to check if callee needs
4851   // stack for passing arguments.
4852   assert(CB && "Expected to have a CallBase!");
4853   if (!hasSameArgumentList(&Caller, *CB) &&
4854       needStackSlotPassParameters(Subtarget, Outs)) {
4855     return false;
4856   }
4857 
4858   return true;
4859 }
4860 
4861 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4862 /// for tail call optimization. Targets which want to do tail call
4863 /// optimization should implement this function.
4864 bool
4865 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4866                                                      CallingConv::ID CalleeCC,
4867                                                      bool isVarArg,
4868                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4869                                                      SelectionDAG& DAG) const {
4870   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4871     return false;
4872 
4873   // Variable argument functions are not supported.
4874   if (isVarArg)
4875     return false;
4876 
4877   MachineFunction &MF = DAG.getMachineFunction();
4878   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4879   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4880     // Functions containing by val parameters are not supported.
4881     for (unsigned i = 0; i != Ins.size(); i++) {
4882        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4883        if (Flags.isByVal()) return false;
4884     }
4885 
4886     // Non-PIC/GOT tail calls are supported.
4887     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4888       return true;
4889 
4890     // At the moment we can only do local tail calls (in same module, hidden
4891     // or protected) if we are generating PIC.
4892     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4893       return G->getGlobal()->hasHiddenVisibility()
4894           || G->getGlobal()->hasProtectedVisibility();
4895   }
4896 
4897   return false;
4898 }
4899 
4900 /// isCallCompatibleAddress - Return the immediate to use if the specified
4901 /// 32-bit value is representable in the immediate field of a BxA instruction.
4902 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4903   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4904   if (!C) return nullptr;
4905 
4906   int Addr = C->getZExtValue();
4907   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4908       SignExtend32<26>(Addr) != Addr)
4909     return nullptr;  // Top 6 bits have to be sext of immediate.
4910 
4911   return DAG
4912       .getConstant(
4913           (int)C->getZExtValue() >> 2, SDLoc(Op),
4914           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4915       .getNode();
4916 }
4917 
4918 namespace {
4919 
4920 struct TailCallArgumentInfo {
4921   SDValue Arg;
4922   SDValue FrameIdxOp;
4923   int FrameIdx = 0;
4924 
4925   TailCallArgumentInfo() = default;
4926 };
4927 
4928 } // end anonymous namespace
4929 
4930 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4931 static void StoreTailCallArgumentsToStackSlot(
4932     SelectionDAG &DAG, SDValue Chain,
4933     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4934     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4935   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4936     SDValue Arg = TailCallArgs[i].Arg;
4937     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4938     int FI = TailCallArgs[i].FrameIdx;
4939     // Store relative to framepointer.
4940     MemOpChains.push_back(DAG.getStore(
4941         Chain, dl, Arg, FIN,
4942         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4943   }
4944 }
4945 
4946 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4947 /// the appropriate stack slot for the tail call optimized function call.
4948 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4949                                              SDValue OldRetAddr, SDValue OldFP,
4950                                              int SPDiff, const SDLoc &dl) {
4951   if (SPDiff) {
4952     // Calculate the new stack slot for the return address.
4953     MachineFunction &MF = DAG.getMachineFunction();
4954     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4955     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4956     bool isPPC64 = Subtarget.isPPC64();
4957     int SlotSize = isPPC64 ? 8 : 4;
4958     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4959     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4960                                                          NewRetAddrLoc, true);
4961     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4962     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4963     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4964                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4965   }
4966   return Chain;
4967 }
4968 
4969 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4970 /// the position of the argument.
4971 static void
4972 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4973                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4974                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4975   int Offset = ArgOffset + SPDiff;
4976   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4977   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4978   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4979   SDValue FIN = DAG.getFrameIndex(FI, VT);
4980   TailCallArgumentInfo Info;
4981   Info.Arg = Arg;
4982   Info.FrameIdxOp = FIN;
4983   Info.FrameIdx = FI;
4984   TailCallArguments.push_back(Info);
4985 }
4986 
4987 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4988 /// stack slot. Returns the chain as result and the loaded frame pointers in
4989 /// LROpOut/FPOpout. Used when tail calling.
4990 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4991     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4992     SDValue &FPOpOut, const SDLoc &dl) const {
4993   if (SPDiff) {
4994     // Load the LR and FP stack slot for later adjusting.
4995     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4996     LROpOut = getReturnAddrFrameIndex(DAG);
4997     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4998     Chain = SDValue(LROpOut.getNode(), 1);
4999   }
5000   return Chain;
5001 }
5002 
5003 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5004 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5005 /// specified by the specific parameter attribute. The copy will be passed as
5006 /// a byval function parameter.
5007 /// Sometimes what we are copying is the end of a larger object, the part that
5008 /// does not fit in registers.
5009 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5010                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5011                                          SelectionDAG &DAG, const SDLoc &dl) {
5012   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5013   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5014                        Flags.getNonZeroByValAlign(), false, false, false,
5015                        MachinePointerInfo(), MachinePointerInfo());
5016 }
5017 
5018 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5019 /// tail calls.
5020 static void LowerMemOpCallTo(
5021     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5022     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5023     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5024     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5025   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5026   if (!isTailCall) {
5027     if (isVector) {
5028       SDValue StackPtr;
5029       if (isPPC64)
5030         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5031       else
5032         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5033       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5034                            DAG.getConstant(ArgOffset, dl, PtrVT));
5035     }
5036     MemOpChains.push_back(
5037         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5038     // Calculate and remember argument location.
5039   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5040                                   TailCallArguments);
5041 }
5042 
5043 static void
5044 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5045                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5046                 SDValue FPOp,
5047                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5048   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5049   // might overwrite each other in case of tail call optimization.
5050   SmallVector<SDValue, 8> MemOpChains2;
5051   // Do not flag preceding copytoreg stuff together with the following stuff.
5052   InFlag = SDValue();
5053   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5054                                     MemOpChains2, dl);
5055   if (!MemOpChains2.empty())
5056     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5057 
5058   // Store the return address to the appropriate stack slot.
5059   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5060 
5061   // Emit callseq_end just before tailcall node.
5062   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5063                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5064   InFlag = Chain.getValue(1);
5065 }
5066 
5067 // Is this global address that of a function that can be called by name? (as
5068 // opposed to something that must hold a descriptor for an indirect call).
5069 static bool isFunctionGlobalAddress(SDValue Callee) {
5070   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5071     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5072         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5073       return false;
5074 
5075     return G->getGlobal()->getValueType()->isFunctionTy();
5076   }
5077 
5078   return false;
5079 }
5080 
5081 SDValue PPCTargetLowering::LowerCallResult(
5082     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5083     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5084     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5085   SmallVector<CCValAssign, 16> RVLocs;
5086   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5087                     *DAG.getContext());
5088 
5089   CCRetInfo.AnalyzeCallResult(
5090       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5091                ? RetCC_PPC_Cold
5092                : RetCC_PPC);
5093 
5094   // Copy all of the result registers out of their specified physreg.
5095   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5096     CCValAssign &VA = RVLocs[i];
5097     assert(VA.isRegLoc() && "Can only return in registers!");
5098 
5099     SDValue Val;
5100 
5101     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5102       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5103                                       InFlag);
5104       Chain = Lo.getValue(1);
5105       InFlag = Lo.getValue(2);
5106       VA = RVLocs[++i]; // skip ahead to next loc
5107       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5108                                       InFlag);
5109       Chain = Hi.getValue(1);
5110       InFlag = Hi.getValue(2);
5111       if (!Subtarget.isLittleEndian())
5112         std::swap (Lo, Hi);
5113       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5114     } else {
5115       Val = DAG.getCopyFromReg(Chain, dl,
5116                                VA.getLocReg(), VA.getLocVT(), InFlag);
5117       Chain = Val.getValue(1);
5118       InFlag = Val.getValue(2);
5119     }
5120 
5121     switch (VA.getLocInfo()) {
5122     default: llvm_unreachable("Unknown loc info!");
5123     case CCValAssign::Full: break;
5124     case CCValAssign::AExt:
5125       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5126       break;
5127     case CCValAssign::ZExt:
5128       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5129                         DAG.getValueType(VA.getValVT()));
5130       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5131       break;
5132     case CCValAssign::SExt:
5133       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5134                         DAG.getValueType(VA.getValVT()));
5135       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5136       break;
5137     }
5138 
5139     InVals.push_back(Val);
5140   }
5141 
5142   return Chain;
5143 }
5144 
5145 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5146                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5147   // PatchPoint calls are not indirect.
5148   if (isPatchPoint)
5149     return false;
5150 
5151   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5152     return false;
5153 
5154   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5155   // becuase the immediate function pointer points to a descriptor instead of
5156   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5157   // pointer immediate points to the global entry point, while the BLA would
5158   // need to jump to the local entry point (see rL211174).
5159   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5160       isBLACompatibleAddress(Callee, DAG))
5161     return false;
5162 
5163   return true;
5164 }
5165 
5166 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5167 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5168   return Subtarget.isAIXABI() ||
5169          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5170 }
5171 
5172 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5173                               const Function &Caller,
5174                               const SDValue &Callee,
5175                               const PPCSubtarget &Subtarget,
5176                               const TargetMachine &TM) {
5177   if (CFlags.IsTailCall)
5178     return PPCISD::TC_RETURN;
5179 
5180   // This is a call through a function pointer.
5181   if (CFlags.IsIndirect) {
5182     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5183     // indirect calls. The save of the caller's TOC pointer to the stack will be
5184     // inserted into the DAG as part of call lowering. The restore of the TOC
5185     // pointer is modeled by using a pseudo instruction for the call opcode that
5186     // represents the 2 instruction sequence of an indirect branch and link,
5187     // immediately followed by a load of the TOC pointer from the the stack save
5188     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5189     // as it is not saved or used.
5190     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5191                                                : PPCISD::BCTRL;
5192   }
5193 
5194   if (Subtarget.isUsingPCRelativeCalls()) {
5195     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5196     return PPCISD::CALL_NOTOC;
5197   }
5198 
5199   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5200   // immediately following the call instruction if the caller and callee may
5201   // have different TOC bases. At link time if the linker determines the calls
5202   // may not share a TOC base, the call is redirected to a trampoline inserted
5203   // by the linker. The trampoline will (among other things) save the callers
5204   // TOC pointer at an ABI designated offset in the linkage area and the linker
5205   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5206   // into gpr2.
5207   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5208       return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5209                                                     : PPCISD::CALL_NOP;
5210 
5211   return PPCISD::CALL;
5212 }
5213 
5214 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5215                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5216   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5217     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5218       return SDValue(Dest, 0);
5219 
5220   // Returns true if the callee is local, and false otherwise.
5221   auto isLocalCallee = [&]() {
5222     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5223     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5224     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5225 
5226     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5227            !dyn_cast_or_null<GlobalIFunc>(GV);
5228   };
5229 
5230   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5231   // a static relocation model causes some versions of GNU LD (2.17.50, at
5232   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5233   // built with secure-PLT.
5234   bool UsePlt =
5235       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5236       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5237 
5238   // On AIX, direct function calls reference the symbol for the function's
5239   // entry point, which is named by prepending a "." before the function's
5240   // C-linkage name.
5241   const auto getAIXFuncEntryPointSymbolSDNode =
5242       [&](StringRef FuncName, bool IsDeclaration,
5243           const XCOFF::StorageClass &SC) {
5244         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5245 
5246         MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5247             Context.getOrCreateSymbol(Twine(".") + Twine(FuncName)));
5248 
5249         if (IsDeclaration && !S->hasRepresentedCsectSet()) {
5250           // On AIX, an undefined symbol needs to be associated with a
5251           // MCSectionXCOFF to get the correct storage mapping class.
5252           // In this case, XCOFF::XMC_PR.
5253           MCSectionXCOFF *Sec = Context.getXCOFFSection(
5254               S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC,
5255               SectionKind::getMetadata());
5256           S->setRepresentedCsect(Sec);
5257         }
5258 
5259         MVT PtrVT =
5260             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5261         return DAG.getMCSymbol(S, PtrVT);
5262       };
5263 
5264   if (isFunctionGlobalAddress(Callee)) {
5265     const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5266     const GlobalValue *GV = G->getGlobal();
5267 
5268     if (!Subtarget.isAIXABI())
5269       return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5270                                         UsePlt ? PPCII::MO_PLT : 0);
5271 
5272     assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5273     const GlobalObject *GO = cast<GlobalObject>(GV);
5274     const XCOFF::StorageClass SC =
5275         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5276     return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(),
5277                                             SC);
5278   }
5279 
5280   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5281     const char *SymName = S->getSymbol();
5282     if (!Subtarget.isAIXABI())
5283       return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5284                                          UsePlt ? PPCII::MO_PLT : 0);
5285 
5286     // If there exists a user-declared function whose name is the same as the
5287     // ExternalSymbol's, then we pick up the user-declared version.
5288     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5289     if (const Function *F =
5290             dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) {
5291       const XCOFF::StorageClass SC =
5292           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F);
5293       return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(),
5294                                               SC);
5295     }
5296 
5297     return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT);
5298   }
5299 
5300   // No transformation needed.
5301   assert(Callee.getNode() && "What no callee?");
5302   return Callee;
5303 }
5304 
5305 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5306   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5307          "Expected a CALLSEQ_STARTSDNode.");
5308 
5309   // The last operand is the chain, except when the node has glue. If the node
5310   // has glue, then the last operand is the glue, and the chain is the second
5311   // last operand.
5312   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5313   if (LastValue.getValueType() != MVT::Glue)
5314     return LastValue;
5315 
5316   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5317 }
5318 
5319 // Creates the node that moves a functions address into the count register
5320 // to prepare for an indirect call instruction.
5321 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5322                                 SDValue &Glue, SDValue &Chain,
5323                                 const SDLoc &dl) {
5324   SDValue MTCTROps[] = {Chain, Callee, Glue};
5325   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5326   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5327                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5328   // The glue is the second value produced.
5329   Glue = Chain.getValue(1);
5330 }
5331 
5332 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5333                                           SDValue &Glue, SDValue &Chain,
5334                                           SDValue CallSeqStart,
5335                                           const CallBase *CB, const SDLoc &dl,
5336                                           bool hasNest,
5337                                           const PPCSubtarget &Subtarget) {
5338   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5339   // entry point, but to the function descriptor (the function entry point
5340   // address is part of the function descriptor though).
5341   // The function descriptor is a three doubleword structure with the
5342   // following fields: function entry point, TOC base address and
5343   // environment pointer.
5344   // Thus for a call through a function pointer, the following actions need
5345   // to be performed:
5346   //   1. Save the TOC of the caller in the TOC save area of its stack
5347   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5348   //   2. Load the address of the function entry point from the function
5349   //      descriptor.
5350   //   3. Load the TOC of the callee from the function descriptor into r2.
5351   //   4. Load the environment pointer from the function descriptor into
5352   //      r11.
5353   //   5. Branch to the function entry point address.
5354   //   6. On return of the callee, the TOC of the caller needs to be
5355   //      restored (this is done in FinishCall()).
5356   //
5357   // The loads are scheduled at the beginning of the call sequence, and the
5358   // register copies are flagged together to ensure that no other
5359   // operations can be scheduled in between. E.g. without flagging the
5360   // copies together, a TOC access in the caller could be scheduled between
5361   // the assignment of the callee TOC and the branch to the callee, which leads
5362   // to incorrect code.
5363 
5364   // Start by loading the function address from the descriptor.
5365   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5366   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5367                       ? (MachineMemOperand::MODereferenceable |
5368                          MachineMemOperand::MOInvariant)
5369                       : MachineMemOperand::MONone;
5370 
5371   MachinePointerInfo MPI(CB ? CB->getCalledValue() : nullptr);
5372 
5373   // Registers used in building the DAG.
5374   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5375   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5376 
5377   // Offsets of descriptor members.
5378   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5379   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5380 
5381   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5382   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5383 
5384   // One load for the functions entry point address.
5385   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5386                                     Alignment, MMOFlags);
5387 
5388   // One for loading the TOC anchor for the module that contains the called
5389   // function.
5390   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5391   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5392   SDValue TOCPtr =
5393       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5394                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5395 
5396   // One for loading the environment pointer.
5397   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5398   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5399   SDValue LoadEnvPtr =
5400       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5401                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5402 
5403 
5404   // Then copy the newly loaded TOC anchor to the TOC pointer.
5405   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5406   Chain = TOCVal.getValue(0);
5407   Glue = TOCVal.getValue(1);
5408 
5409   // If the function call has an explicit 'nest' parameter, it takes the
5410   // place of the environment pointer.
5411   assert((!hasNest || !Subtarget.isAIXABI()) &&
5412          "Nest parameter is not supported on AIX.");
5413   if (!hasNest) {
5414     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5415     Chain = EnvVal.getValue(0);
5416     Glue = EnvVal.getValue(1);
5417   }
5418 
5419   // The rest of the indirect call sequence is the same as the non-descriptor
5420   // DAG.
5421   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5422 }
5423 
5424 static void
5425 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5426                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5427                   SelectionDAG &DAG,
5428                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5429                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5430                   const PPCSubtarget &Subtarget) {
5431   const bool IsPPC64 = Subtarget.isPPC64();
5432   // MVT for a general purpose register.
5433   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5434 
5435   // First operand is always the chain.
5436   Ops.push_back(Chain);
5437 
5438   // If it's a direct call pass the callee as the second operand.
5439   if (!CFlags.IsIndirect)
5440     Ops.push_back(Callee);
5441   else {
5442     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5443 
5444     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5445     // on the stack (this would have been done in `LowerCall_64SVR4` or
5446     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5447     // represents both the indirect branch and a load that restores the TOC
5448     // pointer from the linkage area. The operand for the TOC restore is an add
5449     // of the TOC save offset to the stack pointer. This must be the second
5450     // operand: after the chain input but before any other variadic arguments.
5451     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5452     // saved or used.
5453     if (isTOCSaveRestoreRequired(Subtarget)) {
5454       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5455 
5456       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5457       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5458       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5459       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5460       Ops.push_back(AddTOC);
5461     }
5462 
5463     // Add the register used for the environment pointer.
5464     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5465       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5466                                     RegVT));
5467 
5468 
5469     // Add CTR register as callee so a bctr can be emitted later.
5470     if (CFlags.IsTailCall)
5471       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5472   }
5473 
5474   // If this is a tail call add stack pointer delta.
5475   if (CFlags.IsTailCall)
5476     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5477 
5478   // Add argument registers to the end of the list so that they are known live
5479   // into the call.
5480   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5481     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5482                                   RegsToPass[i].second.getValueType()));
5483 
5484   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5485   // no way to mark dependencies as implicit here.
5486   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5487   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5488        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5489     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5490 
5491   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5492   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5493     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5494 
5495   // Add a register mask operand representing the call-preserved registers.
5496   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5497   const uint32_t *Mask =
5498       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5499   assert(Mask && "Missing call preserved mask for calling convention");
5500   Ops.push_back(DAG.getRegisterMask(Mask));
5501 
5502   // If the glue is valid, it is the last operand.
5503   if (Glue.getNode())
5504     Ops.push_back(Glue);
5505 }
5506 
5507 SDValue PPCTargetLowering::FinishCall(
5508     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5509     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5510     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5511     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5512     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5513 
5514   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5515       Subtarget.isAIXABI())
5516     setUsesTOCBasePtr(DAG);
5517 
5518   unsigned CallOpc =
5519       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5520                     Subtarget, DAG.getTarget());
5521 
5522   if (!CFlags.IsIndirect)
5523     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5524   else if (Subtarget.usesFunctionDescriptors())
5525     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5526                                   dl, CFlags.HasNest, Subtarget);
5527   else
5528     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5529 
5530   // Build the operand list for the call instruction.
5531   SmallVector<SDValue, 8> Ops;
5532   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5533                     SPDiff, Subtarget);
5534 
5535   // Emit tail call.
5536   if (CFlags.IsTailCall) {
5537     assert(((Callee.getOpcode() == ISD::Register &&
5538              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5539             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5540             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5541             isa<ConstantSDNode>(Callee)) &&
5542            "Expecting a global address, external symbol, absolute value or "
5543            "register");
5544     assert(CallOpc == PPCISD::TC_RETURN &&
5545            "Unexpected call opcode for a tail call.");
5546     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5547     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5548   }
5549 
5550   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5551   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5552   Glue = Chain.getValue(1);
5553 
5554   // When performing tail call optimization the callee pops its arguments off
5555   // the stack. Account for this here so these bytes can be pushed back on in
5556   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5557   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5558                          getTargetMachine().Options.GuaranteedTailCallOpt)
5559                             ? NumBytes
5560                             : 0;
5561 
5562   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5563                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5564                              Glue, dl);
5565   Glue = Chain.getValue(1);
5566 
5567   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5568                          DAG, InVals);
5569 }
5570 
5571 SDValue
5572 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5573                              SmallVectorImpl<SDValue> &InVals) const {
5574   SelectionDAG &DAG                     = CLI.DAG;
5575   SDLoc &dl                             = CLI.DL;
5576   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5577   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5578   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5579   SDValue Chain                         = CLI.Chain;
5580   SDValue Callee                        = CLI.Callee;
5581   bool &isTailCall                      = CLI.IsTailCall;
5582   CallingConv::ID CallConv              = CLI.CallConv;
5583   bool isVarArg                         = CLI.IsVarArg;
5584   bool isPatchPoint                     = CLI.IsPatchPoint;
5585   const CallBase *CB                    = CLI.CB;
5586 
5587   if (isTailCall) {
5588     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5589       isTailCall = false;
5590     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5591       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5592           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5593     else
5594       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5595                                                      Ins, DAG);
5596     if (isTailCall) {
5597       ++NumTailCalls;
5598       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5599         ++NumSiblingCalls;
5600 
5601       assert(isa<GlobalAddressSDNode>(Callee) &&
5602              "Callee should be an llvm::Function object.");
5603       LLVM_DEBUG(
5604           const GlobalValue *GV =
5605               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5606           const unsigned Width =
5607               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5608           dbgs() << "TCO caller: "
5609                  << left_justify(DAG.getMachineFunction().getName(), Width)
5610                  << ", callee linkage: " << GV->getVisibility() << ", "
5611                  << GV->getLinkage() << "\n");
5612     }
5613   }
5614 
5615   if (!isTailCall && CB && CB->isMustTailCall())
5616     report_fatal_error("failed to perform tail call elimination on a call "
5617                        "site marked musttail");
5618 
5619   // When long calls (i.e. indirect calls) are always used, calls are always
5620   // made via function pointer. If we have a function name, first translate it
5621   // into a pointer.
5622   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5623       !isTailCall)
5624     Callee = LowerGlobalAddress(Callee, DAG);
5625 
5626   CallFlags CFlags(
5627       CallConv, isTailCall, isVarArg, isPatchPoint,
5628       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5629       // hasNest
5630       Subtarget.is64BitELFABI() &&
5631           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }));
5632 
5633   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5634     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5635                             InVals, CB);
5636 
5637   if (Subtarget.isSVR4ABI())
5638     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5639                             InVals, CB);
5640 
5641   if (Subtarget.isAIXABI())
5642     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5643                          InVals, CB);
5644 
5645   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5646                           InVals, CB);
5647 }
5648 
5649 SDValue PPCTargetLowering::LowerCall_32SVR4(
5650     SDValue Chain, SDValue Callee, CallFlags CFlags,
5651     const SmallVectorImpl<ISD::OutputArg> &Outs,
5652     const SmallVectorImpl<SDValue> &OutVals,
5653     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5654     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5655     const CallBase *CB) const {
5656   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5657   // of the 32-bit SVR4 ABI stack frame layout.
5658 
5659   const CallingConv::ID CallConv = CFlags.CallConv;
5660   const bool IsVarArg = CFlags.IsVarArg;
5661   const bool IsTailCall = CFlags.IsTailCall;
5662 
5663   assert((CallConv == CallingConv::C ||
5664           CallConv == CallingConv::Cold ||
5665           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5666 
5667   unsigned PtrByteSize = 4;
5668 
5669   MachineFunction &MF = DAG.getMachineFunction();
5670 
5671   // Mark this function as potentially containing a function that contains a
5672   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5673   // and restoring the callers stack pointer in this functions epilog. This is
5674   // done because by tail calling the called function might overwrite the value
5675   // in this function's (MF) stack pointer stack slot 0(SP).
5676   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5677       CallConv == CallingConv::Fast)
5678     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5679 
5680   // Count how many bytes are to be pushed on the stack, including the linkage
5681   // area, parameter list area and the part of the local variable space which
5682   // contains copies of aggregates which are passed by value.
5683 
5684   // Assign locations to all of the outgoing arguments.
5685   SmallVector<CCValAssign, 16> ArgLocs;
5686   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5687 
5688   // Reserve space for the linkage area on the stack.
5689   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5690                        PtrByteSize);
5691   if (useSoftFloat())
5692     CCInfo.PreAnalyzeCallOperands(Outs);
5693 
5694   if (IsVarArg) {
5695     // Handle fixed and variable vector arguments differently.
5696     // Fixed vector arguments go into registers as long as registers are
5697     // available. Variable vector arguments always go into memory.
5698     unsigned NumArgs = Outs.size();
5699 
5700     for (unsigned i = 0; i != NumArgs; ++i) {
5701       MVT ArgVT = Outs[i].VT;
5702       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5703       bool Result;
5704 
5705       if (Outs[i].IsFixed) {
5706         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5707                                CCInfo);
5708       } else {
5709         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5710                                       ArgFlags, CCInfo);
5711       }
5712 
5713       if (Result) {
5714 #ifndef NDEBUG
5715         errs() << "Call operand #" << i << " has unhandled type "
5716              << EVT(ArgVT).getEVTString() << "\n";
5717 #endif
5718         llvm_unreachable(nullptr);
5719       }
5720     }
5721   } else {
5722     // All arguments are treated the same.
5723     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5724   }
5725   CCInfo.clearWasPPCF128();
5726 
5727   // Assign locations to all of the outgoing aggregate by value arguments.
5728   SmallVector<CCValAssign, 16> ByValArgLocs;
5729   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5730 
5731   // Reserve stack space for the allocations in CCInfo.
5732   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5733 
5734   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5735 
5736   // Size of the linkage area, parameter list area and the part of the local
5737   // space variable where copies of aggregates which are passed by value are
5738   // stored.
5739   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5740 
5741   // Calculate by how many bytes the stack has to be adjusted in case of tail
5742   // call optimization.
5743   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5744 
5745   // Adjust the stack pointer for the new arguments...
5746   // These operations are automatically eliminated by the prolog/epilog pass
5747   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5748   SDValue CallSeqStart = Chain;
5749 
5750   // Load the return address and frame pointer so it can be moved somewhere else
5751   // later.
5752   SDValue LROp, FPOp;
5753   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5754 
5755   // Set up a copy of the stack pointer for use loading and storing any
5756   // arguments that may not fit in the registers available for argument
5757   // passing.
5758   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5759 
5760   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5761   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5762   SmallVector<SDValue, 8> MemOpChains;
5763 
5764   bool seenFloatArg = false;
5765   // Walk the register/memloc assignments, inserting copies/loads.
5766   // i - Tracks the index into the list of registers allocated for the call
5767   // RealArgIdx - Tracks the index into the list of actual function arguments
5768   // j - Tracks the index into the list of byval arguments
5769   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5770        i != e;
5771        ++i, ++RealArgIdx) {
5772     CCValAssign &VA = ArgLocs[i];
5773     SDValue Arg = OutVals[RealArgIdx];
5774     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5775 
5776     if (Flags.isByVal()) {
5777       // Argument is an aggregate which is passed by value, thus we need to
5778       // create a copy of it in the local variable space of the current stack
5779       // frame (which is the stack frame of the caller) and pass the address of
5780       // this copy to the callee.
5781       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5782       CCValAssign &ByValVA = ByValArgLocs[j++];
5783       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5784 
5785       // Memory reserved in the local variable space of the callers stack frame.
5786       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5787 
5788       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5789       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5790                            StackPtr, PtrOff);
5791 
5792       // Create a copy of the argument in the local area of the current
5793       // stack frame.
5794       SDValue MemcpyCall =
5795         CreateCopyOfByValArgument(Arg, PtrOff,
5796                                   CallSeqStart.getNode()->getOperand(0),
5797                                   Flags, DAG, dl);
5798 
5799       // This must go outside the CALLSEQ_START..END.
5800       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5801                                                      SDLoc(MemcpyCall));
5802       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5803                              NewCallSeqStart.getNode());
5804       Chain = CallSeqStart = NewCallSeqStart;
5805 
5806       // Pass the address of the aggregate copy on the stack either in a
5807       // physical register or in the parameter list area of the current stack
5808       // frame to the callee.
5809       Arg = PtrOff;
5810     }
5811 
5812     // When useCRBits() is true, there can be i1 arguments.
5813     // It is because getRegisterType(MVT::i1) => MVT::i1,
5814     // and for other integer types getRegisterType() => MVT::i32.
5815     // Extend i1 and ensure callee will get i32.
5816     if (Arg.getValueType() == MVT::i1)
5817       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5818                         dl, MVT::i32, Arg);
5819 
5820     if (VA.isRegLoc()) {
5821       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5822       // Put argument in a physical register.
5823       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5824         bool IsLE = Subtarget.isLittleEndian();
5825         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5826                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5827         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5828         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5829                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5830         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5831                              SVal.getValue(0)));
5832       } else
5833         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5834     } else {
5835       // Put argument in the parameter list area of the current stack frame.
5836       assert(VA.isMemLoc());
5837       unsigned LocMemOffset = VA.getLocMemOffset();
5838 
5839       if (!IsTailCall) {
5840         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5841         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5842                              StackPtr, PtrOff);
5843 
5844         MemOpChains.push_back(
5845             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5846       } else {
5847         // Calculate and remember argument location.
5848         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5849                                  TailCallArguments);
5850       }
5851     }
5852   }
5853 
5854   if (!MemOpChains.empty())
5855     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5856 
5857   // Build a sequence of copy-to-reg nodes chained together with token chain
5858   // and flag operands which copy the outgoing args into the appropriate regs.
5859   SDValue InFlag;
5860   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5861     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5862                              RegsToPass[i].second, InFlag);
5863     InFlag = Chain.getValue(1);
5864   }
5865 
5866   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5867   // registers.
5868   if (IsVarArg) {
5869     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5870     SDValue Ops[] = { Chain, InFlag };
5871 
5872     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5873                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5874 
5875     InFlag = Chain.getValue(1);
5876   }
5877 
5878   if (IsTailCall)
5879     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5880                     TailCallArguments);
5881 
5882   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5883                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5884 }
5885 
5886 // Copy an argument into memory, being careful to do this outside the
5887 // call sequence for the call to which the argument belongs.
5888 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5889     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5890     SelectionDAG &DAG, const SDLoc &dl) const {
5891   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5892                         CallSeqStart.getNode()->getOperand(0),
5893                         Flags, DAG, dl);
5894   // The MEMCPY must go outside the CALLSEQ_START..END.
5895   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5896   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5897                                                  SDLoc(MemcpyCall));
5898   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5899                          NewCallSeqStart.getNode());
5900   return NewCallSeqStart;
5901 }
5902 
5903 SDValue PPCTargetLowering::LowerCall_64SVR4(
5904     SDValue Chain, SDValue Callee, CallFlags CFlags,
5905     const SmallVectorImpl<ISD::OutputArg> &Outs,
5906     const SmallVectorImpl<SDValue> &OutVals,
5907     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5908     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5909     const CallBase *CB) const {
5910   bool isELFv2ABI = Subtarget.isELFv2ABI();
5911   bool isLittleEndian = Subtarget.isLittleEndian();
5912   unsigned NumOps = Outs.size();
5913   bool IsSibCall = false;
5914   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5915 
5916   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5917   unsigned PtrByteSize = 8;
5918 
5919   MachineFunction &MF = DAG.getMachineFunction();
5920 
5921   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5922     IsSibCall = true;
5923 
5924   // Mark this function as potentially containing a function that contains a
5925   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5926   // and restoring the callers stack pointer in this functions epilog. This is
5927   // done because by tail calling the called function might overwrite the value
5928   // in this function's (MF) stack pointer stack slot 0(SP).
5929   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5930     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5931 
5932   assert(!(IsFastCall && CFlags.IsVarArg) &&
5933          "fastcc not supported on varargs functions");
5934 
5935   // Count how many bytes are to be pushed on the stack, including the linkage
5936   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5937   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5938   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5939   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5940   unsigned NumBytes = LinkageSize;
5941   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5942   unsigned &QFPR_idx = FPR_idx;
5943 
5944   static const MCPhysReg GPR[] = {
5945     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5946     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5947   };
5948   static const MCPhysReg VR[] = {
5949     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5950     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5951   };
5952 
5953   const unsigned NumGPRs = array_lengthof(GPR);
5954   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5955   const unsigned NumVRs  = array_lengthof(VR);
5956   const unsigned NumQFPRs = NumFPRs;
5957 
5958   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5959   // can be passed to the callee in registers.
5960   // For the fast calling convention, there is another check below.
5961   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5962   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5963   if (!HasParameterArea) {
5964     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5965     unsigned AvailableFPRs = NumFPRs;
5966     unsigned AvailableVRs = NumVRs;
5967     unsigned NumBytesTmp = NumBytes;
5968     for (unsigned i = 0; i != NumOps; ++i) {
5969       if (Outs[i].Flags.isNest()) continue;
5970       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5971                                 PtrByteSize, LinkageSize, ParamAreaSize,
5972                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5973                                 Subtarget.hasQPX()))
5974         HasParameterArea = true;
5975     }
5976   }
5977 
5978   // When using the fast calling convention, we don't provide backing for
5979   // arguments that will be in registers.
5980   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5981 
5982   // Avoid allocating parameter area for fastcc functions if all the arguments
5983   // can be passed in the registers.
5984   if (IsFastCall)
5985     HasParameterArea = false;
5986 
5987   // Add up all the space actually used.
5988   for (unsigned i = 0; i != NumOps; ++i) {
5989     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5990     EVT ArgVT = Outs[i].VT;
5991     EVT OrigVT = Outs[i].ArgVT;
5992 
5993     if (Flags.isNest())
5994       continue;
5995 
5996     if (IsFastCall) {
5997       if (Flags.isByVal()) {
5998         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5999         if (NumGPRsUsed > NumGPRs)
6000           HasParameterArea = true;
6001       } else {
6002         switch (ArgVT.getSimpleVT().SimpleTy) {
6003         default: llvm_unreachable("Unexpected ValueType for argument!");
6004         case MVT::i1:
6005         case MVT::i32:
6006         case MVT::i64:
6007           if (++NumGPRsUsed <= NumGPRs)
6008             continue;
6009           break;
6010         case MVT::v4i32:
6011         case MVT::v8i16:
6012         case MVT::v16i8:
6013         case MVT::v2f64:
6014         case MVT::v2i64:
6015         case MVT::v1i128:
6016         case MVT::f128:
6017           if (++NumVRsUsed <= NumVRs)
6018             continue;
6019           break;
6020         case MVT::v4f32:
6021           // When using QPX, this is handled like a FP register, otherwise, it
6022           // is an Altivec register.
6023           if (Subtarget.hasQPX()) {
6024             if (++NumFPRsUsed <= NumFPRs)
6025               continue;
6026           } else {
6027             if (++NumVRsUsed <= NumVRs)
6028               continue;
6029           }
6030           break;
6031         case MVT::f32:
6032         case MVT::f64:
6033         case MVT::v4f64: // QPX
6034         case MVT::v4i1:  // QPX
6035           if (++NumFPRsUsed <= NumFPRs)
6036             continue;
6037           break;
6038         }
6039         HasParameterArea = true;
6040       }
6041     }
6042 
6043     /* Respect alignment of argument on the stack.  */
6044     auto Alignement =
6045         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6046     NumBytes = alignTo(NumBytes, Alignement);
6047 
6048     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6049     if (Flags.isInConsecutiveRegsLast())
6050       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6051   }
6052 
6053   unsigned NumBytesActuallyUsed = NumBytes;
6054 
6055   // In the old ELFv1 ABI,
6056   // the prolog code of the callee may store up to 8 GPR argument registers to
6057   // the stack, allowing va_start to index over them in memory if its varargs.
6058   // Because we cannot tell if this is needed on the caller side, we have to
6059   // conservatively assume that it is needed.  As such, make sure we have at
6060   // least enough stack space for the caller to store the 8 GPRs.
6061   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6062   // really requires memory operands, e.g. a vararg function.
6063   if (HasParameterArea)
6064     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6065   else
6066     NumBytes = LinkageSize;
6067 
6068   // Tail call needs the stack to be aligned.
6069   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6070     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6071 
6072   int SPDiff = 0;
6073 
6074   // Calculate by how many bytes the stack has to be adjusted in case of tail
6075   // call optimization.
6076   if (!IsSibCall)
6077     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6078 
6079   // To protect arguments on the stack from being clobbered in a tail call,
6080   // force all the loads to happen before doing any other lowering.
6081   if (CFlags.IsTailCall)
6082     Chain = DAG.getStackArgumentTokenFactor(Chain);
6083 
6084   // Adjust the stack pointer for the new arguments...
6085   // These operations are automatically eliminated by the prolog/epilog pass
6086   if (!IsSibCall)
6087     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6088   SDValue CallSeqStart = Chain;
6089 
6090   // Load the return address and frame pointer so it can be move somewhere else
6091   // later.
6092   SDValue LROp, FPOp;
6093   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6094 
6095   // Set up a copy of the stack pointer for use loading and storing any
6096   // arguments that may not fit in the registers available for argument
6097   // passing.
6098   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6099 
6100   // Figure out which arguments are going to go in registers, and which in
6101   // memory.  Also, if this is a vararg function, floating point operations
6102   // must be stored to our stack, and loaded into integer regs as well, if
6103   // any integer regs are available for argument passing.
6104   unsigned ArgOffset = LinkageSize;
6105 
6106   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6107   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6108 
6109   SmallVector<SDValue, 8> MemOpChains;
6110   for (unsigned i = 0; i != NumOps; ++i) {
6111     SDValue Arg = OutVals[i];
6112     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6113     EVT ArgVT = Outs[i].VT;
6114     EVT OrigVT = Outs[i].ArgVT;
6115 
6116     // PtrOff will be used to store the current argument to the stack if a
6117     // register cannot be found for it.
6118     SDValue PtrOff;
6119 
6120     // We re-align the argument offset for each argument, except when using the
6121     // fast calling convention, when we need to make sure we do that only when
6122     // we'll actually use a stack slot.
6123     auto ComputePtrOff = [&]() {
6124       /* Respect alignment of argument on the stack.  */
6125       auto Alignment =
6126           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6127       ArgOffset = alignTo(ArgOffset, Alignment);
6128 
6129       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6130 
6131       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6132     };
6133 
6134     if (!IsFastCall) {
6135       ComputePtrOff();
6136 
6137       /* Compute GPR index associated with argument offset.  */
6138       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6139       GPR_idx = std::min(GPR_idx, NumGPRs);
6140     }
6141 
6142     // Promote integers to 64-bit values.
6143     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6144       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6145       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6146       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6147     }
6148 
6149     // FIXME memcpy is used way more than necessary.  Correctness first.
6150     // Note: "by value" is code for passing a structure by value, not
6151     // basic types.
6152     if (Flags.isByVal()) {
6153       // Note: Size includes alignment padding, so
6154       //   struct x { short a; char b; }
6155       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6156       // These are the proper values we need for right-justifying the
6157       // aggregate in a parameter register.
6158       unsigned Size = Flags.getByValSize();
6159 
6160       // An empty aggregate parameter takes up no storage and no
6161       // registers.
6162       if (Size == 0)
6163         continue;
6164 
6165       if (IsFastCall)
6166         ComputePtrOff();
6167 
6168       // All aggregates smaller than 8 bytes must be passed right-justified.
6169       if (Size==1 || Size==2 || Size==4) {
6170         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6171         if (GPR_idx != NumGPRs) {
6172           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6173                                         MachinePointerInfo(), VT);
6174           MemOpChains.push_back(Load.getValue(1));
6175           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6176 
6177           ArgOffset += PtrByteSize;
6178           continue;
6179         }
6180       }
6181 
6182       if (GPR_idx == NumGPRs && Size < 8) {
6183         SDValue AddPtr = PtrOff;
6184         if (!isLittleEndian) {
6185           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6186                                           PtrOff.getValueType());
6187           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6188         }
6189         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6190                                                           CallSeqStart,
6191                                                           Flags, DAG, dl);
6192         ArgOffset += PtrByteSize;
6193         continue;
6194       }
6195       // Copy entire object into memory.  There are cases where gcc-generated
6196       // code assumes it is there, even if it could be put entirely into
6197       // registers.  (This is not what the doc says.)
6198 
6199       // FIXME: The above statement is likely due to a misunderstanding of the
6200       // documents.  All arguments must be copied into the parameter area BY
6201       // THE CALLEE in the event that the callee takes the address of any
6202       // formal argument.  That has not yet been implemented.  However, it is
6203       // reasonable to use the stack area as a staging area for the register
6204       // load.
6205 
6206       // Skip this for small aggregates, as we will use the same slot for a
6207       // right-justified copy, below.
6208       if (Size >= 8)
6209         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6210                                                           CallSeqStart,
6211                                                           Flags, DAG, dl);
6212 
6213       // When a register is available, pass a small aggregate right-justified.
6214       if (Size < 8 && GPR_idx != NumGPRs) {
6215         // The easiest way to get this right-justified in a register
6216         // is to copy the structure into the rightmost portion of a
6217         // local variable slot, then load the whole slot into the
6218         // register.
6219         // FIXME: The memcpy seems to produce pretty awful code for
6220         // small aggregates, particularly for packed ones.
6221         // FIXME: It would be preferable to use the slot in the
6222         // parameter save area instead of a new local variable.
6223         SDValue AddPtr = PtrOff;
6224         if (!isLittleEndian) {
6225           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6226           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6227         }
6228         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6229                                                           CallSeqStart,
6230                                                           Flags, DAG, dl);
6231 
6232         // Load the slot into the register.
6233         SDValue Load =
6234             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6235         MemOpChains.push_back(Load.getValue(1));
6236         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6237 
6238         // Done with this argument.
6239         ArgOffset += PtrByteSize;
6240         continue;
6241       }
6242 
6243       // For aggregates larger than PtrByteSize, copy the pieces of the
6244       // object that fit into registers from the parameter save area.
6245       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6246         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6247         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6248         if (GPR_idx != NumGPRs) {
6249           SDValue Load =
6250               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6251           MemOpChains.push_back(Load.getValue(1));
6252           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6253           ArgOffset += PtrByteSize;
6254         } else {
6255           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6256           break;
6257         }
6258       }
6259       continue;
6260     }
6261 
6262     switch (Arg.getSimpleValueType().SimpleTy) {
6263     default: llvm_unreachable("Unexpected ValueType for argument!");
6264     case MVT::i1:
6265     case MVT::i32:
6266     case MVT::i64:
6267       if (Flags.isNest()) {
6268         // The 'nest' parameter, if any, is passed in R11.
6269         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6270         break;
6271       }
6272 
6273       // These can be scalar arguments or elements of an integer array type
6274       // passed directly.  Clang may use those instead of "byval" aggregate
6275       // types to avoid forcing arguments to memory unnecessarily.
6276       if (GPR_idx != NumGPRs) {
6277         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6278       } else {
6279         if (IsFastCall)
6280           ComputePtrOff();
6281 
6282         assert(HasParameterArea &&
6283                "Parameter area must exist to pass an argument in memory.");
6284         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6285                          true, CFlags.IsTailCall, false, MemOpChains,
6286                          TailCallArguments, dl);
6287         if (IsFastCall)
6288           ArgOffset += PtrByteSize;
6289       }
6290       if (!IsFastCall)
6291         ArgOffset += PtrByteSize;
6292       break;
6293     case MVT::f32:
6294     case MVT::f64: {
6295       // These can be scalar arguments or elements of a float array type
6296       // passed directly.  The latter are used to implement ELFv2 homogenous
6297       // float aggregates.
6298 
6299       // Named arguments go into FPRs first, and once they overflow, the
6300       // remaining arguments go into GPRs and then the parameter save area.
6301       // Unnamed arguments for vararg functions always go to GPRs and
6302       // then the parameter save area.  For now, put all arguments to vararg
6303       // routines always in both locations (FPR *and* GPR or stack slot).
6304       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6305       bool NeededLoad = false;
6306 
6307       // First load the argument into the next available FPR.
6308       if (FPR_idx != NumFPRs)
6309         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6310 
6311       // Next, load the argument into GPR or stack slot if needed.
6312       if (!NeedGPROrStack)
6313         ;
6314       else if (GPR_idx != NumGPRs && !IsFastCall) {
6315         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6316         // once we support fp <-> gpr moves.
6317 
6318         // In the non-vararg case, this can only ever happen in the
6319         // presence of f32 array types, since otherwise we never run
6320         // out of FPRs before running out of GPRs.
6321         SDValue ArgVal;
6322 
6323         // Double values are always passed in a single GPR.
6324         if (Arg.getValueType() != MVT::f32) {
6325           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6326 
6327         // Non-array float values are extended and passed in a GPR.
6328         } else if (!Flags.isInConsecutiveRegs()) {
6329           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6330           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6331 
6332         // If we have an array of floats, we collect every odd element
6333         // together with its predecessor into one GPR.
6334         } else if (ArgOffset % PtrByteSize != 0) {
6335           SDValue Lo, Hi;
6336           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6337           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6338           if (!isLittleEndian)
6339             std::swap(Lo, Hi);
6340           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6341 
6342         // The final element, if even, goes into the first half of a GPR.
6343         } else if (Flags.isInConsecutiveRegsLast()) {
6344           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6345           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6346           if (!isLittleEndian)
6347             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6348                                  DAG.getConstant(32, dl, MVT::i32));
6349 
6350         // Non-final even elements are skipped; they will be handled
6351         // together the with subsequent argument on the next go-around.
6352         } else
6353           ArgVal = SDValue();
6354 
6355         if (ArgVal.getNode())
6356           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6357       } else {
6358         if (IsFastCall)
6359           ComputePtrOff();
6360 
6361         // Single-precision floating-point values are mapped to the
6362         // second (rightmost) word of the stack doubleword.
6363         if (Arg.getValueType() == MVT::f32 &&
6364             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6365           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6366           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6367         }
6368 
6369         assert(HasParameterArea &&
6370                "Parameter area must exist to pass an argument in memory.");
6371         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6372                          true, CFlags.IsTailCall, false, MemOpChains,
6373                          TailCallArguments, dl);
6374 
6375         NeededLoad = true;
6376       }
6377       // When passing an array of floats, the array occupies consecutive
6378       // space in the argument area; only round up to the next doubleword
6379       // at the end of the array.  Otherwise, each float takes 8 bytes.
6380       if (!IsFastCall || NeededLoad) {
6381         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6382                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6383         if (Flags.isInConsecutiveRegsLast())
6384           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6385       }
6386       break;
6387     }
6388     case MVT::v4f32:
6389     case MVT::v4i32:
6390     case MVT::v8i16:
6391     case MVT::v16i8:
6392     case MVT::v2f64:
6393     case MVT::v2i64:
6394     case MVT::v1i128:
6395     case MVT::f128:
6396       if (!Subtarget.hasQPX()) {
6397       // These can be scalar arguments or elements of a vector array type
6398       // passed directly.  The latter are used to implement ELFv2 homogenous
6399       // vector aggregates.
6400 
6401       // For a varargs call, named arguments go into VRs or on the stack as
6402       // usual; unnamed arguments always go to the stack or the corresponding
6403       // GPRs when within range.  For now, we always put the value in both
6404       // locations (or even all three).
6405       if (CFlags.IsVarArg) {
6406         assert(HasParameterArea &&
6407                "Parameter area must exist if we have a varargs call.");
6408         // We could elide this store in the case where the object fits
6409         // entirely in R registers.  Maybe later.
6410         SDValue Store =
6411             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6412         MemOpChains.push_back(Store);
6413         if (VR_idx != NumVRs) {
6414           SDValue Load =
6415               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6416           MemOpChains.push_back(Load.getValue(1));
6417           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6418         }
6419         ArgOffset += 16;
6420         for (unsigned i=0; i<16; i+=PtrByteSize) {
6421           if (GPR_idx == NumGPRs)
6422             break;
6423           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6424                                    DAG.getConstant(i, dl, PtrVT));
6425           SDValue Load =
6426               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6427           MemOpChains.push_back(Load.getValue(1));
6428           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6429         }
6430         break;
6431       }
6432 
6433       // Non-varargs Altivec params go into VRs or on the stack.
6434       if (VR_idx != NumVRs) {
6435         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6436       } else {
6437         if (IsFastCall)
6438           ComputePtrOff();
6439 
6440         assert(HasParameterArea &&
6441                "Parameter area must exist to pass an argument in memory.");
6442         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6443                          true, CFlags.IsTailCall, true, MemOpChains,
6444                          TailCallArguments, dl);
6445         if (IsFastCall)
6446           ArgOffset += 16;
6447       }
6448 
6449       if (!IsFastCall)
6450         ArgOffset += 16;
6451       break;
6452       } // not QPX
6453 
6454       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6455              "Invalid QPX parameter type");
6456 
6457       LLVM_FALLTHROUGH;
6458     case MVT::v4f64:
6459     case MVT::v4i1: {
6460       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6461       if (CFlags.IsVarArg) {
6462         assert(HasParameterArea &&
6463                "Parameter area must exist if we have a varargs call.");
6464         // We could elide this store in the case where the object fits
6465         // entirely in R registers.  Maybe later.
6466         SDValue Store =
6467             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6468         MemOpChains.push_back(Store);
6469         if (QFPR_idx != NumQFPRs) {
6470           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6471                                      PtrOff, MachinePointerInfo());
6472           MemOpChains.push_back(Load.getValue(1));
6473           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6474         }
6475         ArgOffset += (IsF32 ? 16 : 32);
6476         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6477           if (GPR_idx == NumGPRs)
6478             break;
6479           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6480                                    DAG.getConstant(i, dl, PtrVT));
6481           SDValue Load =
6482               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6483           MemOpChains.push_back(Load.getValue(1));
6484           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6485         }
6486         break;
6487       }
6488 
6489       // Non-varargs QPX params go into registers or on the stack.
6490       if (QFPR_idx != NumQFPRs) {
6491         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6492       } else {
6493         if (IsFastCall)
6494           ComputePtrOff();
6495 
6496         assert(HasParameterArea &&
6497                "Parameter area must exist to pass an argument in memory.");
6498         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6499                          true, CFlags.IsTailCall, true, MemOpChains,
6500                          TailCallArguments, dl);
6501         if (IsFastCall)
6502           ArgOffset += (IsF32 ? 16 : 32);
6503       }
6504 
6505       if (!IsFastCall)
6506         ArgOffset += (IsF32 ? 16 : 32);
6507       break;
6508       }
6509     }
6510   }
6511 
6512   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6513          "mismatch in size of parameter area");
6514   (void)NumBytesActuallyUsed;
6515 
6516   if (!MemOpChains.empty())
6517     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6518 
6519   // Check if this is an indirect call (MTCTR/BCTRL).
6520   // See prepareDescriptorIndirectCall and buildCallOperands for more
6521   // information about calls through function pointers in the 64-bit SVR4 ABI.
6522   if (CFlags.IsIndirect) {
6523     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6524     // caller in the TOC save area.
6525     if (isTOCSaveRestoreRequired(Subtarget)) {
6526       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6527       // Load r2 into a virtual register and store it to the TOC save area.
6528       setUsesTOCBasePtr(DAG);
6529       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6530       // TOC save area offset.
6531       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6532       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6533       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6534       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6535                            MachinePointerInfo::getStack(
6536                                DAG.getMachineFunction(), TOCSaveOffset));
6537     }
6538     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6539     // This does not mean the MTCTR instruction must use R12; it's easier
6540     // to model this as an extra parameter, so do that.
6541     if (isELFv2ABI && !CFlags.IsPatchPoint)
6542       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6543   }
6544 
6545   // Build a sequence of copy-to-reg nodes chained together with token chain
6546   // and flag operands which copy the outgoing args into the appropriate regs.
6547   SDValue InFlag;
6548   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6549     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6550                              RegsToPass[i].second, InFlag);
6551     InFlag = Chain.getValue(1);
6552   }
6553 
6554   if (CFlags.IsTailCall && !IsSibCall)
6555     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6556                     TailCallArguments);
6557 
6558   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6559                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6560 }
6561 
6562 SDValue PPCTargetLowering::LowerCall_Darwin(
6563     SDValue Chain, SDValue Callee, CallFlags CFlags,
6564     const SmallVectorImpl<ISD::OutputArg> &Outs,
6565     const SmallVectorImpl<SDValue> &OutVals,
6566     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6567     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6568     const CallBase *CB) const {
6569   unsigned NumOps = Outs.size();
6570 
6571   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6572   bool isPPC64 = PtrVT == MVT::i64;
6573   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6574 
6575   MachineFunction &MF = DAG.getMachineFunction();
6576 
6577   // Mark this function as potentially containing a function that contains a
6578   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6579   // and restoring the callers stack pointer in this functions epilog. This is
6580   // done because by tail calling the called function might overwrite the value
6581   // in this function's (MF) stack pointer stack slot 0(SP).
6582   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6583       CFlags.CallConv == CallingConv::Fast)
6584     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6585 
6586   // Count how many bytes are to be pushed on the stack, including the linkage
6587   // area, and parameter passing area.  We start with 24/48 bytes, which is
6588   // prereserved space for [SP][CR][LR][3 x unused].
6589   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6590   unsigned NumBytes = LinkageSize;
6591 
6592   // Add up all the space actually used.
6593   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6594   // they all go in registers, but we must reserve stack space for them for
6595   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6596   // assigned stack space in order, with padding so Altivec parameters are
6597   // 16-byte aligned.
6598   unsigned nAltivecParamsAtEnd = 0;
6599   for (unsigned i = 0; i != NumOps; ++i) {
6600     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6601     EVT ArgVT = Outs[i].VT;
6602     // Varargs Altivec parameters are padded to a 16 byte boundary.
6603     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6604         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6605         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6606       if (!CFlags.IsVarArg && !isPPC64) {
6607         // Non-varargs Altivec parameters go after all the non-Altivec
6608         // parameters; handle those later so we know how much padding we need.
6609         nAltivecParamsAtEnd++;
6610         continue;
6611       }
6612       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6613       NumBytes = ((NumBytes+15)/16)*16;
6614     }
6615     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6616   }
6617 
6618   // Allow for Altivec parameters at the end, if needed.
6619   if (nAltivecParamsAtEnd) {
6620     NumBytes = ((NumBytes+15)/16)*16;
6621     NumBytes += 16*nAltivecParamsAtEnd;
6622   }
6623 
6624   // The prolog code of the callee may store up to 8 GPR argument registers to
6625   // the stack, allowing va_start to index over them in memory if its varargs.
6626   // Because we cannot tell if this is needed on the caller side, we have to
6627   // conservatively assume that it is needed.  As such, make sure we have at
6628   // least enough stack space for the caller to store the 8 GPRs.
6629   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6630 
6631   // Tail call needs the stack to be aligned.
6632   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6633       CFlags.CallConv == CallingConv::Fast)
6634     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6635 
6636   // Calculate by how many bytes the stack has to be adjusted in case of tail
6637   // call optimization.
6638   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6639 
6640   // To protect arguments on the stack from being clobbered in a tail call,
6641   // force all the loads to happen before doing any other lowering.
6642   if (CFlags.IsTailCall)
6643     Chain = DAG.getStackArgumentTokenFactor(Chain);
6644 
6645   // Adjust the stack pointer for the new arguments...
6646   // These operations are automatically eliminated by the prolog/epilog pass
6647   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6648   SDValue CallSeqStart = Chain;
6649 
6650   // Load the return address and frame pointer so it can be move somewhere else
6651   // later.
6652   SDValue LROp, FPOp;
6653   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6654 
6655   // Set up a copy of the stack pointer for use loading and storing any
6656   // arguments that may not fit in the registers available for argument
6657   // passing.
6658   SDValue StackPtr;
6659   if (isPPC64)
6660     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6661   else
6662     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6663 
6664   // Figure out which arguments are going to go in registers, and which in
6665   // memory.  Also, if this is a vararg function, floating point operations
6666   // must be stored to our stack, and loaded into integer regs as well, if
6667   // any integer regs are available for argument passing.
6668   unsigned ArgOffset = LinkageSize;
6669   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6670 
6671   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6672     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6673     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6674   };
6675   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6676     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6677     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6678   };
6679   static const MCPhysReg VR[] = {
6680     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6681     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6682   };
6683   const unsigned NumGPRs = array_lengthof(GPR_32);
6684   const unsigned NumFPRs = 13;
6685   const unsigned NumVRs  = array_lengthof(VR);
6686 
6687   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6688 
6689   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6690   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6691 
6692   SmallVector<SDValue, 8> MemOpChains;
6693   for (unsigned i = 0; i != NumOps; ++i) {
6694     SDValue Arg = OutVals[i];
6695     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6696 
6697     // PtrOff will be used to store the current argument to the stack if a
6698     // register cannot be found for it.
6699     SDValue PtrOff;
6700 
6701     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6702 
6703     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6704 
6705     // On PPC64, promote integers to 64-bit values.
6706     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6707       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6708       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6709       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6710     }
6711 
6712     // FIXME memcpy is used way more than necessary.  Correctness first.
6713     // Note: "by value" is code for passing a structure by value, not
6714     // basic types.
6715     if (Flags.isByVal()) {
6716       unsigned Size = Flags.getByValSize();
6717       // Very small objects are passed right-justified.  Everything else is
6718       // passed left-justified.
6719       if (Size==1 || Size==2) {
6720         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6721         if (GPR_idx != NumGPRs) {
6722           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6723                                         MachinePointerInfo(), VT);
6724           MemOpChains.push_back(Load.getValue(1));
6725           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6726 
6727           ArgOffset += PtrByteSize;
6728         } else {
6729           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6730                                           PtrOff.getValueType());
6731           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6732           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6733                                                             CallSeqStart,
6734                                                             Flags, DAG, dl);
6735           ArgOffset += PtrByteSize;
6736         }
6737         continue;
6738       }
6739       // Copy entire object into memory.  There are cases where gcc-generated
6740       // code assumes it is there, even if it could be put entirely into
6741       // registers.  (This is not what the doc says.)
6742       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6743                                                         CallSeqStart,
6744                                                         Flags, DAG, dl);
6745 
6746       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6747       // copy the pieces of the object that fit into registers from the
6748       // parameter save area.
6749       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6750         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6751         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6752         if (GPR_idx != NumGPRs) {
6753           SDValue Load =
6754               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6755           MemOpChains.push_back(Load.getValue(1));
6756           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6757           ArgOffset += PtrByteSize;
6758         } else {
6759           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6760           break;
6761         }
6762       }
6763       continue;
6764     }
6765 
6766     switch (Arg.getSimpleValueType().SimpleTy) {
6767     default: llvm_unreachable("Unexpected ValueType for argument!");
6768     case MVT::i1:
6769     case MVT::i32:
6770     case MVT::i64:
6771       if (GPR_idx != NumGPRs) {
6772         if (Arg.getValueType() == MVT::i1)
6773           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6774 
6775         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6776       } else {
6777         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6778                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6779                          TailCallArguments, dl);
6780       }
6781       ArgOffset += PtrByteSize;
6782       break;
6783     case MVT::f32:
6784     case MVT::f64:
6785       if (FPR_idx != NumFPRs) {
6786         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6787 
6788         if (CFlags.IsVarArg) {
6789           SDValue Store =
6790               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6791           MemOpChains.push_back(Store);
6792 
6793           // Float varargs are always shadowed in available integer registers
6794           if (GPR_idx != NumGPRs) {
6795             SDValue Load =
6796                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6797             MemOpChains.push_back(Load.getValue(1));
6798             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6799           }
6800           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6801             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6802             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6803             SDValue Load =
6804                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6805             MemOpChains.push_back(Load.getValue(1));
6806             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6807           }
6808         } else {
6809           // If we have any FPRs remaining, we may also have GPRs remaining.
6810           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6811           // GPRs.
6812           if (GPR_idx != NumGPRs)
6813             ++GPR_idx;
6814           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6815               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6816             ++GPR_idx;
6817         }
6818       } else
6819         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6820                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6821                          TailCallArguments, dl);
6822       if (isPPC64)
6823         ArgOffset += 8;
6824       else
6825         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6826       break;
6827     case MVT::v4f32:
6828     case MVT::v4i32:
6829     case MVT::v8i16:
6830     case MVT::v16i8:
6831       if (CFlags.IsVarArg) {
6832         // These go aligned on the stack, or in the corresponding R registers
6833         // when within range.  The Darwin PPC ABI doc claims they also go in
6834         // V registers; in fact gcc does this only for arguments that are
6835         // prototyped, not for those that match the ...  We do it for all
6836         // arguments, seems to work.
6837         while (ArgOffset % 16 !=0) {
6838           ArgOffset += PtrByteSize;
6839           if (GPR_idx != NumGPRs)
6840             GPR_idx++;
6841         }
6842         // We could elide this store in the case where the object fits
6843         // entirely in R registers.  Maybe later.
6844         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6845                              DAG.getConstant(ArgOffset, dl, PtrVT));
6846         SDValue Store =
6847             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6848         MemOpChains.push_back(Store);
6849         if (VR_idx != NumVRs) {
6850           SDValue Load =
6851               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6852           MemOpChains.push_back(Load.getValue(1));
6853           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6854         }
6855         ArgOffset += 16;
6856         for (unsigned i=0; i<16; i+=PtrByteSize) {
6857           if (GPR_idx == NumGPRs)
6858             break;
6859           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6860                                    DAG.getConstant(i, dl, PtrVT));
6861           SDValue Load =
6862               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6863           MemOpChains.push_back(Load.getValue(1));
6864           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6865         }
6866         break;
6867       }
6868 
6869       // Non-varargs Altivec params generally go in registers, but have
6870       // stack space allocated at the end.
6871       if (VR_idx != NumVRs) {
6872         // Doesn't have GPR space allocated.
6873         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6874       } else if (nAltivecParamsAtEnd==0) {
6875         // We are emitting Altivec params in order.
6876         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6877                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6878                          TailCallArguments, dl);
6879         ArgOffset += 16;
6880       }
6881       break;
6882     }
6883   }
6884   // If all Altivec parameters fit in registers, as they usually do,
6885   // they get stack space following the non-Altivec parameters.  We
6886   // don't track this here because nobody below needs it.
6887   // If there are more Altivec parameters than fit in registers emit
6888   // the stores here.
6889   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6890     unsigned j = 0;
6891     // Offset is aligned; skip 1st 12 params which go in V registers.
6892     ArgOffset = ((ArgOffset+15)/16)*16;
6893     ArgOffset += 12*16;
6894     for (unsigned i = 0; i != NumOps; ++i) {
6895       SDValue Arg = OutVals[i];
6896       EVT ArgType = Outs[i].VT;
6897       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6898           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6899         if (++j > NumVRs) {
6900           SDValue PtrOff;
6901           // We are emitting Altivec params in order.
6902           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6903                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6904                            TailCallArguments, dl);
6905           ArgOffset += 16;
6906         }
6907       }
6908     }
6909   }
6910 
6911   if (!MemOpChains.empty())
6912     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6913 
6914   // On Darwin, R12 must contain the address of an indirect callee.  This does
6915   // not mean the MTCTR instruction must use R12; it's easier to model this as
6916   // an extra parameter, so do that.
6917   if (CFlags.IsIndirect) {
6918     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6919     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6920                                                    PPC::R12), Callee));
6921   }
6922 
6923   // Build a sequence of copy-to-reg nodes chained together with token chain
6924   // and flag operands which copy the outgoing args into the appropriate regs.
6925   SDValue InFlag;
6926   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6927     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6928                              RegsToPass[i].second, InFlag);
6929     InFlag = Chain.getValue(1);
6930   }
6931 
6932   if (CFlags.IsTailCall)
6933     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6934                     TailCallArguments);
6935 
6936   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6937                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6938 }
6939 
6940 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6941                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6942                    CCState &State) {
6943 
6944   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6945       State.getMachineFunction().getSubtarget());
6946   const bool IsPPC64 = Subtarget.isPPC64();
6947   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6948   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6949 
6950   assert((!ValVT.isInteger() ||
6951           (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) &&
6952          "Integer argument exceeds register size: should have been legalized");
6953 
6954   if (ValVT == MVT::f128)
6955     report_fatal_error("f128 is unimplemented on AIX.");
6956 
6957   if (ArgFlags.isNest())
6958     report_fatal_error("Nest arguments are unimplemented.");
6959 
6960   if (ValVT.isVector() || LocVT.isVector())
6961     report_fatal_error("Vector arguments are unimplemented on AIX.");
6962 
6963   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6964                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6965                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6966   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6967                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6968                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6969 
6970   if (ArgFlags.isByVal()) {
6971     if (ArgFlags.getNonZeroByValAlign() > PtrByteSize)
6972       report_fatal_error("Pass-by-value arguments with alignment greater than "
6973                          "register width are not supported.");
6974 
6975     const unsigned ByValSize = ArgFlags.getByValSize();
6976 
6977     // An empty aggregate parameter takes up no storage and no registers,
6978     // but needs a MemLoc for a stack slot for the formal arguments side.
6979     if (ByValSize == 0) {
6980       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6981                                        State.getNextStackOffset(), RegVT,
6982                                        LocInfo));
6983       return false;
6984     }
6985 
6986     const unsigned StackSize = alignTo(ByValSize, PtrByteSize);
6987     unsigned Offset = State.AllocateStack(StackSize, PtrByteSize);
6988     for (const unsigned E = Offset + StackSize; Offset < E;
6989          Offset += PtrByteSize) {
6990       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6991         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6992       else {
6993         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6994                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6995                                          LocInfo));
6996         break;
6997       }
6998     }
6999     return false;
7000   }
7001 
7002   // Arguments always reserve parameter save area.
7003   switch (ValVT.SimpleTy) {
7004   default:
7005     report_fatal_error("Unhandled value type for argument.");
7006   case MVT::i64:
7007     // i64 arguments should have been split to i32 for PPC32.
7008     assert(IsPPC64 && "PPC32 should have split i64 values.");
7009     LLVM_FALLTHROUGH;
7010   case MVT::i1:
7011   case MVT::i32: {
7012     const unsigned Offset = State.AllocateStack(PtrByteSize, PtrByteSize);
7013     // AIX integer arguments are always passed in register width.
7014     if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
7015       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
7016                                   : CCValAssign::LocInfo::ZExt;
7017     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
7018       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7019     else
7020       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
7021 
7022     return false;
7023   }
7024   case MVT::f32:
7025   case MVT::f64: {
7026     // Parameter save area (PSA) is reserved even if the float passes in fpr.
7027     const unsigned StoreSize = LocVT.getStoreSize();
7028     // Floats are always 4-byte aligned in the PSA on AIX.
7029     // This includes f64 in 64-bit mode for ABI compatibility.
7030     const unsigned Offset = State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4);
7031     unsigned FReg = State.AllocateReg(FPR);
7032     if (FReg)
7033       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
7034 
7035     // Reserve and initialize GPRs or initialize the PSA as required.
7036     for (unsigned I = 0; I < StoreSize; I += PtrByteSize) {
7037       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
7038         assert(FReg && "An FPR should be available when a GPR is reserved.");
7039         if (State.isVarArg()) {
7040           // Successfully reserved GPRs are only initialized for vararg calls.
7041           // Custom handling is required for:
7042           //   f64 in PPC32 needs to be split into 2 GPRs.
7043           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
7044           State.addLoc(
7045               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7046         }
7047       } else {
7048         // If there are insufficient GPRs, the PSA needs to be initialized.
7049         // Initialization occurs even if an FPR was initialized for
7050         // compatibility with the AIX XL compiler. The full memory for the
7051         // argument will be initialized even if a prior word is saved in GPR.
7052         // A custom memLoc is used when the argument also passes in FPR so
7053         // that the callee handling can skip over it easily.
7054         State.addLoc(
7055             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
7056                                              LocInfo)
7057                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7058         break;
7059       }
7060     }
7061 
7062     return false;
7063   }
7064   }
7065   return true;
7066 }
7067 
7068 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
7069                                                     bool IsPPC64) {
7070   assert((IsPPC64 || SVT != MVT::i64) &&
7071          "i64 should have been split for 32-bit codegen.");
7072 
7073   switch (SVT) {
7074   default:
7075     report_fatal_error("Unexpected value type for formal argument");
7076   case MVT::i1:
7077   case MVT::i32:
7078   case MVT::i64:
7079     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7080   case MVT::f32:
7081     return &PPC::F4RCRegClass;
7082   case MVT::f64:
7083     return &PPC::F8RCRegClass;
7084   }
7085 }
7086 
7087 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
7088                                         SelectionDAG &DAG, SDValue ArgValue,
7089                                         MVT LocVT, const SDLoc &dl) {
7090   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7091   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
7092 
7093   if (Flags.isSExt())
7094     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7095                            DAG.getValueType(ValVT));
7096   else if (Flags.isZExt())
7097     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7098                            DAG.getValueType(ValVT));
7099 
7100   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7101 }
7102 
7103 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7104   const unsigned LASize = FL->getLinkageSize();
7105 
7106   if (PPC::GPRCRegClass.contains(Reg)) {
7107     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7108            "Reg must be a valid argument register!");
7109     return LASize + 4 * (Reg - PPC::R3);
7110   }
7111 
7112   if (PPC::G8RCRegClass.contains(Reg)) {
7113     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7114            "Reg must be a valid argument register!");
7115     return LASize + 8 * (Reg - PPC::X3);
7116   }
7117 
7118   llvm_unreachable("Only general purpose registers expected.");
7119 }
7120 
7121 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7122     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7123     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7124     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7125 
7126   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7127           CallConv == CallingConv::Fast) &&
7128          "Unexpected calling convention!");
7129 
7130   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7131     report_fatal_error("Tail call support is unimplemented on AIX.");
7132 
7133   if (useSoftFloat())
7134     report_fatal_error("Soft float support is unimplemented on AIX.");
7135 
7136   const PPCSubtarget &Subtarget =
7137       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7138   if (Subtarget.hasQPX())
7139     report_fatal_error("QPX support is not supported on AIX.");
7140 
7141   const bool IsPPC64 = Subtarget.isPPC64();
7142   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7143 
7144   // Assign locations to all of the incoming arguments.
7145   SmallVector<CCValAssign, 16> ArgLocs;
7146   MachineFunction &MF = DAG.getMachineFunction();
7147   MachineFrameInfo &MFI = MF.getFrameInfo();
7148   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7149 
7150   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7151   // Reserve space for the linkage area on the stack.
7152   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7153   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
7154   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7155 
7156   SmallVector<SDValue, 8> MemOps;
7157 
7158   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7159     CCValAssign &VA = ArgLocs[I++];
7160     MVT LocVT = VA.getLocVT();
7161     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7162 
7163     // For compatibility with the AIX XL compiler, the float args in the
7164     // parameter save area are initialized even if the argument is available
7165     // in register.  The caller is required to initialize both the register
7166     // and memory, however, the callee can choose to expect it in either.
7167     // The memloc is dismissed here because the argument is retrieved from
7168     // the register.
7169     if (VA.isMemLoc() && VA.needsCustom())
7170       continue;
7171 
7172     if (Flags.isByVal() && VA.isMemLoc()) {
7173       const unsigned Size =
7174           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7175                   PtrByteSize);
7176       const int FI = MF.getFrameInfo().CreateFixedObject(
7177           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7178           /* IsAliased */ true);
7179       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7180       InVals.push_back(FIN);
7181 
7182       continue;
7183     }
7184 
7185     if (Flags.isByVal()) {
7186       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7187 
7188       const MCPhysReg ArgReg = VA.getLocReg();
7189       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7190 
7191       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7192         report_fatal_error("Over aligned byvals not supported yet.");
7193 
7194       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7195       const int FI = MF.getFrameInfo().CreateFixedObject(
7196           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7197           /* IsAliased */ true);
7198       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7199       InVals.push_back(FIN);
7200 
7201       // Add live ins for all the RegLocs for the same ByVal.
7202       const TargetRegisterClass *RegClass =
7203           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7204 
7205       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7206                                                unsigned Offset) {
7207         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7208         // Since the callers side has left justified the aggregate in the
7209         // register, we can simply store the entire register into the stack
7210         // slot.
7211         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7212         // The store to the fixedstack object is needed becuase accessing a
7213         // field of the ByVal will use a gep and load. Ideally we will optimize
7214         // to extracting the value from the register directly, and elide the
7215         // stores when the arguments address is not taken, but that will need to
7216         // be future work.
7217         SDValue Store =
7218             DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom,
7219                          DAG.getObjectPtrOffset(dl, FIN, Offset),
7220                          MachinePointerInfo::getFixedStack(MF, FI, Offset));
7221 
7222         MemOps.push_back(Store);
7223       };
7224 
7225       unsigned Offset = 0;
7226       HandleRegLoc(VA.getLocReg(), Offset);
7227       Offset += PtrByteSize;
7228       for (; Offset != StackSize; Offset += PtrByteSize) {
7229         assert(I != End &&
7230                "Expecting enough RegLocs to copy entire ByVal arg.");
7231 
7232         if (!ArgLocs[I].isRegLoc())
7233           report_fatal_error("Passing ByVals split between registers and stack "
7234                              "not yet implemented.");
7235 
7236         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7237                "Expecting more RegLocs for ByVal argument.");
7238 
7239         const CCValAssign RL = ArgLocs[I++];
7240         HandleRegLoc(RL.getLocReg(), Offset);
7241       }
7242       continue;
7243     }
7244 
7245     EVT ValVT = VA.getValVT();
7246     if (VA.isRegLoc() && !VA.needsCustom()) {
7247       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7248       unsigned VReg =
7249           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7250       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7251       if (ValVT.isScalarInteger() &&
7252           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7253         ArgValue =
7254             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7255       }
7256       InVals.push_back(ArgValue);
7257       continue;
7258     }
7259     if (VA.isMemLoc()) {
7260       const unsigned LocSize = LocVT.getStoreSize();
7261       const unsigned ValSize = ValVT.getStoreSize();
7262       assert((ValSize <= LocSize) &&
7263              "Object size is larger than size of MemLoc");
7264       int CurArgOffset = VA.getLocMemOffset();
7265       // Objects are right-justified because AIX is big-endian.
7266       if (LocSize > ValSize)
7267         CurArgOffset += LocSize - ValSize;
7268       // Potential tail calls could cause overwriting of argument stack slots.
7269       const bool IsImmutable =
7270           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7271             (CallConv == CallingConv::Fast));
7272       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7273       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7274       SDValue ArgValue =
7275           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7276       InVals.push_back(ArgValue);
7277       continue;
7278     }
7279   }
7280 
7281   // On AIX a minimum of 8 words is saved to the parameter save area.
7282   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7283   // Area that is at least reserved in the caller of this function.
7284   unsigned CallerReservedArea =
7285       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7286 
7287   // Set the size that is at least reserved in caller of this function. Tail
7288   // call optimized function's reserved stack space needs to be aligned so
7289   // that taking the difference between two stack areas will result in an
7290   // aligned stack.
7291   CallerReservedArea =
7292       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7293   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7294   FuncInfo->setMinReservedArea(CallerReservedArea);
7295 
7296   if (isVarArg) {
7297     FuncInfo->setVarArgsFrameIndex(
7298         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7299     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7300 
7301     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7302                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7303 
7304     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7305                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7306     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7307 
7308     // The fixed integer arguments of a variadic function are stored to the
7309     // VarArgsFrameIndex on the stack so that they may be loaded by
7310     // dereferencing the result of va_next.
7311     for (unsigned GPRIndex =
7312              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7313          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7314 
7315       const unsigned VReg =
7316           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7317                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7318 
7319       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7320       SDValue Store =
7321           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7322       MemOps.push_back(Store);
7323       // Increment the address for the next argument to store.
7324       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7325       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7326     }
7327   }
7328 
7329   if (!MemOps.empty())
7330     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7331 
7332   return Chain;
7333 }
7334 
7335 SDValue PPCTargetLowering::LowerCall_AIX(
7336     SDValue Chain, SDValue Callee, CallFlags CFlags,
7337     const SmallVectorImpl<ISD::OutputArg> &Outs,
7338     const SmallVectorImpl<SDValue> &OutVals,
7339     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7340     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7341     const CallBase *CB) const {
7342 
7343   assert((CFlags.CallConv == CallingConv::C ||
7344           CFlags.CallConv == CallingConv::Cold ||
7345           CFlags.CallConv == CallingConv::Fast) &&
7346          "Unexpected calling convention!");
7347 
7348   if (CFlags.IsPatchPoint)
7349     report_fatal_error("This call type is unimplemented on AIX.");
7350 
7351   const PPCSubtarget& Subtarget =
7352       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7353   if (Subtarget.hasQPX())
7354     report_fatal_error("QPX is not supported on AIX.");
7355   if (Subtarget.hasAltivec())
7356     report_fatal_error("Altivec support is unimplemented on AIX.");
7357 
7358   MachineFunction &MF = DAG.getMachineFunction();
7359   SmallVector<CCValAssign, 16> ArgLocs;
7360   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7361                  *DAG.getContext());
7362 
7363   // Reserve space for the linkage save area (LSA) on the stack.
7364   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7365   //   [SP][CR][LR][2 x reserved][TOC].
7366   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7367   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7368   const bool IsPPC64 = Subtarget.isPPC64();
7369   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7370   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7371   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
7372   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7373 
7374   // The prolog code of the callee may store up to 8 GPR argument registers to
7375   // the stack, allowing va_start to index over them in memory if the callee
7376   // is variadic.
7377   // Because we cannot tell if this is needed on the caller side, we have to
7378   // conservatively assume that it is needed.  As such, make sure we have at
7379   // least enough stack space for the caller to store the 8 GPRs.
7380   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7381   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7382                                      CCInfo.getNextStackOffset());
7383 
7384   // Adjust the stack pointer for the new arguments...
7385   // These operations are automatically eliminated by the prolog/epilog pass.
7386   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7387   SDValue CallSeqStart = Chain;
7388 
7389   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7390   SmallVector<SDValue, 8> MemOpChains;
7391 
7392   // Set up a copy of the stack pointer for loading and storing any
7393   // arguments that may not fit in the registers available for argument
7394   // passing.
7395   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7396                                    : DAG.getRegister(PPC::R1, MVT::i32);
7397 
7398   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7399     const unsigned ValNo = ArgLocs[I].getValNo();
7400     SDValue Arg = OutVals[ValNo];
7401     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7402 
7403     if (Flags.isByVal()) {
7404       const unsigned ByValSize = Flags.getByValSize();
7405 
7406       // Nothing to do for zero-sized ByVals on the caller side.
7407       if (!ByValSize) {
7408         ++I;
7409         continue;
7410       }
7411 
7412       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7413         return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain,
7414                               (LoadOffset != 0)
7415                                   ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7416                                   : Arg,
7417                               MachinePointerInfo(), VT);
7418       };
7419 
7420       unsigned LoadOffset = 0;
7421 
7422       // Initialize registers, which are fully occupied by the by-val argument.
7423       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7424         SDValue Load = GetLoad(PtrVT, LoadOffset);
7425         MemOpChains.push_back(Load.getValue(1));
7426         LoadOffset += PtrByteSize;
7427         const CCValAssign &ByValVA = ArgLocs[I++];
7428         assert(ByValVA.getValNo() == ValNo &&
7429                "Unexpected location for pass-by-value argument.");
7430         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7431       }
7432 
7433       if (LoadOffset == ByValSize)
7434         continue;
7435 
7436       // There must be one more loc to handle the remainder.
7437       assert(ArgLocs[I].getValNo() == ValNo &&
7438              "Expected additional location for by-value argument.");
7439 
7440       if (ArgLocs[I].isMemLoc()) {
7441         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7442         const CCValAssign &ByValVA = ArgLocs[I++];
7443         ISD::ArgFlagsTy MemcpyFlags = Flags;
7444         // Only memcpy the bytes that don't pass in register.
7445         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7446         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7447             (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7448                               : Arg,
7449             DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()),
7450             CallSeqStart, MemcpyFlags, DAG, dl);
7451         continue;
7452       }
7453 
7454       // Initialize the final register residue.
7455       // Any residue that occupies the final by-val arg register must be
7456       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7457       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7458       // 2 and 1 byte loads.
7459       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7460       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7461              "Unexpected register residue for by-value argument.");
7462       SDValue ResidueVal;
7463       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7464         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7465         const MVT VT =
7466             N == 1 ? MVT::i8
7467                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7468         SDValue Load = GetLoad(VT, LoadOffset);
7469         MemOpChains.push_back(Load.getValue(1));
7470         LoadOffset += N;
7471         Bytes += N;
7472 
7473         // By-val arguments are passed left-justfied in register.
7474         // Every load here needs to be shifted, otherwise a full register load
7475         // should have been used.
7476         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7477                "Unexpected load emitted during handling of pass-by-value "
7478                "argument.");
7479         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7480         EVT ShiftAmountTy =
7481             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7482         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7483         SDValue ShiftedLoad =
7484             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7485         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7486                                               ShiftedLoad)
7487                                 : ShiftedLoad;
7488       }
7489 
7490       const CCValAssign &ByValVA = ArgLocs[I++];
7491       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7492       continue;
7493     }
7494 
7495     CCValAssign &VA = ArgLocs[I++];
7496     const MVT LocVT = VA.getLocVT();
7497     const MVT ValVT = VA.getValVT();
7498 
7499     switch (VA.getLocInfo()) {
7500     default:
7501       report_fatal_error("Unexpected argument extension type.");
7502     case CCValAssign::Full:
7503       break;
7504     case CCValAssign::ZExt:
7505       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7506       break;
7507     case CCValAssign::SExt:
7508       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7509       break;
7510     }
7511 
7512     if (VA.isRegLoc() && !VA.needsCustom()) {
7513       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7514       continue;
7515     }
7516 
7517     if (VA.isMemLoc()) {
7518       SDValue PtrOff =
7519           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7520       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7521       MemOpChains.push_back(
7522           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7523 
7524       continue;
7525     }
7526 
7527     // Custom handling is used for GPR initializations for vararg float
7528     // arguments.
7529     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7530            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7531            "Unexpected register handling for calling convention.");
7532 
7533     SDValue ArgAsInt =
7534         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7535 
7536     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7537       // f32 in 32-bit GPR
7538       // f64 in 64-bit GPR
7539       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7540     else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits())
7541       // f32 in 64-bit GPR.
7542       RegsToPass.push_back(std::make_pair(
7543           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7544     else {
7545       // f64 in two 32-bit GPRs
7546       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7547       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7548              "Unexpected custom register for argument!");
7549       CCValAssign &GPR1 = VA;
7550       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7551                                      DAG.getConstant(32, dl, MVT::i8));
7552       RegsToPass.push_back(std::make_pair(
7553           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7554 
7555       if (I != E) {
7556         // If only 1 GPR was available, there will only be one custom GPR and
7557         // the argument will also pass in memory.
7558         CCValAssign &PeekArg = ArgLocs[I];
7559         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7560           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7561           CCValAssign &GPR2 = ArgLocs[I++];
7562           RegsToPass.push_back(std::make_pair(
7563               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7564         }
7565       }
7566     }
7567   }
7568 
7569   if (!MemOpChains.empty())
7570     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7571 
7572   // For indirect calls, we need to save the TOC base to the stack for
7573   // restoration after the call.
7574   if (CFlags.IsIndirect) {
7575     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7576     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7577     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7578     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7579     const unsigned TOCSaveOffset =
7580         Subtarget.getFrameLowering()->getTOCSaveOffset();
7581 
7582     setUsesTOCBasePtr(DAG);
7583     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7584     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7585     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7586     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7587     Chain = DAG.getStore(
7588         Val.getValue(1), dl, Val, AddPtr,
7589         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7590   }
7591 
7592   // Build a sequence of copy-to-reg nodes chained together with token chain
7593   // and flag operands which copy the outgoing args into the appropriate regs.
7594   SDValue InFlag;
7595   for (auto Reg : RegsToPass) {
7596     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7597     InFlag = Chain.getValue(1);
7598   }
7599 
7600   const int SPDiff = 0;
7601   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7602                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7603 }
7604 
7605 bool
7606 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7607                                   MachineFunction &MF, bool isVarArg,
7608                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7609                                   LLVMContext &Context) const {
7610   SmallVector<CCValAssign, 16> RVLocs;
7611   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7612   return CCInfo.CheckReturn(
7613       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7614                 ? RetCC_PPC_Cold
7615                 : RetCC_PPC);
7616 }
7617 
7618 SDValue
7619 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7620                                bool isVarArg,
7621                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7622                                const SmallVectorImpl<SDValue> &OutVals,
7623                                const SDLoc &dl, SelectionDAG &DAG) const {
7624   SmallVector<CCValAssign, 16> RVLocs;
7625   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7626                  *DAG.getContext());
7627   CCInfo.AnalyzeReturn(Outs,
7628                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7629                            ? RetCC_PPC_Cold
7630                            : RetCC_PPC);
7631 
7632   SDValue Flag;
7633   SmallVector<SDValue, 4> RetOps(1, Chain);
7634 
7635   // Copy the result values into the output registers.
7636   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7637     CCValAssign &VA = RVLocs[i];
7638     assert(VA.isRegLoc() && "Can only return in registers!");
7639 
7640     SDValue Arg = OutVals[RealResIdx];
7641 
7642     switch (VA.getLocInfo()) {
7643     default: llvm_unreachable("Unknown loc info!");
7644     case CCValAssign::Full: break;
7645     case CCValAssign::AExt:
7646       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7647       break;
7648     case CCValAssign::ZExt:
7649       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7650       break;
7651     case CCValAssign::SExt:
7652       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7653       break;
7654     }
7655     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7656       bool isLittleEndian = Subtarget.isLittleEndian();
7657       // Legalize ret f64 -> ret 2 x i32.
7658       SDValue SVal =
7659           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7660                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7661       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7662       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7663       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7664                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7665       Flag = Chain.getValue(1);
7666       VA = RVLocs[++i]; // skip ahead to next loc
7667       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7668     } else
7669       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7670     Flag = Chain.getValue(1);
7671     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7672   }
7673 
7674   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
7675   const MCPhysReg *I =
7676     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
7677   if (I) {
7678     for (; *I; ++I) {
7679 
7680       if (PPC::G8RCRegClass.contains(*I))
7681         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
7682       else if (PPC::F8RCRegClass.contains(*I))
7683         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
7684       else if (PPC::CRRCRegClass.contains(*I))
7685         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
7686       else if (PPC::VRRCRegClass.contains(*I))
7687         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
7688       else
7689         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
7690     }
7691   }
7692 
7693   RetOps[0] = Chain;  // Update chain.
7694 
7695   // Add the flag if we have it.
7696   if (Flag.getNode())
7697     RetOps.push_back(Flag);
7698 
7699   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7700 }
7701 
7702 SDValue
7703 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7704                                                 SelectionDAG &DAG) const {
7705   SDLoc dl(Op);
7706 
7707   // Get the correct type for integers.
7708   EVT IntVT = Op.getValueType();
7709 
7710   // Get the inputs.
7711   SDValue Chain = Op.getOperand(0);
7712   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7713   // Build a DYNAREAOFFSET node.
7714   SDValue Ops[2] = {Chain, FPSIdx};
7715   SDVTList VTs = DAG.getVTList(IntVT);
7716   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7717 }
7718 
7719 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7720                                              SelectionDAG &DAG) const {
7721   // When we pop the dynamic allocation we need to restore the SP link.
7722   SDLoc dl(Op);
7723 
7724   // Get the correct type for pointers.
7725   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7726 
7727   // Construct the stack pointer operand.
7728   bool isPPC64 = Subtarget.isPPC64();
7729   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7730   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7731 
7732   // Get the operands for the STACKRESTORE.
7733   SDValue Chain = Op.getOperand(0);
7734   SDValue SaveSP = Op.getOperand(1);
7735 
7736   // Load the old link SP.
7737   SDValue LoadLinkSP =
7738       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7739 
7740   // Restore the stack pointer.
7741   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7742 
7743   // Store the old link SP.
7744   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7745 }
7746 
7747 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7748   MachineFunction &MF = DAG.getMachineFunction();
7749   bool isPPC64 = Subtarget.isPPC64();
7750   EVT PtrVT = getPointerTy(MF.getDataLayout());
7751 
7752   // Get current frame pointer save index.  The users of this index will be
7753   // primarily DYNALLOC instructions.
7754   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7755   int RASI = FI->getReturnAddrSaveIndex();
7756 
7757   // If the frame pointer save index hasn't been defined yet.
7758   if (!RASI) {
7759     // Find out what the fix offset of the frame pointer save area.
7760     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7761     // Allocate the frame index for frame pointer save area.
7762     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7763     // Save the result.
7764     FI->setReturnAddrSaveIndex(RASI);
7765   }
7766   return DAG.getFrameIndex(RASI, PtrVT);
7767 }
7768 
7769 SDValue
7770 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7771   MachineFunction &MF = DAG.getMachineFunction();
7772   bool isPPC64 = Subtarget.isPPC64();
7773   EVT PtrVT = getPointerTy(MF.getDataLayout());
7774 
7775   // Get current frame pointer save index.  The users of this index will be
7776   // primarily DYNALLOC instructions.
7777   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7778   int FPSI = FI->getFramePointerSaveIndex();
7779 
7780   // If the frame pointer save index hasn't been defined yet.
7781   if (!FPSI) {
7782     // Find out what the fix offset of the frame pointer save area.
7783     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7784     // Allocate the frame index for frame pointer save area.
7785     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7786     // Save the result.
7787     FI->setFramePointerSaveIndex(FPSI);
7788   }
7789   return DAG.getFrameIndex(FPSI, PtrVT);
7790 }
7791 
7792 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7793                                                    SelectionDAG &DAG) const {
7794   // Get the inputs.
7795   SDValue Chain = Op.getOperand(0);
7796   SDValue Size  = Op.getOperand(1);
7797   SDLoc dl(Op);
7798 
7799   // Get the correct type for pointers.
7800   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7801   // Negate the size.
7802   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7803                                 DAG.getConstant(0, dl, PtrVT), Size);
7804   // Construct a node for the frame pointer save index.
7805   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7806   // Build a DYNALLOC node.
7807   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7808   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7809   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7810 }
7811 
7812 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7813                                                      SelectionDAG &DAG) const {
7814   MachineFunction &MF = DAG.getMachineFunction();
7815 
7816   bool isPPC64 = Subtarget.isPPC64();
7817   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7818 
7819   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7820   return DAG.getFrameIndex(FI, PtrVT);
7821 }
7822 
7823 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7824                                                SelectionDAG &DAG) const {
7825   SDLoc DL(Op);
7826   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7827                      DAG.getVTList(MVT::i32, MVT::Other),
7828                      Op.getOperand(0), Op.getOperand(1));
7829 }
7830 
7831 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7832                                                 SelectionDAG &DAG) const {
7833   SDLoc DL(Op);
7834   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7835                      Op.getOperand(0), Op.getOperand(1));
7836 }
7837 
7838 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7839   if (Op.getValueType().isVector())
7840     return LowerVectorLoad(Op, DAG);
7841 
7842   assert(Op.getValueType() == MVT::i1 &&
7843          "Custom lowering only for i1 loads");
7844 
7845   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7846 
7847   SDLoc dl(Op);
7848   LoadSDNode *LD = cast<LoadSDNode>(Op);
7849 
7850   SDValue Chain = LD->getChain();
7851   SDValue BasePtr = LD->getBasePtr();
7852   MachineMemOperand *MMO = LD->getMemOperand();
7853 
7854   SDValue NewLD =
7855       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7856                      BasePtr, MVT::i8, MMO);
7857   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7858 
7859   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7860   return DAG.getMergeValues(Ops, dl);
7861 }
7862 
7863 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7864   if (Op.getOperand(1).getValueType().isVector())
7865     return LowerVectorStore(Op, DAG);
7866 
7867   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7868          "Custom lowering only for i1 stores");
7869 
7870   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7871 
7872   SDLoc dl(Op);
7873   StoreSDNode *ST = cast<StoreSDNode>(Op);
7874 
7875   SDValue Chain = ST->getChain();
7876   SDValue BasePtr = ST->getBasePtr();
7877   SDValue Value = ST->getValue();
7878   MachineMemOperand *MMO = ST->getMemOperand();
7879 
7880   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7881                       Value);
7882   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7883 }
7884 
7885 // FIXME: Remove this once the ANDI glue bug is fixed:
7886 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7887   assert(Op.getValueType() == MVT::i1 &&
7888          "Custom lowering only for i1 results");
7889 
7890   SDLoc DL(Op);
7891   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7892 }
7893 
7894 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7895                                                SelectionDAG &DAG) const {
7896 
7897   // Implements a vector truncate that fits in a vector register as a shuffle.
7898   // We want to legalize vector truncates down to where the source fits in
7899   // a vector register (and target is therefore smaller than vector register
7900   // size).  At that point legalization will try to custom lower the sub-legal
7901   // result and get here - where we can contain the truncate as a single target
7902   // operation.
7903 
7904   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7905   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7906   //
7907   // We will implement it for big-endian ordering as this (where x denotes
7908   // undefined):
7909   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7910   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7911   //
7912   // The same operation in little-endian ordering will be:
7913   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7914   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7915 
7916   assert(Op.getValueType().isVector() && "Vector type expected.");
7917 
7918   SDLoc DL(Op);
7919   SDValue N1 = Op.getOperand(0);
7920   unsigned SrcSize = N1.getValueType().getSizeInBits();
7921   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7922   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7923 
7924   EVT TrgVT = Op.getValueType();
7925   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7926   EVT EltVT = TrgVT.getVectorElementType();
7927   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7928   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7929 
7930   // First list the elements we want to keep.
7931   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7932   SmallVector<int, 16> ShuffV;
7933   if (Subtarget.isLittleEndian())
7934     for (unsigned i = 0; i < TrgNumElts; ++i)
7935       ShuffV.push_back(i * SizeMult);
7936   else
7937     for (unsigned i = 1; i <= TrgNumElts; ++i)
7938       ShuffV.push_back(i * SizeMult - 1);
7939 
7940   // Populate the remaining elements with undefs.
7941   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7942     // ShuffV.push_back(i + WideNumElts);
7943     ShuffV.push_back(WideNumElts + 1);
7944 
7945   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7946   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7947 }
7948 
7949 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7950 /// possible.
7951 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7952   // Not FP? Not a fsel.
7953   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7954       !Op.getOperand(2).getValueType().isFloatingPoint())
7955     return Op;
7956 
7957   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7958 
7959   EVT ResVT = Op.getValueType();
7960   EVT CmpVT = Op.getOperand(0).getValueType();
7961   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7962   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7963   SDLoc dl(Op);
7964 
7965   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7966   // presence of infinities.
7967   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7968     switch (CC) {
7969     default:
7970       break;
7971     case ISD::SETOGT:
7972     case ISD::SETGT:
7973       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7974     case ISD::SETOLT:
7975     case ISD::SETLT:
7976       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7977     }
7978   }
7979 
7980   // We might be able to do better than this under some circumstances, but in
7981   // general, fsel-based lowering of select is a finite-math-only optimization.
7982   // For more information, see section F.3 of the 2.06 ISA specification.
7983   // With ISA 3.0
7984   if (!DAG.getTarget().Options.NoInfsFPMath ||
7985       !DAG.getTarget().Options.NoNaNsFPMath)
7986     return Op;
7987 
7988   // TODO: Propagate flags from the select rather than global settings.
7989   SDNodeFlags Flags;
7990   Flags.setNoInfs(true);
7991   Flags.setNoNaNs(true);
7992 
7993   // If the RHS of the comparison is a 0.0, we don't need to do the
7994   // subtraction at all.
7995   SDValue Sel1;
7996   if (isFloatingPointZero(RHS))
7997     switch (CC) {
7998     default: break;       // SETUO etc aren't handled by fsel.
7999     case ISD::SETNE:
8000       std::swap(TV, FV);
8001       LLVM_FALLTHROUGH;
8002     case ISD::SETEQ:
8003       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8004         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8005       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8006       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8007         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8008       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8009                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
8010     case ISD::SETULT:
8011     case ISD::SETLT:
8012       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8013       LLVM_FALLTHROUGH;
8014     case ISD::SETOGE:
8015     case ISD::SETGE:
8016       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8017         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8018       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8019     case ISD::SETUGT:
8020     case ISD::SETGT:
8021       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8022       LLVM_FALLTHROUGH;
8023     case ISD::SETOLE:
8024     case ISD::SETLE:
8025       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8026         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8027       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8028                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
8029     }
8030 
8031   SDValue Cmp;
8032   switch (CC) {
8033   default: break;       // SETUO etc aren't handled by fsel.
8034   case ISD::SETNE:
8035     std::swap(TV, FV);
8036     LLVM_FALLTHROUGH;
8037   case ISD::SETEQ:
8038     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8039     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8040       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8041     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8042     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8043       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8044     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8045                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8046   case ISD::SETULT:
8047   case ISD::SETLT:
8048     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8049     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8050       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8051     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8052   case ISD::SETOGE:
8053   case ISD::SETGE:
8054     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8055     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8056       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8057     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8058   case ISD::SETUGT:
8059   case ISD::SETGT:
8060     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8061     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8062       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8063     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8064   case ISD::SETOLE:
8065   case ISD::SETLE:
8066     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8067     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8068       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8069     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8070   }
8071   return Op;
8072 }
8073 
8074 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8075                                                SelectionDAG &DAG,
8076                                                const SDLoc &dl) const {
8077   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8078   SDValue Src = Op.getOperand(0);
8079   if (Src.getValueType() == MVT::f32)
8080     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8081 
8082   SDValue Tmp;
8083   switch (Op.getSimpleValueType().SimpleTy) {
8084   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8085   case MVT::i32:
8086     Tmp = DAG.getNode(
8087         Op.getOpcode() == ISD::FP_TO_SINT
8088             ? PPCISD::FCTIWZ
8089             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8090         dl, MVT::f64, Src);
8091     break;
8092   case MVT::i64:
8093     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8094            "i64 FP_TO_UINT is supported only with FPCVT");
8095     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8096                                                         PPCISD::FCTIDUZ,
8097                       dl, MVT::f64, Src);
8098     break;
8099   }
8100 
8101   // Convert the FP value to an int value through memory.
8102   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8103     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
8104   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8105   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8106   MachinePointerInfo MPI =
8107       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8108 
8109   // Emit a store to the stack slot.
8110   SDValue Chain;
8111   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8112   if (i32Stack) {
8113     MachineFunction &MF = DAG.getMachineFunction();
8114     Alignment = Align(4);
8115     MachineMemOperand *MMO =
8116         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8117     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
8118     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8119               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8120   } else
8121     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment);
8122 
8123   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8124   // add in a bias on big endian.
8125   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8126     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8127                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8128     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8129   }
8130 
8131   RLI.Chain = Chain;
8132   RLI.Ptr = FIPtr;
8133   RLI.MPI = MPI;
8134   RLI.Alignment = Alignment;
8135 }
8136 
8137 /// Custom lowers floating point to integer conversions to use
8138 /// the direct move instructions available in ISA 2.07 to avoid the
8139 /// need for load/store combinations.
8140 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8141                                                     SelectionDAG &DAG,
8142                                                     const SDLoc &dl) const {
8143   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8144   SDValue Src = Op.getOperand(0);
8145 
8146   if (Src.getValueType() == MVT::f32)
8147     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8148 
8149   SDValue Tmp;
8150   switch (Op.getSimpleValueType().SimpleTy) {
8151   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8152   case MVT::i32:
8153     Tmp = DAG.getNode(
8154         Op.getOpcode() == ISD::FP_TO_SINT
8155             ? PPCISD::FCTIWZ
8156             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8157         dl, MVT::f64, Src);
8158     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
8159     break;
8160   case MVT::i64:
8161     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8162            "i64 FP_TO_UINT is supported only with FPCVT");
8163     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8164                                                         PPCISD::FCTIDUZ,
8165                       dl, MVT::f64, Src);
8166     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
8167     break;
8168   }
8169   return Tmp;
8170 }
8171 
8172 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8173                                           const SDLoc &dl) const {
8174 
8175   // FP to INT conversions are legal for f128.
8176   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
8177     return Op;
8178 
8179   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8180   // PPC (the libcall is not available).
8181   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
8182     if (Op.getValueType() == MVT::i32) {
8183       if (Op.getOpcode() == ISD::FP_TO_SINT) {
8184         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8185                                  MVT::f64, Op.getOperand(0),
8186                                  DAG.getIntPtrConstant(0, dl));
8187         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8188                                  MVT::f64, Op.getOperand(0),
8189                                  DAG.getIntPtrConstant(1, dl));
8190 
8191         // Add the two halves of the long double in round-to-zero mode.
8192         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8193 
8194         // Now use a smaller FP_TO_SINT.
8195         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8196       }
8197       if (Op.getOpcode() == ISD::FP_TO_UINT) {
8198         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8199         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8200         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
8201         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8202         // FIXME: generated code sucks.
8203         // TODO: Are there fast-math-flags to propagate to this FSUB?
8204         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
8205                                    Op.getOperand(0), Tmp);
8206         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8207         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
8208                            DAG.getConstant(0x80000000, dl, MVT::i32));
8209         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
8210                                     Op.getOperand(0));
8211         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
8212                                ISD::SETGE);
8213       }
8214     }
8215 
8216     return SDValue();
8217   }
8218 
8219   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8220     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8221 
8222   ReuseLoadInfo RLI;
8223   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8224 
8225   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8226                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8227 }
8228 
8229 // We're trying to insert a regular store, S, and then a load, L. If the
8230 // incoming value, O, is a load, we might just be able to have our load use the
8231 // address used by O. However, we don't know if anything else will store to
8232 // that address before we can load from it. To prevent this situation, we need
8233 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8234 // the same chain operand as O, we create a token factor from the chain results
8235 // of O and L, and we replace all uses of O's chain result with that token
8236 // factor (see spliceIntoChain below for this last part).
8237 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8238                                             ReuseLoadInfo &RLI,
8239                                             SelectionDAG &DAG,
8240                                             ISD::LoadExtType ET) const {
8241   SDLoc dl(Op);
8242   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8243                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8244   if (ET == ISD::NON_EXTLOAD &&
8245       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8246       isOperationLegalOrCustom(Op.getOpcode(),
8247                                Op.getOperand(0).getValueType())) {
8248 
8249     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8250     return true;
8251   }
8252 
8253   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8254   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8255       LD->isNonTemporal())
8256     return false;
8257   if (LD->getMemoryVT() != MemVT)
8258     return false;
8259 
8260   RLI.Ptr = LD->getBasePtr();
8261   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8262     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8263            "Non-pre-inc AM on PPC?");
8264     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8265                           LD->getOffset());
8266   }
8267 
8268   RLI.Chain = LD->getChain();
8269   RLI.MPI = LD->getPointerInfo();
8270   RLI.IsDereferenceable = LD->isDereferenceable();
8271   RLI.IsInvariant = LD->isInvariant();
8272   RLI.Alignment = LD->getAlign();
8273   RLI.AAInfo = LD->getAAInfo();
8274   RLI.Ranges = LD->getRanges();
8275 
8276   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8277   return true;
8278 }
8279 
8280 // Given the head of the old chain, ResChain, insert a token factor containing
8281 // it and NewResChain, and make users of ResChain now be users of that token
8282 // factor.
8283 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8284 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8285                                         SDValue NewResChain,
8286                                         SelectionDAG &DAG) const {
8287   if (!ResChain)
8288     return;
8289 
8290   SDLoc dl(NewResChain);
8291 
8292   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8293                            NewResChain, DAG.getUNDEF(MVT::Other));
8294   assert(TF.getNode() != NewResChain.getNode() &&
8295          "A new TF really is required here");
8296 
8297   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8298   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8299 }
8300 
8301 /// Analyze profitability of direct move
8302 /// prefer float load to int load plus direct move
8303 /// when there is no integer use of int load
8304 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8305   SDNode *Origin = Op.getOperand(0).getNode();
8306   if (Origin->getOpcode() != ISD::LOAD)
8307     return true;
8308 
8309   // If there is no LXSIBZX/LXSIHZX, like Power8,
8310   // prefer direct move if the memory size is 1 or 2 bytes.
8311   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8312   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8313     return true;
8314 
8315   for (SDNode::use_iterator UI = Origin->use_begin(),
8316                             UE = Origin->use_end();
8317        UI != UE; ++UI) {
8318 
8319     // Only look at the users of the loaded value.
8320     if (UI.getUse().get().getResNo() != 0)
8321       continue;
8322 
8323     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8324         UI->getOpcode() != ISD::UINT_TO_FP)
8325       return true;
8326   }
8327 
8328   return false;
8329 }
8330 
8331 /// Custom lowers integer to floating point conversions to use
8332 /// the direct move instructions available in ISA 2.07 to avoid the
8333 /// need for load/store combinations.
8334 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8335                                                     SelectionDAG &DAG,
8336                                                     const SDLoc &dl) const {
8337   assert((Op.getValueType() == MVT::f32 ||
8338           Op.getValueType() == MVT::f64) &&
8339          "Invalid floating point type as target of conversion");
8340   assert(Subtarget.hasFPCVT() &&
8341          "Int to FP conversions with direct moves require FPCVT");
8342   SDValue FP;
8343   SDValue Src = Op.getOperand(0);
8344   bool SinglePrec = Op.getValueType() == MVT::f32;
8345   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8346   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
8347   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
8348                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
8349 
8350   if (WordInt) {
8351     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
8352                      dl, MVT::f64, Src);
8353     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8354   }
8355   else {
8356     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
8357     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8358   }
8359 
8360   return FP;
8361 }
8362 
8363 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8364 
8365   EVT VecVT = Vec.getValueType();
8366   assert(VecVT.isVector() && "Expected a vector type.");
8367   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8368 
8369   EVT EltVT = VecVT.getVectorElementType();
8370   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8371   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8372 
8373   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8374   SmallVector<SDValue, 16> Ops(NumConcat);
8375   Ops[0] = Vec;
8376   SDValue UndefVec = DAG.getUNDEF(VecVT);
8377   for (unsigned i = 1; i < NumConcat; ++i)
8378     Ops[i] = UndefVec;
8379 
8380   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8381 }
8382 
8383 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8384                                                 const SDLoc &dl) const {
8385 
8386   unsigned Opc = Op.getOpcode();
8387   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
8388          "Unexpected conversion type");
8389   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8390          "Supports conversions to v2f64/v4f32 only.");
8391 
8392   bool SignedConv = Opc == ISD::SINT_TO_FP;
8393   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8394 
8395   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
8396   EVT WideVT = Wide.getValueType();
8397   unsigned WideNumElts = WideVT.getVectorNumElements();
8398   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8399 
8400   SmallVector<int, 16> ShuffV;
8401   for (unsigned i = 0; i < WideNumElts; ++i)
8402     ShuffV.push_back(i + WideNumElts);
8403 
8404   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8405   int SaveElts = FourEltRes ? 4 : 2;
8406   if (Subtarget.isLittleEndian())
8407     for (int i = 0; i < SaveElts; i++)
8408       ShuffV[i * Stride] = i;
8409   else
8410     for (int i = 1; i <= SaveElts; i++)
8411       ShuffV[i * Stride - 1] = i - 1;
8412 
8413   SDValue ShuffleSrc2 =
8414       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8415   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8416 
8417   SDValue Extend;
8418   if (SignedConv) {
8419     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8420     EVT ExtVT = Op.getOperand(0).getValueType();
8421     if (Subtarget.hasP9Altivec())
8422       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8423                                IntermediateVT.getVectorNumElements());
8424 
8425     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8426                          DAG.getValueType(ExtVT));
8427   } else
8428     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8429 
8430   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8431 }
8432 
8433 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8434                                           SelectionDAG &DAG) const {
8435   SDLoc dl(Op);
8436 
8437   EVT InVT = Op.getOperand(0).getValueType();
8438   EVT OutVT = Op.getValueType();
8439   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8440       isOperationCustom(Op.getOpcode(), InVT))
8441     return LowerINT_TO_FPVector(Op, DAG, dl);
8442 
8443   // Conversions to f128 are legal.
8444   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
8445     return Op;
8446 
8447   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
8448     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
8449       return SDValue();
8450 
8451     SDValue Value = Op.getOperand(0);
8452     // The values are now known to be -1 (false) or 1 (true). To convert this
8453     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8454     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8455     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8456 
8457     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8458 
8459     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8460 
8461     if (Op.getValueType() != MVT::v4f64)
8462       Value = DAG.getNode(ISD::FP_ROUND, dl,
8463                           Op.getValueType(), Value,
8464                           DAG.getIntPtrConstant(1, dl));
8465     return Value;
8466   }
8467 
8468   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8469   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8470     return SDValue();
8471 
8472   if (Op.getOperand(0).getValueType() == MVT::i1)
8473     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
8474                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8475                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8476 
8477   // If we have direct moves, we can do all the conversion, skip the store/load
8478   // however, without FPCVT we can't do most conversions.
8479   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8480       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8481     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8482 
8483   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8484          "UINT_TO_FP is supported only with FPCVT");
8485 
8486   // If we have FCFIDS, then use it when converting to single-precision.
8487   // Otherwise, convert to double-precision and then round.
8488   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8489                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8490                                                             : PPCISD::FCFIDS)
8491                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8492                                                             : PPCISD::FCFID);
8493   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8494                   ? MVT::f32
8495                   : MVT::f64;
8496 
8497   if (Op.getOperand(0).getValueType() == MVT::i64) {
8498     SDValue SINT = Op.getOperand(0);
8499     // When converting to single-precision, we actually need to convert
8500     // to double-precision first and then round to single-precision.
8501     // To avoid double-rounding effects during that operation, we have
8502     // to prepare the input operand.  Bits that might be truncated when
8503     // converting to double-precision are replaced by a bit that won't
8504     // be lost at this stage, but is below the single-precision rounding
8505     // position.
8506     //
8507     // However, if -enable-unsafe-fp-math is in effect, accept double
8508     // rounding to avoid the extra overhead.
8509     if (Op.getValueType() == MVT::f32 &&
8510         !Subtarget.hasFPCVT() &&
8511         !DAG.getTarget().Options.UnsafeFPMath) {
8512 
8513       // Twiddle input to make sure the low 11 bits are zero.  (If this
8514       // is the case, we are guaranteed the value will fit into the 53 bit
8515       // mantissa of an IEEE double-precision value without rounding.)
8516       // If any of those low 11 bits were not zero originally, make sure
8517       // bit 12 (value 2048) is set instead, so that the final rounding
8518       // to single-precision gets the correct result.
8519       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8520                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8521       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8522                           Round, DAG.getConstant(2047, dl, MVT::i64));
8523       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8524       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8525                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8526 
8527       // However, we cannot use that value unconditionally: if the magnitude
8528       // of the input value is small, the bit-twiddling we did above might
8529       // end up visibly changing the output.  Fortunately, in that case, we
8530       // don't need to twiddle bits since the original input will convert
8531       // exactly to double-precision floating-point already.  Therefore,
8532       // construct a conditional to use the original value if the top 11
8533       // bits are all sign-bit copies, and use the rounded value computed
8534       // above otherwise.
8535       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8536                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8537       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8538                          Cond, DAG.getConstant(1, dl, MVT::i64));
8539       Cond = DAG.getSetCC(
8540           dl,
8541           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8542           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8543 
8544       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8545     }
8546 
8547     ReuseLoadInfo RLI;
8548     SDValue Bits;
8549 
8550     MachineFunction &MF = DAG.getMachineFunction();
8551     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8552       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8553                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8554       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8555     } else if (Subtarget.hasLFIWAX() &&
8556                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8557       MachineMemOperand *MMO =
8558         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8559                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8560       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8561       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8562                                      DAG.getVTList(MVT::f64, MVT::Other),
8563                                      Ops, MVT::i32, MMO);
8564       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8565     } else if (Subtarget.hasFPCVT() &&
8566                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8567       MachineMemOperand *MMO =
8568         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8569                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8570       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8571       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8572                                      DAG.getVTList(MVT::f64, MVT::Other),
8573                                      Ops, MVT::i32, MMO);
8574       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8575     } else if (((Subtarget.hasLFIWAX() &&
8576                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8577                 (Subtarget.hasFPCVT() &&
8578                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8579                SINT.getOperand(0).getValueType() == MVT::i32) {
8580       MachineFrameInfo &MFI = MF.getFrameInfo();
8581       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8582 
8583       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8584       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8585 
8586       SDValue Store =
8587           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8588                        MachinePointerInfo::getFixedStack(
8589                            DAG.getMachineFunction(), FrameIdx));
8590 
8591       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8592              "Expected an i32 store");
8593 
8594       RLI.Ptr = FIdx;
8595       RLI.Chain = Store;
8596       RLI.MPI =
8597           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8598       RLI.Alignment = Align(4);
8599 
8600       MachineMemOperand *MMO =
8601         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8602                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8603       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8604       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8605                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8606                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8607                                      Ops, MVT::i32, MMO);
8608     } else
8609       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8610 
8611     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
8612 
8613     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8614       FP = DAG.getNode(ISD::FP_ROUND, dl,
8615                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8616     return FP;
8617   }
8618 
8619   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
8620          "Unhandled INT_TO_FP type in custom expander!");
8621   // Since we only generate this in 64-bit mode, we can take advantage of
8622   // 64-bit registers.  In particular, sign extend the input value into the
8623   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8624   // then lfd it and fcfid it.
8625   MachineFunction &MF = DAG.getMachineFunction();
8626   MachineFrameInfo &MFI = MF.getFrameInfo();
8627   EVT PtrVT = getPointerTy(MF.getDataLayout());
8628 
8629   SDValue Ld;
8630   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8631     ReuseLoadInfo RLI;
8632     bool ReusingLoad;
8633     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
8634                                             DAG))) {
8635       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8636       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8637 
8638       SDValue Store =
8639           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8640                        MachinePointerInfo::getFixedStack(
8641                            DAG.getMachineFunction(), FrameIdx));
8642 
8643       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8644              "Expected an i32 store");
8645 
8646       RLI.Ptr = FIdx;
8647       RLI.Chain = Store;
8648       RLI.MPI =
8649           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8650       RLI.Alignment = Align(4);
8651     }
8652 
8653     MachineMemOperand *MMO =
8654       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8655                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8656     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8657     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
8658                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
8659                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
8660                                  Ops, MVT::i32, MMO);
8661     if (ReusingLoad)
8662       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8663   } else {
8664     assert(Subtarget.isPPC64() &&
8665            "i32->FP without LFIWAX supported only on PPC64");
8666 
8667     int FrameIdx = MFI.CreateStackObject(8, 8, false);
8668     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8669 
8670     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
8671                                 Op.getOperand(0));
8672 
8673     // STD the extended value into the stack slot.
8674     SDValue Store = DAG.getStore(
8675         DAG.getEntryNode(), dl, Ext64, FIdx,
8676         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8677 
8678     // Load the value as a double.
8679     Ld = DAG.getLoad(
8680         MVT::f64, dl, Store, FIdx,
8681         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8682   }
8683 
8684   // FCFID it and return it.
8685   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
8686   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8687     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8688                      DAG.getIntPtrConstant(0, dl));
8689   return FP;
8690 }
8691 
8692 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8693                                             SelectionDAG &DAG) const {
8694   SDLoc dl(Op);
8695   /*
8696    The rounding mode is in bits 30:31 of FPSR, and has the following
8697    settings:
8698      00 Round to nearest
8699      01 Round to 0
8700      10 Round to +inf
8701      11 Round to -inf
8702 
8703   FLT_ROUNDS, on the other hand, expects the following:
8704     -1 Undefined
8705      0 Round to 0
8706      1 Round to nearest
8707      2 Round to +inf
8708      3 Round to -inf
8709 
8710   To perform the conversion, we do:
8711     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8712   */
8713 
8714   MachineFunction &MF = DAG.getMachineFunction();
8715   EVT VT = Op.getValueType();
8716   EVT PtrVT = getPointerTy(MF.getDataLayout());
8717 
8718   // Save FP Control Word to register
8719   SDValue Chain = Op.getOperand(0);
8720   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8721   Chain = MFFS.getValue(1);
8722 
8723   // Save FP register to stack slot
8724   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
8725   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8726   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8727 
8728   // Load FP Control Word from low 32 bits of stack slot.
8729   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8730   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8731   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8732   Chain = CWD.getValue(1);
8733 
8734   // Transform as necessary
8735   SDValue CWD1 =
8736     DAG.getNode(ISD::AND, dl, MVT::i32,
8737                 CWD, DAG.getConstant(3, dl, MVT::i32));
8738   SDValue CWD2 =
8739     DAG.getNode(ISD::SRL, dl, MVT::i32,
8740                 DAG.getNode(ISD::AND, dl, MVT::i32,
8741                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8742                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8743                             DAG.getConstant(3, dl, MVT::i32)),
8744                 DAG.getConstant(1, dl, MVT::i32));
8745 
8746   SDValue RetVal =
8747     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8748 
8749   RetVal =
8750       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8751                   dl, VT, RetVal);
8752 
8753   return DAG.getMergeValues({RetVal, Chain}, dl);
8754 }
8755 
8756 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8757   EVT VT = Op.getValueType();
8758   unsigned BitWidth = VT.getSizeInBits();
8759   SDLoc dl(Op);
8760   assert(Op.getNumOperands() == 3 &&
8761          VT == Op.getOperand(1).getValueType() &&
8762          "Unexpected SHL!");
8763 
8764   // Expand into a bunch of logical ops.  Note that these ops
8765   // depend on the PPC behavior for oversized shift amounts.
8766   SDValue Lo = Op.getOperand(0);
8767   SDValue Hi = Op.getOperand(1);
8768   SDValue Amt = Op.getOperand(2);
8769   EVT AmtVT = Amt.getValueType();
8770 
8771   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8772                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8773   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8774   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8775   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8776   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8777                              DAG.getConstant(-BitWidth, dl, AmtVT));
8778   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8779   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8780   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8781   SDValue OutOps[] = { OutLo, OutHi };
8782   return DAG.getMergeValues(OutOps, dl);
8783 }
8784 
8785 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8786   EVT VT = Op.getValueType();
8787   SDLoc dl(Op);
8788   unsigned BitWidth = VT.getSizeInBits();
8789   assert(Op.getNumOperands() == 3 &&
8790          VT == Op.getOperand(1).getValueType() &&
8791          "Unexpected SRL!");
8792 
8793   // Expand into a bunch of logical ops.  Note that these ops
8794   // depend on the PPC behavior for oversized shift amounts.
8795   SDValue Lo = Op.getOperand(0);
8796   SDValue Hi = Op.getOperand(1);
8797   SDValue Amt = Op.getOperand(2);
8798   EVT AmtVT = Amt.getValueType();
8799 
8800   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8801                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8802   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8803   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8804   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8805   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8806                              DAG.getConstant(-BitWidth, dl, AmtVT));
8807   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8808   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8809   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8810   SDValue OutOps[] = { OutLo, OutHi };
8811   return DAG.getMergeValues(OutOps, dl);
8812 }
8813 
8814 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8815   SDLoc dl(Op);
8816   EVT VT = Op.getValueType();
8817   unsigned BitWidth = VT.getSizeInBits();
8818   assert(Op.getNumOperands() == 3 &&
8819          VT == Op.getOperand(1).getValueType() &&
8820          "Unexpected SRA!");
8821 
8822   // Expand into a bunch of logical ops, followed by a select_cc.
8823   SDValue Lo = Op.getOperand(0);
8824   SDValue Hi = Op.getOperand(1);
8825   SDValue Amt = Op.getOperand(2);
8826   EVT AmtVT = Amt.getValueType();
8827 
8828   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8829                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8830   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8831   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8832   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8833   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8834                              DAG.getConstant(-BitWidth, dl, AmtVT));
8835   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8836   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8837   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8838                                   Tmp4, Tmp6, ISD::SETLE);
8839   SDValue OutOps[] = { OutLo, OutHi };
8840   return DAG.getMergeValues(OutOps, dl);
8841 }
8842 
8843 //===----------------------------------------------------------------------===//
8844 // Vector related lowering.
8845 //
8846 
8847 /// BuildSplatI - Build a canonical splati of Val with an element size of
8848 /// SplatSize.  Cast the result to VT.
8849 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8850                            SelectionDAG &DAG, const SDLoc &dl) {
8851   static const MVT VTys[] = { // canonical VT to use for each size.
8852     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8853   };
8854 
8855   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8856 
8857   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8858   if (Val == -1)
8859     SplatSize = 1;
8860 
8861   EVT CanonicalVT = VTys[SplatSize-1];
8862 
8863   // Build a canonical splat for this value.
8864   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8865 }
8866 
8867 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8868 /// specified intrinsic ID.
8869 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8870                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8871   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8872   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8873                      DAG.getConstant(IID, dl, MVT::i32), Op);
8874 }
8875 
8876 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8877 /// specified intrinsic ID.
8878 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8879                                 SelectionDAG &DAG, const SDLoc &dl,
8880                                 EVT DestVT = MVT::Other) {
8881   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8882   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8883                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8884 }
8885 
8886 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8887 /// specified intrinsic ID.
8888 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8889                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8890                                 EVT DestVT = MVT::Other) {
8891   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8892   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8893                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8894 }
8895 
8896 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8897 /// amount.  The result has the specified value type.
8898 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8899                            SelectionDAG &DAG, const SDLoc &dl) {
8900   // Force LHS/RHS to be the right type.
8901   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8902   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8903 
8904   int Ops[16];
8905   for (unsigned i = 0; i != 16; ++i)
8906     Ops[i] = i + Amt;
8907   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8908   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8909 }
8910 
8911 /// Do we have an efficient pattern in a .td file for this node?
8912 ///
8913 /// \param V - pointer to the BuildVectorSDNode being matched
8914 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8915 ///
8916 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8917 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8918 /// the opposite is true (expansion is beneficial) are:
8919 /// - The node builds a vector out of integers that are not 32 or 64-bits
8920 /// - The node builds a vector out of constants
8921 /// - The node is a "load-and-splat"
8922 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8923 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8924                                             bool HasDirectMove,
8925                                             bool HasP8Vector) {
8926   EVT VecVT = V->getValueType(0);
8927   bool RightType = VecVT == MVT::v2f64 ||
8928     (HasP8Vector && VecVT == MVT::v4f32) ||
8929     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8930   if (!RightType)
8931     return false;
8932 
8933   bool IsSplat = true;
8934   bool IsLoad = false;
8935   SDValue Op0 = V->getOperand(0);
8936 
8937   // This function is called in a block that confirms the node is not a constant
8938   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8939   // different constants.
8940   if (V->isConstant())
8941     return false;
8942   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8943     if (V->getOperand(i).isUndef())
8944       return false;
8945     // We want to expand nodes that represent load-and-splat even if the
8946     // loaded value is a floating point truncation or conversion to int.
8947     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8948         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8949          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8950         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8951          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8952         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8953          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8954       IsLoad = true;
8955     // If the operands are different or the input is not a load and has more
8956     // uses than just this BV node, then it isn't a splat.
8957     if (V->getOperand(i) != Op0 ||
8958         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8959       IsSplat = false;
8960   }
8961   return !(IsSplat && IsLoad);
8962 }
8963 
8964 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8965 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8966 
8967   SDLoc dl(Op);
8968   SDValue Op0 = Op->getOperand(0);
8969 
8970   if (!EnableQuadPrecision ||
8971       (Op.getValueType() != MVT::f128 ) ||
8972       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8973       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
8974       (Op0.getOperand(1).getValueType() != MVT::i64))
8975     return SDValue();
8976 
8977   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8978                      Op0.getOperand(1));
8979 }
8980 
8981 static const SDValue *getNormalLoadInput(const SDValue &Op) {
8982   const SDValue *InputLoad = &Op;
8983   if (InputLoad->getOpcode() == ISD::BITCAST)
8984     InputLoad = &InputLoad->getOperand(0);
8985   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR)
8986     InputLoad = &InputLoad->getOperand(0);
8987   if (InputLoad->getOpcode() != ISD::LOAD)
8988     return nullptr;
8989   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8990   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8991 }
8992 
8993 // If this is a case we can't handle, return null and let the default
8994 // expansion code take care of it.  If we CAN select this case, and if it
8995 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8996 // this case more efficiently than a constant pool load, lower it to the
8997 // sequence of ops that should be used.
8998 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8999                                              SelectionDAG &DAG) const {
9000   SDLoc dl(Op);
9001   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9002   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9003 
9004   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
9005     // We first build an i32 vector, load it into a QPX register,
9006     // then convert it to a floating-point vector and compare it
9007     // to a zero vector to get the boolean result.
9008     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9009     int FrameIdx = MFI.CreateStackObject(16, 16, false);
9010     MachinePointerInfo PtrInfo =
9011         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9012     EVT PtrVT = getPointerTy(DAG.getDataLayout());
9013     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9014 
9015     assert(BVN->getNumOperands() == 4 &&
9016       "BUILD_VECTOR for v4i1 does not have 4 operands");
9017 
9018     bool IsConst = true;
9019     for (unsigned i = 0; i < 4; ++i) {
9020       if (BVN->getOperand(i).isUndef()) continue;
9021       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
9022         IsConst = false;
9023         break;
9024       }
9025     }
9026 
9027     if (IsConst) {
9028       Constant *One =
9029         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
9030       Constant *NegOne =
9031         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
9032 
9033       Constant *CV[4];
9034       for (unsigned i = 0; i < 4; ++i) {
9035         if (BVN->getOperand(i).isUndef())
9036           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
9037         else if (isNullConstant(BVN->getOperand(i)))
9038           CV[i] = NegOne;
9039         else
9040           CV[i] = One;
9041       }
9042 
9043       Constant *CP = ConstantVector::get(CV);
9044       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
9045                                           16 /* alignment */);
9046 
9047       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
9048       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
9049       return DAG.getMemIntrinsicNode(
9050           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
9051           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
9052     }
9053 
9054     SmallVector<SDValue, 4> Stores;
9055     for (unsigned i = 0; i < 4; ++i) {
9056       if (BVN->getOperand(i).isUndef()) continue;
9057 
9058       unsigned Offset = 4*i;
9059       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9060       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9061 
9062       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
9063       if (StoreSize > 4) {
9064         Stores.push_back(
9065             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
9066                               PtrInfo.getWithOffset(Offset), MVT::i32));
9067       } else {
9068         SDValue StoreValue = BVN->getOperand(i);
9069         if (StoreSize < 4)
9070           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
9071 
9072         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
9073                                       PtrInfo.getWithOffset(Offset)));
9074       }
9075     }
9076 
9077     SDValue StoreChain;
9078     if (!Stores.empty())
9079       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9080     else
9081       StoreChain = DAG.getEntryNode();
9082 
9083     // Now load from v4i32 into the QPX register; this will extend it to
9084     // v4i64 but not yet convert it to a floating point. Nevertheless, this
9085     // is typed as v4f64 because the QPX register integer states are not
9086     // explicitly represented.
9087 
9088     SDValue Ops[] = {StoreChain,
9089                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
9090                      FIdx};
9091     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
9092 
9093     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
9094       dl, VTs, Ops, MVT::v4i32, PtrInfo);
9095     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9096       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
9097       LoadedVect);
9098 
9099     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
9100 
9101     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
9102   }
9103 
9104   // All other QPX vectors are handled by generic code.
9105   if (Subtarget.hasQPX())
9106     return SDValue();
9107 
9108   // Check if this is a splat of a constant value.
9109   APInt APSplatBits, APSplatUndef;
9110   unsigned SplatBitSize;
9111   bool HasAnyUndefs;
9112   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9113                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9114       SplatBitSize > 32) {
9115 
9116     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
9117     // Handle load-and-splat patterns as we have instructions that will do this
9118     // in one go.
9119     if (InputLoad && DAG.isSplatValue(Op, true)) {
9120       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9121 
9122       // We have handling for 4 and 8 byte elements.
9123       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9124 
9125       // Checking for a single use of this load, we have to check for vector
9126       // width (128 bits) / ElementSize uses (since each operand of the
9127       // BUILD_VECTOR is a separate use of the value.
9128       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
9129           ((Subtarget.hasVSX() && ElementSize == 64) ||
9130            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9131         SDValue Ops[] = {
9132           LD->getChain(),    // Chain
9133           LD->getBasePtr(),  // Ptr
9134           DAG.getValueType(Op.getValueType()) // VT
9135         };
9136         return
9137           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
9138                                   DAG.getVTList(Op.getValueType(), MVT::Other),
9139                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
9140       }
9141     }
9142 
9143     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
9144     // lowered to VSX instructions under certain conditions.
9145     // Without VSX, there is no pattern more efficient than expanding the node.
9146     if (Subtarget.hasVSX() &&
9147         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9148                                         Subtarget.hasP8Vector()))
9149       return Op;
9150     return SDValue();
9151   }
9152 
9153   unsigned SplatBits = APSplatBits.getZExtValue();
9154   unsigned SplatUndef = APSplatUndef.getZExtValue();
9155   unsigned SplatSize = SplatBitSize / 8;
9156 
9157   // First, handle single instruction cases.
9158 
9159   // All zeros?
9160   if (SplatBits == 0) {
9161     // Canonicalize all zero vectors to be v4i32.
9162     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9163       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9164       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9165     }
9166     return Op;
9167   }
9168 
9169   // We have XXSPLTIB for constant splats one byte wide
9170   // FIXME: SplatBits is an unsigned int being cast to an int while passing it
9171   // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here.
9172   if (Subtarget.hasP9Vector() && SplatSize == 1)
9173     return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl);
9174 
9175   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9176   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9177                     (32-SplatBitSize));
9178   if (SextVal >= -16 && SextVal <= 15)
9179     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
9180 
9181   // Two instruction sequences.
9182 
9183   // If this value is in the range [-32,30] and is even, use:
9184   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9185   // If this value is in the range [17,31] and is odd, use:
9186   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9187   // If this value is in the range [-31,-17] and is odd, use:
9188   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9189   // Note the last two are three-instruction sequences.
9190   if (SextVal >= -32 && SextVal <= 31) {
9191     // To avoid having these optimizations undone by constant folding,
9192     // we convert to a pseudo that will be expanded later into one of
9193     // the above forms.
9194     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9195     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9196               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9197     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9198     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9199     if (VT == Op.getValueType())
9200       return RetVal;
9201     else
9202       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9203   }
9204 
9205   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9206   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9207   // for fneg/fabs.
9208   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9209     // Make -1 and vspltisw -1:
9210     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
9211 
9212     // Make the VSLW intrinsic, computing 0x8000_0000.
9213     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9214                                    OnesV, DAG, dl);
9215 
9216     // xor by OnesV to invert it.
9217     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9218     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9219   }
9220 
9221   // Check to see if this is a wide variety of vsplti*, binop self cases.
9222   static const signed char SplatCsts[] = {
9223     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9224     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9225   };
9226 
9227   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9228     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9229     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9230     int i = SplatCsts[idx];
9231 
9232     // Figure out what shift amount will be used by altivec if shifted by i in
9233     // this splat size.
9234     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9235 
9236     // vsplti + shl self.
9237     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9238       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9239       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9240         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9241         Intrinsic::ppc_altivec_vslw
9242       };
9243       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9244       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9245     }
9246 
9247     // vsplti + srl self.
9248     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9249       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9250       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9251         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9252         Intrinsic::ppc_altivec_vsrw
9253       };
9254       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9255       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9256     }
9257 
9258     // vsplti + sra self.
9259     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9260       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9261       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9262         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9263         Intrinsic::ppc_altivec_vsraw
9264       };
9265       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9266       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9267     }
9268 
9269     // vsplti + rol self.
9270     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9271                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9272       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9273       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9274         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9275         Intrinsic::ppc_altivec_vrlw
9276       };
9277       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9278       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9279     }
9280 
9281     // t = vsplti c, result = vsldoi t, t, 1
9282     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9283       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9284       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9285       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9286     }
9287     // t = vsplti c, result = vsldoi t, t, 2
9288     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9289       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9290       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9291       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9292     }
9293     // t = vsplti c, result = vsldoi t, t, 3
9294     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9295       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9296       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9297       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9298     }
9299   }
9300 
9301   return SDValue();
9302 }
9303 
9304 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9305 /// the specified operations to build the shuffle.
9306 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9307                                       SDValue RHS, SelectionDAG &DAG,
9308                                       const SDLoc &dl) {
9309   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9310   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9311   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9312 
9313   enum {
9314     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9315     OP_VMRGHW,
9316     OP_VMRGLW,
9317     OP_VSPLTISW0,
9318     OP_VSPLTISW1,
9319     OP_VSPLTISW2,
9320     OP_VSPLTISW3,
9321     OP_VSLDOI4,
9322     OP_VSLDOI8,
9323     OP_VSLDOI12
9324   };
9325 
9326   if (OpNum == OP_COPY) {
9327     if (LHSID == (1*9+2)*9+3) return LHS;
9328     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9329     return RHS;
9330   }
9331 
9332   SDValue OpLHS, OpRHS;
9333   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9334   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9335 
9336   int ShufIdxs[16];
9337   switch (OpNum) {
9338   default: llvm_unreachable("Unknown i32 permute!");
9339   case OP_VMRGHW:
9340     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9341     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9342     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9343     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9344     break;
9345   case OP_VMRGLW:
9346     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9347     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9348     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9349     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9350     break;
9351   case OP_VSPLTISW0:
9352     for (unsigned i = 0; i != 16; ++i)
9353       ShufIdxs[i] = (i&3)+0;
9354     break;
9355   case OP_VSPLTISW1:
9356     for (unsigned i = 0; i != 16; ++i)
9357       ShufIdxs[i] = (i&3)+4;
9358     break;
9359   case OP_VSPLTISW2:
9360     for (unsigned i = 0; i != 16; ++i)
9361       ShufIdxs[i] = (i&3)+8;
9362     break;
9363   case OP_VSPLTISW3:
9364     for (unsigned i = 0; i != 16; ++i)
9365       ShufIdxs[i] = (i&3)+12;
9366     break;
9367   case OP_VSLDOI4:
9368     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9369   case OP_VSLDOI8:
9370     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9371   case OP_VSLDOI12:
9372     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9373   }
9374   EVT VT = OpLHS.getValueType();
9375   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9376   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9377   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9378   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9379 }
9380 
9381 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9382 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9383 /// SDValue.
9384 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9385                                            SelectionDAG &DAG) const {
9386   const unsigned BytesInVector = 16;
9387   bool IsLE = Subtarget.isLittleEndian();
9388   SDLoc dl(N);
9389   SDValue V1 = N->getOperand(0);
9390   SDValue V2 = N->getOperand(1);
9391   unsigned ShiftElts = 0, InsertAtByte = 0;
9392   bool Swap = false;
9393 
9394   // Shifts required to get the byte we want at element 7.
9395   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9396                                    0, 15, 14, 13, 12, 11, 10, 9};
9397   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9398                                 1, 2,  3,  4,  5,  6,  7,  8};
9399 
9400   ArrayRef<int> Mask = N->getMask();
9401   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9402 
9403   // For each mask element, find out if we're just inserting something
9404   // from V2 into V1 or vice versa.
9405   // Possible permutations inserting an element from V2 into V1:
9406   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9407   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9408   //   ...
9409   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9410   // Inserting from V1 into V2 will be similar, except mask range will be
9411   // [16,31].
9412 
9413   bool FoundCandidate = false;
9414   // If both vector operands for the shuffle are the same vector, the mask
9415   // will contain only elements from the first one and the second one will be
9416   // undef.
9417   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9418   // Go through the mask of half-words to find an element that's being moved
9419   // from one vector to the other.
9420   for (unsigned i = 0; i < BytesInVector; ++i) {
9421     unsigned CurrentElement = Mask[i];
9422     // If 2nd operand is undefined, we should only look for element 7 in the
9423     // Mask.
9424     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9425       continue;
9426 
9427     bool OtherElementsInOrder = true;
9428     // Examine the other elements in the Mask to see if they're in original
9429     // order.
9430     for (unsigned j = 0; j < BytesInVector; ++j) {
9431       if (j == i)
9432         continue;
9433       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9434       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9435       // in which we always assume we're always picking from the 1st operand.
9436       int MaskOffset =
9437           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9438       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9439         OtherElementsInOrder = false;
9440         break;
9441       }
9442     }
9443     // If other elements are in original order, we record the number of shifts
9444     // we need to get the element we want into element 7. Also record which byte
9445     // in the vector we should insert into.
9446     if (OtherElementsInOrder) {
9447       // If 2nd operand is undefined, we assume no shifts and no swapping.
9448       if (V2.isUndef()) {
9449         ShiftElts = 0;
9450         Swap = false;
9451       } else {
9452         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9453         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9454                          : BigEndianShifts[CurrentElement & 0xF];
9455         Swap = CurrentElement < BytesInVector;
9456       }
9457       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9458       FoundCandidate = true;
9459       break;
9460     }
9461   }
9462 
9463   if (!FoundCandidate)
9464     return SDValue();
9465 
9466   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9467   // optionally with VECSHL if shift is required.
9468   if (Swap)
9469     std::swap(V1, V2);
9470   if (V2.isUndef())
9471     V2 = V1;
9472   if (ShiftElts) {
9473     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9474                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9475     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9476                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9477   }
9478   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9479                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9480 }
9481 
9482 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9483 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9484 /// SDValue.
9485 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9486                                            SelectionDAG &DAG) const {
9487   const unsigned NumHalfWords = 8;
9488   const unsigned BytesInVector = NumHalfWords * 2;
9489   // Check that the shuffle is on half-words.
9490   if (!isNByteElemShuffleMask(N, 2, 1))
9491     return SDValue();
9492 
9493   bool IsLE = Subtarget.isLittleEndian();
9494   SDLoc dl(N);
9495   SDValue V1 = N->getOperand(0);
9496   SDValue V2 = N->getOperand(1);
9497   unsigned ShiftElts = 0, InsertAtByte = 0;
9498   bool Swap = false;
9499 
9500   // Shifts required to get the half-word we want at element 3.
9501   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9502   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9503 
9504   uint32_t Mask = 0;
9505   uint32_t OriginalOrderLow = 0x1234567;
9506   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9507   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9508   // 32-bit space, only need 4-bit nibbles per element.
9509   for (unsigned i = 0; i < NumHalfWords; ++i) {
9510     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9511     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9512   }
9513 
9514   // For each mask element, find out if we're just inserting something
9515   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9516   // from V2 into V1:
9517   //   X, 1, 2, 3, 4, 5, 6, 7
9518   //   0, X, 2, 3, 4, 5, 6, 7
9519   //   0, 1, X, 3, 4, 5, 6, 7
9520   //   0, 1, 2, X, 4, 5, 6, 7
9521   //   0, 1, 2, 3, X, 5, 6, 7
9522   //   0, 1, 2, 3, 4, X, 6, 7
9523   //   0, 1, 2, 3, 4, 5, X, 7
9524   //   0, 1, 2, 3, 4, 5, 6, X
9525   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9526 
9527   bool FoundCandidate = false;
9528   // Go through the mask of half-words to find an element that's being moved
9529   // from one vector to the other.
9530   for (unsigned i = 0; i < NumHalfWords; ++i) {
9531     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9532     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9533     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9534     uint32_t TargetOrder = 0x0;
9535 
9536     // If both vector operands for the shuffle are the same vector, the mask
9537     // will contain only elements from the first one and the second one will be
9538     // undef.
9539     if (V2.isUndef()) {
9540       ShiftElts = 0;
9541       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9542       TargetOrder = OriginalOrderLow;
9543       Swap = false;
9544       // Skip if not the correct element or mask of other elements don't equal
9545       // to our expected order.
9546       if (MaskOneElt == VINSERTHSrcElem &&
9547           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9548         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9549         FoundCandidate = true;
9550         break;
9551       }
9552     } else { // If both operands are defined.
9553       // Target order is [8,15] if the current mask is between [0,7].
9554       TargetOrder =
9555           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9556       // Skip if mask of other elements don't equal our expected order.
9557       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9558         // We only need the last 3 bits for the number of shifts.
9559         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9560                          : BigEndianShifts[MaskOneElt & 0x7];
9561         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9562         Swap = MaskOneElt < NumHalfWords;
9563         FoundCandidate = true;
9564         break;
9565       }
9566     }
9567   }
9568 
9569   if (!FoundCandidate)
9570     return SDValue();
9571 
9572   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9573   // optionally with VECSHL if shift is required.
9574   if (Swap)
9575     std::swap(V1, V2);
9576   if (V2.isUndef())
9577     V2 = V1;
9578   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9579   if (ShiftElts) {
9580     // Double ShiftElts because we're left shifting on v16i8 type.
9581     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9582                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9583     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9584     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9585                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9586     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9587   }
9588   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9589   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9590                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9591   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9592 }
9593 
9594 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9595 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9596 /// return the code it can be lowered into.  Worst case, it can always be
9597 /// lowered into a vperm.
9598 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9599                                                SelectionDAG &DAG) const {
9600   SDLoc dl(Op);
9601   SDValue V1 = Op.getOperand(0);
9602   SDValue V2 = Op.getOperand(1);
9603   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9604   EVT VT = Op.getValueType();
9605   bool isLittleEndian = Subtarget.isLittleEndian();
9606 
9607   unsigned ShiftElts, InsertAtByte;
9608   bool Swap = false;
9609 
9610   // If this is a load-and-splat, we can do that with a single instruction
9611   // in some cases. However if the load has multiple uses, we don't want to
9612   // combine it because that will just produce multiple loads.
9613   const SDValue *InputLoad = getNormalLoadInput(V1);
9614   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9615       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9616       InputLoad->hasOneUse()) {
9617     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9618     int SplatIdx =
9619       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9620 
9621     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9622     // For 4-byte load-and-splat, we need Power9.
9623     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9624       uint64_t Offset = 0;
9625       if (IsFourByte)
9626         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9627       else
9628         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9629       SDValue BasePtr = LD->getBasePtr();
9630       if (Offset != 0)
9631         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9632                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9633       SDValue Ops[] = {
9634         LD->getChain(),    // Chain
9635         BasePtr,           // BasePtr
9636         DAG.getValueType(Op.getValueType()) // VT
9637       };
9638       SDVTList VTL =
9639         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9640       SDValue LdSplt =
9641         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9642                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9643       if (LdSplt.getValueType() != SVOp->getValueType(0))
9644         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9645       return LdSplt;
9646     }
9647   }
9648   if (Subtarget.hasP9Vector() &&
9649       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9650                            isLittleEndian)) {
9651     if (Swap)
9652       std::swap(V1, V2);
9653     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9654     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9655     if (ShiftElts) {
9656       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9657                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9658       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9659                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9660       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9661     }
9662     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9663                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9664     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9665   }
9666 
9667   if (Subtarget.hasP9Altivec()) {
9668     SDValue NewISDNode;
9669     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9670       return NewISDNode;
9671 
9672     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9673       return NewISDNode;
9674   }
9675 
9676   if (Subtarget.hasVSX() &&
9677       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9678     if (Swap)
9679       std::swap(V1, V2);
9680     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9681     SDValue Conv2 =
9682         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9683 
9684     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9685                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9686     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9687   }
9688 
9689   if (Subtarget.hasVSX() &&
9690     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9691     if (Swap)
9692       std::swap(V1, V2);
9693     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9694     SDValue Conv2 =
9695         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9696 
9697     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9698                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9699     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9700   }
9701 
9702   if (Subtarget.hasP9Vector()) {
9703      if (PPC::isXXBRHShuffleMask(SVOp)) {
9704       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9705       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9706       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9707     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9708       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9709       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9710       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9711     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9712       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9713       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9714       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9715     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9716       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9717       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9718       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9719     }
9720   }
9721 
9722   if (Subtarget.hasVSX()) {
9723     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9724       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9725 
9726       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9727       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9728                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9729       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9730     }
9731 
9732     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9733     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9734       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9735       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9736       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9737     }
9738   }
9739 
9740   if (Subtarget.hasQPX()) {
9741     if (VT.getVectorNumElements() != 4)
9742       return SDValue();
9743 
9744     if (V2.isUndef()) V2 = V1;
9745 
9746     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
9747     if (AlignIdx != -1) {
9748       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
9749                          DAG.getConstant(AlignIdx, dl, MVT::i32));
9750     } else if (SVOp->isSplat()) {
9751       int SplatIdx = SVOp->getSplatIndex();
9752       if (SplatIdx >= 4) {
9753         std::swap(V1, V2);
9754         SplatIdx -= 4;
9755       }
9756 
9757       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
9758                          DAG.getConstant(SplatIdx, dl, MVT::i32));
9759     }
9760 
9761     // Lower this into a qvgpci/qvfperm pair.
9762 
9763     // Compute the qvgpci literal
9764     unsigned idx = 0;
9765     for (unsigned i = 0; i < 4; ++i) {
9766       int m = SVOp->getMaskElt(i);
9767       unsigned mm = m >= 0 ? (unsigned) m : i;
9768       idx |= mm << (3-i)*3;
9769     }
9770 
9771     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
9772                              DAG.getConstant(idx, dl, MVT::i32));
9773     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
9774   }
9775 
9776   // Cases that are handled by instructions that take permute immediates
9777   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9778   // selected by the instruction selector.
9779   if (V2.isUndef()) {
9780     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9781         PPC::isSplatShuffleMask(SVOp, 2) ||
9782         PPC::isSplatShuffleMask(SVOp, 4) ||
9783         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9784         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9785         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9786         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9787         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9788         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9789         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9790         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9791         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9792         (Subtarget.hasP8Altivec() && (
9793          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9794          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9795          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9796       return Op;
9797     }
9798   }
9799 
9800   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9801   // and produce a fixed permutation.  If any of these match, do not lower to
9802   // VPERM.
9803   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9804   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9805       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9806       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9807       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9808       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9809       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9810       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9811       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9812       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9813       (Subtarget.hasP8Altivec() && (
9814        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9815        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9816        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9817     return Op;
9818 
9819   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9820   // perfect shuffle table to emit an optimal matching sequence.
9821   ArrayRef<int> PermMask = SVOp->getMask();
9822 
9823   unsigned PFIndexes[4];
9824   bool isFourElementShuffle = true;
9825   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9826     unsigned EltNo = 8;   // Start out undef.
9827     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9828       if (PermMask[i*4+j] < 0)
9829         continue;   // Undef, ignore it.
9830 
9831       unsigned ByteSource = PermMask[i*4+j];
9832       if ((ByteSource & 3) != j) {
9833         isFourElementShuffle = false;
9834         break;
9835       }
9836 
9837       if (EltNo == 8) {
9838         EltNo = ByteSource/4;
9839       } else if (EltNo != ByteSource/4) {
9840         isFourElementShuffle = false;
9841         break;
9842       }
9843     }
9844     PFIndexes[i] = EltNo;
9845   }
9846 
9847   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9848   // perfect shuffle vector to determine if it is cost effective to do this as
9849   // discrete instructions, or whether we should use a vperm.
9850   // For now, we skip this for little endian until such time as we have a
9851   // little-endian perfect shuffle table.
9852   if (isFourElementShuffle && !isLittleEndian) {
9853     // Compute the index in the perfect shuffle table.
9854     unsigned PFTableIndex =
9855       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9856 
9857     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9858     unsigned Cost  = (PFEntry >> 30);
9859 
9860     // Determining when to avoid vperm is tricky.  Many things affect the cost
9861     // of vperm, particularly how many times the perm mask needs to be computed.
9862     // For example, if the perm mask can be hoisted out of a loop or is already
9863     // used (perhaps because there are multiple permutes with the same shuffle
9864     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9865     // the loop requires an extra register.
9866     //
9867     // As a compromise, we only emit discrete instructions if the shuffle can be
9868     // generated in 3 or fewer operations.  When we have loop information
9869     // available, if this block is within a loop, we should avoid using vperm
9870     // for 3-operation perms and use a constant pool load instead.
9871     if (Cost < 3)
9872       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9873   }
9874 
9875   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9876   // vector that will get spilled to the constant pool.
9877   if (V2.isUndef()) V2 = V1;
9878 
9879   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9880   // that it is in input element units, not in bytes.  Convert now.
9881 
9882   // For little endian, the order of the input vectors is reversed, and
9883   // the permutation mask is complemented with respect to 31.  This is
9884   // necessary to produce proper semantics with the big-endian-biased vperm
9885   // instruction.
9886   EVT EltVT = V1.getValueType().getVectorElementType();
9887   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9888 
9889   SmallVector<SDValue, 16> ResultMask;
9890   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9891     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9892 
9893     for (unsigned j = 0; j != BytesPerElement; ++j)
9894       if (isLittleEndian)
9895         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9896                                              dl, MVT::i32));
9897       else
9898         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9899                                              MVT::i32));
9900   }
9901 
9902   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9903   if (isLittleEndian)
9904     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9905                        V2, V1, VPermMask);
9906   else
9907     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9908                        V1, V2, VPermMask);
9909 }
9910 
9911 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9912 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9913 /// information about the intrinsic.
9914 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9915                                  bool &isDot, const PPCSubtarget &Subtarget) {
9916   unsigned IntrinsicID =
9917       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9918   CompareOpc = -1;
9919   isDot = false;
9920   switch (IntrinsicID) {
9921   default:
9922     return false;
9923   // Comparison predicates.
9924   case Intrinsic::ppc_altivec_vcmpbfp_p:
9925     CompareOpc = 966;
9926     isDot = true;
9927     break;
9928   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9929     CompareOpc = 198;
9930     isDot = true;
9931     break;
9932   case Intrinsic::ppc_altivec_vcmpequb_p:
9933     CompareOpc = 6;
9934     isDot = true;
9935     break;
9936   case Intrinsic::ppc_altivec_vcmpequh_p:
9937     CompareOpc = 70;
9938     isDot = true;
9939     break;
9940   case Intrinsic::ppc_altivec_vcmpequw_p:
9941     CompareOpc = 134;
9942     isDot = true;
9943     break;
9944   case Intrinsic::ppc_altivec_vcmpequd_p:
9945     if (Subtarget.hasP8Altivec()) {
9946       CompareOpc = 199;
9947       isDot = true;
9948     } else
9949       return false;
9950     break;
9951   case Intrinsic::ppc_altivec_vcmpneb_p:
9952   case Intrinsic::ppc_altivec_vcmpneh_p:
9953   case Intrinsic::ppc_altivec_vcmpnew_p:
9954   case Intrinsic::ppc_altivec_vcmpnezb_p:
9955   case Intrinsic::ppc_altivec_vcmpnezh_p:
9956   case Intrinsic::ppc_altivec_vcmpnezw_p:
9957     if (Subtarget.hasP9Altivec()) {
9958       switch (IntrinsicID) {
9959       default:
9960         llvm_unreachable("Unknown comparison intrinsic.");
9961       case Intrinsic::ppc_altivec_vcmpneb_p:
9962         CompareOpc = 7;
9963         break;
9964       case Intrinsic::ppc_altivec_vcmpneh_p:
9965         CompareOpc = 71;
9966         break;
9967       case Intrinsic::ppc_altivec_vcmpnew_p:
9968         CompareOpc = 135;
9969         break;
9970       case Intrinsic::ppc_altivec_vcmpnezb_p:
9971         CompareOpc = 263;
9972         break;
9973       case Intrinsic::ppc_altivec_vcmpnezh_p:
9974         CompareOpc = 327;
9975         break;
9976       case Intrinsic::ppc_altivec_vcmpnezw_p:
9977         CompareOpc = 391;
9978         break;
9979       }
9980       isDot = true;
9981     } else
9982       return false;
9983     break;
9984   case Intrinsic::ppc_altivec_vcmpgefp_p:
9985     CompareOpc = 454;
9986     isDot = true;
9987     break;
9988   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9989     CompareOpc = 710;
9990     isDot = true;
9991     break;
9992   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9993     CompareOpc = 774;
9994     isDot = true;
9995     break;
9996   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9997     CompareOpc = 838;
9998     isDot = true;
9999     break;
10000   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10001     CompareOpc = 902;
10002     isDot = true;
10003     break;
10004   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10005     if (Subtarget.hasP8Altivec()) {
10006       CompareOpc = 967;
10007       isDot = true;
10008     } else
10009       return false;
10010     break;
10011   case Intrinsic::ppc_altivec_vcmpgtub_p:
10012     CompareOpc = 518;
10013     isDot = true;
10014     break;
10015   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10016     CompareOpc = 582;
10017     isDot = true;
10018     break;
10019   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10020     CompareOpc = 646;
10021     isDot = true;
10022     break;
10023   case Intrinsic::ppc_altivec_vcmpgtud_p:
10024     if (Subtarget.hasP8Altivec()) {
10025       CompareOpc = 711;
10026       isDot = true;
10027     } else
10028       return false;
10029     break;
10030 
10031   // VSX predicate comparisons use the same infrastructure
10032   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10033   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10034   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10035   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10036   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10037   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10038     if (Subtarget.hasVSX()) {
10039       switch (IntrinsicID) {
10040       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10041         CompareOpc = 99;
10042         break;
10043       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10044         CompareOpc = 115;
10045         break;
10046       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10047         CompareOpc = 107;
10048         break;
10049       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10050         CompareOpc = 67;
10051         break;
10052       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10053         CompareOpc = 83;
10054         break;
10055       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10056         CompareOpc = 75;
10057         break;
10058       }
10059       isDot = true;
10060     } else
10061       return false;
10062     break;
10063 
10064   // Normal Comparisons.
10065   case Intrinsic::ppc_altivec_vcmpbfp:
10066     CompareOpc = 966;
10067     break;
10068   case Intrinsic::ppc_altivec_vcmpeqfp:
10069     CompareOpc = 198;
10070     break;
10071   case Intrinsic::ppc_altivec_vcmpequb:
10072     CompareOpc = 6;
10073     break;
10074   case Intrinsic::ppc_altivec_vcmpequh:
10075     CompareOpc = 70;
10076     break;
10077   case Intrinsic::ppc_altivec_vcmpequw:
10078     CompareOpc = 134;
10079     break;
10080   case Intrinsic::ppc_altivec_vcmpequd:
10081     if (Subtarget.hasP8Altivec())
10082       CompareOpc = 199;
10083     else
10084       return false;
10085     break;
10086   case Intrinsic::ppc_altivec_vcmpneb:
10087   case Intrinsic::ppc_altivec_vcmpneh:
10088   case Intrinsic::ppc_altivec_vcmpnew:
10089   case Intrinsic::ppc_altivec_vcmpnezb:
10090   case Intrinsic::ppc_altivec_vcmpnezh:
10091   case Intrinsic::ppc_altivec_vcmpnezw:
10092     if (Subtarget.hasP9Altivec())
10093       switch (IntrinsicID) {
10094       default:
10095         llvm_unreachable("Unknown comparison intrinsic.");
10096       case Intrinsic::ppc_altivec_vcmpneb:
10097         CompareOpc = 7;
10098         break;
10099       case Intrinsic::ppc_altivec_vcmpneh:
10100         CompareOpc = 71;
10101         break;
10102       case Intrinsic::ppc_altivec_vcmpnew:
10103         CompareOpc = 135;
10104         break;
10105       case Intrinsic::ppc_altivec_vcmpnezb:
10106         CompareOpc = 263;
10107         break;
10108       case Intrinsic::ppc_altivec_vcmpnezh:
10109         CompareOpc = 327;
10110         break;
10111       case Intrinsic::ppc_altivec_vcmpnezw:
10112         CompareOpc = 391;
10113         break;
10114       }
10115     else
10116       return false;
10117     break;
10118   case Intrinsic::ppc_altivec_vcmpgefp:
10119     CompareOpc = 454;
10120     break;
10121   case Intrinsic::ppc_altivec_vcmpgtfp:
10122     CompareOpc = 710;
10123     break;
10124   case Intrinsic::ppc_altivec_vcmpgtsb:
10125     CompareOpc = 774;
10126     break;
10127   case Intrinsic::ppc_altivec_vcmpgtsh:
10128     CompareOpc = 838;
10129     break;
10130   case Intrinsic::ppc_altivec_vcmpgtsw:
10131     CompareOpc = 902;
10132     break;
10133   case Intrinsic::ppc_altivec_vcmpgtsd:
10134     if (Subtarget.hasP8Altivec())
10135       CompareOpc = 967;
10136     else
10137       return false;
10138     break;
10139   case Intrinsic::ppc_altivec_vcmpgtub:
10140     CompareOpc = 518;
10141     break;
10142   case Intrinsic::ppc_altivec_vcmpgtuh:
10143     CompareOpc = 582;
10144     break;
10145   case Intrinsic::ppc_altivec_vcmpgtuw:
10146     CompareOpc = 646;
10147     break;
10148   case Intrinsic::ppc_altivec_vcmpgtud:
10149     if (Subtarget.hasP8Altivec())
10150       CompareOpc = 711;
10151     else
10152       return false;
10153     break;
10154   }
10155   return true;
10156 }
10157 
10158 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10159 /// lower, do it, otherwise return null.
10160 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10161                                                    SelectionDAG &DAG) const {
10162   unsigned IntrinsicID =
10163     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10164 
10165   SDLoc dl(Op);
10166 
10167   if (IntrinsicID == Intrinsic::thread_pointer) {
10168     // Reads the thread pointer register, used for __builtin_thread_pointer.
10169     if (Subtarget.isPPC64())
10170       return DAG.getRegister(PPC::X13, MVT::i64);
10171     return DAG.getRegister(PPC::R2, MVT::i32);
10172   }
10173 
10174   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10175   // opcode number of the comparison.
10176   int CompareOpc;
10177   bool isDot;
10178   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10179     return SDValue();    // Don't custom lower most intrinsics.
10180 
10181   // If this is a non-dot comparison, make the VCMP node and we are done.
10182   if (!isDot) {
10183     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10184                               Op.getOperand(1), Op.getOperand(2),
10185                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10186     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10187   }
10188 
10189   // Create the PPCISD altivec 'dot' comparison node.
10190   SDValue Ops[] = {
10191     Op.getOperand(2),  // LHS
10192     Op.getOperand(3),  // RHS
10193     DAG.getConstant(CompareOpc, dl, MVT::i32)
10194   };
10195   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10196   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10197 
10198   // Now that we have the comparison, emit a copy from the CR to a GPR.
10199   // This is flagged to the above dot comparison.
10200   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10201                                 DAG.getRegister(PPC::CR6, MVT::i32),
10202                                 CompNode.getValue(1));
10203 
10204   // Unpack the result based on how the target uses it.
10205   unsigned BitNo;   // Bit # of CR6.
10206   bool InvertBit;   // Invert result?
10207   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10208   default:  // Can't happen, don't crash on invalid number though.
10209   case 0:   // Return the value of the EQ bit of CR6.
10210     BitNo = 0; InvertBit = false;
10211     break;
10212   case 1:   // Return the inverted value of the EQ bit of CR6.
10213     BitNo = 0; InvertBit = true;
10214     break;
10215   case 2:   // Return the value of the LT bit of CR6.
10216     BitNo = 2; InvertBit = false;
10217     break;
10218   case 3:   // Return the inverted value of the LT bit of CR6.
10219     BitNo = 2; InvertBit = true;
10220     break;
10221   }
10222 
10223   // Shift the bit into the low position.
10224   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10225                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10226   // Isolate the bit.
10227   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10228                       DAG.getConstant(1, dl, MVT::i32));
10229 
10230   // If we are supposed to, toggle the bit.
10231   if (InvertBit)
10232     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10233                         DAG.getConstant(1, dl, MVT::i32));
10234   return Flags;
10235 }
10236 
10237 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10238                                                SelectionDAG &DAG) const {
10239   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10240   // the beginning of the argument list.
10241   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10242   SDLoc DL(Op);
10243   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10244   case Intrinsic::ppc_cfence: {
10245     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10246     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10247     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10248                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10249                                                   Op.getOperand(ArgStart + 1)),
10250                                       Op.getOperand(0)),
10251                    0);
10252   }
10253   default:
10254     break;
10255   }
10256   return SDValue();
10257 }
10258 
10259 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
10260   // Check for a DIV with the same operands as this REM.
10261   for (auto UI : Op.getOperand(1)->uses()) {
10262     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
10263         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
10264       if (UI->getOperand(0) == Op.getOperand(0) &&
10265           UI->getOperand(1) == Op.getOperand(1))
10266         return SDValue();
10267   }
10268   return Op;
10269 }
10270 
10271 // Lower scalar BSWAP64 to xxbrd.
10272 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10273   SDLoc dl(Op);
10274   // MTVSRDD
10275   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10276                    Op.getOperand(0));
10277   // XXBRD
10278   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10279   // MFVSRD
10280   int VectorIndex = 0;
10281   if (Subtarget.isLittleEndian())
10282     VectorIndex = 1;
10283   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10284                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10285   return Op;
10286 }
10287 
10288 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10289 // compared to a value that is atomically loaded (atomic loads zero-extend).
10290 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10291                                                 SelectionDAG &DAG) const {
10292   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10293          "Expecting an atomic compare-and-swap here.");
10294   SDLoc dl(Op);
10295   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10296   EVT MemVT = AtomicNode->getMemoryVT();
10297   if (MemVT.getSizeInBits() >= 32)
10298     return Op;
10299 
10300   SDValue CmpOp = Op.getOperand(2);
10301   // If this is already correctly zero-extended, leave it alone.
10302   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10303   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10304     return Op;
10305 
10306   // Clear the high bits of the compare operand.
10307   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10308   SDValue NewCmpOp =
10309     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10310                 DAG.getConstant(MaskVal, dl, MVT::i32));
10311 
10312   // Replace the existing compare operand with the properly zero-extended one.
10313   SmallVector<SDValue, 4> Ops;
10314   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10315     Ops.push_back(AtomicNode->getOperand(i));
10316   Ops[2] = NewCmpOp;
10317   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10318   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10319   auto NodeTy =
10320     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10321   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10322 }
10323 
10324 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10325                                                  SelectionDAG &DAG) const {
10326   SDLoc dl(Op);
10327   // Create a stack slot that is 16-byte aligned.
10328   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10329   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10330   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10331   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10332 
10333   // Store the input value into Value#0 of the stack slot.
10334   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10335                                MachinePointerInfo());
10336   // Load it out.
10337   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10338 }
10339 
10340 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10341                                                   SelectionDAG &DAG) const {
10342   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10343          "Should only be called for ISD::INSERT_VECTOR_ELT");
10344 
10345   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10346   // We have legal lowering for constant indices but not for variable ones.
10347   if (!C)
10348     return SDValue();
10349 
10350   EVT VT = Op.getValueType();
10351   SDLoc dl(Op);
10352   SDValue V1 = Op.getOperand(0);
10353   SDValue V2 = Op.getOperand(1);
10354   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10355   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10356     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10357     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10358     unsigned InsertAtElement = C->getZExtValue();
10359     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10360     if (Subtarget.isLittleEndian()) {
10361       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10362     }
10363     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10364                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10365   }
10366   return Op;
10367 }
10368 
10369 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10370                                                    SelectionDAG &DAG) const {
10371   SDLoc dl(Op);
10372   SDNode *N = Op.getNode();
10373 
10374   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
10375          "Unknown extract_vector_elt type");
10376 
10377   SDValue Value = N->getOperand(0);
10378 
10379   // The first part of this is like the store lowering except that we don't
10380   // need to track the chain.
10381 
10382   // The values are now known to be -1 (false) or 1 (true). To convert this
10383   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10384   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10385   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10386 
10387   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10388   // understand how to form the extending load.
10389   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10390 
10391   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10392 
10393   // Now convert to an integer and store.
10394   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10395     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10396     Value);
10397 
10398   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10399   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10400   MachinePointerInfo PtrInfo =
10401       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10402   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10403   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10404 
10405   SDValue StoreChain = DAG.getEntryNode();
10406   SDValue Ops[] = {StoreChain,
10407                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10408                    Value, FIdx};
10409   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10410 
10411   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10412     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10413 
10414   // Extract the value requested.
10415   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10416   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10417   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10418 
10419   SDValue IntVal =
10420       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
10421 
10422   if (!Subtarget.useCRBits())
10423     return IntVal;
10424 
10425   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
10426 }
10427 
10428 /// Lowering for QPX v4i1 loads
10429 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10430                                            SelectionDAG &DAG) const {
10431   SDLoc dl(Op);
10432   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10433   SDValue LoadChain = LN->getChain();
10434   SDValue BasePtr = LN->getBasePtr();
10435 
10436   if (Op.getValueType() == MVT::v4f64 ||
10437       Op.getValueType() == MVT::v4f32) {
10438     EVT MemVT = LN->getMemoryVT();
10439     unsigned Alignment = LN->getAlignment();
10440 
10441     // If this load is properly aligned, then it is legal.
10442     if (Alignment >= MemVT.getStoreSize())
10443       return Op;
10444 
10445     EVT ScalarVT = Op.getValueType().getScalarType(),
10446         ScalarMemVT = MemVT.getScalarType();
10447     unsigned Stride = ScalarMemVT.getStoreSize();
10448 
10449     SDValue Vals[4], LoadChains[4];
10450     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10451       SDValue Load;
10452       if (ScalarVT != ScalarMemVT)
10453         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
10454                               BasePtr,
10455                               LN->getPointerInfo().getWithOffset(Idx * Stride),
10456                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10457                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
10458       else
10459         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
10460                            LN->getPointerInfo().getWithOffset(Idx * Stride),
10461                            MinAlign(Alignment, Idx * Stride),
10462                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
10463 
10464       if (Idx == 0 && LN->isIndexed()) {
10465         assert(LN->getAddressingMode() == ISD::PRE_INC &&
10466                "Unknown addressing mode on vector load");
10467         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
10468                                   LN->getAddressingMode());
10469       }
10470 
10471       Vals[Idx] = Load;
10472       LoadChains[Idx] = Load.getValue(1);
10473 
10474       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10475                             DAG.getConstant(Stride, dl,
10476                                             BasePtr.getValueType()));
10477     }
10478 
10479     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10480     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
10481 
10482     if (LN->isIndexed()) {
10483       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
10484       return DAG.getMergeValues(RetOps, dl);
10485     }
10486 
10487     SDValue RetOps[] = { Value, TF };
10488     return DAG.getMergeValues(RetOps, dl);
10489   }
10490 
10491   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
10492   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
10493 
10494   // To lower v4i1 from a byte array, we load the byte elements of the
10495   // vector and then reuse the BUILD_VECTOR logic.
10496 
10497   SDValue VectElmts[4], VectElmtChains[4];
10498   for (unsigned i = 0; i < 4; ++i) {
10499     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10500     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10501 
10502     VectElmts[i] = DAG.getExtLoad(
10503         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
10504         LN->getPointerInfo().getWithOffset(i), MVT::i8,
10505         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
10506     VectElmtChains[i] = VectElmts[i].getValue(1);
10507   }
10508 
10509   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
10510   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
10511 
10512   SDValue RVals[] = { Value, LoadChain };
10513   return DAG.getMergeValues(RVals, dl);
10514 }
10515 
10516 /// Lowering for QPX v4i1 stores
10517 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10518                                             SelectionDAG &DAG) const {
10519   SDLoc dl(Op);
10520   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10521   SDValue StoreChain = SN->getChain();
10522   SDValue BasePtr = SN->getBasePtr();
10523   SDValue Value = SN->getValue();
10524 
10525   if (Value.getValueType() == MVT::v4f64 ||
10526       Value.getValueType() == MVT::v4f32) {
10527     EVT MemVT = SN->getMemoryVT();
10528     unsigned Alignment = SN->getAlignment();
10529 
10530     // If this store is properly aligned, then it is legal.
10531     if (Alignment >= MemVT.getStoreSize())
10532       return Op;
10533 
10534     EVT ScalarVT = Value.getValueType().getScalarType(),
10535         ScalarMemVT = MemVT.getScalarType();
10536     unsigned Stride = ScalarMemVT.getStoreSize();
10537 
10538     SDValue Stores[4];
10539     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10540       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
10541                                DAG.getVectorIdxConstant(Idx, dl));
10542       SDValue Store;
10543       if (ScalarVT != ScalarMemVT)
10544         Store =
10545             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
10546                               SN->getPointerInfo().getWithOffset(Idx * Stride),
10547                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10548                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
10549       else
10550         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
10551                              SN->getPointerInfo().getWithOffset(Idx * Stride),
10552                              MinAlign(Alignment, Idx * Stride),
10553                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
10554 
10555       if (Idx == 0 && SN->isIndexed()) {
10556         assert(SN->getAddressingMode() == ISD::PRE_INC &&
10557                "Unknown addressing mode on vector store");
10558         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
10559                                     SN->getAddressingMode());
10560       }
10561 
10562       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10563                             DAG.getConstant(Stride, dl,
10564                                             BasePtr.getValueType()));
10565       Stores[Idx] = Store;
10566     }
10567 
10568     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10569 
10570     if (SN->isIndexed()) {
10571       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
10572       return DAG.getMergeValues(RetOps, dl);
10573     }
10574 
10575     return TF;
10576   }
10577 
10578   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
10579   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
10580 
10581   // The values are now known to be -1 (false) or 1 (true). To convert this
10582   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10583   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10584   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10585 
10586   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10587   // understand how to form the extending load.
10588   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10589 
10590   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10591 
10592   // Now convert to an integer and store.
10593   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10594     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10595     Value);
10596 
10597   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10598   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10599   MachinePointerInfo PtrInfo =
10600       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10601   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10602   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10603 
10604   SDValue Ops[] = {StoreChain,
10605                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10606                    Value, FIdx};
10607   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10608 
10609   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10610     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10611 
10612   // Move data into the byte array.
10613   SDValue Loads[4], LoadChains[4];
10614   for (unsigned i = 0; i < 4; ++i) {
10615     unsigned Offset = 4*i;
10616     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10617     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10618 
10619     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
10620                            PtrInfo.getWithOffset(Offset));
10621     LoadChains[i] = Loads[i].getValue(1);
10622   }
10623 
10624   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10625 
10626   SDValue Stores[4];
10627   for (unsigned i = 0; i < 4; ++i) {
10628     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10629     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10630 
10631     Stores[i] = DAG.getTruncStore(
10632         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
10633         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
10634         SN->getAAInfo());
10635   }
10636 
10637   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10638 
10639   return StoreChain;
10640 }
10641 
10642 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10643   SDLoc dl(Op);
10644   if (Op.getValueType() == MVT::v4i32) {
10645     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10646 
10647     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
10648     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
10649 
10650     SDValue RHSSwap =   // = vrlw RHS, 16
10651       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10652 
10653     // Shrinkify inputs to v8i16.
10654     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10655     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10656     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10657 
10658     // Low parts multiplied together, generating 32-bit results (we ignore the
10659     // top parts).
10660     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10661                                         LHS, RHS, DAG, dl, MVT::v4i32);
10662 
10663     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10664                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10665     // Shift the high parts up 16 bits.
10666     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10667                               Neg16, DAG, dl);
10668     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10669   } else if (Op.getValueType() == MVT::v16i8) {
10670     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10671     bool isLittleEndian = Subtarget.isLittleEndian();
10672 
10673     // Multiply the even 8-bit parts, producing 16-bit sums.
10674     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10675                                            LHS, RHS, DAG, dl, MVT::v8i16);
10676     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10677 
10678     // Multiply the odd 8-bit parts, producing 16-bit sums.
10679     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10680                                           LHS, RHS, DAG, dl, MVT::v8i16);
10681     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10682 
10683     // Merge the results together.  Because vmuleub and vmuloub are
10684     // instructions with a big-endian bias, we must reverse the
10685     // element numbering and reverse the meaning of "odd" and "even"
10686     // when generating little endian code.
10687     int Ops[16];
10688     for (unsigned i = 0; i != 8; ++i) {
10689       if (isLittleEndian) {
10690         Ops[i*2  ] = 2*i;
10691         Ops[i*2+1] = 2*i+16;
10692       } else {
10693         Ops[i*2  ] = 2*i+1;
10694         Ops[i*2+1] = 2*i+1+16;
10695       }
10696     }
10697     if (isLittleEndian)
10698       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10699     else
10700       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10701   } else {
10702     llvm_unreachable("Unknown mul to lower!");
10703   }
10704 }
10705 
10706 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10707 
10708   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10709 
10710   EVT VT = Op.getValueType();
10711   assert(VT.isVector() &&
10712          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10713   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10714           VT == MVT::v16i8) &&
10715          "Unexpected vector element type!");
10716   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10717          "Current subtarget doesn't support smax v2i64!");
10718 
10719   // For vector abs, it can be lowered to:
10720   // abs x
10721   // ==>
10722   // y = -x
10723   // smax(x, y)
10724 
10725   SDLoc dl(Op);
10726   SDValue X = Op.getOperand(0);
10727   SDValue Zero = DAG.getConstant(0, dl, VT);
10728   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10729 
10730   // SMAX patch https://reviews.llvm.org/D47332
10731   // hasn't landed yet, so use intrinsic first here.
10732   // TODO: Should use SMAX directly once SMAX patch landed
10733   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10734   if (VT == MVT::v2i64)
10735     BifID = Intrinsic::ppc_altivec_vmaxsd;
10736   else if (VT == MVT::v8i16)
10737     BifID = Intrinsic::ppc_altivec_vmaxsh;
10738   else if (VT == MVT::v16i8)
10739     BifID = Intrinsic::ppc_altivec_vmaxsb;
10740 
10741   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10742 }
10743 
10744 // Custom lowering for fpext vf32 to v2f64
10745 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10746 
10747   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10748          "Should only be called for ISD::FP_EXTEND");
10749 
10750   // We only want to custom lower an extend from v2f32 to v2f64.
10751   if (Op.getValueType() != MVT::v2f64 ||
10752       Op.getOperand(0).getValueType() != MVT::v2f32)
10753     return SDValue();
10754 
10755   SDLoc dl(Op);
10756   SDValue Op0 = Op.getOperand(0);
10757 
10758   switch (Op0.getOpcode()) {
10759   default:
10760     return SDValue();
10761   case ISD::EXTRACT_SUBVECTOR: {
10762     assert(Op0.getNumOperands() == 2 &&
10763            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10764            "Node should have 2 operands with second one being a constant!");
10765 
10766     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10767       return SDValue();
10768 
10769     // Custom lower is only done for high or low doubleword.
10770     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10771     if (Idx % 2 != 0)
10772       return SDValue();
10773 
10774     // Since input is v4f32, at this point Idx is either 0 or 2.
10775     // Shift to get the doubleword position we want.
10776     int DWord = Idx >> 1;
10777 
10778     // High and low word positions are different on little endian.
10779     if (Subtarget.isLittleEndian())
10780       DWord ^= 0x1;
10781 
10782     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10783                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10784   }
10785   case ISD::FADD:
10786   case ISD::FMUL:
10787   case ISD::FSUB: {
10788     SDValue NewLoad[2];
10789     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10790       // Ensure both input are loads.
10791       SDValue LdOp = Op0.getOperand(i);
10792       if (LdOp.getOpcode() != ISD::LOAD)
10793         return SDValue();
10794       // Generate new load node.
10795       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10796       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10797       NewLoad[i] = DAG.getMemIntrinsicNode(
10798           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10799           LD->getMemoryVT(), LD->getMemOperand());
10800     }
10801     SDValue NewOp =
10802         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10803                     NewLoad[1], Op0.getNode()->getFlags());
10804     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10805                        DAG.getConstant(0, dl, MVT::i32));
10806   }
10807   case ISD::LOAD: {
10808     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10809     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10810     SDValue NewLd = DAG.getMemIntrinsicNode(
10811         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10812         LD->getMemoryVT(), LD->getMemOperand());
10813     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10814                        DAG.getConstant(0, dl, MVT::i32));
10815   }
10816   }
10817   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10818 }
10819 
10820 /// LowerOperation - Provide custom lowering hooks for some operations.
10821 ///
10822 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10823   switch (Op.getOpcode()) {
10824   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10825   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10826   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10827   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10828   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10829   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10830   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10831   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10832   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10833 
10834   // Variable argument lowering.
10835   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10836   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10837   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10838 
10839   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10840   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10841   case ISD::GET_DYNAMIC_AREA_OFFSET:
10842     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10843 
10844   // Exception handling lowering.
10845   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10846   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10847   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10848 
10849   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10850   case ISD::STORE:              return LowerSTORE(Op, DAG);
10851   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10852   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10853   case ISD::FP_TO_UINT:
10854   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10855   case ISD::UINT_TO_FP:
10856   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10857   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10858 
10859   // Lower 64-bit shifts.
10860   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10861   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10862   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10863 
10864   // Vector-related lowering.
10865   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10866   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10867   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10868   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10869   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10870   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10871   case ISD::MUL:                return LowerMUL(Op, DAG);
10872   case ISD::ABS:                return LowerABS(Op, DAG);
10873   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10874 
10875   // For counter-based loop handling.
10876   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10877 
10878   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10879 
10880   // Frame & Return address.
10881   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10882   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10883 
10884   case ISD::INTRINSIC_VOID:
10885     return LowerINTRINSIC_VOID(Op, DAG);
10886   case ISD::SREM:
10887   case ISD::UREM:
10888     return LowerREM(Op, DAG);
10889   case ISD::BSWAP:
10890     return LowerBSWAP(Op, DAG);
10891   case ISD::ATOMIC_CMP_SWAP:
10892     return LowerATOMIC_CMP_SWAP(Op, DAG);
10893   }
10894 }
10895 
10896 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10897                                            SmallVectorImpl<SDValue>&Results,
10898                                            SelectionDAG &DAG) const {
10899   SDLoc dl(N);
10900   switch (N->getOpcode()) {
10901   default:
10902     llvm_unreachable("Do not know how to custom type legalize this operation!");
10903   case ISD::READCYCLECOUNTER: {
10904     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10905     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10906 
10907     Results.push_back(
10908         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10909     Results.push_back(RTB.getValue(2));
10910     break;
10911   }
10912   case ISD::INTRINSIC_W_CHAIN: {
10913     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10914         Intrinsic::loop_decrement)
10915       break;
10916 
10917     assert(N->getValueType(0) == MVT::i1 &&
10918            "Unexpected result type for CTR decrement intrinsic");
10919     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10920                                  N->getValueType(0));
10921     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10922     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10923                                  N->getOperand(1));
10924 
10925     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10926     Results.push_back(NewInt.getValue(1));
10927     break;
10928   }
10929   case ISD::VAARG: {
10930     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10931       return;
10932 
10933     EVT VT = N->getValueType(0);
10934 
10935     if (VT == MVT::i64) {
10936       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10937 
10938       Results.push_back(NewNode);
10939       Results.push_back(NewNode.getValue(1));
10940     }
10941     return;
10942   }
10943   case ISD::FP_TO_SINT:
10944   case ISD::FP_TO_UINT:
10945     // LowerFP_TO_INT() can only handle f32 and f64.
10946     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10947       return;
10948     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10949     return;
10950   case ISD::TRUNCATE: {
10951     EVT TrgVT = N->getValueType(0);
10952     EVT OpVT = N->getOperand(0).getValueType();
10953     if (TrgVT.isVector() &&
10954         isOperationCustom(N->getOpcode(), TrgVT) &&
10955         OpVT.getSizeInBits() <= 128 &&
10956         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10957       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10958     return;
10959   }
10960   case ISD::BITCAST:
10961     // Don't handle bitcast here.
10962     return;
10963   }
10964 }
10965 
10966 //===----------------------------------------------------------------------===//
10967 //  Other Lowering Code
10968 //===----------------------------------------------------------------------===//
10969 
10970 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10971   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10972   Function *Func = Intrinsic::getDeclaration(M, Id);
10973   return Builder.CreateCall(Func, {});
10974 }
10975 
10976 // The mappings for emitLeading/TrailingFence is taken from
10977 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10978 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10979                                                  Instruction *Inst,
10980                                                  AtomicOrdering Ord) const {
10981   if (Ord == AtomicOrdering::SequentiallyConsistent)
10982     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10983   if (isReleaseOrStronger(Ord))
10984     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10985   return nullptr;
10986 }
10987 
10988 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10989                                                   Instruction *Inst,
10990                                                   AtomicOrdering Ord) const {
10991   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10992     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10993     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10994     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10995     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10996       return Builder.CreateCall(
10997           Intrinsic::getDeclaration(
10998               Builder.GetInsertBlock()->getParent()->getParent(),
10999               Intrinsic::ppc_cfence, {Inst->getType()}),
11000           {Inst});
11001     // FIXME: Can use isync for rmw operation.
11002     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11003   }
11004   return nullptr;
11005 }
11006 
11007 MachineBasicBlock *
11008 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11009                                     unsigned AtomicSize,
11010                                     unsigned BinOpcode,
11011                                     unsigned CmpOpcode,
11012                                     unsigned CmpPred) const {
11013   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11014   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11015 
11016   auto LoadMnemonic = PPC::LDARX;
11017   auto StoreMnemonic = PPC::STDCX;
11018   switch (AtomicSize) {
11019   default:
11020     llvm_unreachable("Unexpected size of atomic entity");
11021   case 1:
11022     LoadMnemonic = PPC::LBARX;
11023     StoreMnemonic = PPC::STBCX;
11024     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11025     break;
11026   case 2:
11027     LoadMnemonic = PPC::LHARX;
11028     StoreMnemonic = PPC::STHCX;
11029     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11030     break;
11031   case 4:
11032     LoadMnemonic = PPC::LWARX;
11033     StoreMnemonic = PPC::STWCX;
11034     break;
11035   case 8:
11036     LoadMnemonic = PPC::LDARX;
11037     StoreMnemonic = PPC::STDCX;
11038     break;
11039   }
11040 
11041   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11042   MachineFunction *F = BB->getParent();
11043   MachineFunction::iterator It = ++BB->getIterator();
11044 
11045   Register dest = MI.getOperand(0).getReg();
11046   Register ptrA = MI.getOperand(1).getReg();
11047   Register ptrB = MI.getOperand(2).getReg();
11048   Register incr = MI.getOperand(3).getReg();
11049   DebugLoc dl = MI.getDebugLoc();
11050 
11051   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11052   MachineBasicBlock *loop2MBB =
11053     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11054   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11055   F->insert(It, loopMBB);
11056   if (CmpOpcode)
11057     F->insert(It, loop2MBB);
11058   F->insert(It, exitMBB);
11059   exitMBB->splice(exitMBB->begin(), BB,
11060                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11061   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11062 
11063   MachineRegisterInfo &RegInfo = F->getRegInfo();
11064   Register TmpReg = (!BinOpcode) ? incr :
11065     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11066                                            : &PPC::GPRCRegClass);
11067 
11068   //  thisMBB:
11069   //   ...
11070   //   fallthrough --> loopMBB
11071   BB->addSuccessor(loopMBB);
11072 
11073   //  loopMBB:
11074   //   l[wd]arx dest, ptr
11075   //   add r0, dest, incr
11076   //   st[wd]cx. r0, ptr
11077   //   bne- loopMBB
11078   //   fallthrough --> exitMBB
11079 
11080   // For max/min...
11081   //  loopMBB:
11082   //   l[wd]arx dest, ptr
11083   //   cmpl?[wd] incr, dest
11084   //   bgt exitMBB
11085   //  loop2MBB:
11086   //   st[wd]cx. dest, ptr
11087   //   bne- loopMBB
11088   //   fallthrough --> exitMBB
11089 
11090   BB = loopMBB;
11091   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11092     .addReg(ptrA).addReg(ptrB);
11093   if (BinOpcode)
11094     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11095   if (CmpOpcode) {
11096     // Signed comparisons of byte or halfword values must be sign-extended.
11097     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11098       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11099       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11100               ExtReg).addReg(dest);
11101       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11102         .addReg(incr).addReg(ExtReg);
11103     } else
11104       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11105         .addReg(incr).addReg(dest);
11106 
11107     BuildMI(BB, dl, TII->get(PPC::BCC))
11108       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11109     BB->addSuccessor(loop2MBB);
11110     BB->addSuccessor(exitMBB);
11111     BB = loop2MBB;
11112   }
11113   BuildMI(BB, dl, TII->get(StoreMnemonic))
11114     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11115   BuildMI(BB, dl, TII->get(PPC::BCC))
11116     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11117   BB->addSuccessor(loopMBB);
11118   BB->addSuccessor(exitMBB);
11119 
11120   //  exitMBB:
11121   //   ...
11122   BB = exitMBB;
11123   return BB;
11124 }
11125 
11126 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11127     MachineInstr &MI, MachineBasicBlock *BB,
11128     bool is8bit, // operation
11129     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11130   // If we support part-word atomic mnemonics, just use them
11131   if (Subtarget.hasPartwordAtomics())
11132     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11133                             CmpPred);
11134 
11135   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11136   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11137   // In 64 bit mode we have to use 64 bits for addresses, even though the
11138   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11139   // registers without caring whether they're 32 or 64, but here we're
11140   // doing actual arithmetic on the addresses.
11141   bool is64bit = Subtarget.isPPC64();
11142   bool isLittleEndian = Subtarget.isLittleEndian();
11143   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11144 
11145   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11146   MachineFunction *F = BB->getParent();
11147   MachineFunction::iterator It = ++BB->getIterator();
11148 
11149   Register dest = MI.getOperand(0).getReg();
11150   Register ptrA = MI.getOperand(1).getReg();
11151   Register ptrB = MI.getOperand(2).getReg();
11152   Register incr = MI.getOperand(3).getReg();
11153   DebugLoc dl = MI.getDebugLoc();
11154 
11155   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11156   MachineBasicBlock *loop2MBB =
11157       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11158   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11159   F->insert(It, loopMBB);
11160   if (CmpOpcode)
11161     F->insert(It, loop2MBB);
11162   F->insert(It, exitMBB);
11163   exitMBB->splice(exitMBB->begin(), BB,
11164                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11165   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11166 
11167   MachineRegisterInfo &RegInfo = F->getRegInfo();
11168   const TargetRegisterClass *RC =
11169       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11170   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11171 
11172   Register PtrReg = RegInfo.createVirtualRegister(RC);
11173   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11174   Register ShiftReg =
11175       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11176   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11177   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11178   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11179   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11180   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11181   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11182   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11183   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11184   Register Ptr1Reg;
11185   Register TmpReg =
11186       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11187 
11188   //  thisMBB:
11189   //   ...
11190   //   fallthrough --> loopMBB
11191   BB->addSuccessor(loopMBB);
11192 
11193   // The 4-byte load must be aligned, while a char or short may be
11194   // anywhere in the word.  Hence all this nasty bookkeeping code.
11195   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11196   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11197   //   xori shift, shift1, 24 [16]
11198   //   rlwinm ptr, ptr1, 0, 0, 29
11199   //   slw incr2, incr, shift
11200   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11201   //   slw mask, mask2, shift
11202   //  loopMBB:
11203   //   lwarx tmpDest, ptr
11204   //   add tmp, tmpDest, incr2
11205   //   andc tmp2, tmpDest, mask
11206   //   and tmp3, tmp, mask
11207   //   or tmp4, tmp3, tmp2
11208   //   stwcx. tmp4, ptr
11209   //   bne- loopMBB
11210   //   fallthrough --> exitMBB
11211   //   srw dest, tmpDest, shift
11212   if (ptrA != ZeroReg) {
11213     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11214     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11215         .addReg(ptrA)
11216         .addReg(ptrB);
11217   } else {
11218     Ptr1Reg = ptrB;
11219   }
11220   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11221   // mode.
11222   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11223       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11224       .addImm(3)
11225       .addImm(27)
11226       .addImm(is8bit ? 28 : 27);
11227   if (!isLittleEndian)
11228     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11229         .addReg(Shift1Reg)
11230         .addImm(is8bit ? 24 : 16);
11231   if (is64bit)
11232     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11233         .addReg(Ptr1Reg)
11234         .addImm(0)
11235         .addImm(61);
11236   else
11237     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11238         .addReg(Ptr1Reg)
11239         .addImm(0)
11240         .addImm(0)
11241         .addImm(29);
11242   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11243   if (is8bit)
11244     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11245   else {
11246     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11247     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11248         .addReg(Mask3Reg)
11249         .addImm(65535);
11250   }
11251   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11252       .addReg(Mask2Reg)
11253       .addReg(ShiftReg);
11254 
11255   BB = loopMBB;
11256   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11257       .addReg(ZeroReg)
11258       .addReg(PtrReg);
11259   if (BinOpcode)
11260     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11261         .addReg(Incr2Reg)
11262         .addReg(TmpDestReg);
11263   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11264       .addReg(TmpDestReg)
11265       .addReg(MaskReg);
11266   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11267   if (CmpOpcode) {
11268     // For unsigned comparisons, we can directly compare the shifted values.
11269     // For signed comparisons we shift and sign extend.
11270     Register SReg = RegInfo.createVirtualRegister(GPRC);
11271     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11272         .addReg(TmpDestReg)
11273         .addReg(MaskReg);
11274     unsigned ValueReg = SReg;
11275     unsigned CmpReg = Incr2Reg;
11276     if (CmpOpcode == PPC::CMPW) {
11277       ValueReg = RegInfo.createVirtualRegister(GPRC);
11278       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11279           .addReg(SReg)
11280           .addReg(ShiftReg);
11281       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11282       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11283           .addReg(ValueReg);
11284       ValueReg = ValueSReg;
11285       CmpReg = incr;
11286     }
11287     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11288         .addReg(CmpReg)
11289         .addReg(ValueReg);
11290     BuildMI(BB, dl, TII->get(PPC::BCC))
11291         .addImm(CmpPred)
11292         .addReg(PPC::CR0)
11293         .addMBB(exitMBB);
11294     BB->addSuccessor(loop2MBB);
11295     BB->addSuccessor(exitMBB);
11296     BB = loop2MBB;
11297   }
11298   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11299   BuildMI(BB, dl, TII->get(PPC::STWCX))
11300       .addReg(Tmp4Reg)
11301       .addReg(ZeroReg)
11302       .addReg(PtrReg);
11303   BuildMI(BB, dl, TII->get(PPC::BCC))
11304       .addImm(PPC::PRED_NE)
11305       .addReg(PPC::CR0)
11306       .addMBB(loopMBB);
11307   BB->addSuccessor(loopMBB);
11308   BB->addSuccessor(exitMBB);
11309 
11310   //  exitMBB:
11311   //   ...
11312   BB = exitMBB;
11313   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11314       .addReg(TmpDestReg)
11315       .addReg(ShiftReg);
11316   return BB;
11317 }
11318 
11319 llvm::MachineBasicBlock *
11320 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11321                                     MachineBasicBlock *MBB) const {
11322   DebugLoc DL = MI.getDebugLoc();
11323   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11324   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11325 
11326   MachineFunction *MF = MBB->getParent();
11327   MachineRegisterInfo &MRI = MF->getRegInfo();
11328 
11329   const BasicBlock *BB = MBB->getBasicBlock();
11330   MachineFunction::iterator I = ++MBB->getIterator();
11331 
11332   Register DstReg = MI.getOperand(0).getReg();
11333   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11334   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11335   Register mainDstReg = MRI.createVirtualRegister(RC);
11336   Register restoreDstReg = MRI.createVirtualRegister(RC);
11337 
11338   MVT PVT = getPointerTy(MF->getDataLayout());
11339   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11340          "Invalid Pointer Size!");
11341   // For v = setjmp(buf), we generate
11342   //
11343   // thisMBB:
11344   //  SjLjSetup mainMBB
11345   //  bl mainMBB
11346   //  v_restore = 1
11347   //  b sinkMBB
11348   //
11349   // mainMBB:
11350   //  buf[LabelOffset] = LR
11351   //  v_main = 0
11352   //
11353   // sinkMBB:
11354   //  v = phi(main, restore)
11355   //
11356 
11357   MachineBasicBlock *thisMBB = MBB;
11358   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11359   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11360   MF->insert(I, mainMBB);
11361   MF->insert(I, sinkMBB);
11362 
11363   MachineInstrBuilder MIB;
11364 
11365   // Transfer the remainder of BB and its successor edges to sinkMBB.
11366   sinkMBB->splice(sinkMBB->begin(), MBB,
11367                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11368   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11369 
11370   // Note that the structure of the jmp_buf used here is not compatible
11371   // with that used by libc, and is not designed to be. Specifically, it
11372   // stores only those 'reserved' registers that LLVM does not otherwise
11373   // understand how to spill. Also, by convention, by the time this
11374   // intrinsic is called, Clang has already stored the frame address in the
11375   // first slot of the buffer and stack address in the third. Following the
11376   // X86 target code, we'll store the jump address in the second slot. We also
11377   // need to save the TOC pointer (R2) to handle jumps between shared
11378   // libraries, and that will be stored in the fourth slot. The thread
11379   // identifier (R13) is not affected.
11380 
11381   // thisMBB:
11382   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11383   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11384   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11385 
11386   // Prepare IP either in reg.
11387   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11388   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11389   Register BufReg = MI.getOperand(1).getReg();
11390 
11391   if (Subtarget.is64BitELFABI()) {
11392     setUsesTOCBasePtr(*MBB->getParent());
11393     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11394               .addReg(PPC::X2)
11395               .addImm(TOCOffset)
11396               .addReg(BufReg)
11397               .cloneMemRefs(MI);
11398   }
11399 
11400   // Naked functions never have a base pointer, and so we use r1. For all
11401   // other functions, this decision must be delayed until during PEI.
11402   unsigned BaseReg;
11403   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11404     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11405   else
11406     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11407 
11408   MIB = BuildMI(*thisMBB, MI, DL,
11409                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11410             .addReg(BaseReg)
11411             .addImm(BPOffset)
11412             .addReg(BufReg)
11413             .cloneMemRefs(MI);
11414 
11415   // Setup
11416   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11417   MIB.addRegMask(TRI->getNoPreservedMask());
11418 
11419   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11420 
11421   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11422           .addMBB(mainMBB);
11423   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11424 
11425   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11426   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11427 
11428   // mainMBB:
11429   //  mainDstReg = 0
11430   MIB =
11431       BuildMI(mainMBB, DL,
11432               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11433 
11434   // Store IP
11435   if (Subtarget.isPPC64()) {
11436     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11437             .addReg(LabelReg)
11438             .addImm(LabelOffset)
11439             .addReg(BufReg);
11440   } else {
11441     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11442             .addReg(LabelReg)
11443             .addImm(LabelOffset)
11444             .addReg(BufReg);
11445   }
11446   MIB.cloneMemRefs(MI);
11447 
11448   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11449   mainMBB->addSuccessor(sinkMBB);
11450 
11451   // sinkMBB:
11452   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11453           TII->get(PPC::PHI), DstReg)
11454     .addReg(mainDstReg).addMBB(mainMBB)
11455     .addReg(restoreDstReg).addMBB(thisMBB);
11456 
11457   MI.eraseFromParent();
11458   return sinkMBB;
11459 }
11460 
11461 MachineBasicBlock *
11462 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11463                                      MachineBasicBlock *MBB) const {
11464   DebugLoc DL = MI.getDebugLoc();
11465   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11466 
11467   MachineFunction *MF = MBB->getParent();
11468   MachineRegisterInfo &MRI = MF->getRegInfo();
11469 
11470   MVT PVT = getPointerTy(MF->getDataLayout());
11471   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11472          "Invalid Pointer Size!");
11473 
11474   const TargetRegisterClass *RC =
11475     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11476   Register Tmp = MRI.createVirtualRegister(RC);
11477   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11478   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11479   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11480   unsigned BP =
11481       (PVT == MVT::i64)
11482           ? PPC::X30
11483           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11484                                                               : PPC::R30);
11485 
11486   MachineInstrBuilder MIB;
11487 
11488   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11489   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11490   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11491   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11492 
11493   Register BufReg = MI.getOperand(0).getReg();
11494 
11495   // Reload FP (the jumped-to function may not have had a
11496   // frame pointer, and if so, then its r31 will be restored
11497   // as necessary).
11498   if (PVT == MVT::i64) {
11499     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11500             .addImm(0)
11501             .addReg(BufReg);
11502   } else {
11503     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11504             .addImm(0)
11505             .addReg(BufReg);
11506   }
11507   MIB.cloneMemRefs(MI);
11508 
11509   // Reload IP
11510   if (PVT == MVT::i64) {
11511     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11512             .addImm(LabelOffset)
11513             .addReg(BufReg);
11514   } else {
11515     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11516             .addImm(LabelOffset)
11517             .addReg(BufReg);
11518   }
11519   MIB.cloneMemRefs(MI);
11520 
11521   // Reload SP
11522   if (PVT == MVT::i64) {
11523     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11524             .addImm(SPOffset)
11525             .addReg(BufReg);
11526   } else {
11527     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11528             .addImm(SPOffset)
11529             .addReg(BufReg);
11530   }
11531   MIB.cloneMemRefs(MI);
11532 
11533   // Reload BP
11534   if (PVT == MVT::i64) {
11535     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11536             .addImm(BPOffset)
11537             .addReg(BufReg);
11538   } else {
11539     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11540             .addImm(BPOffset)
11541             .addReg(BufReg);
11542   }
11543   MIB.cloneMemRefs(MI);
11544 
11545   // Reload TOC
11546   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11547     setUsesTOCBasePtr(*MBB->getParent());
11548     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11549               .addImm(TOCOffset)
11550               .addReg(BufReg)
11551               .cloneMemRefs(MI);
11552   }
11553 
11554   // Jump
11555   BuildMI(*MBB, MI, DL,
11556           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11557   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11558 
11559   MI.eraseFromParent();
11560   return MBB;
11561 }
11562 
11563 MachineBasicBlock *
11564 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11565                                                MachineBasicBlock *BB) const {
11566   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11567       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11568     if (Subtarget.is64BitELFABI() &&
11569         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11570         !Subtarget.isUsingPCRelativeCalls()) {
11571       // Call lowering should have added an r2 operand to indicate a dependence
11572       // on the TOC base pointer value. It can't however, because there is no
11573       // way to mark the dependence as implicit there, and so the stackmap code
11574       // will confuse it with a regular operand. Instead, add the dependence
11575       // here.
11576       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11577     }
11578 
11579     return emitPatchPoint(MI, BB);
11580   }
11581 
11582   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11583       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11584     return emitEHSjLjSetJmp(MI, BB);
11585   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11586              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11587     return emitEHSjLjLongJmp(MI, BB);
11588   }
11589 
11590   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11591 
11592   // To "insert" these instructions we actually have to insert their
11593   // control-flow patterns.
11594   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11595   MachineFunction::iterator It = ++BB->getIterator();
11596 
11597   MachineFunction *F = BB->getParent();
11598 
11599   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11600       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11601       MI.getOpcode() == PPC::SELECT_I8) {
11602     SmallVector<MachineOperand, 2> Cond;
11603     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11604         MI.getOpcode() == PPC::SELECT_CC_I8)
11605       Cond.push_back(MI.getOperand(4));
11606     else
11607       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11608     Cond.push_back(MI.getOperand(1));
11609 
11610     DebugLoc dl = MI.getDebugLoc();
11611     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11612                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11613   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11614              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11615              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11616              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
11617              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
11618              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
11619              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11620              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11621              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11622              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11623              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11624              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11625              MI.getOpcode() == PPC::SELECT_F4 ||
11626              MI.getOpcode() == PPC::SELECT_F8 ||
11627              MI.getOpcode() == PPC::SELECT_F16 ||
11628              MI.getOpcode() == PPC::SELECT_QFRC ||
11629              MI.getOpcode() == PPC::SELECT_QSRC ||
11630              MI.getOpcode() == PPC::SELECT_QBRC ||
11631              MI.getOpcode() == PPC::SELECT_SPE ||
11632              MI.getOpcode() == PPC::SELECT_SPE4 ||
11633              MI.getOpcode() == PPC::SELECT_VRRC ||
11634              MI.getOpcode() == PPC::SELECT_VSFRC ||
11635              MI.getOpcode() == PPC::SELECT_VSSRC ||
11636              MI.getOpcode() == PPC::SELECT_VSRC) {
11637     // The incoming instruction knows the destination vreg to set, the
11638     // condition code register to branch on, the true/false values to
11639     // select between, and a branch opcode to use.
11640 
11641     //  thisMBB:
11642     //  ...
11643     //   TrueVal = ...
11644     //   cmpTY ccX, r1, r2
11645     //   bCC copy1MBB
11646     //   fallthrough --> copy0MBB
11647     MachineBasicBlock *thisMBB = BB;
11648     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11649     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11650     DebugLoc dl = MI.getDebugLoc();
11651     F->insert(It, copy0MBB);
11652     F->insert(It, sinkMBB);
11653 
11654     // Transfer the remainder of BB and its successor edges to sinkMBB.
11655     sinkMBB->splice(sinkMBB->begin(), BB,
11656                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11657     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11658 
11659     // Next, add the true and fallthrough blocks as its successors.
11660     BB->addSuccessor(copy0MBB);
11661     BB->addSuccessor(sinkMBB);
11662 
11663     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11664         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11665         MI.getOpcode() == PPC::SELECT_F16 ||
11666         MI.getOpcode() == PPC::SELECT_SPE4 ||
11667         MI.getOpcode() == PPC::SELECT_SPE ||
11668         MI.getOpcode() == PPC::SELECT_QFRC ||
11669         MI.getOpcode() == PPC::SELECT_QSRC ||
11670         MI.getOpcode() == PPC::SELECT_QBRC ||
11671         MI.getOpcode() == PPC::SELECT_VRRC ||
11672         MI.getOpcode() == PPC::SELECT_VSFRC ||
11673         MI.getOpcode() == PPC::SELECT_VSSRC ||
11674         MI.getOpcode() == PPC::SELECT_VSRC) {
11675       BuildMI(BB, dl, TII->get(PPC::BC))
11676           .addReg(MI.getOperand(1).getReg())
11677           .addMBB(sinkMBB);
11678     } else {
11679       unsigned SelectPred = MI.getOperand(4).getImm();
11680       BuildMI(BB, dl, TII->get(PPC::BCC))
11681           .addImm(SelectPred)
11682           .addReg(MI.getOperand(1).getReg())
11683           .addMBB(sinkMBB);
11684     }
11685 
11686     //  copy0MBB:
11687     //   %FalseValue = ...
11688     //   # fallthrough to sinkMBB
11689     BB = copy0MBB;
11690 
11691     // Update machine-CFG edges
11692     BB->addSuccessor(sinkMBB);
11693 
11694     //  sinkMBB:
11695     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11696     //  ...
11697     BB = sinkMBB;
11698     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11699         .addReg(MI.getOperand(3).getReg())
11700         .addMBB(copy0MBB)
11701         .addReg(MI.getOperand(2).getReg())
11702         .addMBB(thisMBB);
11703   } else if (MI.getOpcode() == PPC::ReadTB) {
11704     // To read the 64-bit time-base register on a 32-bit target, we read the
11705     // two halves. Should the counter have wrapped while it was being read, we
11706     // need to try again.
11707     // ...
11708     // readLoop:
11709     // mfspr Rx,TBU # load from TBU
11710     // mfspr Ry,TB  # load from TB
11711     // mfspr Rz,TBU # load from TBU
11712     // cmpw crX,Rx,Rz # check if 'old'='new'
11713     // bne readLoop   # branch if they're not equal
11714     // ...
11715 
11716     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11717     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11718     DebugLoc dl = MI.getDebugLoc();
11719     F->insert(It, readMBB);
11720     F->insert(It, sinkMBB);
11721 
11722     // Transfer the remainder of BB and its successor edges to sinkMBB.
11723     sinkMBB->splice(sinkMBB->begin(), BB,
11724                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11725     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11726 
11727     BB->addSuccessor(readMBB);
11728     BB = readMBB;
11729 
11730     MachineRegisterInfo &RegInfo = F->getRegInfo();
11731     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11732     Register LoReg = MI.getOperand(0).getReg();
11733     Register HiReg = MI.getOperand(1).getReg();
11734 
11735     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11736     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11737     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11738 
11739     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11740 
11741     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11742         .addReg(HiReg)
11743         .addReg(ReadAgainReg);
11744     BuildMI(BB, dl, TII->get(PPC::BCC))
11745         .addImm(PPC::PRED_NE)
11746         .addReg(CmpReg)
11747         .addMBB(readMBB);
11748 
11749     BB->addSuccessor(readMBB);
11750     BB->addSuccessor(sinkMBB);
11751   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11752     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11753   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11754     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11755   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11756     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11757   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11758     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11759 
11760   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11761     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11762   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11763     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11764   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11765     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11766   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11767     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11768 
11769   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11770     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11771   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11772     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11773   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11774     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11775   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11776     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11777 
11778   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11779     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11780   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11781     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11782   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11783     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11784   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11785     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11786 
11787   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11788     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11789   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11790     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11791   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11792     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11793   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11794     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11795 
11796   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11797     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11798   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11799     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11800   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11801     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11802   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11803     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11804 
11805   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11806     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11807   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11808     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11809   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11810     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11811   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11812     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11813 
11814   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11815     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11816   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11817     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11818   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11819     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11820   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11821     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11822 
11823   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11824     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11825   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11826     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11827   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11828     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11829   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11830     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11831 
11832   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11833     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11834   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11835     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11836   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11837     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11838   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11839     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11840 
11841   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11842     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11843   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11844     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11845   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11846     BB = EmitAtomicBinary(MI, BB, 4, 0);
11847   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11848     BB = EmitAtomicBinary(MI, BB, 8, 0);
11849   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11850            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11851            (Subtarget.hasPartwordAtomics() &&
11852             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11853            (Subtarget.hasPartwordAtomics() &&
11854             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11855     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11856 
11857     auto LoadMnemonic = PPC::LDARX;
11858     auto StoreMnemonic = PPC::STDCX;
11859     switch (MI.getOpcode()) {
11860     default:
11861       llvm_unreachable("Compare and swap of unknown size");
11862     case PPC::ATOMIC_CMP_SWAP_I8:
11863       LoadMnemonic = PPC::LBARX;
11864       StoreMnemonic = PPC::STBCX;
11865       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11866       break;
11867     case PPC::ATOMIC_CMP_SWAP_I16:
11868       LoadMnemonic = PPC::LHARX;
11869       StoreMnemonic = PPC::STHCX;
11870       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11871       break;
11872     case PPC::ATOMIC_CMP_SWAP_I32:
11873       LoadMnemonic = PPC::LWARX;
11874       StoreMnemonic = PPC::STWCX;
11875       break;
11876     case PPC::ATOMIC_CMP_SWAP_I64:
11877       LoadMnemonic = PPC::LDARX;
11878       StoreMnemonic = PPC::STDCX;
11879       break;
11880     }
11881     Register dest = MI.getOperand(0).getReg();
11882     Register ptrA = MI.getOperand(1).getReg();
11883     Register ptrB = MI.getOperand(2).getReg();
11884     Register oldval = MI.getOperand(3).getReg();
11885     Register newval = MI.getOperand(4).getReg();
11886     DebugLoc dl = MI.getDebugLoc();
11887 
11888     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11889     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11890     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11891     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11892     F->insert(It, loop1MBB);
11893     F->insert(It, loop2MBB);
11894     F->insert(It, midMBB);
11895     F->insert(It, exitMBB);
11896     exitMBB->splice(exitMBB->begin(), BB,
11897                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11898     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11899 
11900     //  thisMBB:
11901     //   ...
11902     //   fallthrough --> loopMBB
11903     BB->addSuccessor(loop1MBB);
11904 
11905     // loop1MBB:
11906     //   l[bhwd]arx dest, ptr
11907     //   cmp[wd] dest, oldval
11908     //   bne- midMBB
11909     // loop2MBB:
11910     //   st[bhwd]cx. newval, ptr
11911     //   bne- loopMBB
11912     //   b exitBB
11913     // midMBB:
11914     //   st[bhwd]cx. dest, ptr
11915     // exitBB:
11916     BB = loop1MBB;
11917     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11918     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11919         .addReg(oldval)
11920         .addReg(dest);
11921     BuildMI(BB, dl, TII->get(PPC::BCC))
11922         .addImm(PPC::PRED_NE)
11923         .addReg(PPC::CR0)
11924         .addMBB(midMBB);
11925     BB->addSuccessor(loop2MBB);
11926     BB->addSuccessor(midMBB);
11927 
11928     BB = loop2MBB;
11929     BuildMI(BB, dl, TII->get(StoreMnemonic))
11930         .addReg(newval)
11931         .addReg(ptrA)
11932         .addReg(ptrB);
11933     BuildMI(BB, dl, TII->get(PPC::BCC))
11934         .addImm(PPC::PRED_NE)
11935         .addReg(PPC::CR0)
11936         .addMBB(loop1MBB);
11937     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11938     BB->addSuccessor(loop1MBB);
11939     BB->addSuccessor(exitMBB);
11940 
11941     BB = midMBB;
11942     BuildMI(BB, dl, TII->get(StoreMnemonic))
11943         .addReg(dest)
11944         .addReg(ptrA)
11945         .addReg(ptrB);
11946     BB->addSuccessor(exitMBB);
11947 
11948     //  exitMBB:
11949     //   ...
11950     BB = exitMBB;
11951   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11952              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11953     // We must use 64-bit registers for addresses when targeting 64-bit,
11954     // since we're actually doing arithmetic on them.  Other registers
11955     // can be 32-bit.
11956     bool is64bit = Subtarget.isPPC64();
11957     bool isLittleEndian = Subtarget.isLittleEndian();
11958     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11959 
11960     Register dest = MI.getOperand(0).getReg();
11961     Register ptrA = MI.getOperand(1).getReg();
11962     Register ptrB = MI.getOperand(2).getReg();
11963     Register oldval = MI.getOperand(3).getReg();
11964     Register newval = MI.getOperand(4).getReg();
11965     DebugLoc dl = MI.getDebugLoc();
11966 
11967     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11968     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11969     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11970     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11971     F->insert(It, loop1MBB);
11972     F->insert(It, loop2MBB);
11973     F->insert(It, midMBB);
11974     F->insert(It, exitMBB);
11975     exitMBB->splice(exitMBB->begin(), BB,
11976                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11977     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11978 
11979     MachineRegisterInfo &RegInfo = F->getRegInfo();
11980     const TargetRegisterClass *RC =
11981         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11982     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11983 
11984     Register PtrReg = RegInfo.createVirtualRegister(RC);
11985     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11986     Register ShiftReg =
11987         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11988     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11989     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11990     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11991     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11992     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11993     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11994     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11995     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11996     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11997     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11998     Register Ptr1Reg;
11999     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12000     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12001     //  thisMBB:
12002     //   ...
12003     //   fallthrough --> loopMBB
12004     BB->addSuccessor(loop1MBB);
12005 
12006     // The 4-byte load must be aligned, while a char or short may be
12007     // anywhere in the word.  Hence all this nasty bookkeeping code.
12008     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12009     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12010     //   xori shift, shift1, 24 [16]
12011     //   rlwinm ptr, ptr1, 0, 0, 29
12012     //   slw newval2, newval, shift
12013     //   slw oldval2, oldval,shift
12014     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12015     //   slw mask, mask2, shift
12016     //   and newval3, newval2, mask
12017     //   and oldval3, oldval2, mask
12018     // loop1MBB:
12019     //   lwarx tmpDest, ptr
12020     //   and tmp, tmpDest, mask
12021     //   cmpw tmp, oldval3
12022     //   bne- midMBB
12023     // loop2MBB:
12024     //   andc tmp2, tmpDest, mask
12025     //   or tmp4, tmp2, newval3
12026     //   stwcx. tmp4, ptr
12027     //   bne- loop1MBB
12028     //   b exitBB
12029     // midMBB:
12030     //   stwcx. tmpDest, ptr
12031     // exitBB:
12032     //   srw dest, tmpDest, shift
12033     if (ptrA != ZeroReg) {
12034       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12035       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12036           .addReg(ptrA)
12037           .addReg(ptrB);
12038     } else {
12039       Ptr1Reg = ptrB;
12040     }
12041 
12042     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12043     // mode.
12044     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12045         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12046         .addImm(3)
12047         .addImm(27)
12048         .addImm(is8bit ? 28 : 27);
12049     if (!isLittleEndian)
12050       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12051           .addReg(Shift1Reg)
12052           .addImm(is8bit ? 24 : 16);
12053     if (is64bit)
12054       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12055           .addReg(Ptr1Reg)
12056           .addImm(0)
12057           .addImm(61);
12058     else
12059       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12060           .addReg(Ptr1Reg)
12061           .addImm(0)
12062           .addImm(0)
12063           .addImm(29);
12064     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12065         .addReg(newval)
12066         .addReg(ShiftReg);
12067     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12068         .addReg(oldval)
12069         .addReg(ShiftReg);
12070     if (is8bit)
12071       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12072     else {
12073       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12074       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12075           .addReg(Mask3Reg)
12076           .addImm(65535);
12077     }
12078     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12079         .addReg(Mask2Reg)
12080         .addReg(ShiftReg);
12081     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12082         .addReg(NewVal2Reg)
12083         .addReg(MaskReg);
12084     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12085         .addReg(OldVal2Reg)
12086         .addReg(MaskReg);
12087 
12088     BB = loop1MBB;
12089     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12090         .addReg(ZeroReg)
12091         .addReg(PtrReg);
12092     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12093         .addReg(TmpDestReg)
12094         .addReg(MaskReg);
12095     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12096         .addReg(TmpReg)
12097         .addReg(OldVal3Reg);
12098     BuildMI(BB, dl, TII->get(PPC::BCC))
12099         .addImm(PPC::PRED_NE)
12100         .addReg(PPC::CR0)
12101         .addMBB(midMBB);
12102     BB->addSuccessor(loop2MBB);
12103     BB->addSuccessor(midMBB);
12104 
12105     BB = loop2MBB;
12106     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12107         .addReg(TmpDestReg)
12108         .addReg(MaskReg);
12109     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12110         .addReg(Tmp2Reg)
12111         .addReg(NewVal3Reg);
12112     BuildMI(BB, dl, TII->get(PPC::STWCX))
12113         .addReg(Tmp4Reg)
12114         .addReg(ZeroReg)
12115         .addReg(PtrReg);
12116     BuildMI(BB, dl, TII->get(PPC::BCC))
12117         .addImm(PPC::PRED_NE)
12118         .addReg(PPC::CR0)
12119         .addMBB(loop1MBB);
12120     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12121     BB->addSuccessor(loop1MBB);
12122     BB->addSuccessor(exitMBB);
12123 
12124     BB = midMBB;
12125     BuildMI(BB, dl, TII->get(PPC::STWCX))
12126         .addReg(TmpDestReg)
12127         .addReg(ZeroReg)
12128         .addReg(PtrReg);
12129     BB->addSuccessor(exitMBB);
12130 
12131     //  exitMBB:
12132     //   ...
12133     BB = exitMBB;
12134     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12135         .addReg(TmpReg)
12136         .addReg(ShiftReg);
12137   } else if (MI.getOpcode() == PPC::FADDrtz) {
12138     // This pseudo performs an FADD with rounding mode temporarily forced
12139     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12140     // is not modeled at the SelectionDAG level.
12141     Register Dest = MI.getOperand(0).getReg();
12142     Register Src1 = MI.getOperand(1).getReg();
12143     Register Src2 = MI.getOperand(2).getReg();
12144     DebugLoc dl = MI.getDebugLoc();
12145 
12146     MachineRegisterInfo &RegInfo = F->getRegInfo();
12147     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12148 
12149     // Save FPSCR value.
12150     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12151 
12152     // Set rounding mode to round-to-zero.
12153     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
12154     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
12155 
12156     // Perform addition.
12157     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
12158 
12159     // Restore FPSCR value.
12160     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12161   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12162              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12163              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12164              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12165     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12166                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12167                           ? PPC::ANDI8_rec
12168                           : PPC::ANDI_rec;
12169     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12170                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12171 
12172     MachineRegisterInfo &RegInfo = F->getRegInfo();
12173     Register Dest = RegInfo.createVirtualRegister(
12174         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12175 
12176     DebugLoc Dl = MI.getDebugLoc();
12177     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12178         .addReg(MI.getOperand(1).getReg())
12179         .addImm(1);
12180     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12181             MI.getOperand(0).getReg())
12182         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12183   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12184     DebugLoc Dl = MI.getDebugLoc();
12185     MachineRegisterInfo &RegInfo = F->getRegInfo();
12186     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12187     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12188     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12189             MI.getOperand(0).getReg())
12190         .addReg(CRReg);
12191   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12192     DebugLoc Dl = MI.getDebugLoc();
12193     unsigned Imm = MI.getOperand(1).getImm();
12194     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12195     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12196             MI.getOperand(0).getReg())
12197         .addReg(PPC::CR0EQ);
12198   } else if (MI.getOpcode() == PPC::SETRNDi) {
12199     DebugLoc dl = MI.getDebugLoc();
12200     Register OldFPSCRReg = MI.getOperand(0).getReg();
12201 
12202     // Save FPSCR value.
12203     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12204 
12205     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12206     // the following settings:
12207     //   00 Round to nearest
12208     //   01 Round to 0
12209     //   10 Round to +inf
12210     //   11 Round to -inf
12211 
12212     // When the operand is immediate, using the two least significant bits of
12213     // the immediate to set the bits 62:63 of FPSCR.
12214     unsigned Mode = MI.getOperand(1).getImm();
12215     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12216       .addImm(31);
12217 
12218     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12219       .addImm(30);
12220   } else if (MI.getOpcode() == PPC::SETRND) {
12221     DebugLoc dl = MI.getDebugLoc();
12222 
12223     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12224     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12225     // If the target doesn't have DirectMove, we should use stack to do the
12226     // conversion, because the target doesn't have the instructions like mtvsrd
12227     // or mfvsrd to do this conversion directly.
12228     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12229       if (Subtarget.hasDirectMove()) {
12230         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12231           .addReg(SrcReg);
12232       } else {
12233         // Use stack to do the register copy.
12234         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12235         MachineRegisterInfo &RegInfo = F->getRegInfo();
12236         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12237         if (RC == &PPC::F8RCRegClass) {
12238           // Copy register from F8RCRegClass to G8RCRegclass.
12239           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12240                  "Unsupported RegClass.");
12241 
12242           StoreOp = PPC::STFD;
12243           LoadOp = PPC::LD;
12244         } else {
12245           // Copy register from G8RCRegClass to F8RCRegclass.
12246           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12247                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12248                  "Unsupported RegClass.");
12249         }
12250 
12251         MachineFrameInfo &MFI = F->getFrameInfo();
12252         int FrameIdx = MFI.CreateStackObject(8, 8, false);
12253 
12254         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12255             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12256             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12257             MFI.getObjectAlign(FrameIdx));
12258 
12259         // Store the SrcReg into the stack.
12260         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12261           .addReg(SrcReg)
12262           .addImm(0)
12263           .addFrameIndex(FrameIdx)
12264           .addMemOperand(MMOStore);
12265 
12266         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12267             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12268             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12269             MFI.getObjectAlign(FrameIdx));
12270 
12271         // Load from the stack where SrcReg is stored, and save to DestReg,
12272         // so we have done the RegClass conversion from RegClass::SrcReg to
12273         // RegClass::DestReg.
12274         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12275           .addImm(0)
12276           .addFrameIndex(FrameIdx)
12277           .addMemOperand(MMOLoad);
12278       }
12279     };
12280 
12281     Register OldFPSCRReg = MI.getOperand(0).getReg();
12282 
12283     // Save FPSCR value.
12284     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12285 
12286     // When the operand is gprc register, use two least significant bits of the
12287     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12288     //
12289     // copy OldFPSCRTmpReg, OldFPSCRReg
12290     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12291     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12292     // copy NewFPSCRReg, NewFPSCRTmpReg
12293     // mtfsf 255, NewFPSCRReg
12294     MachineOperand SrcOp = MI.getOperand(1);
12295     MachineRegisterInfo &RegInfo = F->getRegInfo();
12296     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12297 
12298     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12299 
12300     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12301     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12302 
12303     // The first operand of INSERT_SUBREG should be a register which has
12304     // subregisters, we only care about its RegClass, so we should use an
12305     // IMPLICIT_DEF register.
12306     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12307     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12308       .addReg(ImDefReg)
12309       .add(SrcOp)
12310       .addImm(1);
12311 
12312     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12313     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12314       .addReg(OldFPSCRTmpReg)
12315       .addReg(ExtSrcReg)
12316       .addImm(0)
12317       .addImm(62);
12318 
12319     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12320     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12321 
12322     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12323     // bits of FPSCR.
12324     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12325       .addImm(255)
12326       .addReg(NewFPSCRReg)
12327       .addImm(0)
12328       .addImm(0);
12329   } else {
12330     llvm_unreachable("Unexpected instr type to insert");
12331   }
12332 
12333   MI.eraseFromParent(); // The pseudo instruction is gone now.
12334   return BB;
12335 }
12336 
12337 //===----------------------------------------------------------------------===//
12338 // Target Optimization Hooks
12339 //===----------------------------------------------------------------------===//
12340 
12341 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12342   // For the estimates, convergence is quadratic, so we essentially double the
12343   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12344   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12345   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12346   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12347   if (VT.getScalarType() == MVT::f64)
12348     RefinementSteps++;
12349   return RefinementSteps;
12350 }
12351 
12352 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12353                                            int Enabled, int &RefinementSteps,
12354                                            bool &UseOneConstNR,
12355                                            bool Reciprocal) const {
12356   EVT VT = Operand.getValueType();
12357   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12358       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12359       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12360       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12361       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12362       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12363     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12364       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12365 
12366     // The Newton-Raphson computation with a single constant does not provide
12367     // enough accuracy on some CPUs.
12368     UseOneConstNR = !Subtarget.needsTwoConstNR();
12369     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12370   }
12371   return SDValue();
12372 }
12373 
12374 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12375                                             int Enabled,
12376                                             int &RefinementSteps) const {
12377   EVT VT = Operand.getValueType();
12378   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12379       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12380       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12381       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12382       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12383       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12384     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12385       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12386     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12387   }
12388   return SDValue();
12389 }
12390 
12391 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12392   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12393   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12394   // enabled for division), this functionality is redundant with the default
12395   // combiner logic (once the division -> reciprocal/multiply transformation
12396   // has taken place). As a result, this matters more for older cores than for
12397   // newer ones.
12398 
12399   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12400   // reciprocal if there are two or more FDIVs (for embedded cores with only
12401   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12402   switch (Subtarget.getCPUDirective()) {
12403   default:
12404     return 3;
12405   case PPC::DIR_440:
12406   case PPC::DIR_A2:
12407   case PPC::DIR_E500:
12408   case PPC::DIR_E500mc:
12409   case PPC::DIR_E5500:
12410     return 2;
12411   }
12412 }
12413 
12414 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12415 // collapsed, and so we need to look through chains of them.
12416 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12417                                      int64_t& Offset, SelectionDAG &DAG) {
12418   if (DAG.isBaseWithConstantOffset(Loc)) {
12419     Base = Loc.getOperand(0);
12420     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12421 
12422     // The base might itself be a base plus an offset, and if so, accumulate
12423     // that as well.
12424     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12425   }
12426 }
12427 
12428 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12429                             unsigned Bytes, int Dist,
12430                             SelectionDAG &DAG) {
12431   if (VT.getSizeInBits() / 8 != Bytes)
12432     return false;
12433 
12434   SDValue BaseLoc = Base->getBasePtr();
12435   if (Loc.getOpcode() == ISD::FrameIndex) {
12436     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12437       return false;
12438     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12439     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12440     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12441     int FS  = MFI.getObjectSize(FI);
12442     int BFS = MFI.getObjectSize(BFI);
12443     if (FS != BFS || FS != (int)Bytes) return false;
12444     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12445   }
12446 
12447   SDValue Base1 = Loc, Base2 = BaseLoc;
12448   int64_t Offset1 = 0, Offset2 = 0;
12449   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12450   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12451   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12452     return true;
12453 
12454   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12455   const GlobalValue *GV1 = nullptr;
12456   const GlobalValue *GV2 = nullptr;
12457   Offset1 = 0;
12458   Offset2 = 0;
12459   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12460   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12461   if (isGA1 && isGA2 && GV1 == GV2)
12462     return Offset1 == (Offset2 + Dist*Bytes);
12463   return false;
12464 }
12465 
12466 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12467 // not enforce equality of the chain operands.
12468 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12469                             unsigned Bytes, int Dist,
12470                             SelectionDAG &DAG) {
12471   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12472     EVT VT = LS->getMemoryVT();
12473     SDValue Loc = LS->getBasePtr();
12474     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12475   }
12476 
12477   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12478     EVT VT;
12479     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12480     default: return false;
12481     case Intrinsic::ppc_qpx_qvlfd:
12482     case Intrinsic::ppc_qpx_qvlfda:
12483       VT = MVT::v4f64;
12484       break;
12485     case Intrinsic::ppc_qpx_qvlfs:
12486     case Intrinsic::ppc_qpx_qvlfsa:
12487       VT = MVT::v4f32;
12488       break;
12489     case Intrinsic::ppc_qpx_qvlfcd:
12490     case Intrinsic::ppc_qpx_qvlfcda:
12491       VT = MVT::v2f64;
12492       break;
12493     case Intrinsic::ppc_qpx_qvlfcs:
12494     case Intrinsic::ppc_qpx_qvlfcsa:
12495       VT = MVT::v2f32;
12496       break;
12497     case Intrinsic::ppc_qpx_qvlfiwa:
12498     case Intrinsic::ppc_qpx_qvlfiwz:
12499     case Intrinsic::ppc_altivec_lvx:
12500     case Intrinsic::ppc_altivec_lvxl:
12501     case Intrinsic::ppc_vsx_lxvw4x:
12502     case Intrinsic::ppc_vsx_lxvw4x_be:
12503       VT = MVT::v4i32;
12504       break;
12505     case Intrinsic::ppc_vsx_lxvd2x:
12506     case Intrinsic::ppc_vsx_lxvd2x_be:
12507       VT = MVT::v2f64;
12508       break;
12509     case Intrinsic::ppc_altivec_lvebx:
12510       VT = MVT::i8;
12511       break;
12512     case Intrinsic::ppc_altivec_lvehx:
12513       VT = MVT::i16;
12514       break;
12515     case Intrinsic::ppc_altivec_lvewx:
12516       VT = MVT::i32;
12517       break;
12518     }
12519 
12520     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12521   }
12522 
12523   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12524     EVT VT;
12525     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12526     default: return false;
12527     case Intrinsic::ppc_qpx_qvstfd:
12528     case Intrinsic::ppc_qpx_qvstfda:
12529       VT = MVT::v4f64;
12530       break;
12531     case Intrinsic::ppc_qpx_qvstfs:
12532     case Intrinsic::ppc_qpx_qvstfsa:
12533       VT = MVT::v4f32;
12534       break;
12535     case Intrinsic::ppc_qpx_qvstfcd:
12536     case Intrinsic::ppc_qpx_qvstfcda:
12537       VT = MVT::v2f64;
12538       break;
12539     case Intrinsic::ppc_qpx_qvstfcs:
12540     case Intrinsic::ppc_qpx_qvstfcsa:
12541       VT = MVT::v2f32;
12542       break;
12543     case Intrinsic::ppc_qpx_qvstfiw:
12544     case Intrinsic::ppc_qpx_qvstfiwa:
12545     case Intrinsic::ppc_altivec_stvx:
12546     case Intrinsic::ppc_altivec_stvxl:
12547     case Intrinsic::ppc_vsx_stxvw4x:
12548       VT = MVT::v4i32;
12549       break;
12550     case Intrinsic::ppc_vsx_stxvd2x:
12551       VT = MVT::v2f64;
12552       break;
12553     case Intrinsic::ppc_vsx_stxvw4x_be:
12554       VT = MVT::v4i32;
12555       break;
12556     case Intrinsic::ppc_vsx_stxvd2x_be:
12557       VT = MVT::v2f64;
12558       break;
12559     case Intrinsic::ppc_altivec_stvebx:
12560       VT = MVT::i8;
12561       break;
12562     case Intrinsic::ppc_altivec_stvehx:
12563       VT = MVT::i16;
12564       break;
12565     case Intrinsic::ppc_altivec_stvewx:
12566       VT = MVT::i32;
12567       break;
12568     }
12569 
12570     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12571   }
12572 
12573   return false;
12574 }
12575 
12576 // Return true is there is a nearyby consecutive load to the one provided
12577 // (regardless of alignment). We search up and down the chain, looking though
12578 // token factors and other loads (but nothing else). As a result, a true result
12579 // indicates that it is safe to create a new consecutive load adjacent to the
12580 // load provided.
12581 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12582   SDValue Chain = LD->getChain();
12583   EVT VT = LD->getMemoryVT();
12584 
12585   SmallSet<SDNode *, 16> LoadRoots;
12586   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12587   SmallSet<SDNode *, 16> Visited;
12588 
12589   // First, search up the chain, branching to follow all token-factor operands.
12590   // If we find a consecutive load, then we're done, otherwise, record all
12591   // nodes just above the top-level loads and token factors.
12592   while (!Queue.empty()) {
12593     SDNode *ChainNext = Queue.pop_back_val();
12594     if (!Visited.insert(ChainNext).second)
12595       continue;
12596 
12597     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12598       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12599         return true;
12600 
12601       if (!Visited.count(ChainLD->getChain().getNode()))
12602         Queue.push_back(ChainLD->getChain().getNode());
12603     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12604       for (const SDUse &O : ChainNext->ops())
12605         if (!Visited.count(O.getNode()))
12606           Queue.push_back(O.getNode());
12607     } else
12608       LoadRoots.insert(ChainNext);
12609   }
12610 
12611   // Second, search down the chain, starting from the top-level nodes recorded
12612   // in the first phase. These top-level nodes are the nodes just above all
12613   // loads and token factors. Starting with their uses, recursively look though
12614   // all loads (just the chain uses) and token factors to find a consecutive
12615   // load.
12616   Visited.clear();
12617   Queue.clear();
12618 
12619   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12620        IE = LoadRoots.end(); I != IE; ++I) {
12621     Queue.push_back(*I);
12622 
12623     while (!Queue.empty()) {
12624       SDNode *LoadRoot = Queue.pop_back_val();
12625       if (!Visited.insert(LoadRoot).second)
12626         continue;
12627 
12628       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12629         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12630           return true;
12631 
12632       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12633            UE = LoadRoot->use_end(); UI != UE; ++UI)
12634         if (((isa<MemSDNode>(*UI) &&
12635             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12636             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12637           Queue.push_back(*UI);
12638     }
12639   }
12640 
12641   return false;
12642 }
12643 
12644 /// This function is called when we have proved that a SETCC node can be replaced
12645 /// by subtraction (and other supporting instructions) so that the result of
12646 /// comparison is kept in a GPR instead of CR. This function is purely for
12647 /// codegen purposes and has some flags to guide the codegen process.
12648 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12649                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12650   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12651 
12652   // Zero extend the operands to the largest legal integer. Originally, they
12653   // must be of a strictly smaller size.
12654   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12655                          DAG.getConstant(Size, DL, MVT::i32));
12656   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12657                          DAG.getConstant(Size, DL, MVT::i32));
12658 
12659   // Swap if needed. Depends on the condition code.
12660   if (Swap)
12661     std::swap(Op0, Op1);
12662 
12663   // Subtract extended integers.
12664   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12665 
12666   // Move the sign bit to the least significant position and zero out the rest.
12667   // Now the least significant bit carries the result of original comparison.
12668   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12669                              DAG.getConstant(Size - 1, DL, MVT::i32));
12670   auto Final = Shifted;
12671 
12672   // Complement the result if needed. Based on the condition code.
12673   if (Complement)
12674     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12675                         DAG.getConstant(1, DL, MVT::i64));
12676 
12677   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12678 }
12679 
12680 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12681                                                   DAGCombinerInfo &DCI) const {
12682   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12683 
12684   SelectionDAG &DAG = DCI.DAG;
12685   SDLoc DL(N);
12686 
12687   // Size of integers being compared has a critical role in the following
12688   // analysis, so we prefer to do this when all types are legal.
12689   if (!DCI.isAfterLegalizeDAG())
12690     return SDValue();
12691 
12692   // If all users of SETCC extend its value to a legal integer type
12693   // then we replace SETCC with a subtraction
12694   for (SDNode::use_iterator UI = N->use_begin(),
12695        UE = N->use_end(); UI != UE; ++UI) {
12696     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12697       return SDValue();
12698   }
12699 
12700   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12701   auto OpSize = N->getOperand(0).getValueSizeInBits();
12702 
12703   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12704 
12705   if (OpSize < Size) {
12706     switch (CC) {
12707     default: break;
12708     case ISD::SETULT:
12709       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12710     case ISD::SETULE:
12711       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12712     case ISD::SETUGT:
12713       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12714     case ISD::SETUGE:
12715       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12716     }
12717   }
12718 
12719   return SDValue();
12720 }
12721 
12722 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12723                                                   DAGCombinerInfo &DCI) const {
12724   SelectionDAG &DAG = DCI.DAG;
12725   SDLoc dl(N);
12726 
12727   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12728   // If we're tracking CR bits, we need to be careful that we don't have:
12729   //   trunc(binary-ops(zext(x), zext(y)))
12730   // or
12731   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12732   // such that we're unnecessarily moving things into GPRs when it would be
12733   // better to keep them in CR bits.
12734 
12735   // Note that trunc here can be an actual i1 trunc, or can be the effective
12736   // truncation that comes from a setcc or select_cc.
12737   if (N->getOpcode() == ISD::TRUNCATE &&
12738       N->getValueType(0) != MVT::i1)
12739     return SDValue();
12740 
12741   if (N->getOperand(0).getValueType() != MVT::i32 &&
12742       N->getOperand(0).getValueType() != MVT::i64)
12743     return SDValue();
12744 
12745   if (N->getOpcode() == ISD::SETCC ||
12746       N->getOpcode() == ISD::SELECT_CC) {
12747     // If we're looking at a comparison, then we need to make sure that the
12748     // high bits (all except for the first) don't matter the result.
12749     ISD::CondCode CC =
12750       cast<CondCodeSDNode>(N->getOperand(
12751         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12752     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12753 
12754     if (ISD::isSignedIntSetCC(CC)) {
12755       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12756           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12757         return SDValue();
12758     } else if (ISD::isUnsignedIntSetCC(CC)) {
12759       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12760                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12761           !DAG.MaskedValueIsZero(N->getOperand(1),
12762                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12763         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12764                                              : SDValue());
12765     } else {
12766       // This is neither a signed nor an unsigned comparison, just make sure
12767       // that the high bits are equal.
12768       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12769       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12770 
12771       // We don't really care about what is known about the first bit (if
12772       // anything), so clear it in all masks prior to comparing them.
12773       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12774       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12775 
12776       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12777         return SDValue();
12778     }
12779   }
12780 
12781   // We now know that the higher-order bits are irrelevant, we just need to
12782   // make sure that all of the intermediate operations are bit operations, and
12783   // all inputs are extensions.
12784   if (N->getOperand(0).getOpcode() != ISD::AND &&
12785       N->getOperand(0).getOpcode() != ISD::OR  &&
12786       N->getOperand(0).getOpcode() != ISD::XOR &&
12787       N->getOperand(0).getOpcode() != ISD::SELECT &&
12788       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12789       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12790       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12791       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12792       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12793     return SDValue();
12794 
12795   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12796       N->getOperand(1).getOpcode() != ISD::AND &&
12797       N->getOperand(1).getOpcode() != ISD::OR  &&
12798       N->getOperand(1).getOpcode() != ISD::XOR &&
12799       N->getOperand(1).getOpcode() != ISD::SELECT &&
12800       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12801       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12802       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12803       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12804       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12805     return SDValue();
12806 
12807   SmallVector<SDValue, 4> Inputs;
12808   SmallVector<SDValue, 8> BinOps, PromOps;
12809   SmallPtrSet<SDNode *, 16> Visited;
12810 
12811   for (unsigned i = 0; i < 2; ++i) {
12812     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12813           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12814           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12815           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12816         isa<ConstantSDNode>(N->getOperand(i)))
12817       Inputs.push_back(N->getOperand(i));
12818     else
12819       BinOps.push_back(N->getOperand(i));
12820 
12821     if (N->getOpcode() == ISD::TRUNCATE)
12822       break;
12823   }
12824 
12825   // Visit all inputs, collect all binary operations (and, or, xor and
12826   // select) that are all fed by extensions.
12827   while (!BinOps.empty()) {
12828     SDValue BinOp = BinOps.back();
12829     BinOps.pop_back();
12830 
12831     if (!Visited.insert(BinOp.getNode()).second)
12832       continue;
12833 
12834     PromOps.push_back(BinOp);
12835 
12836     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12837       // The condition of the select is not promoted.
12838       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12839         continue;
12840       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12841         continue;
12842 
12843       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12844             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12845             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12846            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12847           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12848         Inputs.push_back(BinOp.getOperand(i));
12849       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12850                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12851                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12852                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12853                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12854                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12855                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12856                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12857                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12858         BinOps.push_back(BinOp.getOperand(i));
12859       } else {
12860         // We have an input that is not an extension or another binary
12861         // operation; we'll abort this transformation.
12862         return SDValue();
12863       }
12864     }
12865   }
12866 
12867   // Make sure that this is a self-contained cluster of operations (which
12868   // is not quite the same thing as saying that everything has only one
12869   // use).
12870   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12871     if (isa<ConstantSDNode>(Inputs[i]))
12872       continue;
12873 
12874     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12875                               UE = Inputs[i].getNode()->use_end();
12876          UI != UE; ++UI) {
12877       SDNode *User = *UI;
12878       if (User != N && !Visited.count(User))
12879         return SDValue();
12880 
12881       // Make sure that we're not going to promote the non-output-value
12882       // operand(s) or SELECT or SELECT_CC.
12883       // FIXME: Although we could sometimes handle this, and it does occur in
12884       // practice that one of the condition inputs to the select is also one of
12885       // the outputs, we currently can't deal with this.
12886       if (User->getOpcode() == ISD::SELECT) {
12887         if (User->getOperand(0) == Inputs[i])
12888           return SDValue();
12889       } else if (User->getOpcode() == ISD::SELECT_CC) {
12890         if (User->getOperand(0) == Inputs[i] ||
12891             User->getOperand(1) == Inputs[i])
12892           return SDValue();
12893       }
12894     }
12895   }
12896 
12897   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12898     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12899                               UE = PromOps[i].getNode()->use_end();
12900          UI != UE; ++UI) {
12901       SDNode *User = *UI;
12902       if (User != N && !Visited.count(User))
12903         return SDValue();
12904 
12905       // Make sure that we're not going to promote the non-output-value
12906       // operand(s) or SELECT or SELECT_CC.
12907       // FIXME: Although we could sometimes handle this, and it does occur in
12908       // practice that one of the condition inputs to the select is also one of
12909       // the outputs, we currently can't deal with this.
12910       if (User->getOpcode() == ISD::SELECT) {
12911         if (User->getOperand(0) == PromOps[i])
12912           return SDValue();
12913       } else if (User->getOpcode() == ISD::SELECT_CC) {
12914         if (User->getOperand(0) == PromOps[i] ||
12915             User->getOperand(1) == PromOps[i])
12916           return SDValue();
12917       }
12918     }
12919   }
12920 
12921   // Replace all inputs with the extension operand.
12922   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12923     // Constants may have users outside the cluster of to-be-promoted nodes,
12924     // and so we need to replace those as we do the promotions.
12925     if (isa<ConstantSDNode>(Inputs[i]))
12926       continue;
12927     else
12928       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12929   }
12930 
12931   std::list<HandleSDNode> PromOpHandles;
12932   for (auto &PromOp : PromOps)
12933     PromOpHandles.emplace_back(PromOp);
12934 
12935   // Replace all operations (these are all the same, but have a different
12936   // (i1) return type). DAG.getNode will validate that the types of
12937   // a binary operator match, so go through the list in reverse so that
12938   // we've likely promoted both operands first. Any intermediate truncations or
12939   // extensions disappear.
12940   while (!PromOpHandles.empty()) {
12941     SDValue PromOp = PromOpHandles.back().getValue();
12942     PromOpHandles.pop_back();
12943 
12944     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12945         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12946         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12947         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12948       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12949           PromOp.getOperand(0).getValueType() != MVT::i1) {
12950         // The operand is not yet ready (see comment below).
12951         PromOpHandles.emplace_front(PromOp);
12952         continue;
12953       }
12954 
12955       SDValue RepValue = PromOp.getOperand(0);
12956       if (isa<ConstantSDNode>(RepValue))
12957         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12958 
12959       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12960       continue;
12961     }
12962 
12963     unsigned C;
12964     switch (PromOp.getOpcode()) {
12965     default:             C = 0; break;
12966     case ISD::SELECT:    C = 1; break;
12967     case ISD::SELECT_CC: C = 2; break;
12968     }
12969 
12970     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12971          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12972         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12973          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12974       // The to-be-promoted operands of this node have not yet been
12975       // promoted (this should be rare because we're going through the
12976       // list backward, but if one of the operands has several users in
12977       // this cluster of to-be-promoted nodes, it is possible).
12978       PromOpHandles.emplace_front(PromOp);
12979       continue;
12980     }
12981 
12982     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12983                                 PromOp.getNode()->op_end());
12984 
12985     // If there are any constant inputs, make sure they're replaced now.
12986     for (unsigned i = 0; i < 2; ++i)
12987       if (isa<ConstantSDNode>(Ops[C+i]))
12988         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12989 
12990     DAG.ReplaceAllUsesOfValueWith(PromOp,
12991       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12992   }
12993 
12994   // Now we're left with the initial truncation itself.
12995   if (N->getOpcode() == ISD::TRUNCATE)
12996     return N->getOperand(0);
12997 
12998   // Otherwise, this is a comparison. The operands to be compared have just
12999   // changed type (to i1), but everything else is the same.
13000   return SDValue(N, 0);
13001 }
13002 
13003 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13004                                                   DAGCombinerInfo &DCI) const {
13005   SelectionDAG &DAG = DCI.DAG;
13006   SDLoc dl(N);
13007 
13008   // If we're tracking CR bits, we need to be careful that we don't have:
13009   //   zext(binary-ops(trunc(x), trunc(y)))
13010   // or
13011   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13012   // such that we're unnecessarily moving things into CR bits that can more
13013   // efficiently stay in GPRs. Note that if we're not certain that the high
13014   // bits are set as required by the final extension, we still may need to do
13015   // some masking to get the proper behavior.
13016 
13017   // This same functionality is important on PPC64 when dealing with
13018   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13019   // the return values of functions. Because it is so similar, it is handled
13020   // here as well.
13021 
13022   if (N->getValueType(0) != MVT::i32 &&
13023       N->getValueType(0) != MVT::i64)
13024     return SDValue();
13025 
13026   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13027         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13028     return SDValue();
13029 
13030   if (N->getOperand(0).getOpcode() != ISD::AND &&
13031       N->getOperand(0).getOpcode() != ISD::OR  &&
13032       N->getOperand(0).getOpcode() != ISD::XOR &&
13033       N->getOperand(0).getOpcode() != ISD::SELECT &&
13034       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13035     return SDValue();
13036 
13037   SmallVector<SDValue, 4> Inputs;
13038   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13039   SmallPtrSet<SDNode *, 16> Visited;
13040 
13041   // Visit all inputs, collect all binary operations (and, or, xor and
13042   // select) that are all fed by truncations.
13043   while (!BinOps.empty()) {
13044     SDValue BinOp = BinOps.back();
13045     BinOps.pop_back();
13046 
13047     if (!Visited.insert(BinOp.getNode()).second)
13048       continue;
13049 
13050     PromOps.push_back(BinOp);
13051 
13052     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13053       // The condition of the select is not promoted.
13054       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13055         continue;
13056       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13057         continue;
13058 
13059       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13060           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13061         Inputs.push_back(BinOp.getOperand(i));
13062       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13063                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13064                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13065                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13066                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13067         BinOps.push_back(BinOp.getOperand(i));
13068       } else {
13069         // We have an input that is not a truncation or another binary
13070         // operation; we'll abort this transformation.
13071         return SDValue();
13072       }
13073     }
13074   }
13075 
13076   // The operands of a select that must be truncated when the select is
13077   // promoted because the operand is actually part of the to-be-promoted set.
13078   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13079 
13080   // Make sure that this is a self-contained cluster of operations (which
13081   // is not quite the same thing as saying that everything has only one
13082   // use).
13083   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13084     if (isa<ConstantSDNode>(Inputs[i]))
13085       continue;
13086 
13087     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13088                               UE = Inputs[i].getNode()->use_end();
13089          UI != UE; ++UI) {
13090       SDNode *User = *UI;
13091       if (User != N && !Visited.count(User))
13092         return SDValue();
13093 
13094       // If we're going to promote the non-output-value operand(s) or SELECT or
13095       // SELECT_CC, record them for truncation.
13096       if (User->getOpcode() == ISD::SELECT) {
13097         if (User->getOperand(0) == Inputs[i])
13098           SelectTruncOp[0].insert(std::make_pair(User,
13099                                     User->getOperand(0).getValueType()));
13100       } else if (User->getOpcode() == ISD::SELECT_CC) {
13101         if (User->getOperand(0) == Inputs[i])
13102           SelectTruncOp[0].insert(std::make_pair(User,
13103                                     User->getOperand(0).getValueType()));
13104         if (User->getOperand(1) == Inputs[i])
13105           SelectTruncOp[1].insert(std::make_pair(User,
13106                                     User->getOperand(1).getValueType()));
13107       }
13108     }
13109   }
13110 
13111   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13112     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13113                               UE = PromOps[i].getNode()->use_end();
13114          UI != UE; ++UI) {
13115       SDNode *User = *UI;
13116       if (User != N && !Visited.count(User))
13117         return SDValue();
13118 
13119       // If we're going to promote the non-output-value operand(s) or SELECT or
13120       // SELECT_CC, record them for truncation.
13121       if (User->getOpcode() == ISD::SELECT) {
13122         if (User->getOperand(0) == PromOps[i])
13123           SelectTruncOp[0].insert(std::make_pair(User,
13124                                     User->getOperand(0).getValueType()));
13125       } else if (User->getOpcode() == ISD::SELECT_CC) {
13126         if (User->getOperand(0) == PromOps[i])
13127           SelectTruncOp[0].insert(std::make_pair(User,
13128                                     User->getOperand(0).getValueType()));
13129         if (User->getOperand(1) == PromOps[i])
13130           SelectTruncOp[1].insert(std::make_pair(User,
13131                                     User->getOperand(1).getValueType()));
13132       }
13133     }
13134   }
13135 
13136   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13137   bool ReallyNeedsExt = false;
13138   if (N->getOpcode() != ISD::ANY_EXTEND) {
13139     // If all of the inputs are not already sign/zero extended, then
13140     // we'll still need to do that at the end.
13141     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13142       if (isa<ConstantSDNode>(Inputs[i]))
13143         continue;
13144 
13145       unsigned OpBits =
13146         Inputs[i].getOperand(0).getValueSizeInBits();
13147       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13148 
13149       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13150            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13151                                   APInt::getHighBitsSet(OpBits,
13152                                                         OpBits-PromBits))) ||
13153           (N->getOpcode() == ISD::SIGN_EXTEND &&
13154            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13155              (OpBits-(PromBits-1)))) {
13156         ReallyNeedsExt = true;
13157         break;
13158       }
13159     }
13160   }
13161 
13162   // Replace all inputs, either with the truncation operand, or a
13163   // truncation or extension to the final output type.
13164   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13165     // Constant inputs need to be replaced with the to-be-promoted nodes that
13166     // use them because they might have users outside of the cluster of
13167     // promoted nodes.
13168     if (isa<ConstantSDNode>(Inputs[i]))
13169       continue;
13170 
13171     SDValue InSrc = Inputs[i].getOperand(0);
13172     if (Inputs[i].getValueType() == N->getValueType(0))
13173       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13174     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13175       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13176         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13177     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13178       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13179         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13180     else
13181       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13182         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13183   }
13184 
13185   std::list<HandleSDNode> PromOpHandles;
13186   for (auto &PromOp : PromOps)
13187     PromOpHandles.emplace_back(PromOp);
13188 
13189   // Replace all operations (these are all the same, but have a different
13190   // (promoted) return type). DAG.getNode will validate that the types of
13191   // a binary operator match, so go through the list in reverse so that
13192   // we've likely promoted both operands first.
13193   while (!PromOpHandles.empty()) {
13194     SDValue PromOp = PromOpHandles.back().getValue();
13195     PromOpHandles.pop_back();
13196 
13197     unsigned C;
13198     switch (PromOp.getOpcode()) {
13199     default:             C = 0; break;
13200     case ISD::SELECT:    C = 1; break;
13201     case ISD::SELECT_CC: C = 2; break;
13202     }
13203 
13204     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13205          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13206         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13207          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13208       // The to-be-promoted operands of this node have not yet been
13209       // promoted (this should be rare because we're going through the
13210       // list backward, but if one of the operands has several users in
13211       // this cluster of to-be-promoted nodes, it is possible).
13212       PromOpHandles.emplace_front(PromOp);
13213       continue;
13214     }
13215 
13216     // For SELECT and SELECT_CC nodes, we do a similar check for any
13217     // to-be-promoted comparison inputs.
13218     if (PromOp.getOpcode() == ISD::SELECT ||
13219         PromOp.getOpcode() == ISD::SELECT_CC) {
13220       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13221            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13222           (SelectTruncOp[1].count(PromOp.getNode()) &&
13223            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13224         PromOpHandles.emplace_front(PromOp);
13225         continue;
13226       }
13227     }
13228 
13229     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13230                                 PromOp.getNode()->op_end());
13231 
13232     // If this node has constant inputs, then they'll need to be promoted here.
13233     for (unsigned i = 0; i < 2; ++i) {
13234       if (!isa<ConstantSDNode>(Ops[C+i]))
13235         continue;
13236       if (Ops[C+i].getValueType() == N->getValueType(0))
13237         continue;
13238 
13239       if (N->getOpcode() == ISD::SIGN_EXTEND)
13240         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13241       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13242         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13243       else
13244         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13245     }
13246 
13247     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13248     // truncate them again to the original value type.
13249     if (PromOp.getOpcode() == ISD::SELECT ||
13250         PromOp.getOpcode() == ISD::SELECT_CC) {
13251       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13252       if (SI0 != SelectTruncOp[0].end())
13253         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13254       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13255       if (SI1 != SelectTruncOp[1].end())
13256         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13257     }
13258 
13259     DAG.ReplaceAllUsesOfValueWith(PromOp,
13260       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13261   }
13262 
13263   // Now we're left with the initial extension itself.
13264   if (!ReallyNeedsExt)
13265     return N->getOperand(0);
13266 
13267   // To zero extend, just mask off everything except for the first bit (in the
13268   // i1 case).
13269   if (N->getOpcode() == ISD::ZERO_EXTEND)
13270     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13271                        DAG.getConstant(APInt::getLowBitsSet(
13272                                          N->getValueSizeInBits(0), PromBits),
13273                                        dl, N->getValueType(0)));
13274 
13275   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13276          "Invalid extension type");
13277   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13278   SDValue ShiftCst =
13279       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13280   return DAG.getNode(
13281       ISD::SRA, dl, N->getValueType(0),
13282       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13283       ShiftCst);
13284 }
13285 
13286 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13287                                         DAGCombinerInfo &DCI) const {
13288   assert(N->getOpcode() == ISD::SETCC &&
13289          "Should be called with a SETCC node");
13290 
13291   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13292   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13293     SDValue LHS = N->getOperand(0);
13294     SDValue RHS = N->getOperand(1);
13295 
13296     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13297     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13298         LHS.hasOneUse())
13299       std::swap(LHS, RHS);
13300 
13301     // x == 0-y --> x+y == 0
13302     // x != 0-y --> x+y != 0
13303     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13304         RHS.hasOneUse()) {
13305       SDLoc DL(N);
13306       SelectionDAG &DAG = DCI.DAG;
13307       EVT VT = N->getValueType(0);
13308       EVT OpVT = LHS.getValueType();
13309       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13310       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13311     }
13312   }
13313 
13314   return DAGCombineTruncBoolExt(N, DCI);
13315 }
13316 
13317 // Is this an extending load from an f32 to an f64?
13318 static bool isFPExtLoad(SDValue Op) {
13319   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13320     return LD->getExtensionType() == ISD::EXTLOAD &&
13321       Op.getValueType() == MVT::f64;
13322   return false;
13323 }
13324 
13325 /// Reduces the number of fp-to-int conversion when building a vector.
13326 ///
13327 /// If this vector is built out of floating to integer conversions,
13328 /// transform it to a vector built out of floating point values followed by a
13329 /// single floating to integer conversion of the vector.
13330 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13331 /// becomes (fptosi (build_vector ($A, $B, ...)))
13332 SDValue PPCTargetLowering::
13333 combineElementTruncationToVectorTruncation(SDNode *N,
13334                                            DAGCombinerInfo &DCI) const {
13335   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13336          "Should be called with a BUILD_VECTOR node");
13337 
13338   SelectionDAG &DAG = DCI.DAG;
13339   SDLoc dl(N);
13340 
13341   SDValue FirstInput = N->getOperand(0);
13342   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13343          "The input operand must be an fp-to-int conversion.");
13344 
13345   // This combine happens after legalization so the fp_to_[su]i nodes are
13346   // already converted to PPCSISD nodes.
13347   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13348   if (FirstConversion == PPCISD::FCTIDZ ||
13349       FirstConversion == PPCISD::FCTIDUZ ||
13350       FirstConversion == PPCISD::FCTIWZ ||
13351       FirstConversion == PPCISD::FCTIWUZ) {
13352     bool IsSplat = true;
13353     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13354       FirstConversion == PPCISD::FCTIWUZ;
13355     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13356     SmallVector<SDValue, 4> Ops;
13357     EVT TargetVT = N->getValueType(0);
13358     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13359       SDValue NextOp = N->getOperand(i);
13360       if (NextOp.getOpcode() != PPCISD::MFVSR)
13361         return SDValue();
13362       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13363       if (NextConversion != FirstConversion)
13364         return SDValue();
13365       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13366       // This is not valid if the input was originally double precision. It is
13367       // also not profitable to do unless this is an extending load in which
13368       // case doing this combine will allow us to combine consecutive loads.
13369       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13370         return SDValue();
13371       if (N->getOperand(i) != FirstInput)
13372         IsSplat = false;
13373     }
13374 
13375     // If this is a splat, we leave it as-is since there will be only a single
13376     // fp-to-int conversion followed by a splat of the integer. This is better
13377     // for 32-bit and smaller ints and neutral for 64-bit ints.
13378     if (IsSplat)
13379       return SDValue();
13380 
13381     // Now that we know we have the right type of node, get its operands
13382     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13383       SDValue In = N->getOperand(i).getOperand(0);
13384       if (Is32Bit) {
13385         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13386         // here, we know that all inputs are extending loads so this is safe).
13387         if (In.isUndef())
13388           Ops.push_back(DAG.getUNDEF(SrcVT));
13389         else {
13390           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13391                                       MVT::f32, In.getOperand(0),
13392                                       DAG.getIntPtrConstant(1, dl));
13393           Ops.push_back(Trunc);
13394         }
13395       } else
13396         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13397     }
13398 
13399     unsigned Opcode;
13400     if (FirstConversion == PPCISD::FCTIDZ ||
13401         FirstConversion == PPCISD::FCTIWZ)
13402       Opcode = ISD::FP_TO_SINT;
13403     else
13404       Opcode = ISD::FP_TO_UINT;
13405 
13406     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13407     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13408     return DAG.getNode(Opcode, dl, TargetVT, BV);
13409   }
13410   return SDValue();
13411 }
13412 
13413 /// Reduce the number of loads when building a vector.
13414 ///
13415 /// Building a vector out of multiple loads can be converted to a load
13416 /// of the vector type if the loads are consecutive. If the loads are
13417 /// consecutive but in descending order, a shuffle is added at the end
13418 /// to reorder the vector.
13419 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13420   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13421          "Should be called with a BUILD_VECTOR node");
13422 
13423   SDLoc dl(N);
13424 
13425   // Return early for non byte-sized type, as they can't be consecutive.
13426   if (!N->getValueType(0).getVectorElementType().isByteSized())
13427     return SDValue();
13428 
13429   bool InputsAreConsecutiveLoads = true;
13430   bool InputsAreReverseConsecutive = true;
13431   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13432   SDValue FirstInput = N->getOperand(0);
13433   bool IsRoundOfExtLoad = false;
13434 
13435   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13436       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13437     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13438     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13439   }
13440   // Not a build vector of (possibly fp_rounded) loads.
13441   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13442       N->getNumOperands() == 1)
13443     return SDValue();
13444 
13445   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13446     // If any inputs are fp_round(extload), they all must be.
13447     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13448       return SDValue();
13449 
13450     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13451       N->getOperand(i);
13452     if (NextInput.getOpcode() != ISD::LOAD)
13453       return SDValue();
13454 
13455     SDValue PreviousInput =
13456       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13457     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13458     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13459 
13460     // If any inputs are fp_round(extload), they all must be.
13461     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13462       return SDValue();
13463 
13464     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13465       InputsAreConsecutiveLoads = false;
13466     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13467       InputsAreReverseConsecutive = false;
13468 
13469     // Exit early if the loads are neither consecutive nor reverse consecutive.
13470     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13471       return SDValue();
13472   }
13473 
13474   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13475          "The loads cannot be both consecutive and reverse consecutive.");
13476 
13477   SDValue FirstLoadOp =
13478     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13479   SDValue LastLoadOp =
13480     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13481                        N->getOperand(N->getNumOperands()-1);
13482 
13483   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13484   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13485   if (InputsAreConsecutiveLoads) {
13486     assert(LD1 && "Input needs to be a LoadSDNode.");
13487     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13488                        LD1->getBasePtr(), LD1->getPointerInfo(),
13489                        LD1->getAlignment());
13490   }
13491   if (InputsAreReverseConsecutive) {
13492     assert(LDL && "Input needs to be a LoadSDNode.");
13493     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13494                                LDL->getBasePtr(), LDL->getPointerInfo(),
13495                                LDL->getAlignment());
13496     SmallVector<int, 16> Ops;
13497     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13498       Ops.push_back(i);
13499 
13500     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13501                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13502   }
13503   return SDValue();
13504 }
13505 
13506 // This function adds the required vector_shuffle needed to get
13507 // the elements of the vector extract in the correct position
13508 // as specified by the CorrectElems encoding.
13509 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13510                                       SDValue Input, uint64_t Elems,
13511                                       uint64_t CorrectElems) {
13512   SDLoc dl(N);
13513 
13514   unsigned NumElems = Input.getValueType().getVectorNumElements();
13515   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13516 
13517   // Knowing the element indices being extracted from the original
13518   // vector and the order in which they're being inserted, just put
13519   // them at element indices required for the instruction.
13520   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13521     if (DAG.getDataLayout().isLittleEndian())
13522       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13523     else
13524       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13525     CorrectElems = CorrectElems >> 8;
13526     Elems = Elems >> 8;
13527   }
13528 
13529   SDValue Shuffle =
13530       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13531                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13532 
13533   EVT VT = N->getValueType(0);
13534   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13535 
13536   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13537                                Input.getValueType().getVectorElementType(),
13538                                VT.getVectorNumElements());
13539   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13540                      DAG.getValueType(ExtVT));
13541 }
13542 
13543 // Look for build vector patterns where input operands come from sign
13544 // extended vector_extract elements of specific indices. If the correct indices
13545 // aren't used, add a vector shuffle to fix up the indices and create
13546 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13547 // during instruction selection.
13548 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13549   // This array encodes the indices that the vector sign extend instructions
13550   // extract from when extending from one type to another for both BE and LE.
13551   // The right nibble of each byte corresponds to the LE incides.
13552   // and the left nibble of each byte corresponds to the BE incides.
13553   // For example: 0x3074B8FC  byte->word
13554   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13555   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13556   // For example: 0x000070F8  byte->double word
13557   // For LE: the allowed indices are: 0x0,0x8
13558   // For BE: the allowed indices are: 0x7,0xF
13559   uint64_t TargetElems[] = {
13560       0x3074B8FC, // b->w
13561       0x000070F8, // b->d
13562       0x10325476, // h->w
13563       0x00003074, // h->d
13564       0x00001032, // w->d
13565   };
13566 
13567   uint64_t Elems = 0;
13568   int Index;
13569   SDValue Input;
13570 
13571   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13572     if (!Op)
13573       return false;
13574     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13575         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13576       return false;
13577 
13578     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13579     // of the right width.
13580     SDValue Extract = Op.getOperand(0);
13581     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13582       Extract = Extract.getOperand(0);
13583     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13584       return false;
13585 
13586     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13587     if (!ExtOp)
13588       return false;
13589 
13590     Index = ExtOp->getZExtValue();
13591     if (Input && Input != Extract.getOperand(0))
13592       return false;
13593 
13594     if (!Input)
13595       Input = Extract.getOperand(0);
13596 
13597     Elems = Elems << 8;
13598     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13599     Elems |= Index;
13600 
13601     return true;
13602   };
13603 
13604   // If the build vector operands aren't sign extended vector extracts,
13605   // of the same input vector, then return.
13606   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13607     if (!isSExtOfVecExtract(N->getOperand(i))) {
13608       return SDValue();
13609     }
13610   }
13611 
13612   // If the vector extract indicies are not correct, add the appropriate
13613   // vector_shuffle.
13614   int TgtElemArrayIdx;
13615   int InputSize = Input.getValueType().getScalarSizeInBits();
13616   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13617   if (InputSize + OutputSize == 40)
13618     TgtElemArrayIdx = 0;
13619   else if (InputSize + OutputSize == 72)
13620     TgtElemArrayIdx = 1;
13621   else if (InputSize + OutputSize == 48)
13622     TgtElemArrayIdx = 2;
13623   else if (InputSize + OutputSize == 80)
13624     TgtElemArrayIdx = 3;
13625   else if (InputSize + OutputSize == 96)
13626     TgtElemArrayIdx = 4;
13627   else
13628     return SDValue();
13629 
13630   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13631   CorrectElems = DAG.getDataLayout().isLittleEndian()
13632                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13633                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13634   if (Elems != CorrectElems) {
13635     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13636   }
13637 
13638   // Regular lowering will catch cases where a shuffle is not needed.
13639   return SDValue();
13640 }
13641 
13642 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13643                                                  DAGCombinerInfo &DCI) const {
13644   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13645          "Should be called with a BUILD_VECTOR node");
13646 
13647   SelectionDAG &DAG = DCI.DAG;
13648   SDLoc dl(N);
13649 
13650   if (!Subtarget.hasVSX())
13651     return SDValue();
13652 
13653   // The target independent DAG combiner will leave a build_vector of
13654   // float-to-int conversions intact. We can generate MUCH better code for
13655   // a float-to-int conversion of a vector of floats.
13656   SDValue FirstInput = N->getOperand(0);
13657   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13658     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13659     if (Reduced)
13660       return Reduced;
13661   }
13662 
13663   // If we're building a vector out of consecutive loads, just load that
13664   // vector type.
13665   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13666   if (Reduced)
13667     return Reduced;
13668 
13669   // If we're building a vector out of extended elements from another vector
13670   // we have P9 vector integer extend instructions. The code assumes legal
13671   // input types (i.e. it can't handle things like v4i16) so do not run before
13672   // legalization.
13673   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13674     Reduced = combineBVOfVecSExt(N, DAG);
13675     if (Reduced)
13676       return Reduced;
13677   }
13678 
13679 
13680   if (N->getValueType(0) != MVT::v2f64)
13681     return SDValue();
13682 
13683   // Looking for:
13684   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13685   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13686       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13687     return SDValue();
13688   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13689       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13690     return SDValue();
13691   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13692     return SDValue();
13693 
13694   SDValue Ext1 = FirstInput.getOperand(0);
13695   SDValue Ext2 = N->getOperand(1).getOperand(0);
13696   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13697      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13698     return SDValue();
13699 
13700   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13701   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13702   if (!Ext1Op || !Ext2Op)
13703     return SDValue();
13704   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13705       Ext1.getOperand(0) != Ext2.getOperand(0))
13706     return SDValue();
13707 
13708   int FirstElem = Ext1Op->getZExtValue();
13709   int SecondElem = Ext2Op->getZExtValue();
13710   int SubvecIdx;
13711   if (FirstElem == 0 && SecondElem == 1)
13712     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13713   else if (FirstElem == 2 && SecondElem == 3)
13714     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13715   else
13716     return SDValue();
13717 
13718   SDValue SrcVec = Ext1.getOperand(0);
13719   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13720     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13721   return DAG.getNode(NodeType, dl, MVT::v2f64,
13722                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13723 }
13724 
13725 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13726                                               DAGCombinerInfo &DCI) const {
13727   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13728           N->getOpcode() == ISD::UINT_TO_FP) &&
13729          "Need an int -> FP conversion node here");
13730 
13731   if (useSoftFloat() || !Subtarget.has64BitSupport())
13732     return SDValue();
13733 
13734   SelectionDAG &DAG = DCI.DAG;
13735   SDLoc dl(N);
13736   SDValue Op(N, 0);
13737 
13738   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13739   // from the hardware.
13740   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13741     return SDValue();
13742   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13743       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13744     return SDValue();
13745 
13746   SDValue FirstOperand(Op.getOperand(0));
13747   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13748     (FirstOperand.getValueType() == MVT::i8 ||
13749      FirstOperand.getValueType() == MVT::i16);
13750   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13751     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13752     bool DstDouble = Op.getValueType() == MVT::f64;
13753     unsigned ConvOp = Signed ?
13754       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13755       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13756     SDValue WidthConst =
13757       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13758                             dl, false);
13759     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13760     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13761     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13762                                          DAG.getVTList(MVT::f64, MVT::Other),
13763                                          Ops, MVT::i8, LDN->getMemOperand());
13764 
13765     // For signed conversion, we need to sign-extend the value in the VSR
13766     if (Signed) {
13767       SDValue ExtOps[] = { Ld, WidthConst };
13768       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13769       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13770     } else
13771       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13772   }
13773 
13774 
13775   // For i32 intermediate values, unfortunately, the conversion functions
13776   // leave the upper 32 bits of the value are undefined. Within the set of
13777   // scalar instructions, we have no method for zero- or sign-extending the
13778   // value. Thus, we cannot handle i32 intermediate values here.
13779   if (Op.getOperand(0).getValueType() == MVT::i32)
13780     return SDValue();
13781 
13782   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13783          "UINT_TO_FP is supported only with FPCVT");
13784 
13785   // If we have FCFIDS, then use it when converting to single-precision.
13786   // Otherwise, convert to double-precision and then round.
13787   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13788                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13789                                                             : PPCISD::FCFIDS)
13790                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13791                                                             : PPCISD::FCFID);
13792   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13793                   ? MVT::f32
13794                   : MVT::f64;
13795 
13796   // If we're converting from a float, to an int, and back to a float again,
13797   // then we don't need the store/load pair at all.
13798   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13799        Subtarget.hasFPCVT()) ||
13800       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13801     SDValue Src = Op.getOperand(0).getOperand(0);
13802     if (Src.getValueType() == MVT::f32) {
13803       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13804       DCI.AddToWorklist(Src.getNode());
13805     } else if (Src.getValueType() != MVT::f64) {
13806       // Make sure that we don't pick up a ppc_fp128 source value.
13807       return SDValue();
13808     }
13809 
13810     unsigned FCTOp =
13811       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13812                                                         PPCISD::FCTIDUZ;
13813 
13814     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13815     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13816 
13817     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13818       FP = DAG.getNode(ISD::FP_ROUND, dl,
13819                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13820       DCI.AddToWorklist(FP.getNode());
13821     }
13822 
13823     return FP;
13824   }
13825 
13826   return SDValue();
13827 }
13828 
13829 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13830 // builtins) into loads with swaps.
13831 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13832                                               DAGCombinerInfo &DCI) const {
13833   SelectionDAG &DAG = DCI.DAG;
13834   SDLoc dl(N);
13835   SDValue Chain;
13836   SDValue Base;
13837   MachineMemOperand *MMO;
13838 
13839   switch (N->getOpcode()) {
13840   default:
13841     llvm_unreachable("Unexpected opcode for little endian VSX load");
13842   case ISD::LOAD: {
13843     LoadSDNode *LD = cast<LoadSDNode>(N);
13844     Chain = LD->getChain();
13845     Base = LD->getBasePtr();
13846     MMO = LD->getMemOperand();
13847     // If the MMO suggests this isn't a load of a full vector, leave
13848     // things alone.  For a built-in, we have to make the change for
13849     // correctness, so if there is a size problem that will be a bug.
13850     if (MMO->getSize() < 16)
13851       return SDValue();
13852     break;
13853   }
13854   case ISD::INTRINSIC_W_CHAIN: {
13855     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13856     Chain = Intrin->getChain();
13857     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13858     // us what we want. Get operand 2 instead.
13859     Base = Intrin->getOperand(2);
13860     MMO = Intrin->getMemOperand();
13861     break;
13862   }
13863   }
13864 
13865   MVT VecTy = N->getValueType(0).getSimpleVT();
13866 
13867   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13868   // aligned and the type is a vector with elements up to 4 bytes
13869   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13870       VecTy.getScalarSizeInBits() <= 32) {
13871     return SDValue();
13872   }
13873 
13874   SDValue LoadOps[] = { Chain, Base };
13875   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13876                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13877                                          LoadOps, MVT::v2f64, MMO);
13878 
13879   DCI.AddToWorklist(Load.getNode());
13880   Chain = Load.getValue(1);
13881   SDValue Swap = DAG.getNode(
13882       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13883   DCI.AddToWorklist(Swap.getNode());
13884 
13885   // Add a bitcast if the resulting load type doesn't match v2f64.
13886   if (VecTy != MVT::v2f64) {
13887     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13888     DCI.AddToWorklist(N.getNode());
13889     // Package {bitcast value, swap's chain} to match Load's shape.
13890     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13891                        N, Swap.getValue(1));
13892   }
13893 
13894   return Swap;
13895 }
13896 
13897 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13898 // builtins) into stores with swaps.
13899 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13900                                                DAGCombinerInfo &DCI) const {
13901   SelectionDAG &DAG = DCI.DAG;
13902   SDLoc dl(N);
13903   SDValue Chain;
13904   SDValue Base;
13905   unsigned SrcOpnd;
13906   MachineMemOperand *MMO;
13907 
13908   switch (N->getOpcode()) {
13909   default:
13910     llvm_unreachable("Unexpected opcode for little endian VSX store");
13911   case ISD::STORE: {
13912     StoreSDNode *ST = cast<StoreSDNode>(N);
13913     Chain = ST->getChain();
13914     Base = ST->getBasePtr();
13915     MMO = ST->getMemOperand();
13916     SrcOpnd = 1;
13917     // If the MMO suggests this isn't a store of a full vector, leave
13918     // things alone.  For a built-in, we have to make the change for
13919     // correctness, so if there is a size problem that will be a bug.
13920     if (MMO->getSize() < 16)
13921       return SDValue();
13922     break;
13923   }
13924   case ISD::INTRINSIC_VOID: {
13925     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13926     Chain = Intrin->getChain();
13927     // Intrin->getBasePtr() oddly does not get what we want.
13928     Base = Intrin->getOperand(3);
13929     MMO = Intrin->getMemOperand();
13930     SrcOpnd = 2;
13931     break;
13932   }
13933   }
13934 
13935   SDValue Src = N->getOperand(SrcOpnd);
13936   MVT VecTy = Src.getValueType().getSimpleVT();
13937 
13938   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13939   // aligned and the type is a vector with elements up to 4 bytes
13940   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13941       VecTy.getScalarSizeInBits() <= 32) {
13942     return SDValue();
13943   }
13944 
13945   // All stores are done as v2f64 and possible bit cast.
13946   if (VecTy != MVT::v2f64) {
13947     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13948     DCI.AddToWorklist(Src.getNode());
13949   }
13950 
13951   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13952                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13953   DCI.AddToWorklist(Swap.getNode());
13954   Chain = Swap.getValue(1);
13955   SDValue StoreOps[] = { Chain, Swap, Base };
13956   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13957                                           DAG.getVTList(MVT::Other),
13958                                           StoreOps, VecTy, MMO);
13959   DCI.AddToWorklist(Store.getNode());
13960   return Store;
13961 }
13962 
13963 // Handle DAG combine for STORE (FP_TO_INT F).
13964 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13965                                                DAGCombinerInfo &DCI) const {
13966 
13967   SelectionDAG &DAG = DCI.DAG;
13968   SDLoc dl(N);
13969   unsigned Opcode = N->getOperand(1).getOpcode();
13970 
13971   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13972          && "Not a FP_TO_INT Instruction!");
13973 
13974   SDValue Val = N->getOperand(1).getOperand(0);
13975   EVT Op1VT = N->getOperand(1).getValueType();
13976   EVT ResVT = Val.getValueType();
13977 
13978   // Floating point types smaller than 32 bits are not legal on Power.
13979   if (ResVT.getScalarSizeInBits() < 32)
13980     return SDValue();
13981 
13982   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13983   bool ValidTypeForStoreFltAsInt =
13984         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13985          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13986 
13987   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
13988       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13989     return SDValue();
13990 
13991   // Extend f32 values to f64
13992   if (ResVT.getScalarSizeInBits() == 32) {
13993     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13994     DCI.AddToWorklist(Val.getNode());
13995   }
13996 
13997   // Set signed or unsigned conversion opcode.
13998   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13999                           PPCISD::FP_TO_SINT_IN_VSR :
14000                           PPCISD::FP_TO_UINT_IN_VSR;
14001 
14002   Val = DAG.getNode(ConvOpcode,
14003                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14004   DCI.AddToWorklist(Val.getNode());
14005 
14006   // Set number of bytes being converted.
14007   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14008   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14009                     DAG.getIntPtrConstant(ByteSize, dl, false),
14010                     DAG.getValueType(Op1VT) };
14011 
14012   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14013           DAG.getVTList(MVT::Other), Ops,
14014           cast<StoreSDNode>(N)->getMemoryVT(),
14015           cast<StoreSDNode>(N)->getMemOperand());
14016 
14017   DCI.AddToWorklist(Val.getNode());
14018   return Val;
14019 }
14020 
14021 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14022                                                 LSBaseSDNode *LSBase,
14023                                                 DAGCombinerInfo &DCI) const {
14024   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14025         "Not a reverse memop pattern!");
14026 
14027   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14028     auto Mask = SVN->getMask();
14029     int i = 0;
14030     auto I = Mask.rbegin();
14031     auto E = Mask.rend();
14032 
14033     for (; I != E; ++I) {
14034       if (*I != i)
14035         return false;
14036       i++;
14037     }
14038     return true;
14039   };
14040 
14041   SelectionDAG &DAG = DCI.DAG;
14042   EVT VT = SVN->getValueType(0);
14043 
14044   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14045     return SDValue();
14046 
14047   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14048   // See comment in PPCVSXSwapRemoval.cpp.
14049   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14050   if (!Subtarget.hasP9Vector())
14051     return SDValue();
14052 
14053   if(!IsElementReverse(SVN))
14054     return SDValue();
14055 
14056   if (LSBase->getOpcode() == ISD::LOAD) {
14057     SDLoc dl(SVN);
14058     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14059     return DAG.getMemIntrinsicNode(
14060         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14061         LSBase->getMemoryVT(), LSBase->getMemOperand());
14062   }
14063 
14064   if (LSBase->getOpcode() == ISD::STORE) {
14065     SDLoc dl(LSBase);
14066     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14067                           LSBase->getBasePtr()};
14068     return DAG.getMemIntrinsicNode(
14069         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14070         LSBase->getMemoryVT(), LSBase->getMemOperand());
14071   }
14072 
14073   llvm_unreachable("Expected a load or store node here");
14074 }
14075 
14076 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14077                                              DAGCombinerInfo &DCI) const {
14078   SelectionDAG &DAG = DCI.DAG;
14079   SDLoc dl(N);
14080   switch (N->getOpcode()) {
14081   default: break;
14082   case ISD::ADD:
14083     return combineADD(N, DCI);
14084   case ISD::SHL:
14085     return combineSHL(N, DCI);
14086   case ISD::SRA:
14087     return combineSRA(N, DCI);
14088   case ISD::SRL:
14089     return combineSRL(N, DCI);
14090   case ISD::MUL:
14091     return combineMUL(N, DCI);
14092   case PPCISD::SHL:
14093     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14094         return N->getOperand(0);
14095     break;
14096   case PPCISD::SRL:
14097     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14098         return N->getOperand(0);
14099     break;
14100   case PPCISD::SRA:
14101     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14102       if (C->isNullValue() ||   //  0 >>s V -> 0.
14103           C->isAllOnesValue())    // -1 >>s V -> -1.
14104         return N->getOperand(0);
14105     }
14106     break;
14107   case ISD::SIGN_EXTEND:
14108   case ISD::ZERO_EXTEND:
14109   case ISD::ANY_EXTEND:
14110     return DAGCombineExtBoolTrunc(N, DCI);
14111   case ISD::TRUNCATE:
14112     return combineTRUNCATE(N, DCI);
14113   case ISD::SETCC:
14114     if (SDValue CSCC = combineSetCC(N, DCI))
14115       return CSCC;
14116     LLVM_FALLTHROUGH;
14117   case ISD::SELECT_CC:
14118     return DAGCombineTruncBoolExt(N, DCI);
14119   case ISD::SINT_TO_FP:
14120   case ISD::UINT_TO_FP:
14121     return combineFPToIntToFP(N, DCI);
14122   case ISD::VECTOR_SHUFFLE:
14123     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14124       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14125       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14126     }
14127     break;
14128   case ISD::STORE: {
14129 
14130     EVT Op1VT = N->getOperand(1).getValueType();
14131     unsigned Opcode = N->getOperand(1).getOpcode();
14132 
14133     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14134       SDValue Val= combineStoreFPToInt(N, DCI);
14135       if (Val)
14136         return Val;
14137     }
14138 
14139     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14140       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14141       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14142       if (Val)
14143         return Val;
14144     }
14145 
14146     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14147     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14148         N->getOperand(1).getNode()->hasOneUse() &&
14149         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14150          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14151 
14152       // STBRX can only handle simple types and it makes no sense to store less
14153       // two bytes in byte-reversed order.
14154       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14155       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14156         break;
14157 
14158       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14159       // Do an any-extend to 32-bits if this is a half-word input.
14160       if (BSwapOp.getValueType() == MVT::i16)
14161         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14162 
14163       // If the type of BSWAP operand is wider than stored memory width
14164       // it need to be shifted to the right side before STBRX.
14165       if (Op1VT.bitsGT(mVT)) {
14166         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14167         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14168                               DAG.getConstant(Shift, dl, MVT::i32));
14169         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14170         if (Op1VT == MVT::i64)
14171           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14172       }
14173 
14174       SDValue Ops[] = {
14175         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14176       };
14177       return
14178         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14179                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14180                                 cast<StoreSDNode>(N)->getMemOperand());
14181     }
14182 
14183     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14184     // So it can increase the chance of CSE constant construction.
14185     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14186         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14187       // Need to sign-extended to 64-bits to handle negative values.
14188       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14189       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14190                                     MemVT.getSizeInBits());
14191       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14192 
14193       // DAG.getTruncStore() can't be used here because it doesn't accept
14194       // the general (base + offset) addressing mode.
14195       // So we use UpdateNodeOperands and setTruncatingStore instead.
14196       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14197                              N->getOperand(3));
14198       cast<StoreSDNode>(N)->setTruncatingStore(true);
14199       return SDValue(N, 0);
14200     }
14201 
14202     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14203     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14204     if (Op1VT.isSimple()) {
14205       MVT StoreVT = Op1VT.getSimpleVT();
14206       if (Subtarget.needsSwapsForVSXMemOps() &&
14207           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14208            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14209         return expandVSXStoreForLE(N, DCI);
14210     }
14211     break;
14212   }
14213   case ISD::LOAD: {
14214     LoadSDNode *LD = cast<LoadSDNode>(N);
14215     EVT VT = LD->getValueType(0);
14216 
14217     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14218     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14219     if (VT.isSimple()) {
14220       MVT LoadVT = VT.getSimpleVT();
14221       if (Subtarget.needsSwapsForVSXMemOps() &&
14222           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14223            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14224         return expandVSXLoadForLE(N, DCI);
14225     }
14226 
14227     // We sometimes end up with a 64-bit integer load, from which we extract
14228     // two single-precision floating-point numbers. This happens with
14229     // std::complex<float>, and other similar structures, because of the way we
14230     // canonicalize structure copies. However, if we lack direct moves,
14231     // then the final bitcasts from the extracted integer values to the
14232     // floating-point numbers turn into store/load pairs. Even with direct moves,
14233     // just loading the two floating-point numbers is likely better.
14234     auto ReplaceTwoFloatLoad = [&]() {
14235       if (VT != MVT::i64)
14236         return false;
14237 
14238       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14239           LD->isVolatile())
14240         return false;
14241 
14242       //  We're looking for a sequence like this:
14243       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14244       //      t16: i64 = srl t13, Constant:i32<32>
14245       //    t17: i32 = truncate t16
14246       //  t18: f32 = bitcast t17
14247       //    t19: i32 = truncate t13
14248       //  t20: f32 = bitcast t19
14249 
14250       if (!LD->hasNUsesOfValue(2, 0))
14251         return false;
14252 
14253       auto UI = LD->use_begin();
14254       while (UI.getUse().getResNo() != 0) ++UI;
14255       SDNode *Trunc = *UI++;
14256       while (UI.getUse().getResNo() != 0) ++UI;
14257       SDNode *RightShift = *UI;
14258       if (Trunc->getOpcode() != ISD::TRUNCATE)
14259         std::swap(Trunc, RightShift);
14260 
14261       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14262           Trunc->getValueType(0) != MVT::i32 ||
14263           !Trunc->hasOneUse())
14264         return false;
14265       if (RightShift->getOpcode() != ISD::SRL ||
14266           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14267           RightShift->getConstantOperandVal(1) != 32 ||
14268           !RightShift->hasOneUse())
14269         return false;
14270 
14271       SDNode *Trunc2 = *RightShift->use_begin();
14272       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14273           Trunc2->getValueType(0) != MVT::i32 ||
14274           !Trunc2->hasOneUse())
14275         return false;
14276 
14277       SDNode *Bitcast = *Trunc->use_begin();
14278       SDNode *Bitcast2 = *Trunc2->use_begin();
14279 
14280       if (Bitcast->getOpcode() != ISD::BITCAST ||
14281           Bitcast->getValueType(0) != MVT::f32)
14282         return false;
14283       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14284           Bitcast2->getValueType(0) != MVT::f32)
14285         return false;
14286 
14287       if (Subtarget.isLittleEndian())
14288         std::swap(Bitcast, Bitcast2);
14289 
14290       // Bitcast has the second float (in memory-layout order) and Bitcast2
14291       // has the first one.
14292 
14293       SDValue BasePtr = LD->getBasePtr();
14294       if (LD->isIndexed()) {
14295         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14296                "Non-pre-inc AM on PPC?");
14297         BasePtr =
14298           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14299                       LD->getOffset());
14300       }
14301 
14302       auto MMOFlags =
14303           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14304       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14305                                       LD->getPointerInfo(), LD->getAlignment(),
14306                                       MMOFlags, LD->getAAInfo());
14307       SDValue AddPtr =
14308         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14309                     BasePtr, DAG.getIntPtrConstant(4, dl));
14310       SDValue FloatLoad2 = DAG.getLoad(
14311           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14312           LD->getPointerInfo().getWithOffset(4),
14313           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14314 
14315       if (LD->isIndexed()) {
14316         // Note that DAGCombine should re-form any pre-increment load(s) from
14317         // what is produced here if that makes sense.
14318         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14319       }
14320 
14321       DCI.CombineTo(Bitcast2, FloatLoad);
14322       DCI.CombineTo(Bitcast, FloatLoad2);
14323 
14324       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14325                                     SDValue(FloatLoad2.getNode(), 1));
14326       return true;
14327     };
14328 
14329     if (ReplaceTwoFloatLoad())
14330       return SDValue(N, 0);
14331 
14332     EVT MemVT = LD->getMemoryVT();
14333     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14334     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
14335     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
14336     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
14337     if (LD->isUnindexed() && VT.isVector() &&
14338         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14339           // P8 and later hardware should just use LOAD.
14340           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
14341                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
14342          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
14343           LD->getAlignment() >= ScalarABIAlignment)) &&
14344         LD->getAlignment() < ABIAlignment) {
14345       // This is a type-legal unaligned Altivec or QPX load.
14346       SDValue Chain = LD->getChain();
14347       SDValue Ptr = LD->getBasePtr();
14348       bool isLittleEndian = Subtarget.isLittleEndian();
14349 
14350       // This implements the loading of unaligned vectors as described in
14351       // the venerable Apple Velocity Engine overview. Specifically:
14352       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14353       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14354       //
14355       // The general idea is to expand a sequence of one or more unaligned
14356       // loads into an alignment-based permutation-control instruction (lvsl
14357       // or lvsr), a series of regular vector loads (which always truncate
14358       // their input address to an aligned address), and a series of
14359       // permutations.  The results of these permutations are the requested
14360       // loaded values.  The trick is that the last "extra" load is not taken
14361       // from the address you might suspect (sizeof(vector) bytes after the
14362       // last requested load), but rather sizeof(vector) - 1 bytes after the
14363       // last requested vector. The point of this is to avoid a page fault if
14364       // the base address happened to be aligned. This works because if the
14365       // base address is aligned, then adding less than a full vector length
14366       // will cause the last vector in the sequence to be (re)loaded.
14367       // Otherwise, the next vector will be fetched as you might suspect was
14368       // necessary.
14369 
14370       // We might be able to reuse the permutation generation from
14371       // a different base address offset from this one by an aligned amount.
14372       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14373       // optimization later.
14374       Intrinsic::ID Intr, IntrLD, IntrPerm;
14375       MVT PermCntlTy, PermTy, LDTy;
14376       if (Subtarget.hasAltivec()) {
14377         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
14378                                  Intrinsic::ppc_altivec_lvsl;
14379         IntrLD = Intrinsic::ppc_altivec_lvx;
14380         IntrPerm = Intrinsic::ppc_altivec_vperm;
14381         PermCntlTy = MVT::v16i8;
14382         PermTy = MVT::v4i32;
14383         LDTy = MVT::v4i32;
14384       } else {
14385         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
14386                                        Intrinsic::ppc_qpx_qvlpcls;
14387         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
14388                                        Intrinsic::ppc_qpx_qvlfs;
14389         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
14390         PermCntlTy = MVT::v4f64;
14391         PermTy = MVT::v4f64;
14392         LDTy = MemVT.getSimpleVT();
14393       }
14394 
14395       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14396 
14397       // Create the new MMO for the new base load. It is like the original MMO,
14398       // but represents an area in memory almost twice the vector size centered
14399       // on the original address. If the address is unaligned, we might start
14400       // reading up to (sizeof(vector)-1) bytes below the address of the
14401       // original unaligned load.
14402       MachineFunction &MF = DAG.getMachineFunction();
14403       MachineMemOperand *BaseMMO =
14404         MF.getMachineMemOperand(LD->getMemOperand(),
14405                                 -(long)MemVT.getStoreSize()+1,
14406                                 2*MemVT.getStoreSize()-1);
14407 
14408       // Create the new base load.
14409       SDValue LDXIntID =
14410           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14411       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14412       SDValue BaseLoad =
14413         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14414                                 DAG.getVTList(PermTy, MVT::Other),
14415                                 BaseLoadOps, LDTy, BaseMMO);
14416 
14417       // Note that the value of IncOffset (which is provided to the next
14418       // load's pointer info offset value, and thus used to calculate the
14419       // alignment), and the value of IncValue (which is actually used to
14420       // increment the pointer value) are different! This is because we
14421       // require the next load to appear to be aligned, even though it
14422       // is actually offset from the base pointer by a lesser amount.
14423       int IncOffset = VT.getSizeInBits() / 8;
14424       int IncValue = IncOffset;
14425 
14426       // Walk (both up and down) the chain looking for another load at the real
14427       // (aligned) offset (the alignment of the other load does not matter in
14428       // this case). If found, then do not use the offset reduction trick, as
14429       // that will prevent the loads from being later combined (as they would
14430       // otherwise be duplicates).
14431       if (!findConsecutiveLoad(LD, DAG))
14432         --IncValue;
14433 
14434       SDValue Increment =
14435           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14436       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14437 
14438       MachineMemOperand *ExtraMMO =
14439         MF.getMachineMemOperand(LD->getMemOperand(),
14440                                 1, 2*MemVT.getStoreSize()-1);
14441       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14442       SDValue ExtraLoad =
14443         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14444                                 DAG.getVTList(PermTy, MVT::Other),
14445                                 ExtraLoadOps, LDTy, ExtraMMO);
14446 
14447       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14448         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14449 
14450       // Because vperm has a big-endian bias, we must reverse the order
14451       // of the input vectors and complement the permute control vector
14452       // when generating little endian code.  We have already handled the
14453       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14454       // and ExtraLoad here.
14455       SDValue Perm;
14456       if (isLittleEndian)
14457         Perm = BuildIntrinsicOp(IntrPerm,
14458                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14459       else
14460         Perm = BuildIntrinsicOp(IntrPerm,
14461                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14462 
14463       if (VT != PermTy)
14464         Perm = Subtarget.hasAltivec() ?
14465                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
14466                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
14467                                DAG.getTargetConstant(1, dl, MVT::i64));
14468                                // second argument is 1 because this rounding
14469                                // is always exact.
14470 
14471       // The output of the permutation is our loaded result, the TokenFactor is
14472       // our new chain.
14473       DCI.CombineTo(N, Perm, TF);
14474       return SDValue(N, 0);
14475     }
14476     }
14477     break;
14478     case ISD::INTRINSIC_WO_CHAIN: {
14479       bool isLittleEndian = Subtarget.isLittleEndian();
14480       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14481       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14482                                            : Intrinsic::ppc_altivec_lvsl);
14483       if ((IID == Intr ||
14484            IID == Intrinsic::ppc_qpx_qvlpcld  ||
14485            IID == Intrinsic::ppc_qpx_qvlpcls) &&
14486         N->getOperand(1)->getOpcode() == ISD::ADD) {
14487         SDValue Add = N->getOperand(1);
14488 
14489         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
14490                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
14491 
14492         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14493                                   APInt::getAllOnesValue(Bits /* alignment */)
14494                                       .zext(Add.getScalarValueSizeInBits()))) {
14495           SDNode *BasePtr = Add->getOperand(0).getNode();
14496           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14497                                     UE = BasePtr->use_end();
14498                UI != UE; ++UI) {
14499             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14500                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
14501               // We've found another LVSL/LVSR, and this address is an aligned
14502               // multiple of that one. The results will be the same, so use the
14503               // one we've just found instead.
14504 
14505               return SDValue(*UI, 0);
14506             }
14507           }
14508         }
14509 
14510         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14511           SDNode *BasePtr = Add->getOperand(0).getNode();
14512           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14513                UE = BasePtr->use_end(); UI != UE; ++UI) {
14514             if (UI->getOpcode() == ISD::ADD &&
14515                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14516                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14517                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14518                 (1ULL << Bits) == 0) {
14519               SDNode *OtherAdd = *UI;
14520               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14521                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14522                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14523                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14524                   return SDValue(*VI, 0);
14525                 }
14526               }
14527             }
14528           }
14529         }
14530       }
14531 
14532       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14533       // Expose the vabsduw/h/b opportunity for down stream
14534       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14535           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14536            IID == Intrinsic::ppc_altivec_vmaxsh ||
14537            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14538         SDValue V1 = N->getOperand(1);
14539         SDValue V2 = N->getOperand(2);
14540         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14541              V1.getSimpleValueType() == MVT::v8i16 ||
14542              V1.getSimpleValueType() == MVT::v16i8) &&
14543             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14544           // (0-a, a)
14545           if (V1.getOpcode() == ISD::SUB &&
14546               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14547               V1.getOperand(1) == V2) {
14548             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14549           }
14550           // (a, 0-a)
14551           if (V2.getOpcode() == ISD::SUB &&
14552               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14553               V2.getOperand(1) == V1) {
14554             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14555           }
14556           // (x-y, y-x)
14557           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14558               V1.getOperand(0) == V2.getOperand(1) &&
14559               V1.getOperand(1) == V2.getOperand(0)) {
14560             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14561           }
14562         }
14563       }
14564     }
14565 
14566     break;
14567   case ISD::INTRINSIC_W_CHAIN:
14568     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14569     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14570     if (Subtarget.needsSwapsForVSXMemOps()) {
14571       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14572       default:
14573         break;
14574       case Intrinsic::ppc_vsx_lxvw4x:
14575       case Intrinsic::ppc_vsx_lxvd2x:
14576         return expandVSXLoadForLE(N, DCI);
14577       }
14578     }
14579     break;
14580   case ISD::INTRINSIC_VOID:
14581     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14582     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14583     if (Subtarget.needsSwapsForVSXMemOps()) {
14584       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14585       default:
14586         break;
14587       case Intrinsic::ppc_vsx_stxvw4x:
14588       case Intrinsic::ppc_vsx_stxvd2x:
14589         return expandVSXStoreForLE(N, DCI);
14590       }
14591     }
14592     break;
14593   case ISD::BSWAP:
14594     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14595     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14596         N->getOperand(0).hasOneUse() &&
14597         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14598          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14599           N->getValueType(0) == MVT::i64))) {
14600       SDValue Load = N->getOperand(0);
14601       LoadSDNode *LD = cast<LoadSDNode>(Load);
14602       // Create the byte-swapping load.
14603       SDValue Ops[] = {
14604         LD->getChain(),    // Chain
14605         LD->getBasePtr(),  // Ptr
14606         DAG.getValueType(N->getValueType(0)) // VT
14607       };
14608       SDValue BSLoad =
14609         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14610                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14611                                               MVT::i64 : MVT::i32, MVT::Other),
14612                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14613 
14614       // If this is an i16 load, insert the truncate.
14615       SDValue ResVal = BSLoad;
14616       if (N->getValueType(0) == MVT::i16)
14617         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14618 
14619       // First, combine the bswap away.  This makes the value produced by the
14620       // load dead.
14621       DCI.CombineTo(N, ResVal);
14622 
14623       // Next, combine the load away, we give it a bogus result value but a real
14624       // chain result.  The result value is dead because the bswap is dead.
14625       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14626 
14627       // Return N so it doesn't get rechecked!
14628       return SDValue(N, 0);
14629     }
14630     break;
14631   case PPCISD::VCMP:
14632     // If a VCMPo node already exists with exactly the same operands as this
14633     // node, use its result instead of this node (VCMPo computes both a CR6 and
14634     // a normal output).
14635     //
14636     if (!N->getOperand(0).hasOneUse() &&
14637         !N->getOperand(1).hasOneUse() &&
14638         !N->getOperand(2).hasOneUse()) {
14639 
14640       // Scan all of the users of the LHS, looking for VCMPo's that match.
14641       SDNode *VCMPoNode = nullptr;
14642 
14643       SDNode *LHSN = N->getOperand(0).getNode();
14644       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14645            UI != E; ++UI)
14646         if (UI->getOpcode() == PPCISD::VCMPo &&
14647             UI->getOperand(1) == N->getOperand(1) &&
14648             UI->getOperand(2) == N->getOperand(2) &&
14649             UI->getOperand(0) == N->getOperand(0)) {
14650           VCMPoNode = *UI;
14651           break;
14652         }
14653 
14654       // If there is no VCMPo node, or if the flag value has a single use, don't
14655       // transform this.
14656       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14657         break;
14658 
14659       // Look at the (necessarily single) use of the flag value.  If it has a
14660       // chain, this transformation is more complex.  Note that multiple things
14661       // could use the value result, which we should ignore.
14662       SDNode *FlagUser = nullptr;
14663       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14664            FlagUser == nullptr; ++UI) {
14665         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14666         SDNode *User = *UI;
14667         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14668           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14669             FlagUser = User;
14670             break;
14671           }
14672         }
14673       }
14674 
14675       // If the user is a MFOCRF instruction, we know this is safe.
14676       // Otherwise we give up for right now.
14677       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14678         return SDValue(VCMPoNode, 0);
14679     }
14680     break;
14681   case ISD::BRCOND: {
14682     SDValue Cond = N->getOperand(1);
14683     SDValue Target = N->getOperand(2);
14684 
14685     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14686         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14687           Intrinsic::loop_decrement) {
14688 
14689       // We now need to make the intrinsic dead (it cannot be instruction
14690       // selected).
14691       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14692       assert(Cond.getNode()->hasOneUse() &&
14693              "Counter decrement has more than one use");
14694 
14695       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14696                          N->getOperand(0), Target);
14697     }
14698   }
14699   break;
14700   case ISD::BR_CC: {
14701     // If this is a branch on an altivec predicate comparison, lower this so
14702     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14703     // lowering is done pre-legalize, because the legalizer lowers the predicate
14704     // compare down to code that is difficult to reassemble.
14705     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14706     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14707 
14708     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14709     // value. If so, pass-through the AND to get to the intrinsic.
14710     if (LHS.getOpcode() == ISD::AND &&
14711         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14712         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14713           Intrinsic::loop_decrement &&
14714         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14715         !isNullConstant(LHS.getOperand(1)))
14716       LHS = LHS.getOperand(0);
14717 
14718     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14719         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14720           Intrinsic::loop_decrement &&
14721         isa<ConstantSDNode>(RHS)) {
14722       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14723              "Counter decrement comparison is not EQ or NE");
14724 
14725       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14726       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14727                     (CC == ISD::SETNE && !Val);
14728 
14729       // We now need to make the intrinsic dead (it cannot be instruction
14730       // selected).
14731       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14732       assert(LHS.getNode()->hasOneUse() &&
14733              "Counter decrement has more than one use");
14734 
14735       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14736                          N->getOperand(0), N->getOperand(4));
14737     }
14738 
14739     int CompareOpc;
14740     bool isDot;
14741 
14742     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14743         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14744         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14745       assert(isDot && "Can't compare against a vector result!");
14746 
14747       // If this is a comparison against something other than 0/1, then we know
14748       // that the condition is never/always true.
14749       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14750       if (Val != 0 && Val != 1) {
14751         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14752           return N->getOperand(0);
14753         // Always !=, turn it into an unconditional branch.
14754         return DAG.getNode(ISD::BR, dl, MVT::Other,
14755                            N->getOperand(0), N->getOperand(4));
14756       }
14757 
14758       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14759 
14760       // Create the PPCISD altivec 'dot' comparison node.
14761       SDValue Ops[] = {
14762         LHS.getOperand(2),  // LHS of compare
14763         LHS.getOperand(3),  // RHS of compare
14764         DAG.getConstant(CompareOpc, dl, MVT::i32)
14765       };
14766       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14767       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14768 
14769       // Unpack the result based on how the target uses it.
14770       PPC::Predicate CompOpc;
14771       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14772       default:  // Can't happen, don't crash on invalid number though.
14773       case 0:   // Branch on the value of the EQ bit of CR6.
14774         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14775         break;
14776       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14777         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14778         break;
14779       case 2:   // Branch on the value of the LT bit of CR6.
14780         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14781         break;
14782       case 3:   // Branch on the inverted value of the LT bit of CR6.
14783         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14784         break;
14785       }
14786 
14787       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14788                          DAG.getConstant(CompOpc, dl, MVT::i32),
14789                          DAG.getRegister(PPC::CR6, MVT::i32),
14790                          N->getOperand(4), CompNode.getValue(1));
14791     }
14792     break;
14793   }
14794   case ISD::BUILD_VECTOR:
14795     return DAGCombineBuildVector(N, DCI);
14796   case ISD::ABS:
14797     return combineABS(N, DCI);
14798   case ISD::VSELECT:
14799     return combineVSelect(N, DCI);
14800   }
14801 
14802   return SDValue();
14803 }
14804 
14805 SDValue
14806 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14807                                  SelectionDAG &DAG,
14808                                  SmallVectorImpl<SDNode *> &Created) const {
14809   // fold (sdiv X, pow2)
14810   EVT VT = N->getValueType(0);
14811   if (VT == MVT::i64 && !Subtarget.isPPC64())
14812     return SDValue();
14813   if ((VT != MVT::i32 && VT != MVT::i64) ||
14814       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14815     return SDValue();
14816 
14817   SDLoc DL(N);
14818   SDValue N0 = N->getOperand(0);
14819 
14820   bool IsNegPow2 = (-Divisor).isPowerOf2();
14821   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14822   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14823 
14824   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14825   Created.push_back(Op.getNode());
14826 
14827   if (IsNegPow2) {
14828     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14829     Created.push_back(Op.getNode());
14830   }
14831 
14832   return Op;
14833 }
14834 
14835 //===----------------------------------------------------------------------===//
14836 // Inline Assembly Support
14837 //===----------------------------------------------------------------------===//
14838 
14839 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14840                                                       KnownBits &Known,
14841                                                       const APInt &DemandedElts,
14842                                                       const SelectionDAG &DAG,
14843                                                       unsigned Depth) const {
14844   Known.resetAll();
14845   switch (Op.getOpcode()) {
14846   default: break;
14847   case PPCISD::LBRX: {
14848     // lhbrx is known to have the top bits cleared out.
14849     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14850       Known.Zero = 0xFFFF0000;
14851     break;
14852   }
14853   case ISD::INTRINSIC_WO_CHAIN: {
14854     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14855     default: break;
14856     case Intrinsic::ppc_altivec_vcmpbfp_p:
14857     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14858     case Intrinsic::ppc_altivec_vcmpequb_p:
14859     case Intrinsic::ppc_altivec_vcmpequh_p:
14860     case Intrinsic::ppc_altivec_vcmpequw_p:
14861     case Intrinsic::ppc_altivec_vcmpequd_p:
14862     case Intrinsic::ppc_altivec_vcmpgefp_p:
14863     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14864     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14865     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14866     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14867     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14868     case Intrinsic::ppc_altivec_vcmpgtub_p:
14869     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14870     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14871     case Intrinsic::ppc_altivec_vcmpgtud_p:
14872       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14873       break;
14874     }
14875   }
14876   }
14877 }
14878 
14879 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14880   switch (Subtarget.getCPUDirective()) {
14881   default: break;
14882   case PPC::DIR_970:
14883   case PPC::DIR_PWR4:
14884   case PPC::DIR_PWR5:
14885   case PPC::DIR_PWR5X:
14886   case PPC::DIR_PWR6:
14887   case PPC::DIR_PWR6X:
14888   case PPC::DIR_PWR7:
14889   case PPC::DIR_PWR8:
14890   case PPC::DIR_PWR9:
14891   case PPC::DIR_PWR_FUTURE: {
14892     if (!ML)
14893       break;
14894 
14895     if (!DisableInnermostLoopAlign32) {
14896       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14897       // so that we can decrease cache misses and branch-prediction misses.
14898       // Actual alignment of the loop will depend on the hotness check and other
14899       // logic in alignBlocks.
14900       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14901         return Align(32);
14902     }
14903 
14904     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14905 
14906     // For small loops (between 5 and 8 instructions), align to a 32-byte
14907     // boundary so that the entire loop fits in one instruction-cache line.
14908     uint64_t LoopSize = 0;
14909     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14910       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14911         LoopSize += TII->getInstSizeInBytes(*J);
14912         if (LoopSize > 32)
14913           break;
14914       }
14915 
14916     if (LoopSize > 16 && LoopSize <= 32)
14917       return Align(32);
14918 
14919     break;
14920   }
14921   }
14922 
14923   return TargetLowering::getPrefLoopAlignment(ML);
14924 }
14925 
14926 /// getConstraintType - Given a constraint, return the type of
14927 /// constraint it is for this target.
14928 PPCTargetLowering::ConstraintType
14929 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14930   if (Constraint.size() == 1) {
14931     switch (Constraint[0]) {
14932     default: break;
14933     case 'b':
14934     case 'r':
14935     case 'f':
14936     case 'd':
14937     case 'v':
14938     case 'y':
14939       return C_RegisterClass;
14940     case 'Z':
14941       // FIXME: While Z does indicate a memory constraint, it specifically
14942       // indicates an r+r address (used in conjunction with the 'y' modifier
14943       // in the replacement string). Currently, we're forcing the base
14944       // register to be r0 in the asm printer (which is interpreted as zero)
14945       // and forming the complete address in the second register. This is
14946       // suboptimal.
14947       return C_Memory;
14948     }
14949   } else if (Constraint == "wc") { // individual CR bits.
14950     return C_RegisterClass;
14951   } else if (Constraint == "wa" || Constraint == "wd" ||
14952              Constraint == "wf" || Constraint == "ws" ||
14953              Constraint == "wi" || Constraint == "ww") {
14954     return C_RegisterClass; // VSX registers.
14955   }
14956   return TargetLowering::getConstraintType(Constraint);
14957 }
14958 
14959 /// Examine constraint type and operand type and determine a weight value.
14960 /// This object must already have been set up with the operand type
14961 /// and the current alternative constraint selected.
14962 TargetLowering::ConstraintWeight
14963 PPCTargetLowering::getSingleConstraintMatchWeight(
14964     AsmOperandInfo &info, const char *constraint) const {
14965   ConstraintWeight weight = CW_Invalid;
14966   Value *CallOperandVal = info.CallOperandVal;
14967     // If we don't have a value, we can't do a match,
14968     // but allow it at the lowest weight.
14969   if (!CallOperandVal)
14970     return CW_Default;
14971   Type *type = CallOperandVal->getType();
14972 
14973   // Look at the constraint type.
14974   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
14975     return CW_Register; // an individual CR bit.
14976   else if ((StringRef(constraint) == "wa" ||
14977             StringRef(constraint) == "wd" ||
14978             StringRef(constraint) == "wf") &&
14979            type->isVectorTy())
14980     return CW_Register;
14981   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
14982     return CW_Register; // just hold 64-bit integers data.
14983   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
14984     return CW_Register;
14985   else if (StringRef(constraint) == "ww" && type->isFloatTy())
14986     return CW_Register;
14987 
14988   switch (*constraint) {
14989   default:
14990     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14991     break;
14992   case 'b':
14993     if (type->isIntegerTy())
14994       weight = CW_Register;
14995     break;
14996   case 'f':
14997     if (type->isFloatTy())
14998       weight = CW_Register;
14999     break;
15000   case 'd':
15001     if (type->isDoubleTy())
15002       weight = CW_Register;
15003     break;
15004   case 'v':
15005     if (type->isVectorTy())
15006       weight = CW_Register;
15007     break;
15008   case 'y':
15009     weight = CW_Register;
15010     break;
15011   case 'Z':
15012     weight = CW_Memory;
15013     break;
15014   }
15015   return weight;
15016 }
15017 
15018 std::pair<unsigned, const TargetRegisterClass *>
15019 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15020                                                 StringRef Constraint,
15021                                                 MVT VT) const {
15022   if (Constraint.size() == 1) {
15023     // GCC RS6000 Constraint Letters
15024     switch (Constraint[0]) {
15025     case 'b':   // R1-R31
15026       if (VT == MVT::i64 && Subtarget.isPPC64())
15027         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15028       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15029     case 'r':   // R0-R31
15030       if (VT == MVT::i64 && Subtarget.isPPC64())
15031         return std::make_pair(0U, &PPC::G8RCRegClass);
15032       return std::make_pair(0U, &PPC::GPRCRegClass);
15033     // 'd' and 'f' constraints are both defined to be "the floating point
15034     // registers", where one is for 32-bit and the other for 64-bit. We don't
15035     // really care overly much here so just give them all the same reg classes.
15036     case 'd':
15037     case 'f':
15038       if (Subtarget.hasSPE()) {
15039         if (VT == MVT::f32 || VT == MVT::i32)
15040           return std::make_pair(0U, &PPC::GPRCRegClass);
15041         if (VT == MVT::f64 || VT == MVT::i64)
15042           return std::make_pair(0U, &PPC::SPERCRegClass);
15043       } else {
15044         if (VT == MVT::f32 || VT == MVT::i32)
15045           return std::make_pair(0U, &PPC::F4RCRegClass);
15046         if (VT == MVT::f64 || VT == MVT::i64)
15047           return std::make_pair(0U, &PPC::F8RCRegClass);
15048         if (VT == MVT::v4f64 && Subtarget.hasQPX())
15049           return std::make_pair(0U, &PPC::QFRCRegClass);
15050         if (VT == MVT::v4f32 && Subtarget.hasQPX())
15051           return std::make_pair(0U, &PPC::QSRCRegClass);
15052       }
15053       break;
15054     case 'v':
15055       if (VT == MVT::v4f64 && Subtarget.hasQPX())
15056         return std::make_pair(0U, &PPC::QFRCRegClass);
15057       if (VT == MVT::v4f32 && Subtarget.hasQPX())
15058         return std::make_pair(0U, &PPC::QSRCRegClass);
15059       if (Subtarget.hasAltivec())
15060         return std::make_pair(0U, &PPC::VRRCRegClass);
15061       break;
15062     case 'y':   // crrc
15063       return std::make_pair(0U, &PPC::CRRCRegClass);
15064     }
15065   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15066     // An individual CR bit.
15067     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15068   } else if ((Constraint == "wa" || Constraint == "wd" ||
15069              Constraint == "wf" || Constraint == "wi") &&
15070              Subtarget.hasVSX()) {
15071     return std::make_pair(0U, &PPC::VSRCRegClass);
15072   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15073     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15074       return std::make_pair(0U, &PPC::VSSRCRegClass);
15075     else
15076       return std::make_pair(0U, &PPC::VSFRCRegClass);
15077   }
15078 
15079   // If we name a VSX register, we can't defer to the base class because it
15080   // will not recognize the correct register (their names will be VSL{0-31}
15081   // and V{0-31} so they won't match). So we match them here.
15082   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15083     int VSNum = atoi(Constraint.data() + 3);
15084     assert(VSNum >= 0 && VSNum <= 63 &&
15085            "Attempted to access a vsr out of range");
15086     if (VSNum < 32)
15087       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15088     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15089   }
15090   std::pair<unsigned, const TargetRegisterClass *> R =
15091       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15092 
15093   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15094   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15095   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15096   // register.
15097   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15098   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15099   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15100       PPC::GPRCRegClass.contains(R.first))
15101     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15102                             PPC::sub_32, &PPC::G8RCRegClass),
15103                           &PPC::G8RCRegClass);
15104 
15105   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15106   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15107     R.first = PPC::CR0;
15108     R.second = &PPC::CRRCRegClass;
15109   }
15110 
15111   return R;
15112 }
15113 
15114 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15115 /// vector.  If it is invalid, don't add anything to Ops.
15116 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15117                                                      std::string &Constraint,
15118                                                      std::vector<SDValue>&Ops,
15119                                                      SelectionDAG &DAG) const {
15120   SDValue Result;
15121 
15122   // Only support length 1 constraints.
15123   if (Constraint.length() > 1) return;
15124 
15125   char Letter = Constraint[0];
15126   switch (Letter) {
15127   default: break;
15128   case 'I':
15129   case 'J':
15130   case 'K':
15131   case 'L':
15132   case 'M':
15133   case 'N':
15134   case 'O':
15135   case 'P': {
15136     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15137     if (!CST) return; // Must be an immediate to match.
15138     SDLoc dl(Op);
15139     int64_t Value = CST->getSExtValue();
15140     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15141                          // numbers are printed as such.
15142     switch (Letter) {
15143     default: llvm_unreachable("Unknown constraint letter!");
15144     case 'I':  // "I" is a signed 16-bit constant.
15145       if (isInt<16>(Value))
15146         Result = DAG.getTargetConstant(Value, dl, TCVT);
15147       break;
15148     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15149       if (isShiftedUInt<16, 16>(Value))
15150         Result = DAG.getTargetConstant(Value, dl, TCVT);
15151       break;
15152     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15153       if (isShiftedInt<16, 16>(Value))
15154         Result = DAG.getTargetConstant(Value, dl, TCVT);
15155       break;
15156     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15157       if (isUInt<16>(Value))
15158         Result = DAG.getTargetConstant(Value, dl, TCVT);
15159       break;
15160     case 'M':  // "M" is a constant that is greater than 31.
15161       if (Value > 31)
15162         Result = DAG.getTargetConstant(Value, dl, TCVT);
15163       break;
15164     case 'N':  // "N" is a positive constant that is an exact power of two.
15165       if (Value > 0 && isPowerOf2_64(Value))
15166         Result = DAG.getTargetConstant(Value, dl, TCVT);
15167       break;
15168     case 'O':  // "O" is the constant zero.
15169       if (Value == 0)
15170         Result = DAG.getTargetConstant(Value, dl, TCVT);
15171       break;
15172     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15173       if (isInt<16>(-Value))
15174         Result = DAG.getTargetConstant(Value, dl, TCVT);
15175       break;
15176     }
15177     break;
15178   }
15179   }
15180 
15181   if (Result.getNode()) {
15182     Ops.push_back(Result);
15183     return;
15184   }
15185 
15186   // Handle standard constraint letters.
15187   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15188 }
15189 
15190 // isLegalAddressingMode - Return true if the addressing mode represented
15191 // by AM is legal for this target, for a load/store of the specified type.
15192 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15193                                               const AddrMode &AM, Type *Ty,
15194                                               unsigned AS, Instruction *I) const {
15195   // PPC does not allow r+i addressing modes for vectors!
15196   if (Ty->isVectorTy() && AM.BaseOffs != 0)
15197     return false;
15198 
15199   // PPC allows a sign-extended 16-bit immediate field.
15200   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15201     return false;
15202 
15203   // No global is ever allowed as a base.
15204   if (AM.BaseGV)
15205     return false;
15206 
15207   // PPC only support r+r,
15208   switch (AM.Scale) {
15209   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15210     break;
15211   case 1:
15212     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15213       return false;
15214     // Otherwise we have r+r or r+i.
15215     break;
15216   case 2:
15217     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15218       return false;
15219     // Allow 2*r as r+r.
15220     break;
15221   default:
15222     // No other scales are supported.
15223     return false;
15224   }
15225 
15226   return true;
15227 }
15228 
15229 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15230                                            SelectionDAG &DAG) const {
15231   MachineFunction &MF = DAG.getMachineFunction();
15232   MachineFrameInfo &MFI = MF.getFrameInfo();
15233   MFI.setReturnAddressIsTaken(true);
15234 
15235   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15236     return SDValue();
15237 
15238   SDLoc dl(Op);
15239   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15240 
15241   // Make sure the function does not optimize away the store of the RA to
15242   // the stack.
15243   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15244   FuncInfo->setLRStoreRequired();
15245   bool isPPC64 = Subtarget.isPPC64();
15246   auto PtrVT = getPointerTy(MF.getDataLayout());
15247 
15248   if (Depth > 0) {
15249     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15250     SDValue Offset =
15251         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15252                         isPPC64 ? MVT::i64 : MVT::i32);
15253     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15254                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15255                        MachinePointerInfo());
15256   }
15257 
15258   // Just load the return address off the stack.
15259   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15260   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15261                      MachinePointerInfo());
15262 }
15263 
15264 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15265                                           SelectionDAG &DAG) const {
15266   SDLoc dl(Op);
15267   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15268 
15269   MachineFunction &MF = DAG.getMachineFunction();
15270   MachineFrameInfo &MFI = MF.getFrameInfo();
15271   MFI.setFrameAddressIsTaken(true);
15272 
15273   EVT PtrVT = getPointerTy(MF.getDataLayout());
15274   bool isPPC64 = PtrVT == MVT::i64;
15275 
15276   // Naked functions never have a frame pointer, and so we use r1. For all
15277   // other functions, this decision must be delayed until during PEI.
15278   unsigned FrameReg;
15279   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15280     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15281   else
15282     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15283 
15284   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15285                                          PtrVT);
15286   while (Depth--)
15287     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15288                             FrameAddr, MachinePointerInfo());
15289   return FrameAddr;
15290 }
15291 
15292 // FIXME? Maybe this could be a TableGen attribute on some registers and
15293 // this table could be generated automatically from RegInfo.
15294 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15295                                               const MachineFunction &MF) const {
15296   bool isPPC64 = Subtarget.isPPC64();
15297 
15298   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15299   if (!is64Bit && VT != LLT::scalar(32))
15300     report_fatal_error("Invalid register global variable type");
15301 
15302   Register Reg = StringSwitch<Register>(RegName)
15303                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15304                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15305                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15306                      .Default(Register());
15307 
15308   if (Reg)
15309     return Reg;
15310   report_fatal_error("Invalid register name global variable");
15311 }
15312 
15313 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15314   // 32-bit SVR4 ABI access everything as got-indirect.
15315   if (Subtarget.is32BitELFABI())
15316     return true;
15317 
15318   // AIX accesses everything indirectly through the TOC, which is similar to
15319   // the GOT.
15320   if (Subtarget.isAIXABI())
15321     return true;
15322 
15323   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15324   // If it is small or large code model, module locals are accessed
15325   // indirectly by loading their address from .toc/.got.
15326   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15327     return true;
15328 
15329   // JumpTable and BlockAddress are accessed as got-indirect.
15330   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15331     return true;
15332 
15333   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15334     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15335 
15336   return false;
15337 }
15338 
15339 bool
15340 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15341   // The PowerPC target isn't yet aware of offsets.
15342   return false;
15343 }
15344 
15345 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15346                                            const CallInst &I,
15347                                            MachineFunction &MF,
15348                                            unsigned Intrinsic) const {
15349   switch (Intrinsic) {
15350   case Intrinsic::ppc_qpx_qvlfd:
15351   case Intrinsic::ppc_qpx_qvlfs:
15352   case Intrinsic::ppc_qpx_qvlfcd:
15353   case Intrinsic::ppc_qpx_qvlfcs:
15354   case Intrinsic::ppc_qpx_qvlfiwa:
15355   case Intrinsic::ppc_qpx_qvlfiwz:
15356   case Intrinsic::ppc_altivec_lvx:
15357   case Intrinsic::ppc_altivec_lvxl:
15358   case Intrinsic::ppc_altivec_lvebx:
15359   case Intrinsic::ppc_altivec_lvehx:
15360   case Intrinsic::ppc_altivec_lvewx:
15361   case Intrinsic::ppc_vsx_lxvd2x:
15362   case Intrinsic::ppc_vsx_lxvw4x: {
15363     EVT VT;
15364     switch (Intrinsic) {
15365     case Intrinsic::ppc_altivec_lvebx:
15366       VT = MVT::i8;
15367       break;
15368     case Intrinsic::ppc_altivec_lvehx:
15369       VT = MVT::i16;
15370       break;
15371     case Intrinsic::ppc_altivec_lvewx:
15372       VT = MVT::i32;
15373       break;
15374     case Intrinsic::ppc_vsx_lxvd2x:
15375       VT = MVT::v2f64;
15376       break;
15377     case Intrinsic::ppc_qpx_qvlfd:
15378       VT = MVT::v4f64;
15379       break;
15380     case Intrinsic::ppc_qpx_qvlfs:
15381       VT = MVT::v4f32;
15382       break;
15383     case Intrinsic::ppc_qpx_qvlfcd:
15384       VT = MVT::v2f64;
15385       break;
15386     case Intrinsic::ppc_qpx_qvlfcs:
15387       VT = MVT::v2f32;
15388       break;
15389     default:
15390       VT = MVT::v4i32;
15391       break;
15392     }
15393 
15394     Info.opc = ISD::INTRINSIC_W_CHAIN;
15395     Info.memVT = VT;
15396     Info.ptrVal = I.getArgOperand(0);
15397     Info.offset = -VT.getStoreSize()+1;
15398     Info.size = 2*VT.getStoreSize()-1;
15399     Info.align = Align(1);
15400     Info.flags = MachineMemOperand::MOLoad;
15401     return true;
15402   }
15403   case Intrinsic::ppc_qpx_qvlfda:
15404   case Intrinsic::ppc_qpx_qvlfsa:
15405   case Intrinsic::ppc_qpx_qvlfcda:
15406   case Intrinsic::ppc_qpx_qvlfcsa:
15407   case Intrinsic::ppc_qpx_qvlfiwaa:
15408   case Intrinsic::ppc_qpx_qvlfiwza: {
15409     EVT VT;
15410     switch (Intrinsic) {
15411     case Intrinsic::ppc_qpx_qvlfda:
15412       VT = MVT::v4f64;
15413       break;
15414     case Intrinsic::ppc_qpx_qvlfsa:
15415       VT = MVT::v4f32;
15416       break;
15417     case Intrinsic::ppc_qpx_qvlfcda:
15418       VT = MVT::v2f64;
15419       break;
15420     case Intrinsic::ppc_qpx_qvlfcsa:
15421       VT = MVT::v2f32;
15422       break;
15423     default:
15424       VT = MVT::v4i32;
15425       break;
15426     }
15427 
15428     Info.opc = ISD::INTRINSIC_W_CHAIN;
15429     Info.memVT = VT;
15430     Info.ptrVal = I.getArgOperand(0);
15431     Info.offset = 0;
15432     Info.size = VT.getStoreSize();
15433     Info.align = Align(1);
15434     Info.flags = MachineMemOperand::MOLoad;
15435     return true;
15436   }
15437   case Intrinsic::ppc_qpx_qvstfd:
15438   case Intrinsic::ppc_qpx_qvstfs:
15439   case Intrinsic::ppc_qpx_qvstfcd:
15440   case Intrinsic::ppc_qpx_qvstfcs:
15441   case Intrinsic::ppc_qpx_qvstfiw:
15442   case Intrinsic::ppc_altivec_stvx:
15443   case Intrinsic::ppc_altivec_stvxl:
15444   case Intrinsic::ppc_altivec_stvebx:
15445   case Intrinsic::ppc_altivec_stvehx:
15446   case Intrinsic::ppc_altivec_stvewx:
15447   case Intrinsic::ppc_vsx_stxvd2x:
15448   case Intrinsic::ppc_vsx_stxvw4x: {
15449     EVT VT;
15450     switch (Intrinsic) {
15451     case Intrinsic::ppc_altivec_stvebx:
15452       VT = MVT::i8;
15453       break;
15454     case Intrinsic::ppc_altivec_stvehx:
15455       VT = MVT::i16;
15456       break;
15457     case Intrinsic::ppc_altivec_stvewx:
15458       VT = MVT::i32;
15459       break;
15460     case Intrinsic::ppc_vsx_stxvd2x:
15461       VT = MVT::v2f64;
15462       break;
15463     case Intrinsic::ppc_qpx_qvstfd:
15464       VT = MVT::v4f64;
15465       break;
15466     case Intrinsic::ppc_qpx_qvstfs:
15467       VT = MVT::v4f32;
15468       break;
15469     case Intrinsic::ppc_qpx_qvstfcd:
15470       VT = MVT::v2f64;
15471       break;
15472     case Intrinsic::ppc_qpx_qvstfcs:
15473       VT = MVT::v2f32;
15474       break;
15475     default:
15476       VT = MVT::v4i32;
15477       break;
15478     }
15479 
15480     Info.opc = ISD::INTRINSIC_VOID;
15481     Info.memVT = VT;
15482     Info.ptrVal = I.getArgOperand(1);
15483     Info.offset = -VT.getStoreSize()+1;
15484     Info.size = 2*VT.getStoreSize()-1;
15485     Info.align = Align(1);
15486     Info.flags = MachineMemOperand::MOStore;
15487     return true;
15488   }
15489   case Intrinsic::ppc_qpx_qvstfda:
15490   case Intrinsic::ppc_qpx_qvstfsa:
15491   case Intrinsic::ppc_qpx_qvstfcda:
15492   case Intrinsic::ppc_qpx_qvstfcsa:
15493   case Intrinsic::ppc_qpx_qvstfiwa: {
15494     EVT VT;
15495     switch (Intrinsic) {
15496     case Intrinsic::ppc_qpx_qvstfda:
15497       VT = MVT::v4f64;
15498       break;
15499     case Intrinsic::ppc_qpx_qvstfsa:
15500       VT = MVT::v4f32;
15501       break;
15502     case Intrinsic::ppc_qpx_qvstfcda:
15503       VT = MVT::v2f64;
15504       break;
15505     case Intrinsic::ppc_qpx_qvstfcsa:
15506       VT = MVT::v2f32;
15507       break;
15508     default:
15509       VT = MVT::v4i32;
15510       break;
15511     }
15512 
15513     Info.opc = ISD::INTRINSIC_VOID;
15514     Info.memVT = VT;
15515     Info.ptrVal = I.getArgOperand(1);
15516     Info.offset = 0;
15517     Info.size = VT.getStoreSize();
15518     Info.align = Align(1);
15519     Info.flags = MachineMemOperand::MOStore;
15520     return true;
15521   }
15522   default:
15523     break;
15524   }
15525 
15526   return false;
15527 }
15528 
15529 /// It returns EVT::Other if the type should be determined using generic
15530 /// target-independent logic.
15531 EVT PPCTargetLowering::getOptimalMemOpType(
15532     const MemOp &Op, const AttributeList &FuncAttributes) const {
15533   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15534     // When expanding a memset, require at least two QPX instructions to cover
15535     // the cost of loading the value to be stored from the constant pool.
15536     if (Subtarget.hasQPX() && Op.size() >= 32 &&
15537         (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) &&
15538         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15539       return MVT::v4f64;
15540     }
15541 
15542     // We should use Altivec/VSX loads and stores when available. For unaligned
15543     // addresses, unaligned VSX loads are only fast starting with the P8.
15544     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15545         (Op.isAligned(Align(16)) ||
15546          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15547       return MVT::v4i32;
15548   }
15549 
15550   if (Subtarget.isPPC64()) {
15551     return MVT::i64;
15552   }
15553 
15554   return MVT::i32;
15555 }
15556 
15557 /// Returns true if it is beneficial to convert a load of a constant
15558 /// to just the constant itself.
15559 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15560                                                           Type *Ty) const {
15561   assert(Ty->isIntegerTy());
15562 
15563   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15564   return !(BitSize == 0 || BitSize > 64);
15565 }
15566 
15567 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15568   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15569     return false;
15570   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15571   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15572   return NumBits1 == 64 && NumBits2 == 32;
15573 }
15574 
15575 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15576   if (!VT1.isInteger() || !VT2.isInteger())
15577     return false;
15578   unsigned NumBits1 = VT1.getSizeInBits();
15579   unsigned NumBits2 = VT2.getSizeInBits();
15580   return NumBits1 == 64 && NumBits2 == 32;
15581 }
15582 
15583 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15584   // Generally speaking, zexts are not free, but they are free when they can be
15585   // folded with other operations.
15586   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15587     EVT MemVT = LD->getMemoryVT();
15588     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15589          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15590         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15591          LD->getExtensionType() == ISD::ZEXTLOAD))
15592       return true;
15593   }
15594 
15595   // FIXME: Add other cases...
15596   //  - 32-bit shifts with a zext to i64
15597   //  - zext after ctlz, bswap, etc.
15598   //  - zext after and by a constant mask
15599 
15600   return TargetLowering::isZExtFree(Val, VT2);
15601 }
15602 
15603 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15604   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15605          "invalid fpext types");
15606   // Extending to float128 is not free.
15607   if (DestVT == MVT::f128)
15608     return false;
15609   return true;
15610 }
15611 
15612 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15613   return isInt<16>(Imm) || isUInt<16>(Imm);
15614 }
15615 
15616 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15617   return isInt<16>(Imm) || isUInt<16>(Imm);
15618 }
15619 
15620 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15621                                                        unsigned,
15622                                                        unsigned,
15623                                                        MachineMemOperand::Flags,
15624                                                        bool *Fast) const {
15625   if (DisablePPCUnaligned)
15626     return false;
15627 
15628   // PowerPC supports unaligned memory access for simple non-vector types.
15629   // Although accessing unaligned addresses is not as efficient as accessing
15630   // aligned addresses, it is generally more efficient than manual expansion,
15631   // and generally only traps for software emulation when crossing page
15632   // boundaries.
15633 
15634   if (!VT.isSimple())
15635     return false;
15636 
15637   if (VT.isFloatingPoint() && !Subtarget.allowsUnalignedFPAccess())
15638     return false;
15639 
15640   if (VT.getSimpleVT().isVector()) {
15641     if (Subtarget.hasVSX()) {
15642       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15643           VT != MVT::v4f32 && VT != MVT::v4i32)
15644         return false;
15645     } else {
15646       return false;
15647     }
15648   }
15649 
15650   if (VT == MVT::ppcf128)
15651     return false;
15652 
15653   if (Fast)
15654     *Fast = true;
15655 
15656   return true;
15657 }
15658 
15659 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15660                                                    EVT VT) const {
15661   return isFMAFasterThanFMulAndFAdd(
15662       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15663 }
15664 
15665 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15666                                                    Type *Ty) const {
15667   switch (Ty->getScalarType()->getTypeID()) {
15668   case Type::FloatTyID:
15669   case Type::DoubleTyID:
15670     return true;
15671   case Type::FP128TyID:
15672     return EnableQuadPrecision && Subtarget.hasP9Vector();
15673   default:
15674     return false;
15675   }
15676 }
15677 
15678 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist.
15679 // FIXME: add more patterns which are profitable to hoist.
15680 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
15681   if (I->getOpcode() != Instruction::FMul)
15682     return true;
15683 
15684   if (!I->hasOneUse())
15685     return true;
15686 
15687   Instruction *User = I->user_back();
15688   assert(User && "A single use instruction with no uses.");
15689 
15690   if (User->getOpcode() != Instruction::FSub &&
15691       User->getOpcode() != Instruction::FAdd)
15692     return true;
15693 
15694   const TargetOptions &Options = getTargetMachine().Options;
15695   const Function *F = I->getFunction();
15696   const DataLayout &DL = F->getParent()->getDataLayout();
15697   Type *Ty = User->getOperand(0)->getType();
15698 
15699   return !(
15700       isFMAFasterThanFMulAndFAdd(*F, Ty) &&
15701       isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
15702       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
15703 }
15704 
15705 const MCPhysReg *
15706 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15707   // LR is a callee-save register, but we must treat it as clobbered by any call
15708   // site. Hence we include LR in the scratch registers, which are in turn added
15709   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15710   // to CTR, which is used by any indirect call.
15711   static const MCPhysReg ScratchRegs[] = {
15712     PPC::X12, PPC::LR8, PPC::CTR8, 0
15713   };
15714 
15715   return ScratchRegs;
15716 }
15717 
15718 Register PPCTargetLowering::getExceptionPointerRegister(
15719     const Constant *PersonalityFn) const {
15720   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15721 }
15722 
15723 Register PPCTargetLowering::getExceptionSelectorRegister(
15724     const Constant *PersonalityFn) const {
15725   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15726 }
15727 
15728 bool
15729 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15730                      EVT VT , unsigned DefinedValues) const {
15731   if (VT == MVT::v2i64)
15732     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15733 
15734   if (Subtarget.hasVSX() || Subtarget.hasQPX())
15735     return true;
15736 
15737   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15738 }
15739 
15740 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15741   if (DisableILPPref || Subtarget.enableMachineScheduler())
15742     return TargetLowering::getSchedulingPreference(N);
15743 
15744   return Sched::ILP;
15745 }
15746 
15747 // Create a fast isel object.
15748 FastISel *
15749 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15750                                   const TargetLibraryInfo *LibInfo) const {
15751   return PPC::createFastISel(FuncInfo, LibInfo);
15752 }
15753 
15754 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15755   if (!Subtarget.isPPC64()) return;
15756 
15757   // Update IsSplitCSR in PPCFunctionInfo
15758   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
15759   PFI->setIsSplitCSR(true);
15760 }
15761 
15762 void PPCTargetLowering::insertCopiesSplitCSR(
15763   MachineBasicBlock *Entry,
15764   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15765   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
15766   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15767   if (!IStart)
15768     return;
15769 
15770   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
15771   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15772   MachineBasicBlock::iterator MBBI = Entry->begin();
15773   for (const MCPhysReg *I = IStart; *I; ++I) {
15774     const TargetRegisterClass *RC = nullptr;
15775     if (PPC::G8RCRegClass.contains(*I))
15776       RC = &PPC::G8RCRegClass;
15777     else if (PPC::F8RCRegClass.contains(*I))
15778       RC = &PPC::F8RCRegClass;
15779     else if (PPC::CRRCRegClass.contains(*I))
15780       RC = &PPC::CRRCRegClass;
15781     else if (PPC::VRRCRegClass.contains(*I))
15782       RC = &PPC::VRRCRegClass;
15783     else
15784       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15785 
15786     Register NewVR = MRI->createVirtualRegister(RC);
15787     // Create copy from CSR to a virtual register.
15788     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15789     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15790     // nounwind. If we want to generalize this later, we may need to emit
15791     // CFI pseudo-instructions.
15792     assert(Entry->getParent()->getFunction().hasFnAttribute(
15793              Attribute::NoUnwind) &&
15794            "Function should be nounwind in insertCopiesSplitCSR!");
15795     Entry->addLiveIn(*I);
15796     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15797       .addReg(*I);
15798 
15799     // Insert the copy-back instructions right before the terminator.
15800     for (auto *Exit : Exits)
15801       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15802               TII->get(TargetOpcode::COPY), *I)
15803         .addReg(NewVR);
15804   }
15805 }
15806 
15807 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15808 bool PPCTargetLowering::useLoadStackGuardNode() const {
15809   if (!Subtarget.isTargetLinux())
15810     return TargetLowering::useLoadStackGuardNode();
15811   return true;
15812 }
15813 
15814 // Override to disable global variable loading on Linux.
15815 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15816   if (!Subtarget.isTargetLinux())
15817     return TargetLowering::insertSSPDeclarations(M);
15818 }
15819 
15820 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15821                                      bool ForCodeSize) const {
15822   if (!VT.isSimple() || !Subtarget.hasVSX())
15823     return false;
15824 
15825   switch(VT.getSimpleVT().SimpleTy) {
15826   default:
15827     // For FP types that are currently not supported by PPC backend, return
15828     // false. Examples: f16, f80.
15829     return false;
15830   case MVT::f32:
15831   case MVT::f64:
15832   case MVT::ppcf128:
15833     return Imm.isPosZero();
15834   }
15835 }
15836 
15837 // For vector shift operation op, fold
15838 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15839 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15840                                   SelectionDAG &DAG) {
15841   SDValue N0 = N->getOperand(0);
15842   SDValue N1 = N->getOperand(1);
15843   EVT VT = N0.getValueType();
15844   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15845   unsigned Opcode = N->getOpcode();
15846   unsigned TargetOpcode;
15847 
15848   switch (Opcode) {
15849   default:
15850     llvm_unreachable("Unexpected shift operation");
15851   case ISD::SHL:
15852     TargetOpcode = PPCISD::SHL;
15853     break;
15854   case ISD::SRL:
15855     TargetOpcode = PPCISD::SRL;
15856     break;
15857   case ISD::SRA:
15858     TargetOpcode = PPCISD::SRA;
15859     break;
15860   }
15861 
15862   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15863       N1->getOpcode() == ISD::AND)
15864     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15865       if (Mask->getZExtValue() == OpSizeInBits - 1)
15866         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15867 
15868   return SDValue();
15869 }
15870 
15871 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15872   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15873     return Value;
15874 
15875   SDValue N0 = N->getOperand(0);
15876   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15877   if (!Subtarget.isISA3_0() ||
15878       N0.getOpcode() != ISD::SIGN_EXTEND ||
15879       N0.getOperand(0).getValueType() != MVT::i32 ||
15880       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15881     return SDValue();
15882 
15883   // We can't save an operation here if the value is already extended, and
15884   // the existing shift is easier to combine.
15885   SDValue ExtsSrc = N0.getOperand(0);
15886   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15887       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15888     return SDValue();
15889 
15890   SDLoc DL(N0);
15891   SDValue ShiftBy = SDValue(CN1, 0);
15892   // We want the shift amount to be i32 on the extswli, but the shift could
15893   // have an i64.
15894   if (ShiftBy.getValueType() == MVT::i64)
15895     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15896 
15897   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15898                          ShiftBy);
15899 }
15900 
15901 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15902   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15903     return Value;
15904 
15905   return SDValue();
15906 }
15907 
15908 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15909   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15910     return Value;
15911 
15912   return SDValue();
15913 }
15914 
15915 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15916 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15917 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15918 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15919 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15920                                  const PPCSubtarget &Subtarget) {
15921   if (!Subtarget.isPPC64())
15922     return SDValue();
15923 
15924   SDValue LHS = N->getOperand(0);
15925   SDValue RHS = N->getOperand(1);
15926 
15927   auto isZextOfCompareWithConstant = [](SDValue Op) {
15928     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15929         Op.getValueType() != MVT::i64)
15930       return false;
15931 
15932     SDValue Cmp = Op.getOperand(0);
15933     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15934         Cmp.getOperand(0).getValueType() != MVT::i64)
15935       return false;
15936 
15937     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15938       int64_t NegConstant = 0 - Constant->getSExtValue();
15939       // Due to the limitations of the addi instruction,
15940       // -C is required to be [-32768, 32767].
15941       return isInt<16>(NegConstant);
15942     }
15943 
15944     return false;
15945   };
15946 
15947   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15948   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15949 
15950   // If there is a pattern, canonicalize a zext operand to the RHS.
15951   if (LHSHasPattern && !RHSHasPattern)
15952     std::swap(LHS, RHS);
15953   else if (!LHSHasPattern && !RHSHasPattern)
15954     return SDValue();
15955 
15956   SDLoc DL(N);
15957   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15958   SDValue Cmp = RHS.getOperand(0);
15959   SDValue Z = Cmp.getOperand(0);
15960   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15961 
15962   assert(Constant && "Constant Should not be a null pointer.");
15963   int64_t NegConstant = 0 - Constant->getSExtValue();
15964 
15965   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15966   default: break;
15967   case ISD::SETNE: {
15968     //                                 when C == 0
15969     //                             --> addze X, (addic Z, -1).carry
15970     //                            /
15971     // add X, (zext(setne Z, C))--
15972     //                            \    when -32768 <= -C <= 32767 && C != 0
15973     //                             --> addze X, (addic (addi Z, -C), -1).carry
15974     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15975                               DAG.getConstant(NegConstant, DL, MVT::i64));
15976     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15977     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15978                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15979     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15980                        SDValue(Addc.getNode(), 1));
15981     }
15982   case ISD::SETEQ: {
15983     //                                 when C == 0
15984     //                             --> addze X, (subfic Z, 0).carry
15985     //                            /
15986     // add X, (zext(sete  Z, C))--
15987     //                            \    when -32768 <= -C <= 32767 && C != 0
15988     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15989     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15990                               DAG.getConstant(NegConstant, DL, MVT::i64));
15991     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15992     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15993                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15994     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15995                        SDValue(Subc.getNode(), 1));
15996     }
15997   }
15998 
15999   return SDValue();
16000 }
16001 
16002 // Transform
16003 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16004 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16005 // In this case both C1 and C2 must be known constants.
16006 // C1+C2 must fit into a 34 bit signed integer.
16007 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16008                                           const PPCSubtarget &Subtarget) {
16009   if (!Subtarget.isUsingPCRelativeCalls())
16010     return SDValue();
16011 
16012   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16013   // If we find that node try to cast the Global Address and the Constant.
16014   SDValue LHS = N->getOperand(0);
16015   SDValue RHS = N->getOperand(1);
16016 
16017   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16018     std::swap(LHS, RHS);
16019 
16020   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16021     return SDValue();
16022 
16023   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16024   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16025   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16026 
16027   // Check that both casts succeeded.
16028   if (!GSDN || !ConstNode)
16029     return SDValue();
16030 
16031   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16032   SDLoc DL(GSDN);
16033 
16034   // The signed int offset needs to fit in 34 bits.
16035   if (!isInt<34>(NewOffset))
16036     return SDValue();
16037 
16038   // The new global address is a copy of the old global address except
16039   // that it has the updated Offset.
16040   SDValue GA =
16041       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16042                                  NewOffset, GSDN->getTargetFlags());
16043   SDValue MatPCRel =
16044       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16045   return MatPCRel;
16046 }
16047 
16048 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16049   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16050     return Value;
16051 
16052   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16053     return Value;
16054 
16055   return SDValue();
16056 }
16057 
16058 // Detect TRUNCATE operations on bitcasts of float128 values.
16059 // What we are looking for here is the situtation where we extract a subset
16060 // of bits from a 128 bit float.
16061 // This can be of two forms:
16062 // 1) BITCAST of f128 feeding TRUNCATE
16063 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16064 // The reason this is required is because we do not have a legal i128 type
16065 // and so we want to prevent having to store the f128 and then reload part
16066 // of it.
16067 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16068                                            DAGCombinerInfo &DCI) const {
16069   // If we are using CRBits then try that first.
16070   if (Subtarget.useCRBits()) {
16071     // Check if CRBits did anything and return that if it did.
16072     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16073       return CRTruncValue;
16074   }
16075 
16076   SDLoc dl(N);
16077   SDValue Op0 = N->getOperand(0);
16078 
16079   // Looking for a truncate of i128 to i64.
16080   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16081     return SDValue();
16082 
16083   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16084 
16085   // SRL feeding TRUNCATE.
16086   if (Op0.getOpcode() == ISD::SRL) {
16087     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16088     // The right shift has to be by 64 bits.
16089     if (!ConstNode || ConstNode->getZExtValue() != 64)
16090       return SDValue();
16091 
16092     // Switch the element number to extract.
16093     EltToExtract = EltToExtract ? 0 : 1;
16094     // Update Op0 past the SRL.
16095     Op0 = Op0.getOperand(0);
16096   }
16097 
16098   // BITCAST feeding a TRUNCATE possibly via SRL.
16099   if (Op0.getOpcode() == ISD::BITCAST &&
16100       Op0.getValueType() == MVT::i128 &&
16101       Op0.getOperand(0).getValueType() == MVT::f128) {
16102     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16103     return DCI.DAG.getNode(
16104         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16105         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16106   }
16107   return SDValue();
16108 }
16109 
16110 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16111   SelectionDAG &DAG = DCI.DAG;
16112 
16113   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16114   if (!ConstOpOrElement)
16115     return SDValue();
16116 
16117   // An imul is usually smaller than the alternative sequence for legal type.
16118   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16119       isOperationLegal(ISD::MUL, N->getValueType(0)))
16120     return SDValue();
16121 
16122   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16123     switch (this->Subtarget.getCPUDirective()) {
16124     default:
16125       // TODO: enhance the condition for subtarget before pwr8
16126       return false;
16127     case PPC::DIR_PWR8:
16128       //  type        mul     add    shl
16129       // scalar        4       1      1
16130       // vector        7       2      2
16131       return true;
16132     case PPC::DIR_PWR9:
16133     case PPC::DIR_PWR_FUTURE:
16134       //  type        mul     add    shl
16135       // scalar        5       2      2
16136       // vector        7       2      2
16137 
16138       // The cycle RATIO of related operations are showed as a table above.
16139       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16140       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16141       // are 4, it is always profitable; but for 3 instrs patterns
16142       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16143       // So we should only do it for vector type.
16144       return IsAddOne && IsNeg ? VT.isVector() : true;
16145     }
16146   };
16147 
16148   EVT VT = N->getValueType(0);
16149   SDLoc DL(N);
16150 
16151   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16152   bool IsNeg = MulAmt.isNegative();
16153   APInt MulAmtAbs = MulAmt.abs();
16154 
16155   if ((MulAmtAbs - 1).isPowerOf2()) {
16156     // (mul x, 2^N + 1) => (add (shl x, N), x)
16157     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16158 
16159     if (!IsProfitable(IsNeg, true, VT))
16160       return SDValue();
16161 
16162     SDValue Op0 = N->getOperand(0);
16163     SDValue Op1 =
16164         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16165                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16166     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16167 
16168     if (!IsNeg)
16169       return Res;
16170 
16171     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16172   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16173     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16174     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16175 
16176     if (!IsProfitable(IsNeg, false, VT))
16177       return SDValue();
16178 
16179     SDValue Op0 = N->getOperand(0);
16180     SDValue Op1 =
16181         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16182                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16183 
16184     if (!IsNeg)
16185       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16186     else
16187       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16188 
16189   } else {
16190     return SDValue();
16191   }
16192 }
16193 
16194 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16195   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16196   if (!Subtarget.is64BitELFABI())
16197     return false;
16198 
16199   // If not a tail call then no need to proceed.
16200   if (!CI->isTailCall())
16201     return false;
16202 
16203   // If sibling calls have been disabled and tail-calls aren't guaranteed
16204   // there is no reason to duplicate.
16205   auto &TM = getTargetMachine();
16206   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16207     return false;
16208 
16209   // Can't tail call a function called indirectly, or if it has variadic args.
16210   const Function *Callee = CI->getCalledFunction();
16211   if (!Callee || Callee->isVarArg())
16212     return false;
16213 
16214   // Make sure the callee and caller calling conventions are eligible for tco.
16215   const Function *Caller = CI->getParent()->getParent();
16216   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16217                                            CI->getCallingConv()))
16218       return false;
16219 
16220   // If the function is local then we have a good chance at tail-calling it
16221   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16222 }
16223 
16224 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16225   if (!Subtarget.hasVSX())
16226     return false;
16227   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16228     return true;
16229   return VT == MVT::f32 || VT == MVT::f64 ||
16230     VT == MVT::v4f32 || VT == MVT::v2f64;
16231 }
16232 
16233 bool PPCTargetLowering::
16234 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16235   const Value *Mask = AndI.getOperand(1);
16236   // If the mask is suitable for andi. or andis. we should sink the and.
16237   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16238     // Can't handle constants wider than 64-bits.
16239     if (CI->getBitWidth() > 64)
16240       return false;
16241     int64_t ConstVal = CI->getZExtValue();
16242     return isUInt<16>(ConstVal) ||
16243       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16244   }
16245 
16246   // For non-constant masks, we can always use the record-form and.
16247   return true;
16248 }
16249 
16250 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16251 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16252 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16253 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16254 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16255 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16256   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16257   assert(Subtarget.hasP9Altivec() &&
16258          "Only combine this when P9 altivec supported!");
16259   EVT VT = N->getValueType(0);
16260   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16261     return SDValue();
16262 
16263   SelectionDAG &DAG = DCI.DAG;
16264   SDLoc dl(N);
16265   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16266     // Even for signed integers, if it's known to be positive (as signed
16267     // integer) due to zero-extended inputs.
16268     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16269     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16270     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16271          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16272         (SubOpcd1 == ISD::ZERO_EXTEND ||
16273          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16274       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16275                          N->getOperand(0)->getOperand(0),
16276                          N->getOperand(0)->getOperand(1),
16277                          DAG.getTargetConstant(0, dl, MVT::i32));
16278     }
16279 
16280     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16281     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16282         N->getOperand(0).hasOneUse()) {
16283       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16284                          N->getOperand(0)->getOperand(0),
16285                          N->getOperand(0)->getOperand(1),
16286                          DAG.getTargetConstant(1, dl, MVT::i32));
16287     }
16288   }
16289 
16290   return SDValue();
16291 }
16292 
16293 // For type v4i32/v8ii16/v16i8, transform
16294 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16295 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16296 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16297 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16298 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16299                                           DAGCombinerInfo &DCI) const {
16300   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16301   assert(Subtarget.hasP9Altivec() &&
16302          "Only combine this when P9 altivec supported!");
16303 
16304   SelectionDAG &DAG = DCI.DAG;
16305   SDLoc dl(N);
16306   SDValue Cond = N->getOperand(0);
16307   SDValue TrueOpnd = N->getOperand(1);
16308   SDValue FalseOpnd = N->getOperand(2);
16309   EVT VT = N->getOperand(1).getValueType();
16310 
16311   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16312       FalseOpnd.getOpcode() != ISD::SUB)
16313     return SDValue();
16314 
16315   // ABSD only available for type v4i32/v8i16/v16i8
16316   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16317     return SDValue();
16318 
16319   // At least to save one more dependent computation
16320   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16321     return SDValue();
16322 
16323   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16324 
16325   // Can only handle unsigned comparison here
16326   switch (CC) {
16327   default:
16328     return SDValue();
16329   case ISD::SETUGT:
16330   case ISD::SETUGE:
16331     break;
16332   case ISD::SETULT:
16333   case ISD::SETULE:
16334     std::swap(TrueOpnd, FalseOpnd);
16335     break;
16336   }
16337 
16338   SDValue CmpOpnd1 = Cond.getOperand(0);
16339   SDValue CmpOpnd2 = Cond.getOperand(1);
16340 
16341   // SETCC CmpOpnd1 CmpOpnd2 cond
16342   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16343   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16344   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16345       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16346       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16347       FalseOpnd.getOperand(1) == CmpOpnd1) {
16348     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16349                        CmpOpnd1, CmpOpnd2,
16350                        DAG.getTargetConstant(0, dl, MVT::i32));
16351   }
16352 
16353   return SDValue();
16354 }
16355