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/MCSectionXCOFF.h"
78 #include "llvm/MC/MCSymbolXCOFF.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/BranchProbability.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/CodeGen.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/Compiler.h"
85 #include "llvm/Support/Debug.h"
86 #include "llvm/Support/ErrorHandling.h"
87 #include "llvm/Support/Format.h"
88 #include "llvm/Support/KnownBits.h"
89 #include "llvm/Support/MachineValueType.h"
90 #include "llvm/Support/MathExtras.h"
91 #include "llvm/Support/raw_ostream.h"
92 #include "llvm/Target/TargetMachine.h"
93 #include "llvm/Target/TargetOptions.h"
94 #include <algorithm>
95 #include <cassert>
96 #include <cstdint>
97 #include <iterator>
98 #include <list>
99 #include <utility>
100 #include <vector>
101 
102 using namespace llvm;
103 
104 #define DEBUG_TYPE "ppc-lowering"
105 
106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
108 
109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
111 
112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
114 
115 static cl::opt<bool> DisableSCO("disable-ppc-sco",
116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
117 
118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
120 
121 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
122 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
123 
124 STATISTIC(NumTailCalls, "Number of tail calls");
125 STATISTIC(NumSiblingCalls, "Number of sibling calls");
126 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM");
127 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
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       // EFPU2 APU only supports f32
150       if (!Subtarget.hasEFPU2())
151         addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
152     } else {
153       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
154       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
155     }
156   }
157 
158   // Match BITREVERSE to customized fast code sequence in the td file.
159   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
160   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
161 
162   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
163   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
164 
165   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
166   for (MVT VT : MVT::integer_valuetypes()) {
167     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
168     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
169   }
170 
171   if (Subtarget.isISA3_0()) {
172     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
173     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
174     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
175     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
176   } else {
177     // No extending loads from f16 or HW conversions back and forth.
178     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
179     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
180     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
181     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
182     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
183     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
184     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
185     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
186   }
187 
188   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
189 
190   // PowerPC has pre-inc load and store's.
191   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
192   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
193   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
194   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
195   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
196   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
197   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
198   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
199   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
200   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
201   if (!Subtarget.hasSPE()) {
202     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
203     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
204     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
205     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
206   }
207 
208   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
209   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
210   for (MVT VT : ScalarIntVTs) {
211     setOperationAction(ISD::ADDC, VT, Legal);
212     setOperationAction(ISD::ADDE, VT, Legal);
213     setOperationAction(ISD::SUBC, VT, Legal);
214     setOperationAction(ISD::SUBE, VT, Legal);
215   }
216 
217   if (Subtarget.useCRBits()) {
218     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
219 
220     if (isPPC64 || Subtarget.hasFPCVT()) {
221       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote);
222       AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1,
223                         isPPC64 ? MVT::i64 : MVT::i32);
224       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote);
225       AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1,
226                         isPPC64 ? MVT::i64 : MVT::i32);
227 
228       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
229       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
230                          isPPC64 ? MVT::i64 : MVT::i32);
231       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
232       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
233                         isPPC64 ? MVT::i64 : MVT::i32);
234 
235       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote);
236       AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1,
237                         isPPC64 ? MVT::i64 : MVT::i32);
238       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote);
239       AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1,
240                         isPPC64 ? MVT::i64 : MVT::i32);
241 
242       setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
243       AddPromotedToType(ISD::FP_TO_SINT, MVT::i1,
244                         isPPC64 ? MVT::i64 : MVT::i32);
245       setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
246       AddPromotedToType(ISD::FP_TO_UINT, MVT::i1,
247                         isPPC64 ? MVT::i64 : MVT::i32);
248     } else {
249       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom);
250       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom);
251       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
252       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
253     }
254 
255     // PowerPC does not support direct load/store of condition registers.
256     setOperationAction(ISD::LOAD, MVT::i1, Custom);
257     setOperationAction(ISD::STORE, MVT::i1, Custom);
258 
259     // FIXME: Remove this once the ANDI glue bug is fixed:
260     if (ANDIGlueBug)
261       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
262 
263     for (MVT VT : MVT::integer_valuetypes()) {
264       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
265       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
266       setTruncStoreAction(VT, MVT::i1, Expand);
267     }
268 
269     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
270   }
271 
272   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
273   // PPC (the libcall is not available).
274   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
275   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
276   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom);
277   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom);
278 
279   // We do not currently implement these libm ops for PowerPC.
280   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
281   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
282   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
283   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
284   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
285   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
286 
287   // PowerPC has no SREM/UREM instructions unless we are on P9
288   // On P9 we may use a hardware instruction to compute the remainder.
289   // When the result of both the remainder and the division is required it is
290   // more efficient to compute the remainder from the result of the division
291   // rather than use the remainder instruction. The instructions are legalized
292   // directly because the DivRemPairsPass performs the transformation at the IR
293   // level.
294   if (Subtarget.isISA3_0()) {
295     setOperationAction(ISD::SREM, MVT::i32, Legal);
296     setOperationAction(ISD::UREM, MVT::i32, Legal);
297     setOperationAction(ISD::SREM, MVT::i64, Legal);
298     setOperationAction(ISD::UREM, MVT::i64, Legal);
299   } else {
300     setOperationAction(ISD::SREM, MVT::i32, Expand);
301     setOperationAction(ISD::UREM, MVT::i32, Expand);
302     setOperationAction(ISD::SREM, MVT::i64, Expand);
303     setOperationAction(ISD::UREM, MVT::i64, Expand);
304   }
305 
306   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
307   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
308   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
309   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
310   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
311   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
312   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
313   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
314   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
315 
316   // Handle constrained floating-point operations of scalar.
317   // TODO: Handle SPE specific operation.
318   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
319   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
320   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
321   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
322   setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
323   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
324 
325   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
326   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
327   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
328   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
329   setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
330   if (Subtarget.hasVSX()) {
331     setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal);
332     setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal);
333   }
334 
335   if (Subtarget.hasFSQRT()) {
336     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
337     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
338   }
339 
340   if (Subtarget.hasFPRND()) {
341     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
342     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
343     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
344     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
345 
346     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
347     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
348     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
349     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
350   }
351 
352   // We don't support sin/cos/sqrt/fmod/pow
353   setOperationAction(ISD::FSIN , MVT::f64, Expand);
354   setOperationAction(ISD::FCOS , MVT::f64, Expand);
355   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
356   setOperationAction(ISD::FREM , MVT::f64, Expand);
357   setOperationAction(ISD::FPOW , MVT::f64, Expand);
358   setOperationAction(ISD::FSIN , MVT::f32, Expand);
359   setOperationAction(ISD::FCOS , MVT::f32, Expand);
360   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
361   setOperationAction(ISD::FREM , MVT::f32, Expand);
362   setOperationAction(ISD::FPOW , MVT::f32, Expand);
363   if (Subtarget.hasSPE()) {
364     setOperationAction(ISD::FMA  , MVT::f64, Expand);
365     setOperationAction(ISD::FMA  , MVT::f32, Expand);
366   } else {
367     setOperationAction(ISD::FMA  , MVT::f64, Legal);
368     setOperationAction(ISD::FMA  , MVT::f32, Legal);
369   }
370 
371   if (Subtarget.hasSPE())
372     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
373 
374   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
375 
376   // If we're enabling GP optimizations, use hardware square root
377   if (!Subtarget.hasFSQRT() &&
378       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
379         Subtarget.hasFRE()))
380     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
381 
382   if (!Subtarget.hasFSQRT() &&
383       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
384         Subtarget.hasFRES()))
385     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
386 
387   if (Subtarget.hasFCPSGN()) {
388     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
389     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
390   } else {
391     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
392     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
393   }
394 
395   if (Subtarget.hasFPRND()) {
396     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
397     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
398     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
399     setOperationAction(ISD::FROUND, MVT::f64, Legal);
400 
401     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
402     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
403     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
404     setOperationAction(ISD::FROUND, MVT::f32, Legal);
405   }
406 
407   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
408   // to speed up scalar BSWAP64.
409   // CTPOP or CTTZ were introduced in P8/P9 respectively
410   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
411   if (Subtarget.hasP9Vector())
412     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
413   else
414     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
415   if (Subtarget.isISA3_0()) {
416     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
417     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
418   } else {
419     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
420     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
421   }
422 
423   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
424     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
425     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
426   } else {
427     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
428     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
429   }
430 
431   // PowerPC does not have ROTR
432   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
433   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
434 
435   if (!Subtarget.useCRBits()) {
436     // PowerPC does not have Select
437     setOperationAction(ISD::SELECT, MVT::i32, Expand);
438     setOperationAction(ISD::SELECT, MVT::i64, Expand);
439     setOperationAction(ISD::SELECT, MVT::f32, Expand);
440     setOperationAction(ISD::SELECT, MVT::f64, Expand);
441   }
442 
443   // PowerPC wants to turn select_cc of FP into fsel when possible.
444   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
445   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
446 
447   // PowerPC wants to optimize integer setcc a bit
448   if (!Subtarget.useCRBits())
449     setOperationAction(ISD::SETCC, MVT::i32, Custom);
450 
451   if (Subtarget.hasFPU()) {
452     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
453     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
454     setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
455 
456     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
457     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
458     setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
459   }
460 
461   // PowerPC does not have BRCOND which requires SetCC
462   if (!Subtarget.useCRBits())
463     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
464 
465   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
466 
467   if (Subtarget.hasSPE()) {
468     // SPE has built-in conversions
469     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
470     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
471     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
472     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
473     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
474     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
475   } else {
476     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
477     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
478     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
479 
480     // PowerPC does not have [U|S]INT_TO_FP
481     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand);
482     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand);
483     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
484     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
485   }
486 
487   if (Subtarget.hasDirectMove() && isPPC64) {
488     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
489     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
490     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
491     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
492     if (TM.Options.UnsafeFPMath) {
493       setOperationAction(ISD::LRINT, MVT::f64, Legal);
494       setOperationAction(ISD::LRINT, MVT::f32, Legal);
495       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
496       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
497       setOperationAction(ISD::LROUND, MVT::f64, Legal);
498       setOperationAction(ISD::LROUND, MVT::f32, Legal);
499       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
500       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
501     }
502   } else {
503     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
504     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
505     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
506     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
507   }
508 
509   // We cannot sextinreg(i1).  Expand to shifts.
510   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
511 
512   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
513   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
514   // support continuation, user-level threading, and etc.. As a result, no
515   // other SjLj exception interfaces are implemented and please don't build
516   // your own exception handling based on them.
517   // LLVM/Clang supports zero-cost DWARF exception handling.
518   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
519   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
520 
521   // We want to legalize GlobalAddress and ConstantPool nodes into the
522   // appropriate instructions to materialize the address.
523   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
524   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
525   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
526   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
527   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
528   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
529   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
530   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
531   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
532   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
533 
534   // TRAP is legal.
535   setOperationAction(ISD::TRAP, MVT::Other, Legal);
536 
537   // TRAMPOLINE is custom lowered.
538   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
539   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
540 
541   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
542   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
543 
544   if (Subtarget.is64BitELFABI()) {
545     // VAARG always uses double-word chunks, so promote anything smaller.
546     setOperationAction(ISD::VAARG, MVT::i1, Promote);
547     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
548     setOperationAction(ISD::VAARG, MVT::i8, Promote);
549     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
550     setOperationAction(ISD::VAARG, MVT::i16, Promote);
551     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
552     setOperationAction(ISD::VAARG, MVT::i32, Promote);
553     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
554     setOperationAction(ISD::VAARG, MVT::Other, Expand);
555   } else if (Subtarget.is32BitELFABI()) {
556     // VAARG is custom lowered with the 32-bit SVR4 ABI.
557     setOperationAction(ISD::VAARG, MVT::Other, Custom);
558     setOperationAction(ISD::VAARG, MVT::i64, Custom);
559   } else
560     setOperationAction(ISD::VAARG, MVT::Other, Expand);
561 
562   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
563   if (Subtarget.is32BitELFABI())
564     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
565   else
566     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
567 
568   // Use the default implementation.
569   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
570   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
571   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
572   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
573   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
574   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
575   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
576   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
577   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
578 
579   // We want to custom lower some of our intrinsics.
580   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
581 
582   // To handle counter-based loop conditions.
583   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
584 
585   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
586   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
587   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
588   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
589 
590   // Comparisons that require checking two conditions.
591   if (Subtarget.hasSPE()) {
592     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
593     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
594     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
595     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
596   }
597   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
598   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
599   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
600   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
601   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
602   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
603   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
604   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
605   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
606   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
607   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
608   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
609 
610   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
611   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
612 
613   if (Subtarget.has64BitSupport()) {
614     // They also have instructions for converting between i64 and fp.
615     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
616     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
617     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
618     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
619     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
620     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
621     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
622     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
623     // This is just the low 32 bits of a (signed) fp->i64 conversion.
624     // We cannot do this with Promote because i64 is not a legal type.
625     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
626     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
627 
628     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
629       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
630       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
631     }
632   } else {
633     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
634     if (Subtarget.hasSPE()) {
635       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
636       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
637     } else {
638       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
639       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
640     }
641   }
642 
643   // With the instructions enabled under FPCVT, we can do everything.
644   if (Subtarget.hasFPCVT()) {
645     if (Subtarget.has64BitSupport()) {
646       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
647       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
648       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
649       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
650       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
651       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
652       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
653       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
654     }
655 
656     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
657     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
658     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
659     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
660     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
661     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
662     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
663     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
664   }
665 
666   if (Subtarget.use64BitRegs()) {
667     // 64-bit PowerPC implementations can support i64 types directly
668     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
669     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
670     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
671     // 64-bit PowerPC wants to expand i128 shifts itself.
672     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
673     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
674     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
675   } else {
676     // 32-bit PowerPC wants to expand i64 shifts itself.
677     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
678     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
679     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
680   }
681 
682   // PowerPC has better expansions for funnel shifts than the generic
683   // TargetLowering::expandFunnelShift.
684   if (Subtarget.has64BitSupport()) {
685     setOperationAction(ISD::FSHL, MVT::i64, Custom);
686     setOperationAction(ISD::FSHR, MVT::i64, Custom);
687   }
688   setOperationAction(ISD::FSHL, MVT::i32, Custom);
689   setOperationAction(ISD::FSHR, MVT::i32, Custom);
690 
691   if (Subtarget.hasVSX()) {
692     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
693     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
694     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
695     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
696   }
697 
698   if (Subtarget.hasAltivec()) {
699     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
700       setOperationAction(ISD::SADDSAT, VT, Legal);
701       setOperationAction(ISD::SSUBSAT, VT, Legal);
702       setOperationAction(ISD::UADDSAT, VT, Legal);
703       setOperationAction(ISD::USUBSAT, VT, Legal);
704     }
705     // First set operation action for all vector types to expand. Then we
706     // will selectively turn on ones that can be effectively codegen'd.
707     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
708       // add/sub are legal for all supported vector VT's.
709       setOperationAction(ISD::ADD, VT, Legal);
710       setOperationAction(ISD::SUB, VT, Legal);
711 
712       // For v2i64, these are only valid with P8Vector. This is corrected after
713       // the loop.
714       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
715         setOperationAction(ISD::SMAX, VT, Legal);
716         setOperationAction(ISD::SMIN, VT, Legal);
717         setOperationAction(ISD::UMAX, VT, Legal);
718         setOperationAction(ISD::UMIN, VT, Legal);
719       }
720       else {
721         setOperationAction(ISD::SMAX, VT, Expand);
722         setOperationAction(ISD::SMIN, VT, Expand);
723         setOperationAction(ISD::UMAX, VT, Expand);
724         setOperationAction(ISD::UMIN, VT, Expand);
725       }
726 
727       if (Subtarget.hasVSX()) {
728         setOperationAction(ISD::FMAXNUM, VT, Legal);
729         setOperationAction(ISD::FMINNUM, VT, Legal);
730       }
731 
732       // Vector instructions introduced in P8
733       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
734         setOperationAction(ISD::CTPOP, VT, Legal);
735         setOperationAction(ISD::CTLZ, VT, Legal);
736       }
737       else {
738         setOperationAction(ISD::CTPOP, VT, Expand);
739         setOperationAction(ISD::CTLZ, VT, Expand);
740       }
741 
742       // Vector instructions introduced in P9
743       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
744         setOperationAction(ISD::CTTZ, VT, Legal);
745       else
746         setOperationAction(ISD::CTTZ, VT, Expand);
747 
748       // We promote all shuffles to v16i8.
749       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
750       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
751 
752       // We promote all non-typed operations to v4i32.
753       setOperationAction(ISD::AND   , VT, Promote);
754       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
755       setOperationAction(ISD::OR    , VT, Promote);
756       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
757       setOperationAction(ISD::XOR   , VT, Promote);
758       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
759       setOperationAction(ISD::LOAD  , VT, Promote);
760       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
761       setOperationAction(ISD::SELECT, VT, Promote);
762       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
763       setOperationAction(ISD::VSELECT, VT, Legal);
764       setOperationAction(ISD::SELECT_CC, VT, Promote);
765       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
766       setOperationAction(ISD::STORE, VT, Promote);
767       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
768 
769       // No other operations are legal.
770       setOperationAction(ISD::MUL , VT, Expand);
771       setOperationAction(ISD::SDIV, VT, Expand);
772       setOperationAction(ISD::SREM, VT, Expand);
773       setOperationAction(ISD::UDIV, VT, Expand);
774       setOperationAction(ISD::UREM, VT, Expand);
775       setOperationAction(ISD::FDIV, VT, Expand);
776       setOperationAction(ISD::FREM, VT, Expand);
777       setOperationAction(ISD::FNEG, VT, Expand);
778       setOperationAction(ISD::FSQRT, VT, Expand);
779       setOperationAction(ISD::FLOG, VT, Expand);
780       setOperationAction(ISD::FLOG10, VT, Expand);
781       setOperationAction(ISD::FLOG2, VT, Expand);
782       setOperationAction(ISD::FEXP, VT, Expand);
783       setOperationAction(ISD::FEXP2, VT, Expand);
784       setOperationAction(ISD::FSIN, VT, Expand);
785       setOperationAction(ISD::FCOS, VT, Expand);
786       setOperationAction(ISD::FABS, VT, Expand);
787       setOperationAction(ISD::FFLOOR, VT, Expand);
788       setOperationAction(ISD::FCEIL,  VT, Expand);
789       setOperationAction(ISD::FTRUNC, VT, Expand);
790       setOperationAction(ISD::FRINT,  VT, Expand);
791       setOperationAction(ISD::FNEARBYINT, VT, Expand);
792       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
793       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
794       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
795       setOperationAction(ISD::MULHU, VT, Expand);
796       setOperationAction(ISD::MULHS, VT, Expand);
797       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
798       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
799       setOperationAction(ISD::UDIVREM, VT, Expand);
800       setOperationAction(ISD::SDIVREM, VT, Expand);
801       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
802       setOperationAction(ISD::FPOW, VT, Expand);
803       setOperationAction(ISD::BSWAP, VT, Expand);
804       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
805       setOperationAction(ISD::ROTL, VT, Expand);
806       setOperationAction(ISD::ROTR, VT, Expand);
807 
808       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
809         setTruncStoreAction(VT, InnerVT, Expand);
810         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
811         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
812         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
813       }
814     }
815     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
816     if (!Subtarget.hasP8Vector()) {
817       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
818       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
819       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
820       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
821     }
822 
823     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
824     // with merges, splats, etc.
825     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
826 
827     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
828     // are cheap, so handle them before they get expanded to scalar.
829     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
830     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
831     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
832     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
833     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
834 
835     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
836     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
837     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
838     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
839     setOperationAction(ISD::SELECT, MVT::v4i32,
840                        Subtarget.useCRBits() ? Legal : Expand);
841     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
842     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
843     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
844     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
845     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
846     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
847     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
848     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
849     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
850     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
851     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
852     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
853     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
854 
855     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
856     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
857     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
858     if (Subtarget.hasAltivec())
859       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
860         setOperationAction(ISD::ROTL, VT, Legal);
861     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
862     if (Subtarget.hasP8Altivec())
863       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
864 
865     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
866     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
867     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
868     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
869 
870     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
871     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
872 
873     if (Subtarget.hasVSX()) {
874       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
875       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
876       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
877     }
878 
879     if (Subtarget.hasP8Altivec())
880       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
881     else
882       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
883 
884     if (Subtarget.isISA3_1()) {
885       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
886       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
887       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
888       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
889       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
890       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
891       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
892       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
893       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
894       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
895       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
896       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
897       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
898       setOperationAction(ISD::UREM, MVT::v1i128, Legal);
899       setOperationAction(ISD::SREM, MVT::v1i128, Legal);
900       setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
901       setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
902       setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
903     }
904 
905     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
906     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
907 
908     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
909     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
910 
911     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
912     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
913     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
914     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
915 
916     // Altivec does not contain unordered floating-point compare instructions
917     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
918     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
919     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
920     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
921 
922     if (Subtarget.hasVSX()) {
923       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
924       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
925       if (Subtarget.hasP8Vector()) {
926         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
927         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
928       }
929       if (Subtarget.hasDirectMove() && isPPC64) {
930         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
931         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
932         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
933         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
934         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
935         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
936         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
937         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
938       }
939       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
940 
941       // The nearbyint variants are not allowed to raise the inexact exception
942       // so we can only code-gen them with unsafe math.
943       if (TM.Options.UnsafeFPMath) {
944         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
945         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
946       }
947 
948       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
949       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
950       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
951       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
952       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
953       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
954       setOperationAction(ISD::FROUND, MVT::f64, Legal);
955       setOperationAction(ISD::FRINT, MVT::f64, Legal);
956 
957       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
958       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
959       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
960       setOperationAction(ISD::FROUND, MVT::f32, Legal);
961       setOperationAction(ISD::FRINT, MVT::f32, Legal);
962 
963       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
964       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
965 
966       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
967       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
968 
969       // Share the Altivec comparison restrictions.
970       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
971       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
972       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
973       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
974 
975       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
976       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
977 
978       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
979 
980       if (Subtarget.hasP8Vector())
981         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
982 
983       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
984 
985       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
986       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
987       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
988 
989       if (Subtarget.hasP8Altivec()) {
990         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
991         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
992         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
993 
994         // 128 bit shifts can be accomplished via 3 instructions for SHL and
995         // SRL, but not for SRA because of the instructions available:
996         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
997         // doing
998         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
999         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
1000         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1001 
1002         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
1003       }
1004       else {
1005         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
1006         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1007         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1008 
1009         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1010 
1011         // VSX v2i64 only supports non-arithmetic operations.
1012         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1013         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1014       }
1015 
1016       if (Subtarget.isISA3_1())
1017         setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1018       else
1019         setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1020 
1021       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1022       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1023       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1024       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1025 
1026       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
1027 
1028       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1029       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1030       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1031       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1032       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1033       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1034       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1035       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1036 
1037       // Custom handling for partial vectors of integers converted to
1038       // floating point. We already have optimal handling for v2i32 through
1039       // the DAG combine, so those aren't necessary.
1040       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1041       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1042       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1043       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1044       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1045       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1046       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1047       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1048       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1049       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1050       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1051       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1052       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1053       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1054       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1055       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1056 
1057       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1058       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1059       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1060       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1061       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1062       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1063 
1064       if (Subtarget.hasDirectMove())
1065         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1066       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1067 
1068       // Handle constrained floating-point operations of vector.
1069       // The predictor is `hasVSX` because altivec instruction has
1070       // no exception but VSX vector instruction has.
1071       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1072       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1073       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1074       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1075       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1076       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1077       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1078       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1079       setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
1080       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1081       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1082       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1083       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1084 
1085       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1086       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1087       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1088       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1089       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1090       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1091       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1092       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1093       setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
1094       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1095       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1096       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1097       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1098 
1099       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1100       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1101 
1102       for (MVT FPT : MVT::fp_valuetypes())
1103         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1104 
1105       // Expand the SELECT to SELECT_CC
1106       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1107 
1108       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1109       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1110 
1111       // No implementation for these ops for PowerPC.
1112       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1113       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1114       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1115       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1116       setOperationAction(ISD::FREM, MVT::f128, Expand);
1117     }
1118 
1119     if (Subtarget.hasP8Altivec()) {
1120       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1121       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1122     }
1123 
1124     if (Subtarget.hasP9Vector()) {
1125       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1126       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1127 
1128       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1129       // SRL, but not for SRA because of the instructions available:
1130       // VS{RL} and VS{RL}O.
1131       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1132       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1133       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1134 
1135       setOperationAction(ISD::FADD, MVT::f128, Legal);
1136       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1137       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1138       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1139       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1140 
1141       setOperationAction(ISD::FMA, MVT::f128, Legal);
1142       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1143       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1144       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1145       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1146       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1147       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1148 
1149       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1150       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1151       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1152       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1153       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1154       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1155 
1156       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1157       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1158       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1159 
1160       // Handle constrained floating-point operations of fp128
1161       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1162       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1163       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1164       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1165       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1166       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1167       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1168       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1169       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1170       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1171       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1172       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1173       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1174       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1175       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1176       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1177       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1178       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1179       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1180       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1181     } else if (Subtarget.hasVSX()) {
1182       setOperationAction(ISD::LOAD, MVT::f128, Promote);
1183       setOperationAction(ISD::STORE, MVT::f128, Promote);
1184 
1185       AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
1186       AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
1187 
1188       // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1189       // fp_to_uint and int_to_fp.
1190       setOperationAction(ISD::FADD, MVT::f128, LibCall);
1191       setOperationAction(ISD::FSUB, MVT::f128, LibCall);
1192 
1193       setOperationAction(ISD::FMUL, MVT::f128, Expand);
1194       setOperationAction(ISD::FDIV, MVT::f128, Expand);
1195       setOperationAction(ISD::FNEG, MVT::f128, Expand);
1196       setOperationAction(ISD::FABS, MVT::f128, Expand);
1197       setOperationAction(ISD::FSQRT, MVT::f128, Expand);
1198       setOperationAction(ISD::FMA, MVT::f128, Expand);
1199       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
1200 
1201       // Expand the fp_extend if the target type is fp128.
1202       setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand);
1203       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand);
1204 
1205       // Expand the fp_round if the source type is fp128.
1206       for (MVT VT : {MVT::f32, MVT::f64}) {
1207         setOperationAction(ISD::FP_ROUND, VT, Custom);
1208         setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom);
1209       }
1210 
1211       setOperationAction(ISD::SETCC, MVT::f128, Custom);
1212       setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
1213       setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
1214       setOperationAction(ISD::BR_CC, MVT::f128, Expand);
1215 
1216       // Lower following f128 select_cc pattern:
1217       // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
1218       setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
1219 
1220       // We need to handle f128 SELECT_CC with integer result type.
1221       setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1222       setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
1223     }
1224 
1225     if (Subtarget.hasP9Altivec()) {
1226       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1227       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1228 
1229       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1230       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1231       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1232       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1233       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1234       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1235       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1236     }
1237 
1238     if (Subtarget.isISA3_1())
1239       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1240   }
1241 
1242   if (Subtarget.pairedVectorMemops()) {
1243     addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1244     setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1245     setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1246   }
1247   if (Subtarget.hasMMA()) {
1248     addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1249     setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1250     setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1251     setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom);
1252   }
1253 
1254   if (Subtarget.has64BitSupport())
1255     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1256 
1257   if (Subtarget.isISA3_1())
1258     setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1259 
1260   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1261 
1262   if (!isPPC64) {
1263     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1264     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1265   }
1266 
1267   setBooleanContents(ZeroOrOneBooleanContent);
1268 
1269   if (Subtarget.hasAltivec()) {
1270     // Altivec instructions set fields to all zeros or all ones.
1271     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1272   }
1273 
1274   if (!isPPC64) {
1275     // These libcalls are not available in 32-bit.
1276     setLibcallName(RTLIB::SHL_I128, nullptr);
1277     setLibcallName(RTLIB::SRL_I128, nullptr);
1278     setLibcallName(RTLIB::SRA_I128, nullptr);
1279   }
1280 
1281   if (!isPPC64)
1282     setMaxAtomicSizeInBitsSupported(32);
1283 
1284   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1285 
1286   // We have target-specific dag combine patterns for the following nodes:
1287   setTargetDAGCombine(ISD::ADD);
1288   setTargetDAGCombine(ISD::SHL);
1289   setTargetDAGCombine(ISD::SRA);
1290   setTargetDAGCombine(ISD::SRL);
1291   setTargetDAGCombine(ISD::MUL);
1292   setTargetDAGCombine(ISD::FMA);
1293   setTargetDAGCombine(ISD::SINT_TO_FP);
1294   setTargetDAGCombine(ISD::BUILD_VECTOR);
1295   if (Subtarget.hasFPCVT())
1296     setTargetDAGCombine(ISD::UINT_TO_FP);
1297   setTargetDAGCombine(ISD::LOAD);
1298   setTargetDAGCombine(ISD::STORE);
1299   setTargetDAGCombine(ISD::BR_CC);
1300   if (Subtarget.useCRBits())
1301     setTargetDAGCombine(ISD::BRCOND);
1302   setTargetDAGCombine(ISD::BSWAP);
1303   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1304   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1305   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1306 
1307   setTargetDAGCombine(ISD::SIGN_EXTEND);
1308   setTargetDAGCombine(ISD::ZERO_EXTEND);
1309   setTargetDAGCombine(ISD::ANY_EXTEND);
1310 
1311   setTargetDAGCombine(ISD::TRUNCATE);
1312   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1313 
1314 
1315   if (Subtarget.useCRBits()) {
1316     setTargetDAGCombine(ISD::TRUNCATE);
1317     setTargetDAGCombine(ISD::SETCC);
1318     setTargetDAGCombine(ISD::SELECT_CC);
1319   }
1320 
1321   if (Subtarget.hasP9Altivec()) {
1322     setTargetDAGCombine(ISD::ABS);
1323     setTargetDAGCombine(ISD::VSELECT);
1324   }
1325 
1326   setLibcallName(RTLIB::LOG_F128, "logf128");
1327   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1328   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1329   setLibcallName(RTLIB::EXP_F128, "expf128");
1330   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1331   setLibcallName(RTLIB::SIN_F128, "sinf128");
1332   setLibcallName(RTLIB::COS_F128, "cosf128");
1333   setLibcallName(RTLIB::POW_F128, "powf128");
1334   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1335   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1336   setLibcallName(RTLIB::REM_F128, "fmodf128");
1337   setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1338   setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1339   setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1340   setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1341   setLibcallName(RTLIB::ROUND_F128, "roundf128");
1342   setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1343   setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1344   setLibcallName(RTLIB::RINT_F128, "rintf128");
1345   setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1346   setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1347   setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1348   setLibcallName(RTLIB::FMA_F128, "fmaf128");
1349 
1350   // With 32 condition bits, we don't need to sink (and duplicate) compares
1351   // aggressively in CodeGenPrep.
1352   if (Subtarget.useCRBits()) {
1353     setHasMultipleConditionRegisters();
1354     setJumpIsExpensive();
1355   }
1356 
1357   setMinFunctionAlignment(Align(4));
1358 
1359   switch (Subtarget.getCPUDirective()) {
1360   default: break;
1361   case PPC::DIR_970:
1362   case PPC::DIR_A2:
1363   case PPC::DIR_E500:
1364   case PPC::DIR_E500mc:
1365   case PPC::DIR_E5500:
1366   case PPC::DIR_PWR4:
1367   case PPC::DIR_PWR5:
1368   case PPC::DIR_PWR5X:
1369   case PPC::DIR_PWR6:
1370   case PPC::DIR_PWR6X:
1371   case PPC::DIR_PWR7:
1372   case PPC::DIR_PWR8:
1373   case PPC::DIR_PWR9:
1374   case PPC::DIR_PWR10:
1375   case PPC::DIR_PWR_FUTURE:
1376     setPrefLoopAlignment(Align(16));
1377     setPrefFunctionAlignment(Align(16));
1378     break;
1379   }
1380 
1381   if (Subtarget.enableMachineScheduler())
1382     setSchedulingPreference(Sched::Source);
1383   else
1384     setSchedulingPreference(Sched::Hybrid);
1385 
1386   computeRegisterProperties(STI.getRegisterInfo());
1387 
1388   // The Freescale cores do better with aggressive inlining of memcpy and
1389   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1390   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1391       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1392     MaxStoresPerMemset = 32;
1393     MaxStoresPerMemsetOptSize = 16;
1394     MaxStoresPerMemcpy = 32;
1395     MaxStoresPerMemcpyOptSize = 8;
1396     MaxStoresPerMemmove = 32;
1397     MaxStoresPerMemmoveOptSize = 8;
1398   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1399     // The A2 also benefits from (very) aggressive inlining of memcpy and
1400     // friends. The overhead of a the function call, even when warm, can be
1401     // over one hundred cycles.
1402     MaxStoresPerMemset = 128;
1403     MaxStoresPerMemcpy = 128;
1404     MaxStoresPerMemmove = 128;
1405     MaxLoadsPerMemcmp = 128;
1406   } else {
1407     MaxLoadsPerMemcmp = 8;
1408     MaxLoadsPerMemcmpOptSize = 4;
1409   }
1410 
1411   IsStrictFPEnabled = true;
1412 
1413   // Let the subtarget (CPU) decide if a predictable select is more expensive
1414   // than the corresponding branch. This information is used in CGP to decide
1415   // when to convert selects into branches.
1416   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1417 }
1418 
1419 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1420 /// the desired ByVal argument alignment.
1421 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1422   if (MaxAlign == MaxMaxAlign)
1423     return;
1424   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1425     if (MaxMaxAlign >= 32 &&
1426         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1427       MaxAlign = Align(32);
1428     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1429              MaxAlign < 16)
1430       MaxAlign = Align(16);
1431   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1432     Align EltAlign;
1433     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1434     if (EltAlign > MaxAlign)
1435       MaxAlign = EltAlign;
1436   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1437     for (auto *EltTy : STy->elements()) {
1438       Align EltAlign;
1439       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1440       if (EltAlign > MaxAlign)
1441         MaxAlign = EltAlign;
1442       if (MaxAlign == MaxMaxAlign)
1443         break;
1444     }
1445   }
1446 }
1447 
1448 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1449 /// function arguments in the caller parameter area.
1450 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1451                                                   const DataLayout &DL) const {
1452   // 16byte and wider vectors are passed on 16byte boundary.
1453   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1454   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1455   if (Subtarget.hasAltivec())
1456     getMaxByValAlign(Ty, Alignment, Align(16));
1457   return Alignment.value();
1458 }
1459 
1460 bool PPCTargetLowering::useSoftFloat() const {
1461   return Subtarget.useSoftFloat();
1462 }
1463 
1464 bool PPCTargetLowering::hasSPE() const {
1465   return Subtarget.hasSPE();
1466 }
1467 
1468 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1469   return VT.isScalarInteger();
1470 }
1471 
1472 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1473   switch ((PPCISD::NodeType)Opcode) {
1474   case PPCISD::FIRST_NUMBER:    break;
1475   case PPCISD::FSEL:            return "PPCISD::FSEL";
1476   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1477   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1478   case PPCISD::FCFID:           return "PPCISD::FCFID";
1479   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1480   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1481   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1482   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1483   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1484   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1485   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1486   case PPCISD::FP_TO_UINT_IN_VSR:
1487                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1488   case PPCISD::FP_TO_SINT_IN_VSR:
1489                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1490   case PPCISD::FRE:             return "PPCISD::FRE";
1491   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1492   case PPCISD::FTSQRT:
1493     return "PPCISD::FTSQRT";
1494   case PPCISD::FSQRT:
1495     return "PPCISD::FSQRT";
1496   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1497   case PPCISD::VPERM:           return "PPCISD::VPERM";
1498   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1499   case PPCISD::XXSPLTI_SP_TO_DP:
1500     return "PPCISD::XXSPLTI_SP_TO_DP";
1501   case PPCISD::XXSPLTI32DX:
1502     return "PPCISD::XXSPLTI32DX";
1503   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1504   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1505   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1506   case PPCISD::CMPB:            return "PPCISD::CMPB";
1507   case PPCISD::Hi:              return "PPCISD::Hi";
1508   case PPCISD::Lo:              return "PPCISD::Lo";
1509   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1510   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1511   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1512   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1513   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1514   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1515   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1516   case PPCISD::SRL:             return "PPCISD::SRL";
1517   case PPCISD::SRA:             return "PPCISD::SRA";
1518   case PPCISD::SHL:             return "PPCISD::SHL";
1519   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1520   case PPCISD::CALL:            return "PPCISD::CALL";
1521   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1522   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1523   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1524   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1525   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1526   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1527   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1528   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1529   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1530   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1531   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1532   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1533   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1534   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1535   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1536   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1537     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1538   case PPCISD::ANDI_rec_1_EQ_BIT:
1539     return "PPCISD::ANDI_rec_1_EQ_BIT";
1540   case PPCISD::ANDI_rec_1_GT_BIT:
1541     return "PPCISD::ANDI_rec_1_GT_BIT";
1542   case PPCISD::VCMP:            return "PPCISD::VCMP";
1543   case PPCISD::VCMP_rec:        return "PPCISD::VCMP_rec";
1544   case PPCISD::LBRX:            return "PPCISD::LBRX";
1545   case PPCISD::STBRX:           return "PPCISD::STBRX";
1546   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1547   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1548   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1549   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1550   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1551   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1552   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1553   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1554   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1555   case PPCISD::ST_VSR_SCAL_INT:
1556                                 return "PPCISD::ST_VSR_SCAL_INT";
1557   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1558   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1559   case PPCISD::BDZ:             return "PPCISD::BDZ";
1560   case PPCISD::MFFS:            return "PPCISD::MFFS";
1561   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1562   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1563   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1564   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1565   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1566   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1567   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1568   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1569   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1570   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1571   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1572   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1573   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1574   case PPCISD::TLSGD_AIX:       return "PPCISD::TLSGD_AIX";
1575   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1576   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1577   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1578   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1579   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1580   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1581   case PPCISD::PADDI_DTPREL:
1582     return "PPCISD::PADDI_DTPREL";
1583   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1584   case PPCISD::SC:              return "PPCISD::SC";
1585   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1586   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1587   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1588   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1589   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1590   case PPCISD::VABSD:           return "PPCISD::VABSD";
1591   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1592   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1593   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1594   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1595   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1596   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1597   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1598   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1599     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1600   case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1601     return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1602   case PPCISD::ACC_BUILD:       return "PPCISD::ACC_BUILD";
1603   case PPCISD::PAIR_BUILD:      return "PPCISD::PAIR_BUILD";
1604   case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1605   case PPCISD::XXMFACC:         return "PPCISD::XXMFACC";
1606   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1607   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1608   case PPCISD::STRICT_FADDRTZ:
1609     return "PPCISD::STRICT_FADDRTZ";
1610   case PPCISD::STRICT_FCTIDZ:
1611     return "PPCISD::STRICT_FCTIDZ";
1612   case PPCISD::STRICT_FCTIWZ:
1613     return "PPCISD::STRICT_FCTIWZ";
1614   case PPCISD::STRICT_FCTIDUZ:
1615     return "PPCISD::STRICT_FCTIDUZ";
1616   case PPCISD::STRICT_FCTIWUZ:
1617     return "PPCISD::STRICT_FCTIWUZ";
1618   case PPCISD::STRICT_FCFID:
1619     return "PPCISD::STRICT_FCFID";
1620   case PPCISD::STRICT_FCFIDU:
1621     return "PPCISD::STRICT_FCFIDU";
1622   case PPCISD::STRICT_FCFIDS:
1623     return "PPCISD::STRICT_FCFIDS";
1624   case PPCISD::STRICT_FCFIDUS:
1625     return "PPCISD::STRICT_FCFIDUS";
1626   case PPCISD::LXVRZX:          return "PPCISD::LXVRZX";
1627   }
1628   return nullptr;
1629 }
1630 
1631 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1632                                           EVT VT) const {
1633   if (!VT.isVector())
1634     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1635 
1636   return VT.changeVectorElementTypeToInteger();
1637 }
1638 
1639 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1640   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1641   return true;
1642 }
1643 
1644 //===----------------------------------------------------------------------===//
1645 // Node matching predicates, for use by the tblgen matching code.
1646 //===----------------------------------------------------------------------===//
1647 
1648 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1649 static bool isFloatingPointZero(SDValue Op) {
1650   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1651     return CFP->getValueAPF().isZero();
1652   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1653     // Maybe this has already been legalized into the constant pool?
1654     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1655       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1656         return CFP->getValueAPF().isZero();
1657   }
1658   return false;
1659 }
1660 
1661 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1662 /// true if Op is undef or if it matches the specified value.
1663 static bool isConstantOrUndef(int Op, int Val) {
1664   return Op < 0 || Op == Val;
1665 }
1666 
1667 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1668 /// VPKUHUM instruction.
1669 /// The ShuffleKind distinguishes between big-endian operations with
1670 /// two different inputs (0), either-endian operations with two identical
1671 /// inputs (1), and little-endian operations with two different inputs (2).
1672 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1673 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1674                                SelectionDAG &DAG) {
1675   bool IsLE = DAG.getDataLayout().isLittleEndian();
1676   if (ShuffleKind == 0) {
1677     if (IsLE)
1678       return false;
1679     for (unsigned i = 0; i != 16; ++i)
1680       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1681         return false;
1682   } else if (ShuffleKind == 2) {
1683     if (!IsLE)
1684       return false;
1685     for (unsigned i = 0; i != 16; ++i)
1686       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1687         return false;
1688   } else if (ShuffleKind == 1) {
1689     unsigned j = IsLE ? 0 : 1;
1690     for (unsigned i = 0; i != 8; ++i)
1691       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1692           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1693         return false;
1694   }
1695   return true;
1696 }
1697 
1698 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1699 /// VPKUWUM instruction.
1700 /// The ShuffleKind distinguishes between big-endian operations with
1701 /// two different inputs (0), either-endian operations with two identical
1702 /// inputs (1), and little-endian operations with two different inputs (2).
1703 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1704 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1705                                SelectionDAG &DAG) {
1706   bool IsLE = DAG.getDataLayout().isLittleEndian();
1707   if (ShuffleKind == 0) {
1708     if (IsLE)
1709       return false;
1710     for (unsigned i = 0; i != 16; i += 2)
1711       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1712           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1713         return false;
1714   } else if (ShuffleKind == 2) {
1715     if (!IsLE)
1716       return false;
1717     for (unsigned i = 0; i != 16; i += 2)
1718       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1719           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1720         return false;
1721   } else if (ShuffleKind == 1) {
1722     unsigned j = IsLE ? 0 : 2;
1723     for (unsigned i = 0; i != 8; i += 2)
1724       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1725           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1726           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1727           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1728         return false;
1729   }
1730   return true;
1731 }
1732 
1733 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1734 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1735 /// current subtarget.
1736 ///
1737 /// The ShuffleKind distinguishes between big-endian operations with
1738 /// two different inputs (0), either-endian operations with two identical
1739 /// inputs (1), and little-endian operations with two different inputs (2).
1740 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1741 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1742                                SelectionDAG &DAG) {
1743   const PPCSubtarget& Subtarget =
1744       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1745   if (!Subtarget.hasP8Vector())
1746     return false;
1747 
1748   bool IsLE = DAG.getDataLayout().isLittleEndian();
1749   if (ShuffleKind == 0) {
1750     if (IsLE)
1751       return false;
1752     for (unsigned i = 0; i != 16; i += 4)
1753       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1754           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1755           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1756           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1757         return false;
1758   } else if (ShuffleKind == 2) {
1759     if (!IsLE)
1760       return false;
1761     for (unsigned i = 0; i != 16; i += 4)
1762       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1763           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1764           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1765           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1766         return false;
1767   } else if (ShuffleKind == 1) {
1768     unsigned j = IsLE ? 0 : 4;
1769     for (unsigned i = 0; i != 8; i += 4)
1770       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1771           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1772           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1773           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1774           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1775           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1776           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1777           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1778         return false;
1779   }
1780   return true;
1781 }
1782 
1783 /// isVMerge - Common function, used to match vmrg* shuffles.
1784 ///
1785 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1786                      unsigned LHSStart, unsigned RHSStart) {
1787   if (N->getValueType(0) != MVT::v16i8)
1788     return false;
1789   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1790          "Unsupported merge size!");
1791 
1792   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1793     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1794       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1795                              LHSStart+j+i*UnitSize) ||
1796           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1797                              RHSStart+j+i*UnitSize))
1798         return false;
1799     }
1800   return true;
1801 }
1802 
1803 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1804 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1805 /// The ShuffleKind distinguishes between big-endian merges with two
1806 /// different inputs (0), either-endian merges with two identical inputs (1),
1807 /// and little-endian merges with two different inputs (2).  For the latter,
1808 /// the input operands are swapped (see PPCInstrAltivec.td).
1809 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1810                              unsigned ShuffleKind, SelectionDAG &DAG) {
1811   if (DAG.getDataLayout().isLittleEndian()) {
1812     if (ShuffleKind == 1) // unary
1813       return isVMerge(N, UnitSize, 0, 0);
1814     else if (ShuffleKind == 2) // swapped
1815       return isVMerge(N, UnitSize, 0, 16);
1816     else
1817       return false;
1818   } else {
1819     if (ShuffleKind == 1) // unary
1820       return isVMerge(N, UnitSize, 8, 8);
1821     else if (ShuffleKind == 0) // normal
1822       return isVMerge(N, UnitSize, 8, 24);
1823     else
1824       return false;
1825   }
1826 }
1827 
1828 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1829 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1830 /// The ShuffleKind distinguishes between big-endian merges with two
1831 /// different inputs (0), either-endian merges with two identical inputs (1),
1832 /// and little-endian merges with two different inputs (2).  For the latter,
1833 /// the input operands are swapped (see PPCInstrAltivec.td).
1834 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1835                              unsigned ShuffleKind, SelectionDAG &DAG) {
1836   if (DAG.getDataLayout().isLittleEndian()) {
1837     if (ShuffleKind == 1) // unary
1838       return isVMerge(N, UnitSize, 8, 8);
1839     else if (ShuffleKind == 2) // swapped
1840       return isVMerge(N, UnitSize, 8, 24);
1841     else
1842       return false;
1843   } else {
1844     if (ShuffleKind == 1) // unary
1845       return isVMerge(N, UnitSize, 0, 0);
1846     else if (ShuffleKind == 0) // normal
1847       return isVMerge(N, UnitSize, 0, 16);
1848     else
1849       return false;
1850   }
1851 }
1852 
1853 /**
1854  * Common function used to match vmrgew and vmrgow shuffles
1855  *
1856  * The indexOffset determines whether to look for even or odd words in
1857  * the shuffle mask. This is based on the of the endianness of the target
1858  * machine.
1859  *   - Little Endian:
1860  *     - Use offset of 0 to check for odd elements
1861  *     - Use offset of 4 to check for even elements
1862  *   - Big Endian:
1863  *     - Use offset of 0 to check for even elements
1864  *     - Use offset of 4 to check for odd elements
1865  * A detailed description of the vector element ordering for little endian and
1866  * big endian can be found at
1867  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1868  * Targeting your applications - what little endian and big endian IBM XL C/C++
1869  * compiler differences mean to you
1870  *
1871  * The mask to the shuffle vector instruction specifies the indices of the
1872  * elements from the two input vectors to place in the result. The elements are
1873  * numbered in array-access order, starting with the first vector. These vectors
1874  * are always of type v16i8, thus each vector will contain 16 elements of size
1875  * 8. More info on the shuffle vector can be found in the
1876  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1877  * Language Reference.
1878  *
1879  * The RHSStartValue indicates whether the same input vectors are used (unary)
1880  * or two different input vectors are used, based on the following:
1881  *   - If the instruction uses the same vector for both inputs, the range of the
1882  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1883  *     be 0.
1884  *   - If the instruction has two different vectors then the range of the
1885  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1886  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1887  *     to 31 specify elements in the second vector).
1888  *
1889  * \param[in] N The shuffle vector SD Node to analyze
1890  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1891  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1892  * vector to the shuffle_vector instruction
1893  * \return true iff this shuffle vector represents an even or odd word merge
1894  */
1895 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1896                      unsigned RHSStartValue) {
1897   if (N->getValueType(0) != MVT::v16i8)
1898     return false;
1899 
1900   for (unsigned i = 0; i < 2; ++i)
1901     for (unsigned j = 0; j < 4; ++j)
1902       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1903                              i*RHSStartValue+j+IndexOffset) ||
1904           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1905                              i*RHSStartValue+j+IndexOffset+8))
1906         return false;
1907   return true;
1908 }
1909 
1910 /**
1911  * Determine if the specified shuffle mask is suitable for the vmrgew or
1912  * vmrgow instructions.
1913  *
1914  * \param[in] N The shuffle vector SD Node to analyze
1915  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1916  * \param[in] ShuffleKind Identify the type of merge:
1917  *   - 0 = big-endian merge with two different inputs;
1918  *   - 1 = either-endian merge with two identical inputs;
1919  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1920  *     little-endian merges).
1921  * \param[in] DAG The current SelectionDAG
1922  * \return true iff this shuffle mask
1923  */
1924 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1925                               unsigned ShuffleKind, SelectionDAG &DAG) {
1926   if (DAG.getDataLayout().isLittleEndian()) {
1927     unsigned indexOffset = CheckEven ? 4 : 0;
1928     if (ShuffleKind == 1) // Unary
1929       return isVMerge(N, indexOffset, 0);
1930     else if (ShuffleKind == 2) // swapped
1931       return isVMerge(N, indexOffset, 16);
1932     else
1933       return false;
1934   }
1935   else {
1936     unsigned indexOffset = CheckEven ? 0 : 4;
1937     if (ShuffleKind == 1) // Unary
1938       return isVMerge(N, indexOffset, 0);
1939     else if (ShuffleKind == 0) // Normal
1940       return isVMerge(N, indexOffset, 16);
1941     else
1942       return false;
1943   }
1944   return false;
1945 }
1946 
1947 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1948 /// amount, otherwise return -1.
1949 /// The ShuffleKind distinguishes between big-endian operations with two
1950 /// different inputs (0), either-endian operations with two identical inputs
1951 /// (1), and little-endian operations with two different inputs (2).  For the
1952 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1953 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1954                              SelectionDAG &DAG) {
1955   if (N->getValueType(0) != MVT::v16i8)
1956     return -1;
1957 
1958   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1959 
1960   // Find the first non-undef value in the shuffle mask.
1961   unsigned i;
1962   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1963     /*search*/;
1964 
1965   if (i == 16) return -1;  // all undef.
1966 
1967   // Otherwise, check to see if the rest of the elements are consecutively
1968   // numbered from this value.
1969   unsigned ShiftAmt = SVOp->getMaskElt(i);
1970   if (ShiftAmt < i) return -1;
1971 
1972   ShiftAmt -= i;
1973   bool isLE = DAG.getDataLayout().isLittleEndian();
1974 
1975   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1976     // Check the rest of the elements to see if they are consecutive.
1977     for (++i; i != 16; ++i)
1978       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1979         return -1;
1980   } else if (ShuffleKind == 1) {
1981     // Check the rest of the elements to see if they are consecutive.
1982     for (++i; i != 16; ++i)
1983       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1984         return -1;
1985   } else
1986     return -1;
1987 
1988   if (isLE)
1989     ShiftAmt = 16 - ShiftAmt;
1990 
1991   return ShiftAmt;
1992 }
1993 
1994 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1995 /// specifies a splat of a single element that is suitable for input to
1996 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1997 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1998   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1999          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2000 
2001   // The consecutive indices need to specify an element, not part of two
2002   // different elements.  So abandon ship early if this isn't the case.
2003   if (N->getMaskElt(0) % EltSize != 0)
2004     return false;
2005 
2006   // This is a splat operation if each element of the permute is the same, and
2007   // if the value doesn't reference the second vector.
2008   unsigned ElementBase = N->getMaskElt(0);
2009 
2010   // FIXME: Handle UNDEF elements too!
2011   if (ElementBase >= 16)
2012     return false;
2013 
2014   // Check that the indices are consecutive, in the case of a multi-byte element
2015   // splatted with a v16i8 mask.
2016   for (unsigned i = 1; i != EltSize; ++i)
2017     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2018       return false;
2019 
2020   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2021     if (N->getMaskElt(i) < 0) continue;
2022     for (unsigned j = 0; j != EltSize; ++j)
2023       if (N->getMaskElt(i+j) != N->getMaskElt(j))
2024         return false;
2025   }
2026   return true;
2027 }
2028 
2029 /// Check that the mask is shuffling N byte elements. Within each N byte
2030 /// element of the mask, the indices could be either in increasing or
2031 /// decreasing order as long as they are consecutive.
2032 /// \param[in] N the shuffle vector SD Node to analyze
2033 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2034 /// Word/DoubleWord/QuadWord).
2035 /// \param[in] StepLen the delta indices number among the N byte element, if
2036 /// the mask is in increasing/decreasing order then it is 1/-1.
2037 /// \return true iff the mask is shuffling N byte elements.
2038 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2039                                    int StepLen) {
2040   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2041          "Unexpected element width.");
2042   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2043 
2044   unsigned NumOfElem = 16 / Width;
2045   unsigned MaskVal[16]; //  Width is never greater than 16
2046   for (unsigned i = 0; i < NumOfElem; ++i) {
2047     MaskVal[0] = N->getMaskElt(i * Width);
2048     if ((StepLen == 1) && (MaskVal[0] % Width)) {
2049       return false;
2050     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2051       return false;
2052     }
2053 
2054     for (unsigned int j = 1; j < Width; ++j) {
2055       MaskVal[j] = N->getMaskElt(i * Width + j);
2056       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2057         return false;
2058       }
2059     }
2060   }
2061 
2062   return true;
2063 }
2064 
2065 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2066                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2067   if (!isNByteElemShuffleMask(N, 4, 1))
2068     return false;
2069 
2070   // Now we look at mask elements 0,4,8,12
2071   unsigned M0 = N->getMaskElt(0) / 4;
2072   unsigned M1 = N->getMaskElt(4) / 4;
2073   unsigned M2 = N->getMaskElt(8) / 4;
2074   unsigned M3 = N->getMaskElt(12) / 4;
2075   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2076   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2077 
2078   // Below, let H and L be arbitrary elements of the shuffle mask
2079   // where H is in the range [4,7] and L is in the range [0,3].
2080   // H, 1, 2, 3 or L, 5, 6, 7
2081   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2082       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2083     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2084     InsertAtByte = IsLE ? 12 : 0;
2085     Swap = M0 < 4;
2086     return true;
2087   }
2088   // 0, H, 2, 3 or 4, L, 6, 7
2089   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2090       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2091     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2092     InsertAtByte = IsLE ? 8 : 4;
2093     Swap = M1 < 4;
2094     return true;
2095   }
2096   // 0, 1, H, 3 or 4, 5, L, 7
2097   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2098       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2099     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2100     InsertAtByte = IsLE ? 4 : 8;
2101     Swap = M2 < 4;
2102     return true;
2103   }
2104   // 0, 1, 2, H or 4, 5, 6, L
2105   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2106       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2107     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2108     InsertAtByte = IsLE ? 0 : 12;
2109     Swap = M3 < 4;
2110     return true;
2111   }
2112 
2113   // If both vector operands for the shuffle are the same vector, the mask will
2114   // contain only elements from the first one and the second one will be undef.
2115   if (N->getOperand(1).isUndef()) {
2116     ShiftElts = 0;
2117     Swap = true;
2118     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2119     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2120       InsertAtByte = IsLE ? 12 : 0;
2121       return true;
2122     }
2123     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2124       InsertAtByte = IsLE ? 8 : 4;
2125       return true;
2126     }
2127     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2128       InsertAtByte = IsLE ? 4 : 8;
2129       return true;
2130     }
2131     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2132       InsertAtByte = IsLE ? 0 : 12;
2133       return true;
2134     }
2135   }
2136 
2137   return false;
2138 }
2139 
2140 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2141                                bool &Swap, bool IsLE) {
2142   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2143   // Ensure each byte index of the word is consecutive.
2144   if (!isNByteElemShuffleMask(N, 4, 1))
2145     return false;
2146 
2147   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2148   unsigned M0 = N->getMaskElt(0) / 4;
2149   unsigned M1 = N->getMaskElt(4) / 4;
2150   unsigned M2 = N->getMaskElt(8) / 4;
2151   unsigned M3 = N->getMaskElt(12) / 4;
2152 
2153   // If both vector operands for the shuffle are the same vector, the mask will
2154   // contain only elements from the first one and the second one will be undef.
2155   if (N->getOperand(1).isUndef()) {
2156     assert(M0 < 4 && "Indexing into an undef vector?");
2157     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2158       return false;
2159 
2160     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2161     Swap = false;
2162     return true;
2163   }
2164 
2165   // Ensure each word index of the ShuffleVector Mask is consecutive.
2166   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2167     return false;
2168 
2169   if (IsLE) {
2170     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2171       // Input vectors don't need to be swapped if the leading element
2172       // of the result is one of the 3 left elements of the second vector
2173       // (or if there is no shift to be done at all).
2174       Swap = false;
2175       ShiftElts = (8 - M0) % 8;
2176     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2177       // Input vectors need to be swapped if the leading element
2178       // of the result is one of the 3 left elements of the first vector
2179       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2180       Swap = true;
2181       ShiftElts = (4 - M0) % 4;
2182     }
2183 
2184     return true;
2185   } else {                                          // BE
2186     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2187       // Input vectors don't need to be swapped if the leading element
2188       // of the result is one of the 4 elements of the first vector.
2189       Swap = false;
2190       ShiftElts = M0;
2191     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2192       // Input vectors need to be swapped if the leading element
2193       // of the result is one of the 4 elements of the right vector.
2194       Swap = true;
2195       ShiftElts = M0 - 4;
2196     }
2197 
2198     return true;
2199   }
2200 }
2201 
2202 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2203   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2204 
2205   if (!isNByteElemShuffleMask(N, Width, -1))
2206     return false;
2207 
2208   for (int i = 0; i < 16; i += Width)
2209     if (N->getMaskElt(i) != i + Width - 1)
2210       return false;
2211 
2212   return true;
2213 }
2214 
2215 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2216   return isXXBRShuffleMaskHelper(N, 2);
2217 }
2218 
2219 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2220   return isXXBRShuffleMaskHelper(N, 4);
2221 }
2222 
2223 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2224   return isXXBRShuffleMaskHelper(N, 8);
2225 }
2226 
2227 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2228   return isXXBRShuffleMaskHelper(N, 16);
2229 }
2230 
2231 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2232 /// if the inputs to the instruction should be swapped and set \p DM to the
2233 /// value for the immediate.
2234 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2235 /// AND element 0 of the result comes from the first input (LE) or second input
2236 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2237 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2238 /// mask.
2239 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2240                                bool &Swap, bool IsLE) {
2241   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2242 
2243   // Ensure each byte index of the double word is consecutive.
2244   if (!isNByteElemShuffleMask(N, 8, 1))
2245     return false;
2246 
2247   unsigned M0 = N->getMaskElt(0) / 8;
2248   unsigned M1 = N->getMaskElt(8) / 8;
2249   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2250 
2251   // If both vector operands for the shuffle are the same vector, the mask will
2252   // contain only elements from the first one and the second one will be undef.
2253   if (N->getOperand(1).isUndef()) {
2254     if ((M0 | M1) < 2) {
2255       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2256       Swap = false;
2257       return true;
2258     } else
2259       return false;
2260   }
2261 
2262   if (IsLE) {
2263     if (M0 > 1 && M1 < 2) {
2264       Swap = false;
2265     } else if (M0 < 2 && M1 > 1) {
2266       M0 = (M0 + 2) % 4;
2267       M1 = (M1 + 2) % 4;
2268       Swap = true;
2269     } else
2270       return false;
2271 
2272     // Note: if control flow comes here that means Swap is already set above
2273     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2274     return true;
2275   } else { // BE
2276     if (M0 < 2 && M1 > 1) {
2277       Swap = false;
2278     } else if (M0 > 1 && M1 < 2) {
2279       M0 = (M0 + 2) % 4;
2280       M1 = (M1 + 2) % 4;
2281       Swap = true;
2282     } else
2283       return false;
2284 
2285     // Note: if control flow comes here that means Swap is already set above
2286     DM = (M0 << 1) + (M1 & 1);
2287     return true;
2288   }
2289 }
2290 
2291 
2292 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2293 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2294 /// elements are counted from the left of the vector register).
2295 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2296                                          SelectionDAG &DAG) {
2297   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2298   assert(isSplatShuffleMask(SVOp, EltSize));
2299   if (DAG.getDataLayout().isLittleEndian())
2300     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2301   else
2302     return SVOp->getMaskElt(0) / EltSize;
2303 }
2304 
2305 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2306 /// by using a vspltis[bhw] instruction of the specified element size, return
2307 /// the constant being splatted.  The ByteSize field indicates the number of
2308 /// bytes of each element [124] -> [bhw].
2309 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2310   SDValue OpVal(nullptr, 0);
2311 
2312   // If ByteSize of the splat is bigger than the element size of the
2313   // build_vector, then we have a case where we are checking for a splat where
2314   // multiple elements of the buildvector are folded together into a single
2315   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2316   unsigned EltSize = 16/N->getNumOperands();
2317   if (EltSize < ByteSize) {
2318     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2319     SDValue UniquedVals[4];
2320     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2321 
2322     // See if all of the elements in the buildvector agree across.
2323     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2324       if (N->getOperand(i).isUndef()) continue;
2325       // If the element isn't a constant, bail fully out.
2326       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2327 
2328       if (!UniquedVals[i&(Multiple-1)].getNode())
2329         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2330       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2331         return SDValue();  // no match.
2332     }
2333 
2334     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2335     // either constant or undef values that are identical for each chunk.  See
2336     // if these chunks can form into a larger vspltis*.
2337 
2338     // Check to see if all of the leading entries are either 0 or -1.  If
2339     // neither, then this won't fit into the immediate field.
2340     bool LeadingZero = true;
2341     bool LeadingOnes = true;
2342     for (unsigned i = 0; i != Multiple-1; ++i) {
2343       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2344 
2345       LeadingZero &= isNullConstant(UniquedVals[i]);
2346       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2347     }
2348     // Finally, check the least significant entry.
2349     if (LeadingZero) {
2350       if (!UniquedVals[Multiple-1].getNode())
2351         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2352       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2353       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2354         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2355     }
2356     if (LeadingOnes) {
2357       if (!UniquedVals[Multiple-1].getNode())
2358         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2359       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2360       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2361         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2362     }
2363 
2364     return SDValue();
2365   }
2366 
2367   // Check to see if this buildvec has a single non-undef value in its elements.
2368   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2369     if (N->getOperand(i).isUndef()) continue;
2370     if (!OpVal.getNode())
2371       OpVal = N->getOperand(i);
2372     else if (OpVal != N->getOperand(i))
2373       return SDValue();
2374   }
2375 
2376   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2377 
2378   unsigned ValSizeInBytes = EltSize;
2379   uint64_t Value = 0;
2380   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2381     Value = CN->getZExtValue();
2382   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2383     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2384     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2385   }
2386 
2387   // If the splat value is larger than the element value, then we can never do
2388   // this splat.  The only case that we could fit the replicated bits into our
2389   // immediate field for would be zero, and we prefer to use vxor for it.
2390   if (ValSizeInBytes < ByteSize) return SDValue();
2391 
2392   // If the element value is larger than the splat value, check if it consists
2393   // of a repeated bit pattern of size ByteSize.
2394   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2395     return SDValue();
2396 
2397   // Properly sign extend the value.
2398   int MaskVal = SignExtend32(Value, ByteSize * 8);
2399 
2400   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2401   if (MaskVal == 0) return SDValue();
2402 
2403   // Finally, if this value fits in a 5 bit sext field, return it
2404   if (SignExtend32<5>(MaskVal) == MaskVal)
2405     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2406   return SDValue();
2407 }
2408 
2409 //===----------------------------------------------------------------------===//
2410 //  Addressing Mode Selection
2411 //===----------------------------------------------------------------------===//
2412 
2413 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2414 /// or 64-bit immediate, and if the value can be accurately represented as a
2415 /// sign extension from a 16-bit value.  If so, this returns true and the
2416 /// immediate.
2417 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2418   if (!isa<ConstantSDNode>(N))
2419     return false;
2420 
2421   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2422   if (N->getValueType(0) == MVT::i32)
2423     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2424   else
2425     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2426 }
2427 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2428   return isIntS16Immediate(Op.getNode(), Imm);
2429 }
2430 
2431 
2432 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2433 /// be represented as an indexed [r+r] operation.
2434 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2435                                                SDValue &Index,
2436                                                SelectionDAG &DAG) const {
2437   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2438       UI != E; ++UI) {
2439     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2440       if (Memop->getMemoryVT() == MVT::f64) {
2441           Base = N.getOperand(0);
2442           Index = N.getOperand(1);
2443           return true;
2444       }
2445     }
2446   }
2447   return false;
2448 }
2449 
2450 /// isIntS34Immediate - This method tests if value of node given can be
2451 /// accurately represented as a sign extension from a 34-bit value.  If so,
2452 /// this returns true and the immediate.
2453 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2454   if (!isa<ConstantSDNode>(N))
2455     return false;
2456 
2457   Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2458   return isInt<34>(Imm);
2459 }
2460 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2461   return isIntS34Immediate(Op.getNode(), Imm);
2462 }
2463 
2464 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2465 /// can be represented as an indexed [r+r] operation.  Returns false if it
2466 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2467 /// non-zero and N can be represented by a base register plus a signed 16-bit
2468 /// displacement, make a more precise judgement by checking (displacement % \p
2469 /// EncodingAlignment).
2470 bool PPCTargetLowering::SelectAddressRegReg(
2471     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2472     MaybeAlign EncodingAlignment) const {
2473   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2474   // a [pc+imm].
2475   if (SelectAddressPCRel(N, Base))
2476     return false;
2477 
2478   int16_t Imm = 0;
2479   if (N.getOpcode() == ISD::ADD) {
2480     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2481     // SPE load/store can only handle 8-bit offsets.
2482     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2483         return true;
2484     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2485         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2486       return false; // r+i
2487     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2488       return false;    // r+i
2489 
2490     Base = N.getOperand(0);
2491     Index = N.getOperand(1);
2492     return true;
2493   } else if (N.getOpcode() == ISD::OR) {
2494     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2495         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2496       return false; // r+i can fold it if we can.
2497 
2498     // If this is an or of disjoint bitfields, we can codegen this as an add
2499     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2500     // disjoint.
2501     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2502 
2503     if (LHSKnown.Zero.getBoolValue()) {
2504       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2505       // If all of the bits are known zero on the LHS or RHS, the add won't
2506       // carry.
2507       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2508         Base = N.getOperand(0);
2509         Index = N.getOperand(1);
2510         return true;
2511       }
2512     }
2513   }
2514 
2515   return false;
2516 }
2517 
2518 // If we happen to be doing an i64 load or store into a stack slot that has
2519 // less than a 4-byte alignment, then the frame-index elimination may need to
2520 // use an indexed load or store instruction (because the offset may not be a
2521 // multiple of 4). The extra register needed to hold the offset comes from the
2522 // register scavenger, and it is possible that the scavenger will need to use
2523 // an emergency spill slot. As a result, we need to make sure that a spill slot
2524 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2525 // stack slot.
2526 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2527   // FIXME: This does not handle the LWA case.
2528   if (VT != MVT::i64)
2529     return;
2530 
2531   // NOTE: We'll exclude negative FIs here, which come from argument
2532   // lowering, because there are no known test cases triggering this problem
2533   // using packed structures (or similar). We can remove this exclusion if
2534   // we find such a test case. The reason why this is so test-case driven is
2535   // because this entire 'fixup' is only to prevent crashes (from the
2536   // register scavenger) on not-really-valid inputs. For example, if we have:
2537   //   %a = alloca i1
2538   //   %b = bitcast i1* %a to i64*
2539   //   store i64* a, i64 b
2540   // then the store should really be marked as 'align 1', but is not. If it
2541   // were marked as 'align 1' then the indexed form would have been
2542   // instruction-selected initially, and the problem this 'fixup' is preventing
2543   // won't happen regardless.
2544   if (FrameIdx < 0)
2545     return;
2546 
2547   MachineFunction &MF = DAG.getMachineFunction();
2548   MachineFrameInfo &MFI = MF.getFrameInfo();
2549 
2550   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2551     return;
2552 
2553   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2554   FuncInfo->setHasNonRISpills();
2555 }
2556 
2557 /// Returns true if the address N can be represented by a base register plus
2558 /// a signed 16-bit displacement [r+imm], and if it is not better
2559 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2560 /// displacements that are multiples of that value.
2561 bool PPCTargetLowering::SelectAddressRegImm(
2562     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2563     MaybeAlign EncodingAlignment) const {
2564   // FIXME dl should come from parent load or store, not from address
2565   SDLoc dl(N);
2566 
2567   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2568   // a [pc+imm].
2569   if (SelectAddressPCRel(N, Base))
2570     return false;
2571 
2572   // If this can be more profitably realized as r+r, fail.
2573   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2574     return false;
2575 
2576   if (N.getOpcode() == ISD::ADD) {
2577     int16_t imm = 0;
2578     if (isIntS16Immediate(N.getOperand(1), imm) &&
2579         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2580       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2581       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2582         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2583         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2584       } else {
2585         Base = N.getOperand(0);
2586       }
2587       return true; // [r+i]
2588     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2589       // Match LOAD (ADD (X, Lo(G))).
2590       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2591              && "Cannot handle constant offsets yet!");
2592       Disp = N.getOperand(1).getOperand(0);  // The global address.
2593       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2594              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2595              Disp.getOpcode() == ISD::TargetConstantPool ||
2596              Disp.getOpcode() == ISD::TargetJumpTable);
2597       Base = N.getOperand(0);
2598       return true;  // [&g+r]
2599     }
2600   } else if (N.getOpcode() == ISD::OR) {
2601     int16_t imm = 0;
2602     if (isIntS16Immediate(N.getOperand(1), imm) &&
2603         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2604       // If this is an or of disjoint bitfields, we can codegen this as an add
2605       // (for better address arithmetic) if the LHS and RHS of the OR are
2606       // provably disjoint.
2607       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2608 
2609       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2610         // If all of the bits are known zero on the LHS or RHS, the add won't
2611         // carry.
2612         if (FrameIndexSDNode *FI =
2613               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2614           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2615           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2616         } else {
2617           Base = N.getOperand(0);
2618         }
2619         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2620         return true;
2621       }
2622     }
2623   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2624     // Loading from a constant address.
2625 
2626     // If this address fits entirely in a 16-bit sext immediate field, codegen
2627     // this as "d, 0"
2628     int16_t Imm;
2629     if (isIntS16Immediate(CN, Imm) &&
2630         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2631       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2632       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2633                              CN->getValueType(0));
2634       return true;
2635     }
2636 
2637     // Handle 32-bit sext immediates with LIS + addr mode.
2638     if ((CN->getValueType(0) == MVT::i32 ||
2639          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2640         (!EncodingAlignment ||
2641          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2642       int Addr = (int)CN->getZExtValue();
2643 
2644       // Otherwise, break this down into an LIS + disp.
2645       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2646 
2647       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2648                                    MVT::i32);
2649       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2650       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2651       return true;
2652     }
2653   }
2654 
2655   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2656   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2657     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2658     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2659   } else
2660     Base = N;
2661   return true;      // [r+0]
2662 }
2663 
2664 /// Similar to the 16-bit case but for instructions that take a 34-bit
2665 /// displacement field (prefixed loads/stores).
2666 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp,
2667                                               SDValue &Base,
2668                                               SelectionDAG &DAG) const {
2669   // Only on 64-bit targets.
2670   if (N.getValueType() != MVT::i64)
2671     return false;
2672 
2673   SDLoc dl(N);
2674   int64_t Imm = 0;
2675 
2676   if (N.getOpcode() == ISD::ADD) {
2677     if (!isIntS34Immediate(N.getOperand(1), Imm))
2678       return false;
2679     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2680     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2681       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2682     else
2683       Base = N.getOperand(0);
2684     return true;
2685   }
2686 
2687   if (N.getOpcode() == ISD::OR) {
2688     if (!isIntS34Immediate(N.getOperand(1), Imm))
2689       return false;
2690     // If this is an or of disjoint bitfields, we can codegen this as an add
2691     // (for better address arithmetic) if the LHS and RHS of the OR are
2692     // provably disjoint.
2693     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2694     if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2695       return false;
2696     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2697       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2698     else
2699       Base = N.getOperand(0);
2700     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2701     return true;
2702   }
2703 
2704   if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2705     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2706     Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2707     return true;
2708   }
2709 
2710   return false;
2711 }
2712 
2713 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2714 /// represented as an indexed [r+r] operation.
2715 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2716                                                 SDValue &Index,
2717                                                 SelectionDAG &DAG) const {
2718   // Check to see if we can easily represent this as an [r+r] address.  This
2719   // will fail if it thinks that the address is more profitably represented as
2720   // reg+imm, e.g. where imm = 0.
2721   if (SelectAddressRegReg(N, Base, Index, DAG))
2722     return true;
2723 
2724   // If the address is the result of an add, we will utilize the fact that the
2725   // address calculation includes an implicit add.  However, we can reduce
2726   // register pressure if we do not materialize a constant just for use as the
2727   // index register.  We only get rid of the add if it is not an add of a
2728   // value and a 16-bit signed constant and both have a single use.
2729   int16_t imm = 0;
2730   if (N.getOpcode() == ISD::ADD &&
2731       (!isIntS16Immediate(N.getOperand(1), imm) ||
2732        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2733     Base = N.getOperand(0);
2734     Index = N.getOperand(1);
2735     return true;
2736   }
2737 
2738   // Otherwise, do it the hard way, using R0 as the base register.
2739   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2740                          N.getValueType());
2741   Index = N;
2742   return true;
2743 }
2744 
2745 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2746   Ty *PCRelCand = dyn_cast<Ty>(N);
2747   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2748 }
2749 
2750 /// Returns true if this address is a PC Relative address.
2751 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2752 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2753 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2754   // This is a materialize PC Relative node. Always select this as PC Relative.
2755   Base = N;
2756   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2757     return true;
2758   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2759       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2760       isValidPCRelNode<JumpTableSDNode>(N) ||
2761       isValidPCRelNode<BlockAddressSDNode>(N))
2762     return true;
2763   return false;
2764 }
2765 
2766 /// Returns true if we should use a direct load into vector instruction
2767 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2768 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2769 
2770   // If there are any other uses other than scalar to vector, then we should
2771   // keep it as a scalar load -> direct move pattern to prevent multiple
2772   // loads.
2773   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2774   if (!LD)
2775     return false;
2776 
2777   EVT MemVT = LD->getMemoryVT();
2778   if (!MemVT.isSimple())
2779     return false;
2780   switch(MemVT.getSimpleVT().SimpleTy) {
2781   case MVT::i64:
2782     break;
2783   case MVT::i32:
2784     if (!ST.hasP8Vector())
2785       return false;
2786     break;
2787   case MVT::i16:
2788   case MVT::i8:
2789     if (!ST.hasP9Vector())
2790       return false;
2791     break;
2792   default:
2793     return false;
2794   }
2795 
2796   SDValue LoadedVal(N, 0);
2797   if (!LoadedVal.hasOneUse())
2798     return false;
2799 
2800   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2801        UI != UE; ++UI)
2802     if (UI.getUse().get().getResNo() == 0 &&
2803         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2804         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2805       return false;
2806 
2807   return true;
2808 }
2809 
2810 /// getPreIndexedAddressParts - returns true by value, base pointer and
2811 /// offset pointer and addressing mode by reference if the node's address
2812 /// can be legally represented as pre-indexed load / store address.
2813 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2814                                                   SDValue &Offset,
2815                                                   ISD::MemIndexedMode &AM,
2816                                                   SelectionDAG &DAG) const {
2817   if (DisablePPCPreinc) return false;
2818 
2819   bool isLoad = true;
2820   SDValue Ptr;
2821   EVT VT;
2822   unsigned Alignment;
2823   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2824     Ptr = LD->getBasePtr();
2825     VT = LD->getMemoryVT();
2826     Alignment = LD->getAlignment();
2827   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2828     Ptr = ST->getBasePtr();
2829     VT  = ST->getMemoryVT();
2830     Alignment = ST->getAlignment();
2831     isLoad = false;
2832   } else
2833     return false;
2834 
2835   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2836   // instructions because we can fold these into a more efficient instruction
2837   // instead, (such as LXSD).
2838   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2839     return false;
2840   }
2841 
2842   // PowerPC doesn't have preinc load/store instructions for vectors
2843   if (VT.isVector())
2844     return false;
2845 
2846   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2847     // Common code will reject creating a pre-inc form if the base pointer
2848     // is a frame index, or if N is a store and the base pointer is either
2849     // the same as or a predecessor of the value being stored.  Check for
2850     // those situations here, and try with swapped Base/Offset instead.
2851     bool Swap = false;
2852 
2853     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2854       Swap = true;
2855     else if (!isLoad) {
2856       SDValue Val = cast<StoreSDNode>(N)->getValue();
2857       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2858         Swap = true;
2859     }
2860 
2861     if (Swap)
2862       std::swap(Base, Offset);
2863 
2864     AM = ISD::PRE_INC;
2865     return true;
2866   }
2867 
2868   // LDU/STU can only handle immediates that are a multiple of 4.
2869   if (VT != MVT::i64) {
2870     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2871       return false;
2872   } else {
2873     // LDU/STU need an address with at least 4-byte alignment.
2874     if (Alignment < 4)
2875       return false;
2876 
2877     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
2878       return false;
2879   }
2880 
2881   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2882     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2883     // sext i32 to i64 when addr mode is r+i.
2884     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2885         LD->getExtensionType() == ISD::SEXTLOAD &&
2886         isa<ConstantSDNode>(Offset))
2887       return false;
2888   }
2889 
2890   AM = ISD::PRE_INC;
2891   return true;
2892 }
2893 
2894 //===----------------------------------------------------------------------===//
2895 //  LowerOperation implementation
2896 //===----------------------------------------------------------------------===//
2897 
2898 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2899 /// and LoOpFlags to the target MO flags.
2900 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2901                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2902                                const GlobalValue *GV = nullptr) {
2903   HiOpFlags = PPCII::MO_HA;
2904   LoOpFlags = PPCII::MO_LO;
2905 
2906   // Don't use the pic base if not in PIC relocation model.
2907   if (IsPIC) {
2908     HiOpFlags |= PPCII::MO_PIC_FLAG;
2909     LoOpFlags |= PPCII::MO_PIC_FLAG;
2910   }
2911 }
2912 
2913 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2914                              SelectionDAG &DAG) {
2915   SDLoc DL(HiPart);
2916   EVT PtrVT = HiPart.getValueType();
2917   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2918 
2919   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2920   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2921 
2922   // With PIC, the first instruction is actually "GR+hi(&G)".
2923   if (isPIC)
2924     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2925                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2926 
2927   // Generate non-pic code that has direct accesses to the constant pool.
2928   // The address of the global is just (hi(&g)+lo(&g)).
2929   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2930 }
2931 
2932 static void setUsesTOCBasePtr(MachineFunction &MF) {
2933   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2934   FuncInfo->setUsesTOCBasePtr();
2935 }
2936 
2937 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2938   setUsesTOCBasePtr(DAG.getMachineFunction());
2939 }
2940 
2941 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2942                                        SDValue GA) const {
2943   const bool Is64Bit = Subtarget.isPPC64();
2944   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2945   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2946                         : Subtarget.isAIXABI()
2947                               ? DAG.getRegister(PPC::R2, VT)
2948                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2949   SDValue Ops[] = { GA, Reg };
2950   return DAG.getMemIntrinsicNode(
2951       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2952       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2953       MachineMemOperand::MOLoad);
2954 }
2955 
2956 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2957                                              SelectionDAG &DAG) const {
2958   EVT PtrVT = Op.getValueType();
2959   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2960   const Constant *C = CP->getConstVal();
2961 
2962   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2963   // The actual address of the GlobalValue is stored in the TOC.
2964   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2965     if (Subtarget.isUsingPCRelativeCalls()) {
2966       SDLoc DL(CP);
2967       EVT Ty = getPointerTy(DAG.getDataLayout());
2968       SDValue ConstPool = DAG.getTargetConstantPool(
2969           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2970       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2971     }
2972     setUsesTOCBasePtr(DAG);
2973     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2974     return getTOCEntry(DAG, SDLoc(CP), GA);
2975   }
2976 
2977   unsigned MOHiFlag, MOLoFlag;
2978   bool IsPIC = isPositionIndependent();
2979   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2980 
2981   if (IsPIC && Subtarget.isSVR4ABI()) {
2982     SDValue GA =
2983         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2984     return getTOCEntry(DAG, SDLoc(CP), GA);
2985   }
2986 
2987   SDValue CPIHi =
2988       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
2989   SDValue CPILo =
2990       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
2991   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2992 }
2993 
2994 // For 64-bit PowerPC, prefer the more compact relative encodings.
2995 // This trades 32 bits per jump table entry for one or two instructions
2996 // on the jump site.
2997 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2998   if (isJumpTableRelative())
2999     return MachineJumpTableInfo::EK_LabelDifference32;
3000 
3001   return TargetLowering::getJumpTableEncoding();
3002 }
3003 
3004 bool PPCTargetLowering::isJumpTableRelative() const {
3005   if (UseAbsoluteJumpTables)
3006     return false;
3007   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3008     return true;
3009   return TargetLowering::isJumpTableRelative();
3010 }
3011 
3012 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
3013                                                     SelectionDAG &DAG) const {
3014   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3015     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3016 
3017   switch (getTargetMachine().getCodeModel()) {
3018   case CodeModel::Small:
3019   case CodeModel::Medium:
3020     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3021   default:
3022     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3023                        getPointerTy(DAG.getDataLayout()));
3024   }
3025 }
3026 
3027 const MCExpr *
3028 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
3029                                                 unsigned JTI,
3030                                                 MCContext &Ctx) const {
3031   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3032     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3033 
3034   switch (getTargetMachine().getCodeModel()) {
3035   case CodeModel::Small:
3036   case CodeModel::Medium:
3037     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3038   default:
3039     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3040   }
3041 }
3042 
3043 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3044   EVT PtrVT = Op.getValueType();
3045   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3046 
3047   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3048   if (Subtarget.isUsingPCRelativeCalls()) {
3049     SDLoc DL(JT);
3050     EVT Ty = getPointerTy(DAG.getDataLayout());
3051     SDValue GA =
3052         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3053     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3054     return MatAddr;
3055   }
3056 
3057   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3058   // The actual address of the GlobalValue is stored in the TOC.
3059   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3060     setUsesTOCBasePtr(DAG);
3061     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3062     return getTOCEntry(DAG, SDLoc(JT), GA);
3063   }
3064 
3065   unsigned MOHiFlag, MOLoFlag;
3066   bool IsPIC = isPositionIndependent();
3067   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3068 
3069   if (IsPIC && Subtarget.isSVR4ABI()) {
3070     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3071                                         PPCII::MO_PIC_FLAG);
3072     return getTOCEntry(DAG, SDLoc(GA), GA);
3073   }
3074 
3075   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3076   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3077   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3078 }
3079 
3080 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3081                                              SelectionDAG &DAG) const {
3082   EVT PtrVT = Op.getValueType();
3083   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3084   const BlockAddress *BA = BASDN->getBlockAddress();
3085 
3086   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3087   if (Subtarget.isUsingPCRelativeCalls()) {
3088     SDLoc DL(BASDN);
3089     EVT Ty = getPointerTy(DAG.getDataLayout());
3090     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3091                                            PPCII::MO_PCREL_FLAG);
3092     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3093     return MatAddr;
3094   }
3095 
3096   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3097   // The actual BlockAddress is stored in the TOC.
3098   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3099     setUsesTOCBasePtr(DAG);
3100     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3101     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3102   }
3103 
3104   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3105   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3106     return getTOCEntry(
3107         DAG, SDLoc(BASDN),
3108         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3109 
3110   unsigned MOHiFlag, MOLoFlag;
3111   bool IsPIC = isPositionIndependent();
3112   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3113   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3114   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3115   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3116 }
3117 
3118 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3119                                               SelectionDAG &DAG) const {
3120   if (Subtarget.isAIXABI())
3121     return LowerGlobalTLSAddressAIX(Op, DAG);
3122 
3123   return LowerGlobalTLSAddressLinux(Op, DAG);
3124 }
3125 
3126 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3127                                                     SelectionDAG &DAG) const {
3128   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3129 
3130   if (DAG.getTarget().useEmulatedTLS())
3131     report_fatal_error("Emulated TLS is not yet supported on AIX");
3132 
3133   SDLoc dl(GA);
3134   const GlobalValue *GV = GA->getGlobal();
3135   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3136 
3137   // The general-dynamic model is the only access model supported for now, so
3138   // all the GlobalTLSAddress nodes are lowered with this model.
3139   // We need to generate two TOC entries, one for the variable offset, one for
3140   // the region handle. The global address for the TOC entry of the region
3141   // handle is created with the MO_TLSGD_FLAG flag so we can easily identify
3142   // this entry and add the right relocation.
3143   SDValue VariableOffsetTGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3144   SDValue RegionHandleTGA =
3145       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3146   SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3147   SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3148   return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3149                      RegionHandle);
3150 }
3151 
3152 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3153                                                       SelectionDAG &DAG) const {
3154   // FIXME: TLS addresses currently use medium model code sequences,
3155   // which is the most useful form.  Eventually support for small and
3156   // large models could be added if users need it, at the cost of
3157   // additional complexity.
3158   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3159   if (DAG.getTarget().useEmulatedTLS())
3160     return LowerToTLSEmulatedModel(GA, DAG);
3161 
3162   SDLoc dl(GA);
3163   const GlobalValue *GV = GA->getGlobal();
3164   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3165   bool is64bit = Subtarget.isPPC64();
3166   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3167   PICLevel::Level picLevel = M->getPICLevel();
3168 
3169   const TargetMachine &TM = getTargetMachine();
3170   TLSModel::Model Model = TM.getTLSModel(GV);
3171 
3172   if (Model == TLSModel::LocalExec) {
3173     if (Subtarget.isUsingPCRelativeCalls()) {
3174       SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3175       SDValue TGA = DAG.getTargetGlobalAddress(
3176           GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3177       SDValue MatAddr =
3178           DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3179       return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3180     }
3181 
3182     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3183                                                PPCII::MO_TPREL_HA);
3184     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3185                                                PPCII::MO_TPREL_LO);
3186     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3187                              : DAG.getRegister(PPC::R2, MVT::i32);
3188 
3189     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3190     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3191   }
3192 
3193   if (Model == TLSModel::InitialExec) {
3194     bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3195     SDValue TGA = DAG.getTargetGlobalAddress(
3196         GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3197     SDValue TGATLS = DAG.getTargetGlobalAddress(
3198         GV, dl, PtrVT, 0,
3199         IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3200     SDValue TPOffset;
3201     if (IsPCRel) {
3202       SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3203       TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3204                              MachinePointerInfo());
3205     } else {
3206       SDValue GOTPtr;
3207       if (is64bit) {
3208         setUsesTOCBasePtr(DAG);
3209         SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3210         GOTPtr =
3211             DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3212       } else {
3213         if (!TM.isPositionIndependent())
3214           GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3215         else if (picLevel == PICLevel::SmallPIC)
3216           GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3217         else
3218           GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3219       }
3220       TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3221     }
3222     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3223   }
3224 
3225   if (Model == TLSModel::GeneralDynamic) {
3226     if (Subtarget.isUsingPCRelativeCalls()) {
3227       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3228                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3229       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3230     }
3231 
3232     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3233     SDValue GOTPtr;
3234     if (is64bit) {
3235       setUsesTOCBasePtr(DAG);
3236       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3237       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3238                                    GOTReg, TGA);
3239     } else {
3240       if (picLevel == PICLevel::SmallPIC)
3241         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3242       else
3243         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3244     }
3245     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3246                        GOTPtr, TGA, TGA);
3247   }
3248 
3249   if (Model == TLSModel::LocalDynamic) {
3250     if (Subtarget.isUsingPCRelativeCalls()) {
3251       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3252                                                PPCII::MO_GOT_TLSLD_PCREL_FLAG);
3253       SDValue MatPCRel =
3254           DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3255       return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3256     }
3257 
3258     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3259     SDValue GOTPtr;
3260     if (is64bit) {
3261       setUsesTOCBasePtr(DAG);
3262       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3263       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3264                            GOTReg, TGA);
3265     } else {
3266       if (picLevel == PICLevel::SmallPIC)
3267         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3268       else
3269         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3270     }
3271     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3272                                   PtrVT, GOTPtr, TGA, TGA);
3273     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3274                                       PtrVT, TLSAddr, TGA);
3275     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3276   }
3277 
3278   llvm_unreachable("Unknown TLS model!");
3279 }
3280 
3281 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3282                                               SelectionDAG &DAG) const {
3283   EVT PtrVT = Op.getValueType();
3284   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3285   SDLoc DL(GSDN);
3286   const GlobalValue *GV = GSDN->getGlobal();
3287 
3288   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3289   // The actual address of the GlobalValue is stored in the TOC.
3290   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3291     if (Subtarget.isUsingPCRelativeCalls()) {
3292       EVT Ty = getPointerTy(DAG.getDataLayout());
3293       if (isAccessedAsGotIndirect(Op)) {
3294         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3295                                                 PPCII::MO_PCREL_FLAG |
3296                                                     PPCII::MO_GOT_FLAG);
3297         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3298         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3299                                    MachinePointerInfo());
3300         return Load;
3301       } else {
3302         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3303                                                 PPCII::MO_PCREL_FLAG);
3304         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3305       }
3306     }
3307     setUsesTOCBasePtr(DAG);
3308     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3309     return getTOCEntry(DAG, DL, GA);
3310   }
3311 
3312   unsigned MOHiFlag, MOLoFlag;
3313   bool IsPIC = isPositionIndependent();
3314   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3315 
3316   if (IsPIC && Subtarget.isSVR4ABI()) {
3317     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3318                                             GSDN->getOffset(),
3319                                             PPCII::MO_PIC_FLAG);
3320     return getTOCEntry(DAG, DL, GA);
3321   }
3322 
3323   SDValue GAHi =
3324     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3325   SDValue GALo =
3326     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3327 
3328   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3329 }
3330 
3331 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3332   bool IsStrict = Op->isStrictFPOpcode();
3333   ISD::CondCode CC =
3334       cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
3335   SDValue LHS = Op.getOperand(IsStrict ? 1 : 0);
3336   SDValue RHS = Op.getOperand(IsStrict ? 2 : 1);
3337   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
3338   EVT LHSVT = LHS.getValueType();
3339   SDLoc dl(Op);
3340 
3341   // Soften the setcc with libcall if it is fp128.
3342   if (LHSVT == MVT::f128) {
3343     assert(!Subtarget.hasP9Vector() &&
3344            "SETCC for f128 is already legal under Power9!");
3345     softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain,
3346                         Op->getOpcode() == ISD::STRICT_FSETCCS);
3347     if (RHS.getNode())
3348       LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS,
3349                         DAG.getCondCode(CC));
3350     if (IsStrict)
3351       return DAG.getMergeValues({LHS, Chain}, dl);
3352     return LHS;
3353   }
3354 
3355   assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!");
3356 
3357   if (Op.getValueType() == MVT::v2i64) {
3358     // When the operands themselves are v2i64 values, we need to do something
3359     // special because VSX has no underlying comparison operations for these.
3360     if (LHS.getValueType() == MVT::v2i64) {
3361       // Equality can be handled by casting to the legal type for Altivec
3362       // comparisons, everything else needs to be expanded.
3363       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3364         return DAG.getNode(
3365             ISD::BITCAST, dl, MVT::v2i64,
3366             DAG.getSetCC(dl, MVT::v4i32,
3367                          DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS),
3368                          DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC));
3369       }
3370 
3371       return SDValue();
3372     }
3373 
3374     // We handle most of these in the usual way.
3375     return Op;
3376   }
3377 
3378   // If we're comparing for equality to zero, expose the fact that this is
3379   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3380   // fold the new nodes.
3381   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3382     return V;
3383 
3384   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
3385     // Leave comparisons against 0 and -1 alone for now, since they're usually
3386     // optimized.  FIXME: revisit this when we can custom lower all setcc
3387     // optimizations.
3388     if (C->isAllOnesValue() || C->isNullValue())
3389       return SDValue();
3390   }
3391 
3392   // If we have an integer seteq/setne, turn it into a compare against zero
3393   // by xor'ing the rhs with the lhs, which is faster than setting a
3394   // condition register, reading it back out, and masking the correct bit.  The
3395   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3396   // the result to other bit-twiddling opportunities.
3397   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3398     EVT VT = Op.getValueType();
3399     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS);
3400     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3401   }
3402   return SDValue();
3403 }
3404 
3405 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3406   SDNode *Node = Op.getNode();
3407   EVT VT = Node->getValueType(0);
3408   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3409   SDValue InChain = Node->getOperand(0);
3410   SDValue VAListPtr = Node->getOperand(1);
3411   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3412   SDLoc dl(Node);
3413 
3414   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3415 
3416   // gpr_index
3417   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3418                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3419   InChain = GprIndex.getValue(1);
3420 
3421   if (VT == MVT::i64) {
3422     // Check if GprIndex is even
3423     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3424                                  DAG.getConstant(1, dl, MVT::i32));
3425     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3426                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3427     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3428                                           DAG.getConstant(1, dl, MVT::i32));
3429     // Align GprIndex to be even if it isn't
3430     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3431                            GprIndex);
3432   }
3433 
3434   // fpr index is 1 byte after gpr
3435   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3436                                DAG.getConstant(1, dl, MVT::i32));
3437 
3438   // fpr
3439   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3440                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3441   InChain = FprIndex.getValue(1);
3442 
3443   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3444                                        DAG.getConstant(8, dl, MVT::i32));
3445 
3446   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3447                                         DAG.getConstant(4, dl, MVT::i32));
3448 
3449   // areas
3450   SDValue OverflowArea =
3451       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3452   InChain = OverflowArea.getValue(1);
3453 
3454   SDValue RegSaveArea =
3455       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3456   InChain = RegSaveArea.getValue(1);
3457 
3458   // select overflow_area if index > 8
3459   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3460                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3461 
3462   // adjustment constant gpr_index * 4/8
3463   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3464                                     VT.isInteger() ? GprIndex : FprIndex,
3465                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3466                                                     MVT::i32));
3467 
3468   // OurReg = RegSaveArea + RegConstant
3469   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3470                                RegConstant);
3471 
3472   // Floating types are 32 bytes into RegSaveArea
3473   if (VT.isFloatingPoint())
3474     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3475                          DAG.getConstant(32, dl, MVT::i32));
3476 
3477   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3478   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3479                                    VT.isInteger() ? GprIndex : FprIndex,
3480                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3481                                                    MVT::i32));
3482 
3483   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3484                               VT.isInteger() ? VAListPtr : FprPtr,
3485                               MachinePointerInfo(SV), MVT::i8);
3486 
3487   // determine if we should load from reg_save_area or overflow_area
3488   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3489 
3490   // increase overflow_area by 4/8 if gpr/fpr > 8
3491   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3492                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3493                                           dl, MVT::i32));
3494 
3495   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3496                              OverflowAreaPlusN);
3497 
3498   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3499                               MachinePointerInfo(), MVT::i32);
3500 
3501   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3502 }
3503 
3504 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3505   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3506 
3507   // We have to copy the entire va_list struct:
3508   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3509   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3510                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3511                        false, true, false, MachinePointerInfo(),
3512                        MachinePointerInfo());
3513 }
3514 
3515 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3516                                                   SelectionDAG &DAG) const {
3517   if (Subtarget.isAIXABI())
3518     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3519 
3520   return Op.getOperand(0);
3521 }
3522 
3523 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3524                                                 SelectionDAG &DAG) const {
3525   if (Subtarget.isAIXABI())
3526     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3527 
3528   SDValue Chain = Op.getOperand(0);
3529   SDValue Trmp = Op.getOperand(1); // trampoline
3530   SDValue FPtr = Op.getOperand(2); // nested function
3531   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3532   SDLoc dl(Op);
3533 
3534   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3535   bool isPPC64 = (PtrVT == MVT::i64);
3536   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3537 
3538   TargetLowering::ArgListTy Args;
3539   TargetLowering::ArgListEntry Entry;
3540 
3541   Entry.Ty = IntPtrTy;
3542   Entry.Node = Trmp; Args.push_back(Entry);
3543 
3544   // TrampSize == (isPPC64 ? 48 : 40);
3545   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3546                                isPPC64 ? MVT::i64 : MVT::i32);
3547   Args.push_back(Entry);
3548 
3549   Entry.Node = FPtr; Args.push_back(Entry);
3550   Entry.Node = Nest; Args.push_back(Entry);
3551 
3552   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3553   TargetLowering::CallLoweringInfo CLI(DAG);
3554   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3555       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3556       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3557 
3558   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3559   return CallResult.second;
3560 }
3561 
3562 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3563   MachineFunction &MF = DAG.getMachineFunction();
3564   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3565   EVT PtrVT = getPointerTy(MF.getDataLayout());
3566 
3567   SDLoc dl(Op);
3568 
3569   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3570     // vastart just stores the address of the VarArgsFrameIndex slot into the
3571     // memory location argument.
3572     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3573     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3574     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3575                         MachinePointerInfo(SV));
3576   }
3577 
3578   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3579   // We suppose the given va_list is already allocated.
3580   //
3581   // typedef struct {
3582   //  char gpr;     /* index into the array of 8 GPRs
3583   //                 * stored in the register save area
3584   //                 * gpr=0 corresponds to r3,
3585   //                 * gpr=1 to r4, etc.
3586   //                 */
3587   //  char fpr;     /* index into the array of 8 FPRs
3588   //                 * stored in the register save area
3589   //                 * fpr=0 corresponds to f1,
3590   //                 * fpr=1 to f2, etc.
3591   //                 */
3592   //  char *overflow_arg_area;
3593   //                /* location on stack that holds
3594   //                 * the next overflow argument
3595   //                 */
3596   //  char *reg_save_area;
3597   //               /* where r3:r10 and f1:f8 (if saved)
3598   //                * are stored
3599   //                */
3600   // } va_list[1];
3601 
3602   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3603   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3604   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3605                                             PtrVT);
3606   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3607                                  PtrVT);
3608 
3609   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3610   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3611 
3612   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3613   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3614 
3615   uint64_t FPROffset = 1;
3616   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3617 
3618   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3619 
3620   // Store first byte : number of int regs
3621   SDValue firstStore =
3622       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3623                         MachinePointerInfo(SV), MVT::i8);
3624   uint64_t nextOffset = FPROffset;
3625   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3626                                   ConstFPROffset);
3627 
3628   // Store second byte : number of float regs
3629   SDValue secondStore =
3630       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3631                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3632   nextOffset += StackOffset;
3633   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3634 
3635   // Store second word : arguments given on stack
3636   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3637                                     MachinePointerInfo(SV, nextOffset));
3638   nextOffset += FrameOffset;
3639   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3640 
3641   // Store third word : arguments given in registers
3642   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3643                       MachinePointerInfo(SV, nextOffset));
3644 }
3645 
3646 /// FPR - The set of FP registers that should be allocated for arguments
3647 /// on Darwin and AIX.
3648 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3649                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3650                                 PPC::F11, PPC::F12, PPC::F13};
3651 
3652 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3653 /// the stack.
3654 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3655                                        unsigned PtrByteSize) {
3656   unsigned ArgSize = ArgVT.getStoreSize();
3657   if (Flags.isByVal())
3658     ArgSize = Flags.getByValSize();
3659 
3660   // Round up to multiples of the pointer size, except for array members,
3661   // which are always packed.
3662   if (!Flags.isInConsecutiveRegs())
3663     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3664 
3665   return ArgSize;
3666 }
3667 
3668 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3669 /// on the stack.
3670 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3671                                          ISD::ArgFlagsTy Flags,
3672                                          unsigned PtrByteSize) {
3673   Align Alignment(PtrByteSize);
3674 
3675   // Altivec parameters are padded to a 16 byte boundary.
3676   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3677       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3678       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3679       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3680     Alignment = Align(16);
3681 
3682   // ByVal parameters are aligned as requested.
3683   if (Flags.isByVal()) {
3684     auto BVAlign = Flags.getNonZeroByValAlign();
3685     if (BVAlign > PtrByteSize) {
3686       if (BVAlign.value() % PtrByteSize != 0)
3687         llvm_unreachable(
3688             "ByVal alignment is not a multiple of the pointer size");
3689 
3690       Alignment = BVAlign;
3691     }
3692   }
3693 
3694   // Array members are always packed to their original alignment.
3695   if (Flags.isInConsecutiveRegs()) {
3696     // If the array member was split into multiple registers, the first
3697     // needs to be aligned to the size of the full type.  (Except for
3698     // ppcf128, which is only aligned as its f64 components.)
3699     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3700       Alignment = Align(OrigVT.getStoreSize());
3701     else
3702       Alignment = Align(ArgVT.getStoreSize());
3703   }
3704 
3705   return Alignment;
3706 }
3707 
3708 /// CalculateStackSlotUsed - Return whether this argument will use its
3709 /// stack slot (instead of being passed in registers).  ArgOffset,
3710 /// AvailableFPRs, and AvailableVRs must hold the current argument
3711 /// position, and will be updated to account for this argument.
3712 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3713                                    unsigned PtrByteSize, unsigned LinkageSize,
3714                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3715                                    unsigned &AvailableFPRs,
3716                                    unsigned &AvailableVRs) {
3717   bool UseMemory = false;
3718 
3719   // Respect alignment of argument on the stack.
3720   Align Alignment =
3721       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3722   ArgOffset = alignTo(ArgOffset, Alignment);
3723   // If there's no space left in the argument save area, we must
3724   // use memory (this check also catches zero-sized arguments).
3725   if (ArgOffset >= LinkageSize + ParamAreaSize)
3726     UseMemory = true;
3727 
3728   // Allocate argument on the stack.
3729   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3730   if (Flags.isInConsecutiveRegsLast())
3731     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3732   // If we overran the argument save area, we must use memory
3733   // (this check catches arguments passed partially in memory)
3734   if (ArgOffset > LinkageSize + ParamAreaSize)
3735     UseMemory = true;
3736 
3737   // However, if the argument is actually passed in an FPR or a VR,
3738   // we don't use memory after all.
3739   if (!Flags.isByVal()) {
3740     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3741       if (AvailableFPRs > 0) {
3742         --AvailableFPRs;
3743         return false;
3744       }
3745     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3746         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3747         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3748         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3749       if (AvailableVRs > 0) {
3750         --AvailableVRs;
3751         return false;
3752       }
3753   }
3754 
3755   return UseMemory;
3756 }
3757 
3758 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3759 /// ensure minimum alignment required for target.
3760 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3761                                      unsigned NumBytes) {
3762   return alignTo(NumBytes, Lowering->getStackAlign());
3763 }
3764 
3765 SDValue PPCTargetLowering::LowerFormalArguments(
3766     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3767     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3768     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3769   if (Subtarget.isAIXABI())
3770     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3771                                     InVals);
3772   if (Subtarget.is64BitELFABI())
3773     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3774                                        InVals);
3775   assert(Subtarget.is32BitELFABI());
3776   return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3777                                      InVals);
3778 }
3779 
3780 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3781     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3782     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3783     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3784 
3785   // 32-bit SVR4 ABI Stack Frame Layout:
3786   //              +-----------------------------------+
3787   //        +-->  |            Back chain             |
3788   //        |     +-----------------------------------+
3789   //        |     | Floating-point register save area |
3790   //        |     +-----------------------------------+
3791   //        |     |    General register save area     |
3792   //        |     +-----------------------------------+
3793   //        |     |          CR save word             |
3794   //        |     +-----------------------------------+
3795   //        |     |         VRSAVE save word          |
3796   //        |     +-----------------------------------+
3797   //        |     |         Alignment padding         |
3798   //        |     +-----------------------------------+
3799   //        |     |     Vector register save area     |
3800   //        |     +-----------------------------------+
3801   //        |     |       Local variable space        |
3802   //        |     +-----------------------------------+
3803   //        |     |        Parameter list area        |
3804   //        |     +-----------------------------------+
3805   //        |     |           LR save word            |
3806   //        |     +-----------------------------------+
3807   // SP-->  +---  |            Back chain             |
3808   //              +-----------------------------------+
3809   //
3810   // Specifications:
3811   //   System V Application Binary Interface PowerPC Processor Supplement
3812   //   AltiVec Technology Programming Interface Manual
3813 
3814   MachineFunction &MF = DAG.getMachineFunction();
3815   MachineFrameInfo &MFI = MF.getFrameInfo();
3816   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3817 
3818   EVT PtrVT = getPointerTy(MF.getDataLayout());
3819   // Potential tail calls could cause overwriting of argument stack slots.
3820   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3821                        (CallConv == CallingConv::Fast));
3822   const Align PtrAlign(4);
3823 
3824   // Assign locations to all of the incoming arguments.
3825   SmallVector<CCValAssign, 16> ArgLocs;
3826   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3827                  *DAG.getContext());
3828 
3829   // Reserve space for the linkage area on the stack.
3830   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3831   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3832   if (useSoftFloat())
3833     CCInfo.PreAnalyzeFormalArguments(Ins);
3834 
3835   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3836   CCInfo.clearWasPPCF128();
3837 
3838   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3839     CCValAssign &VA = ArgLocs[i];
3840 
3841     // Arguments stored in registers.
3842     if (VA.isRegLoc()) {
3843       const TargetRegisterClass *RC;
3844       EVT ValVT = VA.getValVT();
3845 
3846       switch (ValVT.getSimpleVT().SimpleTy) {
3847         default:
3848           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3849         case MVT::i1:
3850         case MVT::i32:
3851           RC = &PPC::GPRCRegClass;
3852           break;
3853         case MVT::f32:
3854           if (Subtarget.hasP8Vector())
3855             RC = &PPC::VSSRCRegClass;
3856           else if (Subtarget.hasSPE())
3857             RC = &PPC::GPRCRegClass;
3858           else
3859             RC = &PPC::F4RCRegClass;
3860           break;
3861         case MVT::f64:
3862           if (Subtarget.hasVSX())
3863             RC = &PPC::VSFRCRegClass;
3864           else if (Subtarget.hasSPE())
3865             // SPE passes doubles in GPR pairs.
3866             RC = &PPC::GPRCRegClass;
3867           else
3868             RC = &PPC::F8RCRegClass;
3869           break;
3870         case MVT::v16i8:
3871         case MVT::v8i16:
3872         case MVT::v4i32:
3873           RC = &PPC::VRRCRegClass;
3874           break;
3875         case MVT::v4f32:
3876           RC = &PPC::VRRCRegClass;
3877           break;
3878         case MVT::v2f64:
3879         case MVT::v2i64:
3880           RC = &PPC::VRRCRegClass;
3881           break;
3882       }
3883 
3884       SDValue ArgValue;
3885       // Transform the arguments stored in physical registers into
3886       // virtual ones.
3887       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3888         assert(i + 1 < e && "No second half of double precision argument");
3889         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3890         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3891         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3892         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3893         if (!Subtarget.isLittleEndian())
3894           std::swap (ArgValueLo, ArgValueHi);
3895         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3896                                ArgValueHi);
3897       } else {
3898         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3899         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3900                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3901         if (ValVT == MVT::i1)
3902           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3903       }
3904 
3905       InVals.push_back(ArgValue);
3906     } else {
3907       // Argument stored in memory.
3908       assert(VA.isMemLoc());
3909 
3910       // Get the extended size of the argument type in stack
3911       unsigned ArgSize = VA.getLocVT().getStoreSize();
3912       // Get the actual size of the argument type
3913       unsigned ObjSize = VA.getValVT().getStoreSize();
3914       unsigned ArgOffset = VA.getLocMemOffset();
3915       // Stack objects in PPC32 are right justified.
3916       ArgOffset += ArgSize - ObjSize;
3917       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3918 
3919       // Create load nodes to retrieve arguments from the stack.
3920       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3921       InVals.push_back(
3922           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3923     }
3924   }
3925 
3926   // Assign locations to all of the incoming aggregate by value arguments.
3927   // Aggregates passed by value are stored in the local variable space of the
3928   // caller's stack frame, right above the parameter list area.
3929   SmallVector<CCValAssign, 16> ByValArgLocs;
3930   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3931                       ByValArgLocs, *DAG.getContext());
3932 
3933   // Reserve stack space for the allocations in CCInfo.
3934   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
3935 
3936   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3937 
3938   // Area that is at least reserved in the caller of this function.
3939   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3940   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3941 
3942   // Set the size that is at least reserved in caller of this function.  Tail
3943   // call optimized function's reserved stack space needs to be aligned so that
3944   // taking the difference between two stack areas will result in an aligned
3945   // stack.
3946   MinReservedArea =
3947       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3948   FuncInfo->setMinReservedArea(MinReservedArea);
3949 
3950   SmallVector<SDValue, 8> MemOps;
3951 
3952   // If the function takes variable number of arguments, make a frame index for
3953   // the start of the first vararg value... for expansion of llvm.va_start.
3954   if (isVarArg) {
3955     static const MCPhysReg GPArgRegs[] = {
3956       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3957       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3958     };
3959     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3960 
3961     static const MCPhysReg FPArgRegs[] = {
3962       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3963       PPC::F8
3964     };
3965     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3966 
3967     if (useSoftFloat() || hasSPE())
3968        NumFPArgRegs = 0;
3969 
3970     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3971     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3972 
3973     // Make room for NumGPArgRegs and NumFPArgRegs.
3974     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3975                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3976 
3977     FuncInfo->setVarArgsStackOffset(
3978       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3979                             CCInfo.getNextStackOffset(), true));
3980 
3981     FuncInfo->setVarArgsFrameIndex(
3982         MFI.CreateStackObject(Depth, Align(8), false));
3983     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3984 
3985     // The fixed integer arguments of a variadic function are stored to the
3986     // VarArgsFrameIndex on the stack so that they may be loaded by
3987     // dereferencing the result of va_next.
3988     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3989       // Get an existing live-in vreg, or add a new one.
3990       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3991       if (!VReg)
3992         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3993 
3994       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3995       SDValue Store =
3996           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3997       MemOps.push_back(Store);
3998       // Increment the address by four for the next argument to store
3999       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4000       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4001     }
4002 
4003     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
4004     // is set.
4005     // The double arguments are stored to the VarArgsFrameIndex
4006     // on the stack.
4007     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
4008       // Get an existing live-in vreg, or add a new one.
4009       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
4010       if (!VReg)
4011         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
4012 
4013       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
4014       SDValue Store =
4015           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4016       MemOps.push_back(Store);
4017       // Increment the address by eight for the next argument to store
4018       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
4019                                          PtrVT);
4020       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4021     }
4022   }
4023 
4024   if (!MemOps.empty())
4025     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4026 
4027   return Chain;
4028 }
4029 
4030 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4031 // value to MVT::i64 and then truncate to the correct register size.
4032 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
4033                                              EVT ObjectVT, SelectionDAG &DAG,
4034                                              SDValue ArgVal,
4035                                              const SDLoc &dl) const {
4036   if (Flags.isSExt())
4037     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
4038                          DAG.getValueType(ObjectVT));
4039   else if (Flags.isZExt())
4040     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
4041                          DAG.getValueType(ObjectVT));
4042 
4043   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
4044 }
4045 
4046 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
4047     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4048     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4049     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4050   // TODO: add description of PPC stack frame format, or at least some docs.
4051   //
4052   bool isELFv2ABI = Subtarget.isELFv2ABI();
4053   bool isLittleEndian = Subtarget.isLittleEndian();
4054   MachineFunction &MF = DAG.getMachineFunction();
4055   MachineFrameInfo &MFI = MF.getFrameInfo();
4056   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4057 
4058   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4059          "fastcc not supported on varargs functions");
4060 
4061   EVT PtrVT = getPointerTy(MF.getDataLayout());
4062   // Potential tail calls could cause overwriting of argument stack slots.
4063   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4064                        (CallConv == CallingConv::Fast));
4065   unsigned PtrByteSize = 8;
4066   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4067 
4068   static const MCPhysReg GPR[] = {
4069     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4070     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4071   };
4072   static const MCPhysReg VR[] = {
4073     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4074     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4075   };
4076 
4077   const unsigned Num_GPR_Regs = array_lengthof(GPR);
4078   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4079   const unsigned Num_VR_Regs  = array_lengthof(VR);
4080 
4081   // Do a first pass over the arguments to determine whether the ABI
4082   // guarantees that our caller has allocated the parameter save area
4083   // on its stack frame.  In the ELFv1 ABI, this is always the case;
4084   // in the ELFv2 ABI, it is true if this is a vararg function or if
4085   // any parameter is located in a stack slot.
4086 
4087   bool HasParameterArea = !isELFv2ABI || isVarArg;
4088   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4089   unsigned NumBytes = LinkageSize;
4090   unsigned AvailableFPRs = Num_FPR_Regs;
4091   unsigned AvailableVRs = Num_VR_Regs;
4092   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4093     if (Ins[i].Flags.isNest())
4094       continue;
4095 
4096     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
4097                                PtrByteSize, LinkageSize, ParamAreaSize,
4098                                NumBytes, AvailableFPRs, AvailableVRs))
4099       HasParameterArea = true;
4100   }
4101 
4102   // Add DAG nodes to load the arguments or copy them out of registers.  On
4103   // entry to a function on PPC, the arguments start after the linkage area,
4104   // although the first ones are often in registers.
4105 
4106   unsigned ArgOffset = LinkageSize;
4107   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4108   SmallVector<SDValue, 8> MemOps;
4109   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4110   unsigned CurArgIdx = 0;
4111   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4112     SDValue ArgVal;
4113     bool needsLoad = false;
4114     EVT ObjectVT = Ins[ArgNo].VT;
4115     EVT OrigVT = Ins[ArgNo].ArgVT;
4116     unsigned ObjSize = ObjectVT.getStoreSize();
4117     unsigned ArgSize = ObjSize;
4118     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4119     if (Ins[ArgNo].isOrigArg()) {
4120       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4121       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4122     }
4123     // We re-align the argument offset for each argument, except when using the
4124     // fast calling convention, when we need to make sure we do that only when
4125     // we'll actually use a stack slot.
4126     unsigned CurArgOffset;
4127     Align Alignment;
4128     auto ComputeArgOffset = [&]() {
4129       /* Respect alignment of argument on the stack.  */
4130       Alignment =
4131           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4132       ArgOffset = alignTo(ArgOffset, Alignment);
4133       CurArgOffset = ArgOffset;
4134     };
4135 
4136     if (CallConv != CallingConv::Fast) {
4137       ComputeArgOffset();
4138 
4139       /* Compute GPR index associated with argument offset.  */
4140       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4141       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4142     }
4143 
4144     // FIXME the codegen can be much improved in some cases.
4145     // We do not have to keep everything in memory.
4146     if (Flags.isByVal()) {
4147       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4148 
4149       if (CallConv == CallingConv::Fast)
4150         ComputeArgOffset();
4151 
4152       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4153       ObjSize = Flags.getByValSize();
4154       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4155       // Empty aggregate parameters do not take up registers.  Examples:
4156       //   struct { } a;
4157       //   union  { } b;
4158       //   int c[0];
4159       // etc.  However, we have to provide a place-holder in InVals, so
4160       // pretend we have an 8-byte item at the current address for that
4161       // purpose.
4162       if (!ObjSize) {
4163         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4164         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4165         InVals.push_back(FIN);
4166         continue;
4167       }
4168 
4169       // Create a stack object covering all stack doublewords occupied
4170       // by the argument.  If the argument is (fully or partially) on
4171       // the stack, or if the argument is fully in registers but the
4172       // caller has allocated the parameter save anyway, we can refer
4173       // directly to the caller's stack frame.  Otherwise, create a
4174       // local copy in our own frame.
4175       int FI;
4176       if (HasParameterArea ||
4177           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4178         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4179       else
4180         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4181       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4182 
4183       // Handle aggregates smaller than 8 bytes.
4184       if (ObjSize < PtrByteSize) {
4185         // The value of the object is its address, which differs from the
4186         // address of the enclosing doubleword on big-endian systems.
4187         SDValue Arg = FIN;
4188         if (!isLittleEndian) {
4189           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4190           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4191         }
4192         InVals.push_back(Arg);
4193 
4194         if (GPR_idx != Num_GPR_Regs) {
4195           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4196           FuncInfo->addLiveInAttr(VReg, Flags);
4197           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4198           SDValue Store;
4199 
4200           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
4201             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
4202                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
4203             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4204                                       MachinePointerInfo(&*FuncArg), ObjType);
4205           } else {
4206             // For sizes that don't fit a truncating store (3, 5, 6, 7),
4207             // store the whole register as-is to the parameter save area
4208             // slot.
4209             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4210                                  MachinePointerInfo(&*FuncArg));
4211           }
4212 
4213           MemOps.push_back(Store);
4214         }
4215         // Whether we copied from a register or not, advance the offset
4216         // into the parameter save area by a full doubleword.
4217         ArgOffset += PtrByteSize;
4218         continue;
4219       }
4220 
4221       // The value of the object is its address, which is the address of
4222       // its first stack doubleword.
4223       InVals.push_back(FIN);
4224 
4225       // Store whatever pieces of the object are in registers to memory.
4226       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4227         if (GPR_idx == Num_GPR_Regs)
4228           break;
4229 
4230         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4231         FuncInfo->addLiveInAttr(VReg, Flags);
4232         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4233         SDValue Addr = FIN;
4234         if (j) {
4235           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4236           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4237         }
4238         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4239                                      MachinePointerInfo(&*FuncArg, j));
4240         MemOps.push_back(Store);
4241         ++GPR_idx;
4242       }
4243       ArgOffset += ArgSize;
4244       continue;
4245     }
4246 
4247     switch (ObjectVT.getSimpleVT().SimpleTy) {
4248     default: llvm_unreachable("Unhandled argument type!");
4249     case MVT::i1:
4250     case MVT::i32:
4251     case MVT::i64:
4252       if (Flags.isNest()) {
4253         // The 'nest' parameter, if any, is passed in R11.
4254         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4255         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4256 
4257         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4258           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4259 
4260         break;
4261       }
4262 
4263       // These can be scalar arguments or elements of an integer array type
4264       // passed directly.  Clang may use those instead of "byval" aggregate
4265       // types to avoid forcing arguments to memory unnecessarily.
4266       if (GPR_idx != Num_GPR_Regs) {
4267         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4268         FuncInfo->addLiveInAttr(VReg, Flags);
4269         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4270 
4271         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4272           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4273           // value to MVT::i64 and then truncate to the correct register size.
4274           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4275       } else {
4276         if (CallConv == CallingConv::Fast)
4277           ComputeArgOffset();
4278 
4279         needsLoad = true;
4280         ArgSize = PtrByteSize;
4281       }
4282       if (CallConv != CallingConv::Fast || needsLoad)
4283         ArgOffset += 8;
4284       break;
4285 
4286     case MVT::f32:
4287     case MVT::f64:
4288       // These can be scalar arguments or elements of a float array type
4289       // passed directly.  The latter are used to implement ELFv2 homogenous
4290       // float aggregates.
4291       if (FPR_idx != Num_FPR_Regs) {
4292         unsigned VReg;
4293 
4294         if (ObjectVT == MVT::f32)
4295           VReg = MF.addLiveIn(FPR[FPR_idx],
4296                               Subtarget.hasP8Vector()
4297                                   ? &PPC::VSSRCRegClass
4298                                   : &PPC::F4RCRegClass);
4299         else
4300           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4301                                                 ? &PPC::VSFRCRegClass
4302                                                 : &PPC::F8RCRegClass);
4303 
4304         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4305         ++FPR_idx;
4306       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4307         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4308         // once we support fp <-> gpr moves.
4309 
4310         // This can only ever happen in the presence of f32 array types,
4311         // since otherwise we never run out of FPRs before running out
4312         // of GPRs.
4313         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4314         FuncInfo->addLiveInAttr(VReg, Flags);
4315         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4316 
4317         if (ObjectVT == MVT::f32) {
4318           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4319             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4320                                  DAG.getConstant(32, dl, MVT::i32));
4321           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4322         }
4323 
4324         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4325       } else {
4326         if (CallConv == CallingConv::Fast)
4327           ComputeArgOffset();
4328 
4329         needsLoad = true;
4330       }
4331 
4332       // When passing an array of floats, the array occupies consecutive
4333       // space in the argument area; only round up to the next doubleword
4334       // at the end of the array.  Otherwise, each float takes 8 bytes.
4335       if (CallConv != CallingConv::Fast || needsLoad) {
4336         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4337         ArgOffset += ArgSize;
4338         if (Flags.isInConsecutiveRegsLast())
4339           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4340       }
4341       break;
4342     case MVT::v4f32:
4343     case MVT::v4i32:
4344     case MVT::v8i16:
4345     case MVT::v16i8:
4346     case MVT::v2f64:
4347     case MVT::v2i64:
4348     case MVT::v1i128:
4349     case MVT::f128:
4350       // These can be scalar arguments or elements of a vector array type
4351       // passed directly.  The latter are used to implement ELFv2 homogenous
4352       // vector aggregates.
4353       if (VR_idx != Num_VR_Regs) {
4354         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4355         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4356         ++VR_idx;
4357       } else {
4358         if (CallConv == CallingConv::Fast)
4359           ComputeArgOffset();
4360         needsLoad = true;
4361       }
4362       if (CallConv != CallingConv::Fast || needsLoad)
4363         ArgOffset += 16;
4364       break;
4365     }
4366 
4367     // We need to load the argument to a virtual register if we determined
4368     // above that we ran out of physical registers of the appropriate type.
4369     if (needsLoad) {
4370       if (ObjSize < ArgSize && !isLittleEndian)
4371         CurArgOffset += ArgSize - ObjSize;
4372       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4373       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4374       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4375     }
4376 
4377     InVals.push_back(ArgVal);
4378   }
4379 
4380   // Area that is at least reserved in the caller of this function.
4381   unsigned MinReservedArea;
4382   if (HasParameterArea)
4383     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4384   else
4385     MinReservedArea = LinkageSize;
4386 
4387   // Set the size that is at least reserved in caller of this function.  Tail
4388   // call optimized functions' reserved stack space needs to be aligned so that
4389   // taking the difference between two stack areas will result in an aligned
4390   // stack.
4391   MinReservedArea =
4392       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4393   FuncInfo->setMinReservedArea(MinReservedArea);
4394 
4395   // If the function takes variable number of arguments, make a frame index for
4396   // the start of the first vararg value... for expansion of llvm.va_start.
4397   // On ELFv2ABI spec, it writes:
4398   // C programs that are intended to be *portable* across different compilers
4399   // and architectures must use the header file <stdarg.h> to deal with variable
4400   // argument lists.
4401   if (isVarArg && MFI.hasVAStart()) {
4402     int Depth = ArgOffset;
4403 
4404     FuncInfo->setVarArgsFrameIndex(
4405       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4406     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4407 
4408     // If this function is vararg, store any remaining integer argument regs
4409     // to their spots on the stack so that they may be loaded by dereferencing
4410     // the result of va_next.
4411     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4412          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4413       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4414       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4415       SDValue Store =
4416           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4417       MemOps.push_back(Store);
4418       // Increment the address by four for the next argument to store
4419       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4420       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4421     }
4422   }
4423 
4424   if (!MemOps.empty())
4425     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4426 
4427   return Chain;
4428 }
4429 
4430 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4431 /// adjusted to accommodate the arguments for the tailcall.
4432 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4433                                    unsigned ParamSize) {
4434 
4435   if (!isTailCall) return 0;
4436 
4437   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4438   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4439   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4440   // Remember only if the new adjustment is bigger.
4441   if (SPDiff < FI->getTailCallSPDelta())
4442     FI->setTailCallSPDelta(SPDiff);
4443 
4444   return SPDiff;
4445 }
4446 
4447 static bool isFunctionGlobalAddress(SDValue Callee);
4448 
4449 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4450                               const TargetMachine &TM) {
4451   // It does not make sense to call callsShareTOCBase() with a caller that
4452   // is PC Relative since PC Relative callers do not have a TOC.
4453 #ifndef NDEBUG
4454   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4455   assert(!STICaller->isUsingPCRelativeCalls() &&
4456          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4457 #endif
4458 
4459   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4460   // don't have enough information to determine if the caller and callee share
4461   // the same  TOC base, so we have to pessimistically assume they don't for
4462   // correctness.
4463   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4464   if (!G)
4465     return false;
4466 
4467   const GlobalValue *GV = G->getGlobal();
4468 
4469   // If the callee is preemptable, then the static linker will use a plt-stub
4470   // which saves the toc to the stack, and needs a nop after the call
4471   // instruction to convert to a toc-restore.
4472   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4473     return false;
4474 
4475   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4476   // We may need a TOC restore in the situation where the caller requires a
4477   // valid TOC but the callee is PC Relative and does not.
4478   const Function *F = dyn_cast<Function>(GV);
4479   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4480 
4481   // If we have an Alias we can try to get the function from there.
4482   if (Alias) {
4483     const GlobalObject *GlobalObj = Alias->getBaseObject();
4484     F = dyn_cast<Function>(GlobalObj);
4485   }
4486 
4487   // If we still have no valid function pointer we do not have enough
4488   // information to determine if the callee uses PC Relative calls so we must
4489   // assume that it does.
4490   if (!F)
4491     return false;
4492 
4493   // If the callee uses PC Relative we cannot guarantee that the callee won't
4494   // clobber the TOC of the caller and so we must assume that the two
4495   // functions do not share a TOC base.
4496   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4497   if (STICallee->isUsingPCRelativeCalls())
4498     return false;
4499 
4500   // If the GV is not a strong definition then we need to assume it can be
4501   // replaced by another function at link time. The function that replaces
4502   // it may not share the same TOC as the caller since the callee may be
4503   // replaced by a PC Relative version of the same function.
4504   if (!GV->isStrongDefinitionForLinker())
4505     return false;
4506 
4507   // The medium and large code models are expected to provide a sufficiently
4508   // large TOC to provide all data addressing needs of a module with a
4509   // single TOC.
4510   if (CodeModel::Medium == TM.getCodeModel() ||
4511       CodeModel::Large == TM.getCodeModel())
4512     return true;
4513 
4514   // Any explicitly-specified sections and section prefixes must also match.
4515   // Also, if we're using -ffunction-sections, then each function is always in
4516   // a different section (the same is true for COMDAT functions).
4517   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4518       GV->getSection() != Caller->getSection())
4519     return false;
4520   if (const auto *F = dyn_cast<Function>(GV)) {
4521     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4522       return false;
4523   }
4524 
4525   return true;
4526 }
4527 
4528 static bool
4529 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4530                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4531   assert(Subtarget.is64BitELFABI());
4532 
4533   const unsigned PtrByteSize = 8;
4534   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4535 
4536   static const MCPhysReg GPR[] = {
4537     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4538     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4539   };
4540   static const MCPhysReg VR[] = {
4541     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4542     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4543   };
4544 
4545   const unsigned NumGPRs = array_lengthof(GPR);
4546   const unsigned NumFPRs = 13;
4547   const unsigned NumVRs = array_lengthof(VR);
4548   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4549 
4550   unsigned NumBytes = LinkageSize;
4551   unsigned AvailableFPRs = NumFPRs;
4552   unsigned AvailableVRs = NumVRs;
4553 
4554   for (const ISD::OutputArg& Param : Outs) {
4555     if (Param.Flags.isNest()) continue;
4556 
4557     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4558                                LinkageSize, ParamAreaSize, NumBytes,
4559                                AvailableFPRs, AvailableVRs))
4560       return true;
4561   }
4562   return false;
4563 }
4564 
4565 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4566   if (CB.arg_size() != CallerFn->arg_size())
4567     return false;
4568 
4569   auto CalleeArgIter = CB.arg_begin();
4570   auto CalleeArgEnd = CB.arg_end();
4571   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4572 
4573   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4574     const Value* CalleeArg = *CalleeArgIter;
4575     const Value* CallerArg = &(*CallerArgIter);
4576     if (CalleeArg == CallerArg)
4577       continue;
4578 
4579     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4580     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4581     //      }
4582     // 1st argument of callee is undef and has the same type as caller.
4583     if (CalleeArg->getType() == CallerArg->getType() &&
4584         isa<UndefValue>(CalleeArg))
4585       continue;
4586 
4587     return false;
4588   }
4589 
4590   return true;
4591 }
4592 
4593 // Returns true if TCO is possible between the callers and callees
4594 // calling conventions.
4595 static bool
4596 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4597                                     CallingConv::ID CalleeCC) {
4598   // Tail calls are possible with fastcc and ccc.
4599   auto isTailCallableCC  = [] (CallingConv::ID CC){
4600       return  CC == CallingConv::C || CC == CallingConv::Fast;
4601   };
4602   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4603     return false;
4604 
4605   // We can safely tail call both fastcc and ccc callees from a c calling
4606   // convention caller. If the caller is fastcc, we may have less stack space
4607   // than a non-fastcc caller with the same signature so disable tail-calls in
4608   // that case.
4609   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4610 }
4611 
4612 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4613     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4614     const SmallVectorImpl<ISD::OutputArg> &Outs,
4615     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4616   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4617 
4618   if (DisableSCO && !TailCallOpt) return false;
4619 
4620   // Variadic argument functions are not supported.
4621   if (isVarArg) return false;
4622 
4623   auto &Caller = DAG.getMachineFunction().getFunction();
4624   // Check that the calling conventions are compatible for tco.
4625   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4626     return false;
4627 
4628   // Caller contains any byval parameter is not supported.
4629   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4630     return false;
4631 
4632   // Callee contains any byval parameter is not supported, too.
4633   // Note: This is a quick work around, because in some cases, e.g.
4634   // caller's stack size > callee's stack size, we are still able to apply
4635   // sibling call optimization. For example, gcc is able to do SCO for caller1
4636   // in the following example, but not for caller2.
4637   //   struct test {
4638   //     long int a;
4639   //     char ary[56];
4640   //   } gTest;
4641   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4642   //     b->a = v.a;
4643   //     return 0;
4644   //   }
4645   //   void caller1(struct test a, struct test c, struct test *b) {
4646   //     callee(gTest, b); }
4647   //   void caller2(struct test *b) { callee(gTest, b); }
4648   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4649     return false;
4650 
4651   // If callee and caller use different calling conventions, we cannot pass
4652   // parameters on stack since offsets for the parameter area may be different.
4653   if (Caller.getCallingConv() != CalleeCC &&
4654       needStackSlotPassParameters(Subtarget, Outs))
4655     return false;
4656 
4657   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4658   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4659   // callee potentially have different TOC bases then we cannot tail call since
4660   // we need to restore the TOC pointer after the call.
4661   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4662   // We cannot guarantee this for indirect calls or calls to external functions.
4663   // When PC-Relative addressing is used, the concept of the TOC is no longer
4664   // applicable so this check is not required.
4665   // Check first for indirect calls.
4666   if (!Subtarget.isUsingPCRelativeCalls() &&
4667       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4668     return false;
4669 
4670   // Check if we share the TOC base.
4671   if (!Subtarget.isUsingPCRelativeCalls() &&
4672       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4673     return false;
4674 
4675   // TCO allows altering callee ABI, so we don't have to check further.
4676   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4677     return true;
4678 
4679   if (DisableSCO) return false;
4680 
4681   // If callee use the same argument list that caller is using, then we can
4682   // apply SCO on this case. If it is not, then we need to check if callee needs
4683   // stack for passing arguments.
4684   // PC Relative tail calls may not have a CallBase.
4685   // If there is no CallBase we cannot verify if we have the same argument
4686   // list so assume that we don't have the same argument list.
4687   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4688       needStackSlotPassParameters(Subtarget, Outs))
4689     return false;
4690   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4691     return false;
4692 
4693   return true;
4694 }
4695 
4696 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4697 /// for tail call optimization. Targets which want to do tail call
4698 /// optimization should implement this function.
4699 bool
4700 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4701                                                      CallingConv::ID CalleeCC,
4702                                                      bool isVarArg,
4703                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4704                                                      SelectionDAG& DAG) const {
4705   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4706     return false;
4707 
4708   // Variable argument functions are not supported.
4709   if (isVarArg)
4710     return false;
4711 
4712   MachineFunction &MF = DAG.getMachineFunction();
4713   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4714   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4715     // Functions containing by val parameters are not supported.
4716     for (unsigned i = 0; i != Ins.size(); i++) {
4717        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4718        if (Flags.isByVal()) return false;
4719     }
4720 
4721     // Non-PIC/GOT tail calls are supported.
4722     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4723       return true;
4724 
4725     // At the moment we can only do local tail calls (in same module, hidden
4726     // or protected) if we are generating PIC.
4727     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4728       return G->getGlobal()->hasHiddenVisibility()
4729           || G->getGlobal()->hasProtectedVisibility();
4730   }
4731 
4732   return false;
4733 }
4734 
4735 /// isCallCompatibleAddress - Return the immediate to use if the specified
4736 /// 32-bit value is representable in the immediate field of a BxA instruction.
4737 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4738   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4739   if (!C) return nullptr;
4740 
4741   int Addr = C->getZExtValue();
4742   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4743       SignExtend32<26>(Addr) != Addr)
4744     return nullptr;  // Top 6 bits have to be sext of immediate.
4745 
4746   return DAG
4747       .getConstant(
4748           (int)C->getZExtValue() >> 2, SDLoc(Op),
4749           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4750       .getNode();
4751 }
4752 
4753 namespace {
4754 
4755 struct TailCallArgumentInfo {
4756   SDValue Arg;
4757   SDValue FrameIdxOp;
4758   int FrameIdx = 0;
4759 
4760   TailCallArgumentInfo() = default;
4761 };
4762 
4763 } // end anonymous namespace
4764 
4765 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4766 static void StoreTailCallArgumentsToStackSlot(
4767     SelectionDAG &DAG, SDValue Chain,
4768     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4769     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4770   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4771     SDValue Arg = TailCallArgs[i].Arg;
4772     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4773     int FI = TailCallArgs[i].FrameIdx;
4774     // Store relative to framepointer.
4775     MemOpChains.push_back(DAG.getStore(
4776         Chain, dl, Arg, FIN,
4777         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4778   }
4779 }
4780 
4781 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4782 /// the appropriate stack slot for the tail call optimized function call.
4783 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4784                                              SDValue OldRetAddr, SDValue OldFP,
4785                                              int SPDiff, const SDLoc &dl) {
4786   if (SPDiff) {
4787     // Calculate the new stack slot for the return address.
4788     MachineFunction &MF = DAG.getMachineFunction();
4789     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4790     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4791     bool isPPC64 = Subtarget.isPPC64();
4792     int SlotSize = isPPC64 ? 8 : 4;
4793     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4794     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4795                                                          NewRetAddrLoc, true);
4796     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4797     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4798     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4799                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4800   }
4801   return Chain;
4802 }
4803 
4804 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4805 /// the position of the argument.
4806 static void
4807 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4808                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4809                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4810   int Offset = ArgOffset + SPDiff;
4811   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4812   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4813   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4814   SDValue FIN = DAG.getFrameIndex(FI, VT);
4815   TailCallArgumentInfo Info;
4816   Info.Arg = Arg;
4817   Info.FrameIdxOp = FIN;
4818   Info.FrameIdx = FI;
4819   TailCallArguments.push_back(Info);
4820 }
4821 
4822 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4823 /// stack slot. Returns the chain as result and the loaded frame pointers in
4824 /// LROpOut/FPOpout. Used when tail calling.
4825 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4826     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4827     SDValue &FPOpOut, const SDLoc &dl) const {
4828   if (SPDiff) {
4829     // Load the LR and FP stack slot for later adjusting.
4830     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4831     LROpOut = getReturnAddrFrameIndex(DAG);
4832     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4833     Chain = SDValue(LROpOut.getNode(), 1);
4834   }
4835   return Chain;
4836 }
4837 
4838 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4839 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4840 /// specified by the specific parameter attribute. The copy will be passed as
4841 /// a byval function parameter.
4842 /// Sometimes what we are copying is the end of a larger object, the part that
4843 /// does not fit in registers.
4844 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4845                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4846                                          SelectionDAG &DAG, const SDLoc &dl) {
4847   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4848   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
4849                        Flags.getNonZeroByValAlign(), false, false, false,
4850                        MachinePointerInfo(), MachinePointerInfo());
4851 }
4852 
4853 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4854 /// tail calls.
4855 static void LowerMemOpCallTo(
4856     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4857     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4858     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4859     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4860   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4861   if (!isTailCall) {
4862     if (isVector) {
4863       SDValue StackPtr;
4864       if (isPPC64)
4865         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4866       else
4867         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4868       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4869                            DAG.getConstant(ArgOffset, dl, PtrVT));
4870     }
4871     MemOpChains.push_back(
4872         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4873     // Calculate and remember argument location.
4874   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4875                                   TailCallArguments);
4876 }
4877 
4878 static void
4879 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4880                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4881                 SDValue FPOp,
4882                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4883   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4884   // might overwrite each other in case of tail call optimization.
4885   SmallVector<SDValue, 8> MemOpChains2;
4886   // Do not flag preceding copytoreg stuff together with the following stuff.
4887   InFlag = SDValue();
4888   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4889                                     MemOpChains2, dl);
4890   if (!MemOpChains2.empty())
4891     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4892 
4893   // Store the return address to the appropriate stack slot.
4894   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4895 
4896   // Emit callseq_end just before tailcall node.
4897   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4898                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4899   InFlag = Chain.getValue(1);
4900 }
4901 
4902 // Is this global address that of a function that can be called by name? (as
4903 // opposed to something that must hold a descriptor for an indirect call).
4904 static bool isFunctionGlobalAddress(SDValue Callee) {
4905   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4906     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4907         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4908       return false;
4909 
4910     return G->getGlobal()->getValueType()->isFunctionTy();
4911   }
4912 
4913   return false;
4914 }
4915 
4916 SDValue PPCTargetLowering::LowerCallResult(
4917     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4918     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4919     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4920   SmallVector<CCValAssign, 16> RVLocs;
4921   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4922                     *DAG.getContext());
4923 
4924   CCRetInfo.AnalyzeCallResult(
4925       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
4926                ? RetCC_PPC_Cold
4927                : RetCC_PPC);
4928 
4929   // Copy all of the result registers out of their specified physreg.
4930   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4931     CCValAssign &VA = RVLocs[i];
4932     assert(VA.isRegLoc() && "Can only return in registers!");
4933 
4934     SDValue Val;
4935 
4936     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
4937       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
4938                                       InFlag);
4939       Chain = Lo.getValue(1);
4940       InFlag = Lo.getValue(2);
4941       VA = RVLocs[++i]; // skip ahead to next loc
4942       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
4943                                       InFlag);
4944       Chain = Hi.getValue(1);
4945       InFlag = Hi.getValue(2);
4946       if (!Subtarget.isLittleEndian())
4947         std::swap (Lo, Hi);
4948       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
4949     } else {
4950       Val = DAG.getCopyFromReg(Chain, dl,
4951                                VA.getLocReg(), VA.getLocVT(), InFlag);
4952       Chain = Val.getValue(1);
4953       InFlag = Val.getValue(2);
4954     }
4955 
4956     switch (VA.getLocInfo()) {
4957     default: llvm_unreachable("Unknown loc info!");
4958     case CCValAssign::Full: break;
4959     case CCValAssign::AExt:
4960       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4961       break;
4962     case CCValAssign::ZExt:
4963       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4964                         DAG.getValueType(VA.getValVT()));
4965       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4966       break;
4967     case CCValAssign::SExt:
4968       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4969                         DAG.getValueType(VA.getValVT()));
4970       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4971       break;
4972     }
4973 
4974     InVals.push_back(Val);
4975   }
4976 
4977   return Chain;
4978 }
4979 
4980 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
4981                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
4982   // PatchPoint calls are not indirect.
4983   if (isPatchPoint)
4984     return false;
4985 
4986   if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee))
4987     return false;
4988 
4989   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
4990   // becuase the immediate function pointer points to a descriptor instead of
4991   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
4992   // pointer immediate points to the global entry point, while the BLA would
4993   // need to jump to the local entry point (see rL211174).
4994   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
4995       isBLACompatibleAddress(Callee, DAG))
4996     return false;
4997 
4998   return true;
4999 }
5000 
5001 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5002 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5003   return Subtarget.isAIXABI() ||
5004          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5005 }
5006 
5007 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5008                               const Function &Caller,
5009                               const SDValue &Callee,
5010                               const PPCSubtarget &Subtarget,
5011                               const TargetMachine &TM) {
5012   if (CFlags.IsTailCall)
5013     return PPCISD::TC_RETURN;
5014 
5015   // This is a call through a function pointer.
5016   if (CFlags.IsIndirect) {
5017     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5018     // indirect calls. The save of the caller's TOC pointer to the stack will be
5019     // inserted into the DAG as part of call lowering. The restore of the TOC
5020     // pointer is modeled by using a pseudo instruction for the call opcode that
5021     // represents the 2 instruction sequence of an indirect branch and link,
5022     // immediately followed by a load of the TOC pointer from the the stack save
5023     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5024     // as it is not saved or used.
5025     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5026                                                : PPCISD::BCTRL;
5027   }
5028 
5029   if (Subtarget.isUsingPCRelativeCalls()) {
5030     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5031     return PPCISD::CALL_NOTOC;
5032   }
5033 
5034   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5035   // immediately following the call instruction if the caller and callee may
5036   // have different TOC bases. At link time if the linker determines the calls
5037   // may not share a TOC base, the call is redirected to a trampoline inserted
5038   // by the linker. The trampoline will (among other things) save the callers
5039   // TOC pointer at an ABI designated offset in the linkage area and the linker
5040   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5041   // into gpr2.
5042   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5043     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5044                                                   : PPCISD::CALL_NOP;
5045 
5046   return PPCISD::CALL;
5047 }
5048 
5049 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5050                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5051   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5052     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5053       return SDValue(Dest, 0);
5054 
5055   // Returns true if the callee is local, and false otherwise.
5056   auto isLocalCallee = [&]() {
5057     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5058     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5059     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5060 
5061     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5062            !dyn_cast_or_null<GlobalIFunc>(GV);
5063   };
5064 
5065   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5066   // a static relocation model causes some versions of GNU LD (2.17.50, at
5067   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5068   // built with secure-PLT.
5069   bool UsePlt =
5070       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5071       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5072 
5073   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5074     const TargetMachine &TM = Subtarget.getTargetMachine();
5075     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5076     MCSymbolXCOFF *S =
5077         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5078 
5079     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5080     return DAG.getMCSymbol(S, PtrVT);
5081   };
5082 
5083   if (isFunctionGlobalAddress(Callee)) {
5084     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5085 
5086     if (Subtarget.isAIXABI()) {
5087       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5088       return getAIXFuncEntryPointSymbolSDNode(GV);
5089     }
5090     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5091                                       UsePlt ? PPCII::MO_PLT : 0);
5092   }
5093 
5094   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5095     const char *SymName = S->getSymbol();
5096     if (Subtarget.isAIXABI()) {
5097       // If there exists a user-declared function whose name is the same as the
5098       // ExternalSymbol's, then we pick up the user-declared version.
5099       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5100       if (const Function *F =
5101               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5102         return getAIXFuncEntryPointSymbolSDNode(F);
5103 
5104       // On AIX, direct function calls reference the symbol for the function's
5105       // entry point, which is named by prepending a "." before the function's
5106       // C-linkage name. A Qualname is returned here because an external
5107       // function entry point is a csect with XTY_ER property.
5108       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5109         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5110         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5111             (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5112             XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER));
5113         return Sec->getQualNameSymbol();
5114       };
5115 
5116       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5117     }
5118     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5119                                        UsePlt ? PPCII::MO_PLT : 0);
5120   }
5121 
5122   // No transformation needed.
5123   assert(Callee.getNode() && "What no callee?");
5124   return Callee;
5125 }
5126 
5127 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5128   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5129          "Expected a CALLSEQ_STARTSDNode.");
5130 
5131   // The last operand is the chain, except when the node has glue. If the node
5132   // has glue, then the last operand is the glue, and the chain is the second
5133   // last operand.
5134   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5135   if (LastValue.getValueType() != MVT::Glue)
5136     return LastValue;
5137 
5138   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5139 }
5140 
5141 // Creates the node that moves a functions address into the count register
5142 // to prepare for an indirect call instruction.
5143 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5144                                 SDValue &Glue, SDValue &Chain,
5145                                 const SDLoc &dl) {
5146   SDValue MTCTROps[] = {Chain, Callee, Glue};
5147   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5148   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5149                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5150   // The glue is the second value produced.
5151   Glue = Chain.getValue(1);
5152 }
5153 
5154 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5155                                           SDValue &Glue, SDValue &Chain,
5156                                           SDValue CallSeqStart,
5157                                           const CallBase *CB, const SDLoc &dl,
5158                                           bool hasNest,
5159                                           const PPCSubtarget &Subtarget) {
5160   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5161   // entry point, but to the function descriptor (the function entry point
5162   // address is part of the function descriptor though).
5163   // The function descriptor is a three doubleword structure with the
5164   // following fields: function entry point, TOC base address and
5165   // environment pointer.
5166   // Thus for a call through a function pointer, the following actions need
5167   // to be performed:
5168   //   1. Save the TOC of the caller in the TOC save area of its stack
5169   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5170   //   2. Load the address of the function entry point from the function
5171   //      descriptor.
5172   //   3. Load the TOC of the callee from the function descriptor into r2.
5173   //   4. Load the environment pointer from the function descriptor into
5174   //      r11.
5175   //   5. Branch to the function entry point address.
5176   //   6. On return of the callee, the TOC of the caller needs to be
5177   //      restored (this is done in FinishCall()).
5178   //
5179   // The loads are scheduled at the beginning of the call sequence, and the
5180   // register copies are flagged together to ensure that no other
5181   // operations can be scheduled in between. E.g. without flagging the
5182   // copies together, a TOC access in the caller could be scheduled between
5183   // the assignment of the callee TOC and the branch to the callee, which leads
5184   // to incorrect code.
5185 
5186   // Start by loading the function address from the descriptor.
5187   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5188   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5189                       ? (MachineMemOperand::MODereferenceable |
5190                          MachineMemOperand::MOInvariant)
5191                       : MachineMemOperand::MONone;
5192 
5193   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5194 
5195   // Registers used in building the DAG.
5196   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5197   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5198 
5199   // Offsets of descriptor members.
5200   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5201   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5202 
5203   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5204   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5205 
5206   // One load for the functions entry point address.
5207   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5208                                     Alignment, MMOFlags);
5209 
5210   // One for loading the TOC anchor for the module that contains the called
5211   // function.
5212   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5213   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5214   SDValue TOCPtr =
5215       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5216                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5217 
5218   // One for loading the environment pointer.
5219   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5220   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5221   SDValue LoadEnvPtr =
5222       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5223                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5224 
5225 
5226   // Then copy the newly loaded TOC anchor to the TOC pointer.
5227   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5228   Chain = TOCVal.getValue(0);
5229   Glue = TOCVal.getValue(1);
5230 
5231   // If the function call has an explicit 'nest' parameter, it takes the
5232   // place of the environment pointer.
5233   assert((!hasNest || !Subtarget.isAIXABI()) &&
5234          "Nest parameter is not supported on AIX.");
5235   if (!hasNest) {
5236     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5237     Chain = EnvVal.getValue(0);
5238     Glue = EnvVal.getValue(1);
5239   }
5240 
5241   // The rest of the indirect call sequence is the same as the non-descriptor
5242   // DAG.
5243   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5244 }
5245 
5246 static void
5247 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5248                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5249                   SelectionDAG &DAG,
5250                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5251                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5252                   const PPCSubtarget &Subtarget) {
5253   const bool IsPPC64 = Subtarget.isPPC64();
5254   // MVT for a general purpose register.
5255   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5256 
5257   // First operand is always the chain.
5258   Ops.push_back(Chain);
5259 
5260   // If it's a direct call pass the callee as the second operand.
5261   if (!CFlags.IsIndirect)
5262     Ops.push_back(Callee);
5263   else {
5264     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5265 
5266     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5267     // on the stack (this would have been done in `LowerCall_64SVR4` or
5268     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5269     // represents both the indirect branch and a load that restores the TOC
5270     // pointer from the linkage area. The operand for the TOC restore is an add
5271     // of the TOC save offset to the stack pointer. This must be the second
5272     // operand: after the chain input but before any other variadic arguments.
5273     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5274     // saved or used.
5275     if (isTOCSaveRestoreRequired(Subtarget)) {
5276       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5277 
5278       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5279       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5280       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5281       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5282       Ops.push_back(AddTOC);
5283     }
5284 
5285     // Add the register used for the environment pointer.
5286     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5287       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5288                                     RegVT));
5289 
5290 
5291     // Add CTR register as callee so a bctr can be emitted later.
5292     if (CFlags.IsTailCall)
5293       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5294   }
5295 
5296   // If this is a tail call add stack pointer delta.
5297   if (CFlags.IsTailCall)
5298     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5299 
5300   // Add argument registers to the end of the list so that they are known live
5301   // into the call.
5302   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5303     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5304                                   RegsToPass[i].second.getValueType()));
5305 
5306   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5307   // no way to mark dependencies as implicit here.
5308   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5309   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5310        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5311     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5312 
5313   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5314   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5315     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5316 
5317   // Add a register mask operand representing the call-preserved registers.
5318   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5319   const uint32_t *Mask =
5320       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5321   assert(Mask && "Missing call preserved mask for calling convention");
5322   Ops.push_back(DAG.getRegisterMask(Mask));
5323 
5324   // If the glue is valid, it is the last operand.
5325   if (Glue.getNode())
5326     Ops.push_back(Glue);
5327 }
5328 
5329 SDValue PPCTargetLowering::FinishCall(
5330     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5331     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5332     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5333     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5334     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5335 
5336   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5337       Subtarget.isAIXABI())
5338     setUsesTOCBasePtr(DAG);
5339 
5340   unsigned CallOpc =
5341       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5342                     Subtarget, DAG.getTarget());
5343 
5344   if (!CFlags.IsIndirect)
5345     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5346   else if (Subtarget.usesFunctionDescriptors())
5347     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5348                                   dl, CFlags.HasNest, Subtarget);
5349   else
5350     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5351 
5352   // Build the operand list for the call instruction.
5353   SmallVector<SDValue, 8> Ops;
5354   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5355                     SPDiff, Subtarget);
5356 
5357   // Emit tail call.
5358   if (CFlags.IsTailCall) {
5359     // Indirect tail call when using PC Relative calls do not have the same
5360     // constraints.
5361     assert(((Callee.getOpcode() == ISD::Register &&
5362              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5363             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5364             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5365             isa<ConstantSDNode>(Callee) ||
5366             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5367            "Expecting a global address, external symbol, absolute value, "
5368            "register or an indirect tail call when PC Relative calls are "
5369            "used.");
5370     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5371     assert(CallOpc == PPCISD::TC_RETURN &&
5372            "Unexpected call opcode for a tail call.");
5373     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5374     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5375   }
5376 
5377   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5378   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5379   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5380   Glue = Chain.getValue(1);
5381 
5382   // When performing tail call optimization the callee pops its arguments off
5383   // the stack. Account for this here so these bytes can be pushed back on in
5384   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5385   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5386                          getTargetMachine().Options.GuaranteedTailCallOpt)
5387                             ? NumBytes
5388                             : 0;
5389 
5390   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5391                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5392                              Glue, dl);
5393   Glue = Chain.getValue(1);
5394 
5395   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5396                          DAG, InVals);
5397 }
5398 
5399 SDValue
5400 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5401                              SmallVectorImpl<SDValue> &InVals) const {
5402   SelectionDAG &DAG                     = CLI.DAG;
5403   SDLoc &dl                             = CLI.DL;
5404   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5405   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5406   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5407   SDValue Chain                         = CLI.Chain;
5408   SDValue Callee                        = CLI.Callee;
5409   bool &isTailCall                      = CLI.IsTailCall;
5410   CallingConv::ID CallConv              = CLI.CallConv;
5411   bool isVarArg                         = CLI.IsVarArg;
5412   bool isPatchPoint                     = CLI.IsPatchPoint;
5413   const CallBase *CB                    = CLI.CB;
5414 
5415   if (isTailCall) {
5416     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5417       isTailCall = false;
5418     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5419       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5420           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5421     else
5422       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5423                                                      Ins, DAG);
5424     if (isTailCall) {
5425       ++NumTailCalls;
5426       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5427         ++NumSiblingCalls;
5428 
5429       // PC Relative calls no longer guarantee that the callee is a Global
5430       // Address Node. The callee could be an indirect tail call in which
5431       // case the SDValue for the callee could be a load (to load the address
5432       // of a function pointer) or it may be a register copy (to move the
5433       // address of the callee from a function parameter into a virtual
5434       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5435       assert((Subtarget.isUsingPCRelativeCalls() ||
5436               isa<GlobalAddressSDNode>(Callee)) &&
5437              "Callee should be an llvm::Function object.");
5438 
5439       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5440                         << "\nTCO callee: ");
5441       LLVM_DEBUG(Callee.dump());
5442     }
5443   }
5444 
5445   if (!isTailCall && CB && CB->isMustTailCall())
5446     report_fatal_error("failed to perform tail call elimination on a call "
5447                        "site marked musttail");
5448 
5449   // When long calls (i.e. indirect calls) are always used, calls are always
5450   // made via function pointer. If we have a function name, first translate it
5451   // into a pointer.
5452   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5453       !isTailCall)
5454     Callee = LowerGlobalAddress(Callee, DAG);
5455 
5456   CallFlags CFlags(
5457       CallConv, isTailCall, isVarArg, isPatchPoint,
5458       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5459       // hasNest
5460       Subtarget.is64BitELFABI() &&
5461           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5462       CLI.NoMerge);
5463 
5464   if (Subtarget.isAIXABI())
5465     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5466                          InVals, CB);
5467 
5468   assert(Subtarget.isSVR4ABI());
5469   if (Subtarget.isPPC64())
5470     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5471                             InVals, CB);
5472   return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5473                           InVals, CB);
5474 }
5475 
5476 SDValue PPCTargetLowering::LowerCall_32SVR4(
5477     SDValue Chain, SDValue Callee, CallFlags CFlags,
5478     const SmallVectorImpl<ISD::OutputArg> &Outs,
5479     const SmallVectorImpl<SDValue> &OutVals,
5480     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5481     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5482     const CallBase *CB) const {
5483   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5484   // of the 32-bit SVR4 ABI stack frame layout.
5485 
5486   const CallingConv::ID CallConv = CFlags.CallConv;
5487   const bool IsVarArg = CFlags.IsVarArg;
5488   const bool IsTailCall = CFlags.IsTailCall;
5489 
5490   assert((CallConv == CallingConv::C ||
5491           CallConv == CallingConv::Cold ||
5492           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5493 
5494   const Align PtrAlign(4);
5495 
5496   MachineFunction &MF = DAG.getMachineFunction();
5497 
5498   // Mark this function as potentially containing a function that contains a
5499   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5500   // and restoring the callers stack pointer in this functions epilog. This is
5501   // done because by tail calling the called function might overwrite the value
5502   // in this function's (MF) stack pointer stack slot 0(SP).
5503   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5504       CallConv == CallingConv::Fast)
5505     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5506 
5507   // Count how many bytes are to be pushed on the stack, including the linkage
5508   // area, parameter list area and the part of the local variable space which
5509   // contains copies of aggregates which are passed by value.
5510 
5511   // Assign locations to all of the outgoing arguments.
5512   SmallVector<CCValAssign, 16> ArgLocs;
5513   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5514 
5515   // Reserve space for the linkage area on the stack.
5516   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5517                        PtrAlign);
5518   if (useSoftFloat())
5519     CCInfo.PreAnalyzeCallOperands(Outs);
5520 
5521   if (IsVarArg) {
5522     // Handle fixed and variable vector arguments differently.
5523     // Fixed vector arguments go into registers as long as registers are
5524     // available. Variable vector arguments always go into memory.
5525     unsigned NumArgs = Outs.size();
5526 
5527     for (unsigned i = 0; i != NumArgs; ++i) {
5528       MVT ArgVT = Outs[i].VT;
5529       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5530       bool Result;
5531 
5532       if (Outs[i].IsFixed) {
5533         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5534                                CCInfo);
5535       } else {
5536         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5537                                       ArgFlags, CCInfo);
5538       }
5539 
5540       if (Result) {
5541 #ifndef NDEBUG
5542         errs() << "Call operand #" << i << " has unhandled type "
5543              << EVT(ArgVT).getEVTString() << "\n";
5544 #endif
5545         llvm_unreachable(nullptr);
5546       }
5547     }
5548   } else {
5549     // All arguments are treated the same.
5550     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5551   }
5552   CCInfo.clearWasPPCF128();
5553 
5554   // Assign locations to all of the outgoing aggregate by value arguments.
5555   SmallVector<CCValAssign, 16> ByValArgLocs;
5556   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5557 
5558   // Reserve stack space for the allocations in CCInfo.
5559   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5560 
5561   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5562 
5563   // Size of the linkage area, parameter list area and the part of the local
5564   // space variable where copies of aggregates which are passed by value are
5565   // stored.
5566   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5567 
5568   // Calculate by how many bytes the stack has to be adjusted in case of tail
5569   // call optimization.
5570   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5571 
5572   // Adjust the stack pointer for the new arguments...
5573   // These operations are automatically eliminated by the prolog/epilog pass
5574   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5575   SDValue CallSeqStart = Chain;
5576 
5577   // Load the return address and frame pointer so it can be moved somewhere else
5578   // later.
5579   SDValue LROp, FPOp;
5580   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5581 
5582   // Set up a copy of the stack pointer for use loading and storing any
5583   // arguments that may not fit in the registers available for argument
5584   // passing.
5585   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5586 
5587   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5588   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5589   SmallVector<SDValue, 8> MemOpChains;
5590 
5591   bool seenFloatArg = false;
5592   // Walk the register/memloc assignments, inserting copies/loads.
5593   // i - Tracks the index into the list of registers allocated for the call
5594   // RealArgIdx - Tracks the index into the list of actual function arguments
5595   // j - Tracks the index into the list of byval arguments
5596   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5597        i != e;
5598        ++i, ++RealArgIdx) {
5599     CCValAssign &VA = ArgLocs[i];
5600     SDValue Arg = OutVals[RealArgIdx];
5601     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5602 
5603     if (Flags.isByVal()) {
5604       // Argument is an aggregate which is passed by value, thus we need to
5605       // create a copy of it in the local variable space of the current stack
5606       // frame (which is the stack frame of the caller) and pass the address of
5607       // this copy to the callee.
5608       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5609       CCValAssign &ByValVA = ByValArgLocs[j++];
5610       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5611 
5612       // Memory reserved in the local variable space of the callers stack frame.
5613       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5614 
5615       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5616       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5617                            StackPtr, PtrOff);
5618 
5619       // Create a copy of the argument in the local area of the current
5620       // stack frame.
5621       SDValue MemcpyCall =
5622         CreateCopyOfByValArgument(Arg, PtrOff,
5623                                   CallSeqStart.getNode()->getOperand(0),
5624                                   Flags, DAG, dl);
5625 
5626       // This must go outside the CALLSEQ_START..END.
5627       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5628                                                      SDLoc(MemcpyCall));
5629       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5630                              NewCallSeqStart.getNode());
5631       Chain = CallSeqStart = NewCallSeqStart;
5632 
5633       // Pass the address of the aggregate copy on the stack either in a
5634       // physical register or in the parameter list area of the current stack
5635       // frame to the callee.
5636       Arg = PtrOff;
5637     }
5638 
5639     // When useCRBits() is true, there can be i1 arguments.
5640     // It is because getRegisterType(MVT::i1) => MVT::i1,
5641     // and for other integer types getRegisterType() => MVT::i32.
5642     // Extend i1 and ensure callee will get i32.
5643     if (Arg.getValueType() == MVT::i1)
5644       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5645                         dl, MVT::i32, Arg);
5646 
5647     if (VA.isRegLoc()) {
5648       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5649       // Put argument in a physical register.
5650       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5651         bool IsLE = Subtarget.isLittleEndian();
5652         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5653                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5654         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5655         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5656                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5657         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5658                              SVal.getValue(0)));
5659       } else
5660         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5661     } else {
5662       // Put argument in the parameter list area of the current stack frame.
5663       assert(VA.isMemLoc());
5664       unsigned LocMemOffset = VA.getLocMemOffset();
5665 
5666       if (!IsTailCall) {
5667         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5668         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5669                              StackPtr, PtrOff);
5670 
5671         MemOpChains.push_back(
5672             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5673       } else {
5674         // Calculate and remember argument location.
5675         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5676                                  TailCallArguments);
5677       }
5678     }
5679   }
5680 
5681   if (!MemOpChains.empty())
5682     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5683 
5684   // Build a sequence of copy-to-reg nodes chained together with token chain
5685   // and flag operands which copy the outgoing args into the appropriate regs.
5686   SDValue InFlag;
5687   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5688     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5689                              RegsToPass[i].second, InFlag);
5690     InFlag = Chain.getValue(1);
5691   }
5692 
5693   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5694   // registers.
5695   if (IsVarArg) {
5696     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5697     SDValue Ops[] = { Chain, InFlag };
5698 
5699     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5700                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5701 
5702     InFlag = Chain.getValue(1);
5703   }
5704 
5705   if (IsTailCall)
5706     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5707                     TailCallArguments);
5708 
5709   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5710                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5711 }
5712 
5713 // Copy an argument into memory, being careful to do this outside the
5714 // call sequence for the call to which the argument belongs.
5715 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5716     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5717     SelectionDAG &DAG, const SDLoc &dl) const {
5718   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5719                         CallSeqStart.getNode()->getOperand(0),
5720                         Flags, DAG, dl);
5721   // The MEMCPY must go outside the CALLSEQ_START..END.
5722   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5723   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5724                                                  SDLoc(MemcpyCall));
5725   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5726                          NewCallSeqStart.getNode());
5727   return NewCallSeqStart;
5728 }
5729 
5730 SDValue PPCTargetLowering::LowerCall_64SVR4(
5731     SDValue Chain, SDValue Callee, CallFlags CFlags,
5732     const SmallVectorImpl<ISD::OutputArg> &Outs,
5733     const SmallVectorImpl<SDValue> &OutVals,
5734     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5735     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5736     const CallBase *CB) const {
5737   bool isELFv2ABI = Subtarget.isELFv2ABI();
5738   bool isLittleEndian = Subtarget.isLittleEndian();
5739   unsigned NumOps = Outs.size();
5740   bool IsSibCall = false;
5741   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5742 
5743   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5744   unsigned PtrByteSize = 8;
5745 
5746   MachineFunction &MF = DAG.getMachineFunction();
5747 
5748   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5749     IsSibCall = true;
5750 
5751   // Mark this function as potentially containing a function that contains a
5752   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5753   // and restoring the callers stack pointer in this functions epilog. This is
5754   // done because by tail calling the called function might overwrite the value
5755   // in this function's (MF) stack pointer stack slot 0(SP).
5756   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5757     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5758 
5759   assert(!(IsFastCall && CFlags.IsVarArg) &&
5760          "fastcc not supported on varargs functions");
5761 
5762   // Count how many bytes are to be pushed on the stack, including the linkage
5763   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5764   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5765   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5766   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5767   unsigned NumBytes = LinkageSize;
5768   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5769 
5770   static const MCPhysReg GPR[] = {
5771     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5772     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5773   };
5774   static const MCPhysReg VR[] = {
5775     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5776     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5777   };
5778 
5779   const unsigned NumGPRs = array_lengthof(GPR);
5780   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5781   const unsigned NumVRs  = array_lengthof(VR);
5782 
5783   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5784   // can be passed to the callee in registers.
5785   // For the fast calling convention, there is another check below.
5786   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5787   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5788   if (!HasParameterArea) {
5789     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5790     unsigned AvailableFPRs = NumFPRs;
5791     unsigned AvailableVRs = NumVRs;
5792     unsigned NumBytesTmp = NumBytes;
5793     for (unsigned i = 0; i != NumOps; ++i) {
5794       if (Outs[i].Flags.isNest()) continue;
5795       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5796                                  PtrByteSize, LinkageSize, ParamAreaSize,
5797                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
5798         HasParameterArea = true;
5799     }
5800   }
5801 
5802   // When using the fast calling convention, we don't provide backing for
5803   // arguments that will be in registers.
5804   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5805 
5806   // Avoid allocating parameter area for fastcc functions if all the arguments
5807   // can be passed in the registers.
5808   if (IsFastCall)
5809     HasParameterArea = false;
5810 
5811   // Add up all the space actually used.
5812   for (unsigned i = 0; i != NumOps; ++i) {
5813     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5814     EVT ArgVT = Outs[i].VT;
5815     EVT OrigVT = Outs[i].ArgVT;
5816 
5817     if (Flags.isNest())
5818       continue;
5819 
5820     if (IsFastCall) {
5821       if (Flags.isByVal()) {
5822         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5823         if (NumGPRsUsed > NumGPRs)
5824           HasParameterArea = true;
5825       } else {
5826         switch (ArgVT.getSimpleVT().SimpleTy) {
5827         default: llvm_unreachable("Unexpected ValueType for argument!");
5828         case MVT::i1:
5829         case MVT::i32:
5830         case MVT::i64:
5831           if (++NumGPRsUsed <= NumGPRs)
5832             continue;
5833           break;
5834         case MVT::v4i32:
5835         case MVT::v8i16:
5836         case MVT::v16i8:
5837         case MVT::v2f64:
5838         case MVT::v2i64:
5839         case MVT::v1i128:
5840         case MVT::f128:
5841           if (++NumVRsUsed <= NumVRs)
5842             continue;
5843           break;
5844         case MVT::v4f32:
5845           if (++NumVRsUsed <= NumVRs)
5846             continue;
5847           break;
5848         case MVT::f32:
5849         case MVT::f64:
5850           if (++NumFPRsUsed <= NumFPRs)
5851             continue;
5852           break;
5853         }
5854         HasParameterArea = true;
5855       }
5856     }
5857 
5858     /* Respect alignment of argument on the stack.  */
5859     auto Alignement =
5860         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5861     NumBytes = alignTo(NumBytes, Alignement);
5862 
5863     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5864     if (Flags.isInConsecutiveRegsLast())
5865       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5866   }
5867 
5868   unsigned NumBytesActuallyUsed = NumBytes;
5869 
5870   // In the old ELFv1 ABI,
5871   // the prolog code of the callee may store up to 8 GPR argument registers to
5872   // the stack, allowing va_start to index over them in memory if its varargs.
5873   // Because we cannot tell if this is needed on the caller side, we have to
5874   // conservatively assume that it is needed.  As such, make sure we have at
5875   // least enough stack space for the caller to store the 8 GPRs.
5876   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5877   // really requires memory operands, e.g. a vararg function.
5878   if (HasParameterArea)
5879     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5880   else
5881     NumBytes = LinkageSize;
5882 
5883   // Tail call needs the stack to be aligned.
5884   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5885     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5886 
5887   int SPDiff = 0;
5888 
5889   // Calculate by how many bytes the stack has to be adjusted in case of tail
5890   // call optimization.
5891   if (!IsSibCall)
5892     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
5893 
5894   // To protect arguments on the stack from being clobbered in a tail call,
5895   // force all the loads to happen before doing any other lowering.
5896   if (CFlags.IsTailCall)
5897     Chain = DAG.getStackArgumentTokenFactor(Chain);
5898 
5899   // Adjust the stack pointer for the new arguments...
5900   // These operations are automatically eliminated by the prolog/epilog pass
5901   if (!IsSibCall)
5902     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5903   SDValue CallSeqStart = Chain;
5904 
5905   // Load the return address and frame pointer so it can be move somewhere else
5906   // later.
5907   SDValue LROp, FPOp;
5908   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5909 
5910   // Set up a copy of the stack pointer for use loading and storing any
5911   // arguments that may not fit in the registers available for argument
5912   // passing.
5913   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5914 
5915   // Figure out which arguments are going to go in registers, and which in
5916   // memory.  Also, if this is a vararg function, floating point operations
5917   // must be stored to our stack, and loaded into integer regs as well, if
5918   // any integer regs are available for argument passing.
5919   unsigned ArgOffset = LinkageSize;
5920 
5921   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5922   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5923 
5924   SmallVector<SDValue, 8> MemOpChains;
5925   for (unsigned i = 0; i != NumOps; ++i) {
5926     SDValue Arg = OutVals[i];
5927     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5928     EVT ArgVT = Outs[i].VT;
5929     EVT OrigVT = Outs[i].ArgVT;
5930 
5931     // PtrOff will be used to store the current argument to the stack if a
5932     // register cannot be found for it.
5933     SDValue PtrOff;
5934 
5935     // We re-align the argument offset for each argument, except when using the
5936     // fast calling convention, when we need to make sure we do that only when
5937     // we'll actually use a stack slot.
5938     auto ComputePtrOff = [&]() {
5939       /* Respect alignment of argument on the stack.  */
5940       auto Alignment =
5941           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5942       ArgOffset = alignTo(ArgOffset, Alignment);
5943 
5944       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5945 
5946       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5947     };
5948 
5949     if (!IsFastCall) {
5950       ComputePtrOff();
5951 
5952       /* Compute GPR index associated with argument offset.  */
5953       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5954       GPR_idx = std::min(GPR_idx, NumGPRs);
5955     }
5956 
5957     // Promote integers to 64-bit values.
5958     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5959       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5960       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5961       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5962     }
5963 
5964     // FIXME memcpy is used way more than necessary.  Correctness first.
5965     // Note: "by value" is code for passing a structure by value, not
5966     // basic types.
5967     if (Flags.isByVal()) {
5968       // Note: Size includes alignment padding, so
5969       //   struct x { short a; char b; }
5970       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5971       // These are the proper values we need for right-justifying the
5972       // aggregate in a parameter register.
5973       unsigned Size = Flags.getByValSize();
5974 
5975       // An empty aggregate parameter takes up no storage and no
5976       // registers.
5977       if (Size == 0)
5978         continue;
5979 
5980       if (IsFastCall)
5981         ComputePtrOff();
5982 
5983       // All aggregates smaller than 8 bytes must be passed right-justified.
5984       if (Size==1 || Size==2 || Size==4) {
5985         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5986         if (GPR_idx != NumGPRs) {
5987           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5988                                         MachinePointerInfo(), VT);
5989           MemOpChains.push_back(Load.getValue(1));
5990           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5991 
5992           ArgOffset += PtrByteSize;
5993           continue;
5994         }
5995       }
5996 
5997       if (GPR_idx == NumGPRs && Size < 8) {
5998         SDValue AddPtr = PtrOff;
5999         if (!isLittleEndian) {
6000           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6001                                           PtrOff.getValueType());
6002           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6003         }
6004         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6005                                                           CallSeqStart,
6006                                                           Flags, DAG, dl);
6007         ArgOffset += PtrByteSize;
6008         continue;
6009       }
6010       // Copy entire object into memory.  There are cases where gcc-generated
6011       // code assumes it is there, even if it could be put entirely into
6012       // registers.  (This is not what the doc says.)
6013 
6014       // FIXME: The above statement is likely due to a misunderstanding of the
6015       // documents.  All arguments must be copied into the parameter area BY
6016       // THE CALLEE in the event that the callee takes the address of any
6017       // formal argument.  That has not yet been implemented.  However, it is
6018       // reasonable to use the stack area as a staging area for the register
6019       // load.
6020 
6021       // Skip this for small aggregates, as we will use the same slot for a
6022       // right-justified copy, below.
6023       if (Size >= 8)
6024         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6025                                                           CallSeqStart,
6026                                                           Flags, DAG, dl);
6027 
6028       // When a register is available, pass a small aggregate right-justified.
6029       if (Size < 8 && GPR_idx != NumGPRs) {
6030         // The easiest way to get this right-justified in a register
6031         // is to copy the structure into the rightmost portion of a
6032         // local variable slot, then load the whole slot into the
6033         // register.
6034         // FIXME: The memcpy seems to produce pretty awful code for
6035         // small aggregates, particularly for packed ones.
6036         // FIXME: It would be preferable to use the slot in the
6037         // parameter save area instead of a new local variable.
6038         SDValue AddPtr = PtrOff;
6039         if (!isLittleEndian) {
6040           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6041           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6042         }
6043         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6044                                                           CallSeqStart,
6045                                                           Flags, DAG, dl);
6046 
6047         // Load the slot into the register.
6048         SDValue Load =
6049             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6050         MemOpChains.push_back(Load.getValue(1));
6051         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6052 
6053         // Done with this argument.
6054         ArgOffset += PtrByteSize;
6055         continue;
6056       }
6057 
6058       // For aggregates larger than PtrByteSize, copy the pieces of the
6059       // object that fit into registers from the parameter save area.
6060       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6061         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6062         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6063         if (GPR_idx != NumGPRs) {
6064           SDValue Load =
6065               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6066           MemOpChains.push_back(Load.getValue(1));
6067           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6068           ArgOffset += PtrByteSize;
6069         } else {
6070           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6071           break;
6072         }
6073       }
6074       continue;
6075     }
6076 
6077     switch (Arg.getSimpleValueType().SimpleTy) {
6078     default: llvm_unreachable("Unexpected ValueType for argument!");
6079     case MVT::i1:
6080     case MVT::i32:
6081     case MVT::i64:
6082       if (Flags.isNest()) {
6083         // The 'nest' parameter, if any, is passed in R11.
6084         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6085         break;
6086       }
6087 
6088       // These can be scalar arguments or elements of an integer array type
6089       // passed directly.  Clang may use those instead of "byval" aggregate
6090       // types to avoid forcing arguments to memory unnecessarily.
6091       if (GPR_idx != NumGPRs) {
6092         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6093       } else {
6094         if (IsFastCall)
6095           ComputePtrOff();
6096 
6097         assert(HasParameterArea &&
6098                "Parameter area must exist to pass an argument in memory.");
6099         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6100                          true, CFlags.IsTailCall, false, MemOpChains,
6101                          TailCallArguments, dl);
6102         if (IsFastCall)
6103           ArgOffset += PtrByteSize;
6104       }
6105       if (!IsFastCall)
6106         ArgOffset += PtrByteSize;
6107       break;
6108     case MVT::f32:
6109     case MVT::f64: {
6110       // These can be scalar arguments or elements of a float array type
6111       // passed directly.  The latter are used to implement ELFv2 homogenous
6112       // float aggregates.
6113 
6114       // Named arguments go into FPRs first, and once they overflow, the
6115       // remaining arguments go into GPRs and then the parameter save area.
6116       // Unnamed arguments for vararg functions always go to GPRs and
6117       // then the parameter save area.  For now, put all arguments to vararg
6118       // routines always in both locations (FPR *and* GPR or stack slot).
6119       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6120       bool NeededLoad = false;
6121 
6122       // First load the argument into the next available FPR.
6123       if (FPR_idx != NumFPRs)
6124         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6125 
6126       // Next, load the argument into GPR or stack slot if needed.
6127       if (!NeedGPROrStack)
6128         ;
6129       else if (GPR_idx != NumGPRs && !IsFastCall) {
6130         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6131         // once we support fp <-> gpr moves.
6132 
6133         // In the non-vararg case, this can only ever happen in the
6134         // presence of f32 array types, since otherwise we never run
6135         // out of FPRs before running out of GPRs.
6136         SDValue ArgVal;
6137 
6138         // Double values are always passed in a single GPR.
6139         if (Arg.getValueType() != MVT::f32) {
6140           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6141 
6142         // Non-array float values are extended and passed in a GPR.
6143         } else if (!Flags.isInConsecutiveRegs()) {
6144           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6145           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6146 
6147         // If we have an array of floats, we collect every odd element
6148         // together with its predecessor into one GPR.
6149         } else if (ArgOffset % PtrByteSize != 0) {
6150           SDValue Lo, Hi;
6151           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6152           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6153           if (!isLittleEndian)
6154             std::swap(Lo, Hi);
6155           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6156 
6157         // The final element, if even, goes into the first half of a GPR.
6158         } else if (Flags.isInConsecutiveRegsLast()) {
6159           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6160           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6161           if (!isLittleEndian)
6162             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6163                                  DAG.getConstant(32, dl, MVT::i32));
6164 
6165         // Non-final even elements are skipped; they will be handled
6166         // together the with subsequent argument on the next go-around.
6167         } else
6168           ArgVal = SDValue();
6169 
6170         if (ArgVal.getNode())
6171           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6172       } else {
6173         if (IsFastCall)
6174           ComputePtrOff();
6175 
6176         // Single-precision floating-point values are mapped to the
6177         // second (rightmost) word of the stack doubleword.
6178         if (Arg.getValueType() == MVT::f32 &&
6179             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6180           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6181           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6182         }
6183 
6184         assert(HasParameterArea &&
6185                "Parameter area must exist to pass an argument in memory.");
6186         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6187                          true, CFlags.IsTailCall, false, MemOpChains,
6188                          TailCallArguments, dl);
6189 
6190         NeededLoad = true;
6191       }
6192       // When passing an array of floats, the array occupies consecutive
6193       // space in the argument area; only round up to the next doubleword
6194       // at the end of the array.  Otherwise, each float takes 8 bytes.
6195       if (!IsFastCall || NeededLoad) {
6196         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6197                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6198         if (Flags.isInConsecutiveRegsLast())
6199           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6200       }
6201       break;
6202     }
6203     case MVT::v4f32:
6204     case MVT::v4i32:
6205     case MVT::v8i16:
6206     case MVT::v16i8:
6207     case MVT::v2f64:
6208     case MVT::v2i64:
6209     case MVT::v1i128:
6210     case MVT::f128:
6211       // These can be scalar arguments or elements of a vector array type
6212       // passed directly.  The latter are used to implement ELFv2 homogenous
6213       // vector aggregates.
6214 
6215       // For a varargs call, named arguments go into VRs or on the stack as
6216       // usual; unnamed arguments always go to the stack or the corresponding
6217       // GPRs when within range.  For now, we always put the value in both
6218       // locations (or even all three).
6219       if (CFlags.IsVarArg) {
6220         assert(HasParameterArea &&
6221                "Parameter area must exist if we have a varargs call.");
6222         // We could elide this store in the case where the object fits
6223         // entirely in R registers.  Maybe later.
6224         SDValue Store =
6225             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6226         MemOpChains.push_back(Store);
6227         if (VR_idx != NumVRs) {
6228           SDValue Load =
6229               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6230           MemOpChains.push_back(Load.getValue(1));
6231           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6232         }
6233         ArgOffset += 16;
6234         for (unsigned i=0; i<16; i+=PtrByteSize) {
6235           if (GPR_idx == NumGPRs)
6236             break;
6237           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6238                                    DAG.getConstant(i, dl, PtrVT));
6239           SDValue Load =
6240               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6241           MemOpChains.push_back(Load.getValue(1));
6242           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6243         }
6244         break;
6245       }
6246 
6247       // Non-varargs Altivec params go into VRs or on the stack.
6248       if (VR_idx != NumVRs) {
6249         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6250       } else {
6251         if (IsFastCall)
6252           ComputePtrOff();
6253 
6254         assert(HasParameterArea &&
6255                "Parameter area must exist to pass an argument in memory.");
6256         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6257                          true, CFlags.IsTailCall, true, MemOpChains,
6258                          TailCallArguments, dl);
6259         if (IsFastCall)
6260           ArgOffset += 16;
6261       }
6262 
6263       if (!IsFastCall)
6264         ArgOffset += 16;
6265       break;
6266     }
6267   }
6268 
6269   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6270          "mismatch in size of parameter area");
6271   (void)NumBytesActuallyUsed;
6272 
6273   if (!MemOpChains.empty())
6274     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6275 
6276   // Check if this is an indirect call (MTCTR/BCTRL).
6277   // See prepareDescriptorIndirectCall and buildCallOperands for more
6278   // information about calls through function pointers in the 64-bit SVR4 ABI.
6279   if (CFlags.IsIndirect) {
6280     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6281     // caller in the TOC save area.
6282     if (isTOCSaveRestoreRequired(Subtarget)) {
6283       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6284       // Load r2 into a virtual register and store it to the TOC save area.
6285       setUsesTOCBasePtr(DAG);
6286       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6287       // TOC save area offset.
6288       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6289       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6290       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6291       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6292                            MachinePointerInfo::getStack(
6293                                DAG.getMachineFunction(), TOCSaveOffset));
6294     }
6295     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6296     // This does not mean the MTCTR instruction must use R12; it's easier
6297     // to model this as an extra parameter, so do that.
6298     if (isELFv2ABI && !CFlags.IsPatchPoint)
6299       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6300   }
6301 
6302   // Build a sequence of copy-to-reg nodes chained together with token chain
6303   // and flag operands which copy the outgoing args into the appropriate regs.
6304   SDValue InFlag;
6305   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6306     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6307                              RegsToPass[i].second, InFlag);
6308     InFlag = Chain.getValue(1);
6309   }
6310 
6311   if (CFlags.IsTailCall && !IsSibCall)
6312     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6313                     TailCallArguments);
6314 
6315   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6316                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6317 }
6318 
6319 // Returns true when the shadow of a general purpose argument register
6320 // in the parameter save area is aligned to at least 'RequiredAlign'.
6321 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
6322   assert(RequiredAlign.value() <= 16 &&
6323          "Required alignment greater than stack alignment.");
6324   switch (Reg) {
6325   default:
6326     report_fatal_error("called on invalid register.");
6327   case PPC::R5:
6328   case PPC::R9:
6329   case PPC::X3:
6330   case PPC::X5:
6331   case PPC::X7:
6332   case PPC::X9:
6333     // These registers are 16 byte aligned which is the most strict aligment
6334     // we can support.
6335     return true;
6336   case PPC::R3:
6337   case PPC::R7:
6338   case PPC::X4:
6339   case PPC::X6:
6340   case PPC::X8:
6341   case PPC::X10:
6342     // The shadow of these registers in the PSA is 8 byte aligned.
6343     return RequiredAlign <= 8;
6344   case PPC::R4:
6345   case PPC::R6:
6346   case PPC::R8:
6347   case PPC::R10:
6348     return RequiredAlign <= 4;
6349   }
6350 }
6351 
6352 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6353                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6354                    CCState &S) {
6355   AIXCCState &State = static_cast<AIXCCState &>(S);
6356   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6357       State.getMachineFunction().getSubtarget());
6358   const bool IsPPC64 = Subtarget.isPPC64();
6359   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6360   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6361 
6362   if (ValVT == MVT::f128)
6363     report_fatal_error("f128 is unimplemented on AIX.");
6364 
6365   if (ArgFlags.isNest())
6366     report_fatal_error("Nest arguments are unimplemented.");
6367 
6368   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6369                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6370                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6371   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6372                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6373                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6374 
6375   static const MCPhysReg VR[] = {// Vector registers.
6376                                  PPC::V2,  PPC::V3,  PPC::V4,  PPC::V5,
6377                                  PPC::V6,  PPC::V7,  PPC::V8,  PPC::V9,
6378                                  PPC::V10, PPC::V11, PPC::V12, PPC::V13};
6379 
6380   if (ArgFlags.isByVal()) {
6381     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6382       report_fatal_error("Pass-by-value arguments with alignment greater than "
6383                          "register width are not supported.");
6384 
6385     const unsigned ByValSize = ArgFlags.getByValSize();
6386 
6387     // An empty aggregate parameter takes up no storage and no registers,
6388     // but needs a MemLoc for a stack slot for the formal arguments side.
6389     if (ByValSize == 0) {
6390       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6391                                        State.getNextStackOffset(), RegVT,
6392                                        LocInfo));
6393       return false;
6394     }
6395 
6396     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6397     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6398     for (const unsigned E = Offset + StackSize; Offset < E;
6399          Offset += PtrAlign.value()) {
6400       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6401         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6402       else {
6403         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6404                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6405                                          LocInfo));
6406         break;
6407       }
6408     }
6409     return false;
6410   }
6411 
6412   // Arguments always reserve parameter save area.
6413   switch (ValVT.SimpleTy) {
6414   default:
6415     report_fatal_error("Unhandled value type for argument.");
6416   case MVT::i64:
6417     // i64 arguments should have been split to i32 for PPC32.
6418     assert(IsPPC64 && "PPC32 should have split i64 values.");
6419     LLVM_FALLTHROUGH;
6420   case MVT::i1:
6421   case MVT::i32: {
6422     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6423     // AIX integer arguments are always passed in register width.
6424     if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6425       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6426                                   : CCValAssign::LocInfo::ZExt;
6427     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6428       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6429     else
6430       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6431 
6432     return false;
6433   }
6434   case MVT::f32:
6435   case MVT::f64: {
6436     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6437     const unsigned StoreSize = LocVT.getStoreSize();
6438     // Floats are always 4-byte aligned in the PSA on AIX.
6439     // This includes f64 in 64-bit mode for ABI compatibility.
6440     const unsigned Offset =
6441         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6442     unsigned FReg = State.AllocateReg(FPR);
6443     if (FReg)
6444       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6445 
6446     // Reserve and initialize GPRs or initialize the PSA as required.
6447     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6448       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6449         assert(FReg && "An FPR should be available when a GPR is reserved.");
6450         if (State.isVarArg()) {
6451           // Successfully reserved GPRs are only initialized for vararg calls.
6452           // Custom handling is required for:
6453           //   f64 in PPC32 needs to be split into 2 GPRs.
6454           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6455           State.addLoc(
6456               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6457         }
6458       } else {
6459         // If there are insufficient GPRs, the PSA needs to be initialized.
6460         // Initialization occurs even if an FPR was initialized for
6461         // compatibility with the AIX XL compiler. The full memory for the
6462         // argument will be initialized even if a prior word is saved in GPR.
6463         // A custom memLoc is used when the argument also passes in FPR so
6464         // that the callee handling can skip over it easily.
6465         State.addLoc(
6466             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6467                                              LocInfo)
6468                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6469         break;
6470       }
6471     }
6472 
6473     return false;
6474   }
6475   case MVT::v4f32:
6476   case MVT::v4i32:
6477   case MVT::v8i16:
6478   case MVT::v16i8:
6479   case MVT::v2i64:
6480   case MVT::v2f64:
6481   case MVT::v1i128: {
6482     const unsigned VecSize = 16;
6483     const Align VecAlign(VecSize);
6484 
6485     if (!State.isVarArg()) {
6486       // If there are vector registers remaining we don't consume any stack
6487       // space.
6488       if (unsigned VReg = State.AllocateReg(VR)) {
6489         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6490         return false;
6491       }
6492       // Vectors passed on the stack do not shadow GPRs or FPRs even though they
6493       // might be allocated in the portion of the PSA that is shadowed by the
6494       // GPRs.
6495       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6496       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6497       return false;
6498     }
6499 
6500     const unsigned PtrSize = IsPPC64 ? 8 : 4;
6501     ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
6502 
6503     unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
6504     // Burn any underaligned registers and their shadowed stack space until
6505     // we reach the required alignment.
6506     while (NextRegIndex != GPRs.size() &&
6507            !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
6508       // Shadow allocate register and its stack shadow.
6509       unsigned Reg = State.AllocateReg(GPRs);
6510       State.AllocateStack(PtrSize, PtrAlign);
6511       assert(Reg && "Allocating register unexpectedly failed.");
6512       (void)Reg;
6513       NextRegIndex = State.getFirstUnallocated(GPRs);
6514     }
6515 
6516     // Vectors that are passed as fixed arguments are handled differently.
6517     // They are passed in VRs if any are available (unlike arguments passed
6518     // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
6519     // functions)
6520     if (State.isFixed(ValNo)) {
6521       if (unsigned VReg = State.AllocateReg(VR)) {
6522         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6523         // Shadow allocate GPRs and stack space even though we pass in a VR.
6524         for (unsigned I = 0; I != VecSize; I += PtrSize)
6525           State.AllocateReg(GPRs);
6526         State.AllocateStack(VecSize, VecAlign);
6527         return false;
6528       }
6529       // No vector registers remain so pass on the stack.
6530       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6531       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6532       return false;
6533     }
6534 
6535     // If all GPRS are consumed then we pass the argument fully on the stack.
6536     if (NextRegIndex == GPRs.size()) {
6537       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6538       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6539       return false;
6540     }
6541 
6542     // Corner case for 32-bit codegen. We have 2 registers to pass the first
6543     // half of the argument, and then need to pass the remaining half on the
6544     // stack.
6545     if (GPRs[NextRegIndex] == PPC::R9) {
6546       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6547       State.addLoc(
6548           CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6549 
6550       const unsigned FirstReg = State.AllocateReg(PPC::R9);
6551       const unsigned SecondReg = State.AllocateReg(PPC::R10);
6552       assert(FirstReg && SecondReg &&
6553              "Allocating R9 or R10 unexpectedly failed.");
6554       State.addLoc(
6555           CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
6556       State.addLoc(
6557           CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
6558       return false;
6559     }
6560 
6561     // We have enough GPRs to fully pass the vector argument, and we have
6562     // already consumed any underaligned registers. Start with the custom
6563     // MemLoc and then the custom RegLocs.
6564     const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6565     State.addLoc(
6566         CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6567     for (unsigned I = 0; I != VecSize; I += PtrSize) {
6568       const unsigned Reg = State.AllocateReg(GPRs);
6569       assert(Reg && "Failed to allocated register for vararg vector argument");
6570       State.addLoc(
6571           CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6572     }
6573     return false;
6574   }
6575   }
6576   return true;
6577 }
6578 
6579 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6580                                                     bool IsPPC64) {
6581   assert((IsPPC64 || SVT != MVT::i64) &&
6582          "i64 should have been split for 32-bit codegen.");
6583 
6584   switch (SVT) {
6585   default:
6586     report_fatal_error("Unexpected value type for formal argument");
6587   case MVT::i1:
6588   case MVT::i32:
6589   case MVT::i64:
6590     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6591   case MVT::f32:
6592     return &PPC::F4RCRegClass;
6593   case MVT::f64:
6594     return &PPC::F8RCRegClass;
6595   case MVT::v4f32:
6596   case MVT::v4i32:
6597   case MVT::v8i16:
6598   case MVT::v16i8:
6599   case MVT::v2i64:
6600   case MVT::v2f64:
6601   case MVT::v1i128:
6602     return &PPC::VRRCRegClass;
6603   }
6604 }
6605 
6606 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6607                                         SelectionDAG &DAG, SDValue ArgValue,
6608                                         MVT LocVT, const SDLoc &dl) {
6609   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6610   assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
6611 
6612   if (Flags.isSExt())
6613     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6614                            DAG.getValueType(ValVT));
6615   else if (Flags.isZExt())
6616     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6617                            DAG.getValueType(ValVT));
6618 
6619   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6620 }
6621 
6622 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6623   const unsigned LASize = FL->getLinkageSize();
6624 
6625   if (PPC::GPRCRegClass.contains(Reg)) {
6626     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6627            "Reg must be a valid argument register!");
6628     return LASize + 4 * (Reg - PPC::R3);
6629   }
6630 
6631   if (PPC::G8RCRegClass.contains(Reg)) {
6632     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6633            "Reg must be a valid argument register!");
6634     return LASize + 8 * (Reg - PPC::X3);
6635   }
6636 
6637   llvm_unreachable("Only general purpose registers expected.");
6638 }
6639 
6640 //   AIX ABI Stack Frame Layout:
6641 //
6642 //   Low Memory +--------------------------------------------+
6643 //   SP   +---> | Back chain                                 | ---+
6644 //        |     +--------------------------------------------+    |
6645 //        |     | Saved Condition Register                   |    |
6646 //        |     +--------------------------------------------+    |
6647 //        |     | Saved Linkage Register                     |    |
6648 //        |     +--------------------------------------------+    | Linkage Area
6649 //        |     | Reserved for compilers                     |    |
6650 //        |     +--------------------------------------------+    |
6651 //        |     | Reserved for binders                       |    |
6652 //        |     +--------------------------------------------+    |
6653 //        |     | Saved TOC pointer                          | ---+
6654 //        |     +--------------------------------------------+
6655 //        |     | Parameter save area                        |
6656 //        |     +--------------------------------------------+
6657 //        |     | Alloca space                               |
6658 //        |     +--------------------------------------------+
6659 //        |     | Local variable space                       |
6660 //        |     +--------------------------------------------+
6661 //        |     | Float/int conversion temporary             |
6662 //        |     +--------------------------------------------+
6663 //        |     | Save area for AltiVec registers            |
6664 //        |     +--------------------------------------------+
6665 //        |     | AltiVec alignment padding                  |
6666 //        |     +--------------------------------------------+
6667 //        |     | Save area for VRSAVE register              |
6668 //        |     +--------------------------------------------+
6669 //        |     | Save area for General Purpose registers    |
6670 //        |     +--------------------------------------------+
6671 //        |     | Save area for Floating Point registers     |
6672 //        |     +--------------------------------------------+
6673 //        +---- | Back chain                                 |
6674 // High Memory  +--------------------------------------------+
6675 //
6676 //  Specifications:
6677 //  AIX 7.2 Assembler Language Reference
6678 //  Subroutine linkage convention
6679 
6680 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6681     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6682     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6683     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6684 
6685   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6686           CallConv == CallingConv::Fast) &&
6687          "Unexpected calling convention!");
6688 
6689   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6690     report_fatal_error("Tail call support is unimplemented on AIX.");
6691 
6692   if (useSoftFloat())
6693     report_fatal_error("Soft float support is unimplemented on AIX.");
6694 
6695   const PPCSubtarget &Subtarget =
6696       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6697 
6698   const bool IsPPC64 = Subtarget.isPPC64();
6699   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6700 
6701   // Assign locations to all of the incoming arguments.
6702   SmallVector<CCValAssign, 16> ArgLocs;
6703   MachineFunction &MF = DAG.getMachineFunction();
6704   MachineFrameInfo &MFI = MF.getFrameInfo();
6705   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6706   AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6707 
6708   const EVT PtrVT = getPointerTy(MF.getDataLayout());
6709   // Reserve space for the linkage area on the stack.
6710   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6711   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
6712   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6713 
6714   SmallVector<SDValue, 8> MemOps;
6715 
6716   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
6717     CCValAssign &VA = ArgLocs[I++];
6718     MVT LocVT = VA.getLocVT();
6719     MVT ValVT = VA.getValVT();
6720     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
6721     // For compatibility with the AIX XL compiler, the float args in the
6722     // parameter save area are initialized even if the argument is available
6723     // in register.  The caller is required to initialize both the register
6724     // and memory, however, the callee can choose to expect it in either.
6725     // The memloc is dismissed here because the argument is retrieved from
6726     // the register.
6727     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
6728       continue;
6729 
6730     auto HandleMemLoc = [&]() {
6731       const unsigned LocSize = LocVT.getStoreSize();
6732       const unsigned ValSize = ValVT.getStoreSize();
6733       assert((ValSize <= LocSize) &&
6734              "Object size is larger than size of MemLoc");
6735       int CurArgOffset = VA.getLocMemOffset();
6736       // Objects are right-justified because AIX is big-endian.
6737       if (LocSize > ValSize)
6738         CurArgOffset += LocSize - ValSize;
6739       // Potential tail calls could cause overwriting of argument stack slots.
6740       const bool IsImmutable =
6741           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
6742             (CallConv == CallingConv::Fast));
6743       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
6744       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6745       SDValue ArgValue =
6746           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
6747       InVals.push_back(ArgValue);
6748     };
6749 
6750     // Vector arguments to VaArg functions are passed both on the stack, and
6751     // in any available GPRs. Load the value from the stack and add the GPRs
6752     // as live ins.
6753     if (VA.isMemLoc() && VA.needsCustom()) {
6754       assert(ValVT.isVector() && "Unexpected Custom MemLoc type.");
6755       assert(isVarArg && "Only use custom memloc for vararg.");
6756       // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
6757       // matching custom RegLocs.
6758       const unsigned OriginalValNo = VA.getValNo();
6759       (void)OriginalValNo;
6760 
6761       auto HandleCustomVecRegLoc = [&]() {
6762         assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
6763                "Missing custom RegLoc.");
6764         VA = ArgLocs[I++];
6765         assert(VA.getValVT().isVector() &&
6766                "Unexpected Val type for custom RegLoc.");
6767         assert(VA.getValNo() == OriginalValNo &&
6768                "ValNo mismatch between custom MemLoc and RegLoc.");
6769         MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy;
6770         MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
6771       };
6772 
6773       HandleMemLoc();
6774       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
6775       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
6776       // R10.
6777       HandleCustomVecRegLoc();
6778       HandleCustomVecRegLoc();
6779 
6780       // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
6781       // we passed the vector in R5, R6, R7 and R8.
6782       if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
6783         assert(!IsPPC64 &&
6784                "Only 2 custom RegLocs expected for 64-bit codegen.");
6785         HandleCustomVecRegLoc();
6786         HandleCustomVecRegLoc();
6787       }
6788 
6789       continue;
6790     }
6791 
6792     if (VA.isRegLoc()) {
6793       if (VA.getValVT().isScalarInteger())
6794         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
6795       else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector())
6796         FuncInfo->appendParameterType(VA.getValVT().SimpleTy == MVT::f32
6797                                           ? PPCFunctionInfo::ShortFloatPoint
6798                                           : PPCFunctionInfo::LongFloatPoint);
6799     }
6800 
6801     if (Flags.isByVal() && VA.isMemLoc()) {
6802       const unsigned Size =
6803           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
6804                   PtrByteSize);
6805       const int FI = MF.getFrameInfo().CreateFixedObject(
6806           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
6807           /* IsAliased */ true);
6808       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6809       InVals.push_back(FIN);
6810 
6811       continue;
6812     }
6813 
6814     if (Flags.isByVal()) {
6815       assert(VA.isRegLoc() && "MemLocs should already be handled.");
6816 
6817       const MCPhysReg ArgReg = VA.getLocReg();
6818       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
6819 
6820       if (Flags.getNonZeroByValAlign() > PtrByteSize)
6821         report_fatal_error("Over aligned byvals not supported yet.");
6822 
6823       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
6824       const int FI = MF.getFrameInfo().CreateFixedObject(
6825           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
6826           /* IsAliased */ true);
6827       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6828       InVals.push_back(FIN);
6829 
6830       // Add live ins for all the RegLocs for the same ByVal.
6831       const TargetRegisterClass *RegClass =
6832           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6833 
6834       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
6835                                                unsigned Offset) {
6836         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
6837         // Since the callers side has left justified the aggregate in the
6838         // register, we can simply store the entire register into the stack
6839         // slot.
6840         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
6841         // The store to the fixedstack object is needed becuase accessing a
6842         // field of the ByVal will use a gep and load. Ideally we will optimize
6843         // to extracting the value from the register directly, and elide the
6844         // stores when the arguments address is not taken, but that will need to
6845         // be future work.
6846         SDValue Store = DAG.getStore(
6847             CopyFrom.getValue(1), dl, CopyFrom,
6848             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
6849             MachinePointerInfo::getFixedStack(MF, FI, Offset));
6850 
6851         MemOps.push_back(Store);
6852       };
6853 
6854       unsigned Offset = 0;
6855       HandleRegLoc(VA.getLocReg(), Offset);
6856       Offset += PtrByteSize;
6857       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
6858            Offset += PtrByteSize) {
6859         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
6860                "RegLocs should be for ByVal argument.");
6861 
6862         const CCValAssign RL = ArgLocs[I++];
6863         HandleRegLoc(RL.getLocReg(), Offset);
6864         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
6865       }
6866 
6867       if (Offset != StackSize) {
6868         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
6869                "Expected MemLoc for remaining bytes.");
6870         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
6871         // Consume the MemLoc.The InVal has already been emitted, so nothing
6872         // more needs to be done.
6873         ++I;
6874       }
6875 
6876       continue;
6877     }
6878 
6879     if (VA.isRegLoc() && !VA.needsCustom()) {
6880       MVT::SimpleValueType SVT = ValVT.SimpleTy;
6881       unsigned VReg =
6882           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
6883       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
6884       if (ValVT.isScalarInteger() &&
6885           (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
6886         ArgValue =
6887             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
6888       }
6889       InVals.push_back(ArgValue);
6890       continue;
6891     }
6892     if (VA.isMemLoc()) {
6893       HandleMemLoc();
6894       continue;
6895     }
6896   }
6897 
6898   // On AIX a minimum of 8 words is saved to the parameter save area.
6899   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
6900   // Area that is at least reserved in the caller of this function.
6901   unsigned CallerReservedArea =
6902       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
6903 
6904   // Set the size that is at least reserved in caller of this function. Tail
6905   // call optimized function's reserved stack space needs to be aligned so
6906   // that taking the difference between two stack areas will result in an
6907   // aligned stack.
6908   CallerReservedArea =
6909       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
6910   FuncInfo->setMinReservedArea(CallerReservedArea);
6911 
6912   if (isVarArg) {
6913     FuncInfo->setVarArgsFrameIndex(
6914         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
6915     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
6916 
6917     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6918                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6919 
6920     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6921                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6922     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
6923 
6924     // The fixed integer arguments of a variadic function are stored to the
6925     // VarArgsFrameIndex on the stack so that they may be loaded by
6926     // dereferencing the result of va_next.
6927     for (unsigned GPRIndex =
6928              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
6929          GPRIndex < NumGPArgRegs; ++GPRIndex) {
6930 
6931       const unsigned VReg =
6932           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
6933                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
6934 
6935       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
6936       SDValue Store =
6937           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
6938       MemOps.push_back(Store);
6939       // Increment the address for the next argument to store.
6940       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
6941       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
6942     }
6943   }
6944 
6945   if (!MemOps.empty())
6946     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
6947 
6948   return Chain;
6949 }
6950 
6951 SDValue PPCTargetLowering::LowerCall_AIX(
6952     SDValue Chain, SDValue Callee, CallFlags CFlags,
6953     const SmallVectorImpl<ISD::OutputArg> &Outs,
6954     const SmallVectorImpl<SDValue> &OutVals,
6955     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6956     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6957     const CallBase *CB) const {
6958   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
6959   // AIX ABI stack frame layout.
6960 
6961   assert((CFlags.CallConv == CallingConv::C ||
6962           CFlags.CallConv == CallingConv::Cold ||
6963           CFlags.CallConv == CallingConv::Fast) &&
6964          "Unexpected calling convention!");
6965 
6966   if (CFlags.IsPatchPoint)
6967     report_fatal_error("This call type is unimplemented on AIX.");
6968 
6969   const PPCSubtarget& Subtarget =
6970       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
6971 
6972   MachineFunction &MF = DAG.getMachineFunction();
6973   SmallVector<CCValAssign, 16> ArgLocs;
6974   AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
6975                     *DAG.getContext());
6976 
6977   // Reserve space for the linkage save area (LSA) on the stack.
6978   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
6979   //   [SP][CR][LR][2 x reserved][TOC].
6980   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
6981   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6982   const bool IsPPC64 = Subtarget.isPPC64();
6983   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
6984   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6985   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
6986   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
6987 
6988   // The prolog code of the callee may store up to 8 GPR argument registers to
6989   // the stack, allowing va_start to index over them in memory if the callee
6990   // is variadic.
6991   // Because we cannot tell if this is needed on the caller side, we have to
6992   // conservatively assume that it is needed.  As such, make sure we have at
6993   // least enough stack space for the caller to store the 8 GPRs.
6994   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
6995   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
6996                                      CCInfo.getNextStackOffset());
6997 
6998   // Adjust the stack pointer for the new arguments...
6999   // These operations are automatically eliminated by the prolog/epilog pass.
7000   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7001   SDValue CallSeqStart = Chain;
7002 
7003   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7004   SmallVector<SDValue, 8> MemOpChains;
7005 
7006   // Set up a copy of the stack pointer for loading and storing any
7007   // arguments that may not fit in the registers available for argument
7008   // passing.
7009   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7010                                    : DAG.getRegister(PPC::R1, MVT::i32);
7011 
7012   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7013     const unsigned ValNo = ArgLocs[I].getValNo();
7014     SDValue Arg = OutVals[ValNo];
7015     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7016 
7017     if (Flags.isByVal()) {
7018       const unsigned ByValSize = Flags.getByValSize();
7019 
7020       // Nothing to do for zero-sized ByVals on the caller side.
7021       if (!ByValSize) {
7022         ++I;
7023         continue;
7024       }
7025 
7026       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7027         return DAG.getExtLoad(
7028             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7029             (LoadOffset != 0)
7030                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7031                 : Arg,
7032             MachinePointerInfo(), VT);
7033       };
7034 
7035       unsigned LoadOffset = 0;
7036 
7037       // Initialize registers, which are fully occupied by the by-val argument.
7038       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7039         SDValue Load = GetLoad(PtrVT, LoadOffset);
7040         MemOpChains.push_back(Load.getValue(1));
7041         LoadOffset += PtrByteSize;
7042         const CCValAssign &ByValVA = ArgLocs[I++];
7043         assert(ByValVA.getValNo() == ValNo &&
7044                "Unexpected location for pass-by-value argument.");
7045         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7046       }
7047 
7048       if (LoadOffset == ByValSize)
7049         continue;
7050 
7051       // There must be one more loc to handle the remainder.
7052       assert(ArgLocs[I].getValNo() == ValNo &&
7053              "Expected additional location for by-value argument.");
7054 
7055       if (ArgLocs[I].isMemLoc()) {
7056         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7057         const CCValAssign &ByValVA = ArgLocs[I++];
7058         ISD::ArgFlagsTy MemcpyFlags = Flags;
7059         // Only memcpy the bytes that don't pass in register.
7060         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7061         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7062             (LoadOffset != 0)
7063                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7064                 : Arg,
7065             DAG.getObjectPtrOffset(dl, StackPtr,
7066                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7067             CallSeqStart, MemcpyFlags, DAG, dl);
7068         continue;
7069       }
7070 
7071       // Initialize the final register residue.
7072       // Any residue that occupies the final by-val arg register must be
7073       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7074       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7075       // 2 and 1 byte loads.
7076       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7077       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7078              "Unexpected register residue for by-value argument.");
7079       SDValue ResidueVal;
7080       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7081         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7082         const MVT VT =
7083             N == 1 ? MVT::i8
7084                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7085         SDValue Load = GetLoad(VT, LoadOffset);
7086         MemOpChains.push_back(Load.getValue(1));
7087         LoadOffset += N;
7088         Bytes += N;
7089 
7090         // By-val arguments are passed left-justfied in register.
7091         // Every load here needs to be shifted, otherwise a full register load
7092         // should have been used.
7093         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7094                "Unexpected load emitted during handling of pass-by-value "
7095                "argument.");
7096         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7097         EVT ShiftAmountTy =
7098             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7099         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7100         SDValue ShiftedLoad =
7101             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7102         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7103                                               ShiftedLoad)
7104                                 : ShiftedLoad;
7105       }
7106 
7107       const CCValAssign &ByValVA = ArgLocs[I++];
7108       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7109       continue;
7110     }
7111 
7112     CCValAssign &VA = ArgLocs[I++];
7113     const MVT LocVT = VA.getLocVT();
7114     const MVT ValVT = VA.getValVT();
7115 
7116     switch (VA.getLocInfo()) {
7117     default:
7118       report_fatal_error("Unexpected argument extension type.");
7119     case CCValAssign::Full:
7120       break;
7121     case CCValAssign::ZExt:
7122       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7123       break;
7124     case CCValAssign::SExt:
7125       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7126       break;
7127     }
7128 
7129     if (VA.isRegLoc() && !VA.needsCustom()) {
7130       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7131       continue;
7132     }
7133 
7134     // Vector arguments passed to VarArg functions need custom handling when
7135     // they are passed (at least partially) in GPRs.
7136     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
7137       assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.");
7138       // Store value to its stack slot.
7139       SDValue PtrOff =
7140           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7141       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7142       SDValue Store =
7143           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
7144       MemOpChains.push_back(Store);
7145       const unsigned OriginalValNo = VA.getValNo();
7146       // Then load the GPRs from the stack
7147       unsigned LoadOffset = 0;
7148       auto HandleCustomVecRegLoc = [&]() {
7149         assert(I != E && "Unexpected end of CCvalAssigns.");
7150         assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7151                "Expected custom RegLoc.");
7152         CCValAssign RegVA = ArgLocs[I++];
7153         assert(RegVA.getValNo() == OriginalValNo &&
7154                "Custom MemLoc ValNo and custom RegLoc ValNo must match.");
7155         SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
7156                                   DAG.getConstant(LoadOffset, dl, PtrVT));
7157         SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
7158         MemOpChains.push_back(Load.getValue(1));
7159         RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
7160         LoadOffset += PtrByteSize;
7161       };
7162 
7163       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7164       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7165       // R10.
7166       HandleCustomVecRegLoc();
7167       HandleCustomVecRegLoc();
7168 
7169       if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7170           ArgLocs[I].getValNo() == OriginalValNo) {
7171         assert(!IsPPC64 &&
7172                "Only 2 custom RegLocs expected for 64-bit codegen.");
7173         HandleCustomVecRegLoc();
7174         HandleCustomVecRegLoc();
7175       }
7176 
7177       continue;
7178     }
7179 
7180     if (VA.isMemLoc()) {
7181       SDValue PtrOff =
7182           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7183       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7184       MemOpChains.push_back(
7185           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7186 
7187       continue;
7188     }
7189 
7190     if (!ValVT.isFloatingPoint())
7191       report_fatal_error(
7192           "Unexpected register handling for calling convention.");
7193 
7194     // Custom handling is used for GPR initializations for vararg float
7195     // arguments.
7196     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7197            LocVT.isInteger() &&
7198            "Custom register handling only expected for VarArg.");
7199 
7200     SDValue ArgAsInt =
7201         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7202 
7203     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7204       // f32 in 32-bit GPR
7205       // f64 in 64-bit GPR
7206       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7207     else if (Arg.getValueType().getFixedSizeInBits() <
7208              LocVT.getFixedSizeInBits())
7209       // f32 in 64-bit GPR.
7210       RegsToPass.push_back(std::make_pair(
7211           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7212     else {
7213       // f64 in two 32-bit GPRs
7214       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7215       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7216              "Unexpected custom register for argument!");
7217       CCValAssign &GPR1 = VA;
7218       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7219                                      DAG.getConstant(32, dl, MVT::i8));
7220       RegsToPass.push_back(std::make_pair(
7221           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7222 
7223       if (I != E) {
7224         // If only 1 GPR was available, there will only be one custom GPR and
7225         // the argument will also pass in memory.
7226         CCValAssign &PeekArg = ArgLocs[I];
7227         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7228           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7229           CCValAssign &GPR2 = ArgLocs[I++];
7230           RegsToPass.push_back(std::make_pair(
7231               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7232         }
7233       }
7234     }
7235   }
7236 
7237   if (!MemOpChains.empty())
7238     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7239 
7240   // For indirect calls, we need to save the TOC base to the stack for
7241   // restoration after the call.
7242   if (CFlags.IsIndirect) {
7243     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7244     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7245     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7246     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7247     const unsigned TOCSaveOffset =
7248         Subtarget.getFrameLowering()->getTOCSaveOffset();
7249 
7250     setUsesTOCBasePtr(DAG);
7251     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7252     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7253     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7254     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7255     Chain = DAG.getStore(
7256         Val.getValue(1), dl, Val, AddPtr,
7257         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7258   }
7259 
7260   // Build a sequence of copy-to-reg nodes chained together with token chain
7261   // and flag operands which copy the outgoing args into the appropriate regs.
7262   SDValue InFlag;
7263   for (auto Reg : RegsToPass) {
7264     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7265     InFlag = Chain.getValue(1);
7266   }
7267 
7268   const int SPDiff = 0;
7269   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7270                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7271 }
7272 
7273 bool
7274 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7275                                   MachineFunction &MF, bool isVarArg,
7276                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7277                                   LLVMContext &Context) const {
7278   SmallVector<CCValAssign, 16> RVLocs;
7279   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7280   return CCInfo.CheckReturn(
7281       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7282                 ? RetCC_PPC_Cold
7283                 : RetCC_PPC);
7284 }
7285 
7286 SDValue
7287 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7288                                bool isVarArg,
7289                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7290                                const SmallVectorImpl<SDValue> &OutVals,
7291                                const SDLoc &dl, SelectionDAG &DAG) const {
7292   SmallVector<CCValAssign, 16> RVLocs;
7293   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7294                  *DAG.getContext());
7295   CCInfo.AnalyzeReturn(Outs,
7296                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7297                            ? RetCC_PPC_Cold
7298                            : RetCC_PPC);
7299 
7300   SDValue Flag;
7301   SmallVector<SDValue, 4> RetOps(1, Chain);
7302 
7303   // Copy the result values into the output registers.
7304   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7305     CCValAssign &VA = RVLocs[i];
7306     assert(VA.isRegLoc() && "Can only return in registers!");
7307 
7308     SDValue Arg = OutVals[RealResIdx];
7309 
7310     switch (VA.getLocInfo()) {
7311     default: llvm_unreachable("Unknown loc info!");
7312     case CCValAssign::Full: break;
7313     case CCValAssign::AExt:
7314       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7315       break;
7316     case CCValAssign::ZExt:
7317       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7318       break;
7319     case CCValAssign::SExt:
7320       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7321       break;
7322     }
7323     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7324       bool isLittleEndian = Subtarget.isLittleEndian();
7325       // Legalize ret f64 -> ret 2 x i32.
7326       SDValue SVal =
7327           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7328                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7329       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7330       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7331       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7332                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7333       Flag = Chain.getValue(1);
7334       VA = RVLocs[++i]; // skip ahead to next loc
7335       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7336     } else
7337       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7338     Flag = Chain.getValue(1);
7339     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7340   }
7341 
7342   RetOps[0] = Chain;  // Update chain.
7343 
7344   // Add the flag if we have it.
7345   if (Flag.getNode())
7346     RetOps.push_back(Flag);
7347 
7348   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7349 }
7350 
7351 SDValue
7352 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7353                                                 SelectionDAG &DAG) const {
7354   SDLoc dl(Op);
7355 
7356   // Get the correct type for integers.
7357   EVT IntVT = Op.getValueType();
7358 
7359   // Get the inputs.
7360   SDValue Chain = Op.getOperand(0);
7361   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7362   // Build a DYNAREAOFFSET node.
7363   SDValue Ops[2] = {Chain, FPSIdx};
7364   SDVTList VTs = DAG.getVTList(IntVT);
7365   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7366 }
7367 
7368 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7369                                              SelectionDAG &DAG) const {
7370   // When we pop the dynamic allocation we need to restore the SP link.
7371   SDLoc dl(Op);
7372 
7373   // Get the correct type for pointers.
7374   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7375 
7376   // Construct the stack pointer operand.
7377   bool isPPC64 = Subtarget.isPPC64();
7378   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7379   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7380 
7381   // Get the operands for the STACKRESTORE.
7382   SDValue Chain = Op.getOperand(0);
7383   SDValue SaveSP = Op.getOperand(1);
7384 
7385   // Load the old link SP.
7386   SDValue LoadLinkSP =
7387       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7388 
7389   // Restore the stack pointer.
7390   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7391 
7392   // Store the old link SP.
7393   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7394 }
7395 
7396 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7397   MachineFunction &MF = DAG.getMachineFunction();
7398   bool isPPC64 = Subtarget.isPPC64();
7399   EVT PtrVT = getPointerTy(MF.getDataLayout());
7400 
7401   // Get current frame pointer save index.  The users of this index will be
7402   // primarily DYNALLOC instructions.
7403   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7404   int RASI = FI->getReturnAddrSaveIndex();
7405 
7406   // If the frame pointer save index hasn't been defined yet.
7407   if (!RASI) {
7408     // Find out what the fix offset of the frame pointer save area.
7409     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7410     // Allocate the frame index for frame pointer save area.
7411     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7412     // Save the result.
7413     FI->setReturnAddrSaveIndex(RASI);
7414   }
7415   return DAG.getFrameIndex(RASI, PtrVT);
7416 }
7417 
7418 SDValue
7419 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7420   MachineFunction &MF = DAG.getMachineFunction();
7421   bool isPPC64 = Subtarget.isPPC64();
7422   EVT PtrVT = getPointerTy(MF.getDataLayout());
7423 
7424   // Get current frame pointer save index.  The users of this index will be
7425   // primarily DYNALLOC instructions.
7426   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7427   int FPSI = FI->getFramePointerSaveIndex();
7428 
7429   // If the frame pointer save index hasn't been defined yet.
7430   if (!FPSI) {
7431     // Find out what the fix offset of the frame pointer save area.
7432     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7433     // Allocate the frame index for frame pointer save area.
7434     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7435     // Save the result.
7436     FI->setFramePointerSaveIndex(FPSI);
7437   }
7438   return DAG.getFrameIndex(FPSI, PtrVT);
7439 }
7440 
7441 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7442                                                    SelectionDAG &DAG) const {
7443   MachineFunction &MF = DAG.getMachineFunction();
7444   // Get the inputs.
7445   SDValue Chain = Op.getOperand(0);
7446   SDValue Size  = Op.getOperand(1);
7447   SDLoc dl(Op);
7448 
7449   // Get the correct type for pointers.
7450   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7451   // Negate the size.
7452   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7453                                 DAG.getConstant(0, dl, PtrVT), Size);
7454   // Construct a node for the frame pointer save index.
7455   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7456   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7457   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7458   if (hasInlineStackProbe(MF))
7459     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7460   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7461 }
7462 
7463 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7464                                                      SelectionDAG &DAG) const {
7465   MachineFunction &MF = DAG.getMachineFunction();
7466 
7467   bool isPPC64 = Subtarget.isPPC64();
7468   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7469 
7470   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7471   return DAG.getFrameIndex(FI, PtrVT);
7472 }
7473 
7474 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7475                                                SelectionDAG &DAG) const {
7476   SDLoc DL(Op);
7477   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7478                      DAG.getVTList(MVT::i32, MVT::Other),
7479                      Op.getOperand(0), Op.getOperand(1));
7480 }
7481 
7482 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7483                                                 SelectionDAG &DAG) const {
7484   SDLoc DL(Op);
7485   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7486                      Op.getOperand(0), Op.getOperand(1));
7487 }
7488 
7489 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7490   if (Op.getValueType().isVector())
7491     return LowerVectorLoad(Op, DAG);
7492 
7493   assert(Op.getValueType() == MVT::i1 &&
7494          "Custom lowering only for i1 loads");
7495 
7496   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7497 
7498   SDLoc dl(Op);
7499   LoadSDNode *LD = cast<LoadSDNode>(Op);
7500 
7501   SDValue Chain = LD->getChain();
7502   SDValue BasePtr = LD->getBasePtr();
7503   MachineMemOperand *MMO = LD->getMemOperand();
7504 
7505   SDValue NewLD =
7506       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7507                      BasePtr, MVT::i8, MMO);
7508   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7509 
7510   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7511   return DAG.getMergeValues(Ops, dl);
7512 }
7513 
7514 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7515   if (Op.getOperand(1).getValueType().isVector())
7516     return LowerVectorStore(Op, DAG);
7517 
7518   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7519          "Custom lowering only for i1 stores");
7520 
7521   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7522 
7523   SDLoc dl(Op);
7524   StoreSDNode *ST = cast<StoreSDNode>(Op);
7525 
7526   SDValue Chain = ST->getChain();
7527   SDValue BasePtr = ST->getBasePtr();
7528   SDValue Value = ST->getValue();
7529   MachineMemOperand *MMO = ST->getMemOperand();
7530 
7531   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7532                       Value);
7533   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7534 }
7535 
7536 // FIXME: Remove this once the ANDI glue bug is fixed:
7537 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7538   assert(Op.getValueType() == MVT::i1 &&
7539          "Custom lowering only for i1 results");
7540 
7541   SDLoc DL(Op);
7542   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7543 }
7544 
7545 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7546                                                SelectionDAG &DAG) const {
7547 
7548   // Implements a vector truncate that fits in a vector register as a shuffle.
7549   // We want to legalize vector truncates down to where the source fits in
7550   // a vector register (and target is therefore smaller than vector register
7551   // size).  At that point legalization will try to custom lower the sub-legal
7552   // result and get here - where we can contain the truncate as a single target
7553   // operation.
7554 
7555   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7556   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7557   //
7558   // We will implement it for big-endian ordering as this (where x denotes
7559   // undefined):
7560   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7561   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7562   //
7563   // The same operation in little-endian ordering will be:
7564   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7565   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7566 
7567   EVT TrgVT = Op.getValueType();
7568   assert(TrgVT.isVector() && "Vector type expected.");
7569   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7570   EVT EltVT = TrgVT.getVectorElementType();
7571   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
7572       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
7573       !isPowerOf2_32(EltVT.getSizeInBits()))
7574     return SDValue();
7575 
7576   SDValue N1 = Op.getOperand(0);
7577   EVT SrcVT = N1.getValueType();
7578   unsigned SrcSize = SrcVT.getSizeInBits();
7579   if (SrcSize > 256 ||
7580       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
7581       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
7582     return SDValue();
7583   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
7584     return SDValue();
7585 
7586   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7587   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7588 
7589   SDLoc DL(Op);
7590   SDValue Op1, Op2;
7591   if (SrcSize == 256) {
7592     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
7593     EVT SplitVT =
7594         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
7595     unsigned SplitNumElts = SplitVT.getVectorNumElements();
7596     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7597                       DAG.getConstant(0, DL, VecIdxTy));
7598     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7599                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
7600   }
7601   else {
7602     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7603     Op2 = DAG.getUNDEF(WideVT);
7604   }
7605 
7606   // First list the elements we want to keep.
7607   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7608   SmallVector<int, 16> ShuffV;
7609   if (Subtarget.isLittleEndian())
7610     for (unsigned i = 0; i < TrgNumElts; ++i)
7611       ShuffV.push_back(i * SizeMult);
7612   else
7613     for (unsigned i = 1; i <= TrgNumElts; ++i)
7614       ShuffV.push_back(i * SizeMult - 1);
7615 
7616   // Populate the remaining elements with undefs.
7617   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7618     // ShuffV.push_back(i + WideNumElts);
7619     ShuffV.push_back(WideNumElts + 1);
7620 
7621   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
7622   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
7623   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
7624 }
7625 
7626 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7627 /// possible.
7628 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7629   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7630   EVT ResVT = Op.getValueType();
7631   EVT CmpVT = Op.getOperand(0).getValueType();
7632   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7633   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7634   SDLoc dl(Op);
7635 
7636   // Without power9-vector, we don't have native instruction for f128 comparison.
7637   // Following transformation to libcall is needed for setcc:
7638   // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE
7639   if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) {
7640     SDValue Z = DAG.getSetCC(
7641         dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT),
7642         LHS, RHS, CC);
7643     SDValue Zero = DAG.getConstant(0, dl, Z.getValueType());
7644     return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE);
7645   }
7646 
7647   // Not FP, or using SPE? Not a fsel.
7648   if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() ||
7649       Subtarget.hasSPE())
7650     return Op;
7651 
7652   SDNodeFlags Flags = Op.getNode()->getFlags();
7653 
7654   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7655   // presence of infinities.
7656   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7657     switch (CC) {
7658     default:
7659       break;
7660     case ISD::SETOGT:
7661     case ISD::SETGT:
7662       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7663     case ISD::SETOLT:
7664     case ISD::SETLT:
7665       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7666     }
7667   }
7668 
7669   // We might be able to do better than this under some circumstances, but in
7670   // general, fsel-based lowering of select is a finite-math-only optimization.
7671   // For more information, see section F.3 of the 2.06 ISA specification.
7672   // With ISA 3.0
7673   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7674       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7675     return Op;
7676 
7677   // If the RHS of the comparison is a 0.0, we don't need to do the
7678   // subtraction at all.
7679   SDValue Sel1;
7680   if (isFloatingPointZero(RHS))
7681     switch (CC) {
7682     default: break;       // SETUO etc aren't handled by fsel.
7683     case ISD::SETNE:
7684       std::swap(TV, FV);
7685       LLVM_FALLTHROUGH;
7686     case ISD::SETEQ:
7687       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7688         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7689       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7690       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7691         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7692       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7693                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7694     case ISD::SETULT:
7695     case ISD::SETLT:
7696       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7697       LLVM_FALLTHROUGH;
7698     case ISD::SETOGE:
7699     case ISD::SETGE:
7700       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7701         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7702       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7703     case ISD::SETUGT:
7704     case ISD::SETGT:
7705       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7706       LLVM_FALLTHROUGH;
7707     case ISD::SETOLE:
7708     case ISD::SETLE:
7709       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7710         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7711       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7712                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7713     }
7714 
7715   SDValue Cmp;
7716   switch (CC) {
7717   default: break;       // SETUO etc aren't handled by fsel.
7718   case ISD::SETNE:
7719     std::swap(TV, FV);
7720     LLVM_FALLTHROUGH;
7721   case ISD::SETEQ:
7722     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7723     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7724       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7725     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7726     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7727       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7728     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7729                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7730   case ISD::SETULT:
7731   case ISD::SETLT:
7732     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7733     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7734       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7735     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7736   case ISD::SETOGE:
7737   case ISD::SETGE:
7738     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7739     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7740       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7741     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7742   case ISD::SETUGT:
7743   case ISD::SETGT:
7744     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7745     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7746       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7747     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7748   case ISD::SETOLE:
7749   case ISD::SETLE:
7750     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7751     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7752       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7753     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7754   }
7755   return Op;
7756 }
7757 
7758 static unsigned getPPCStrictOpcode(unsigned Opc) {
7759   switch (Opc) {
7760   default:
7761     llvm_unreachable("No strict version of this opcode!");
7762   case PPCISD::FCTIDZ:
7763     return PPCISD::STRICT_FCTIDZ;
7764   case PPCISD::FCTIWZ:
7765     return PPCISD::STRICT_FCTIWZ;
7766   case PPCISD::FCTIDUZ:
7767     return PPCISD::STRICT_FCTIDUZ;
7768   case PPCISD::FCTIWUZ:
7769     return PPCISD::STRICT_FCTIWUZ;
7770   case PPCISD::FCFID:
7771     return PPCISD::STRICT_FCFID;
7772   case PPCISD::FCFIDU:
7773     return PPCISD::STRICT_FCFIDU;
7774   case PPCISD::FCFIDS:
7775     return PPCISD::STRICT_FCFIDS;
7776   case PPCISD::FCFIDUS:
7777     return PPCISD::STRICT_FCFIDUS;
7778   }
7779 }
7780 
7781 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
7782                               const PPCSubtarget &Subtarget) {
7783   SDLoc dl(Op);
7784   bool IsStrict = Op->isStrictFPOpcode();
7785   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
7786                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
7787 
7788   // TODO: Any other flags to propagate?
7789   SDNodeFlags Flags;
7790   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
7791 
7792   // For strict nodes, source is the second operand.
7793   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
7794   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
7795   assert(Src.getValueType().isFloatingPoint());
7796   if (Src.getValueType() == MVT::f32) {
7797     if (IsStrict) {
7798       Src =
7799           DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
7800                       DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
7801       Chain = Src.getValue(1);
7802     } else
7803       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7804   }
7805   SDValue Conv;
7806   unsigned Opc = ISD::DELETED_NODE;
7807   switch (Op.getSimpleValueType().SimpleTy) {
7808   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7809   case MVT::i32:
7810     Opc = IsSigned ? PPCISD::FCTIWZ
7811                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
7812     break;
7813   case MVT::i64:
7814     assert((IsSigned || Subtarget.hasFPCVT()) &&
7815            "i64 FP_TO_UINT is supported only with FPCVT");
7816     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
7817   }
7818   if (IsStrict) {
7819     Opc = getPPCStrictOpcode(Opc);
7820     Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
7821                        {Chain, Src}, Flags);
7822   } else {
7823     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
7824   }
7825   return Conv;
7826 }
7827 
7828 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7829                                                SelectionDAG &DAG,
7830                                                const SDLoc &dl) const {
7831   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
7832   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
7833                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
7834   bool IsStrict = Op->isStrictFPOpcode();
7835 
7836   // Convert the FP value to an int value through memory.
7837   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7838                   (IsSigned || Subtarget.hasFPCVT());
7839   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7840   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7841   MachinePointerInfo MPI =
7842       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7843 
7844   // Emit a store to the stack slot.
7845   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
7846   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
7847   if (i32Stack) {
7848     MachineFunction &MF = DAG.getMachineFunction();
7849     Alignment = Align(4);
7850     MachineMemOperand *MMO =
7851         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
7852     SDValue Ops[] = { Chain, Tmp, FIPtr };
7853     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7854               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7855   } else
7856     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
7857 
7858   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7859   // add in a bias on big endian.
7860   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7861     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7862                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7863     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7864   }
7865 
7866   RLI.Chain = Chain;
7867   RLI.Ptr = FIPtr;
7868   RLI.MPI = MPI;
7869   RLI.Alignment = Alignment;
7870 }
7871 
7872 /// Custom lowers floating point to integer conversions to use
7873 /// the direct move instructions available in ISA 2.07 to avoid the
7874 /// need for load/store combinations.
7875 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7876                                                     SelectionDAG &DAG,
7877                                                     const SDLoc &dl) const {
7878   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
7879   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
7880   if (Op->isStrictFPOpcode())
7881     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
7882   else
7883     return Mov;
7884 }
7885 
7886 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7887                                           const SDLoc &dl) const {
7888   bool IsStrict = Op->isStrictFPOpcode();
7889   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
7890                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
7891   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
7892   EVT SrcVT = Src.getValueType();
7893   EVT DstVT = Op.getValueType();
7894 
7895   // FP to INT conversions are legal for f128.
7896   if (SrcVT == MVT::f128)
7897     return Subtarget.hasP9Vector() ? Op : SDValue();
7898 
7899   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7900   // PPC (the libcall is not available).
7901   if (SrcVT == MVT::ppcf128) {
7902     if (DstVT == MVT::i32) {
7903       // TODO: Conservatively pass only nofpexcept flag here. Need to check and
7904       // set other fast-math flags to FP operations in both strict and
7905       // non-strict cases. (FP_TO_SINT, FSUB)
7906       SDNodeFlags Flags;
7907       Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
7908 
7909       if (IsSigned) {
7910         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
7911                                  DAG.getIntPtrConstant(0, dl));
7912         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
7913                                  DAG.getIntPtrConstant(1, dl));
7914 
7915         // Add the two halves of the long double in round-to-zero mode, and use
7916         // a smaller FP_TO_SINT.
7917         if (IsStrict) {
7918           SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
7919                                     DAG.getVTList(MVT::f64, MVT::Other),
7920                                     {Op.getOperand(0), Lo, Hi}, Flags);
7921           return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
7922                              DAG.getVTList(MVT::i32, MVT::Other),
7923                              {Res.getValue(1), Res}, Flags);
7924         } else {
7925           SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7926           return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7927         }
7928       } else {
7929         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7930         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7931         SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
7932         SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
7933         if (IsStrict) {
7934           // Sel = Src < 0x80000000
7935           // FltOfs = select Sel, 0.0, 0x80000000
7936           // IntOfs = select Sel, 0, 0x80000000
7937           // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
7938           SDValue Chain = Op.getOperand(0);
7939           EVT SetCCVT =
7940               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
7941           EVT DstSetCCVT =
7942               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
7943           SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
7944                                      Chain, true);
7945           Chain = Sel.getValue(1);
7946 
7947           SDValue FltOfs = DAG.getSelect(
7948               dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
7949           Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
7950 
7951           SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
7952                                     DAG.getVTList(SrcVT, MVT::Other),
7953                                     {Chain, Src, FltOfs}, Flags);
7954           Chain = Val.getValue(1);
7955           SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
7956                                      DAG.getVTList(DstVT, MVT::Other),
7957                                      {Chain, Val}, Flags);
7958           Chain = SInt.getValue(1);
7959           SDValue IntOfs = DAG.getSelect(
7960               dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
7961           SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
7962           return DAG.getMergeValues({Result, Chain}, dl);
7963         } else {
7964           // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7965           // FIXME: generated code sucks.
7966           SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
7967           True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7968           True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
7969           SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
7970           return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
7971         }
7972       }
7973     }
7974 
7975     return SDValue();
7976   }
7977 
7978   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
7979     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
7980 
7981   ReuseLoadInfo RLI;
7982   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7983 
7984   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7985                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7986 }
7987 
7988 // We're trying to insert a regular store, S, and then a load, L. If the
7989 // incoming value, O, is a load, we might just be able to have our load use the
7990 // address used by O. However, we don't know if anything else will store to
7991 // that address before we can load from it. To prevent this situation, we need
7992 // to insert our load, L, into the chain as a peer of O. To do this, we give L
7993 // the same chain operand as O, we create a token factor from the chain results
7994 // of O and L, and we replace all uses of O's chain result with that token
7995 // factor (see spliceIntoChain below for this last part).
7996 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
7997                                             ReuseLoadInfo &RLI,
7998                                             SelectionDAG &DAG,
7999                                             ISD::LoadExtType ET) const {
8000   // Conservatively skip reusing for constrained FP nodes.
8001   if (Op->isStrictFPOpcode())
8002     return false;
8003 
8004   SDLoc dl(Op);
8005   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8006                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8007   if (ET == ISD::NON_EXTLOAD &&
8008       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8009       isOperationLegalOrCustom(Op.getOpcode(),
8010                                Op.getOperand(0).getValueType())) {
8011 
8012     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8013     return true;
8014   }
8015 
8016   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8017   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8018       LD->isNonTemporal())
8019     return false;
8020   if (LD->getMemoryVT() != MemVT)
8021     return false;
8022 
8023   // If the result of the load is an illegal type, then we can't build a
8024   // valid chain for reuse since the legalised loads and token factor node that
8025   // ties the legalised loads together uses a different output chain then the
8026   // illegal load.
8027   if (!isTypeLegal(LD->getValueType(0)))
8028     return false;
8029 
8030   RLI.Ptr = LD->getBasePtr();
8031   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8032     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8033            "Non-pre-inc AM on PPC?");
8034     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8035                           LD->getOffset());
8036   }
8037 
8038   RLI.Chain = LD->getChain();
8039   RLI.MPI = LD->getPointerInfo();
8040   RLI.IsDereferenceable = LD->isDereferenceable();
8041   RLI.IsInvariant = LD->isInvariant();
8042   RLI.Alignment = LD->getAlign();
8043   RLI.AAInfo = LD->getAAInfo();
8044   RLI.Ranges = LD->getRanges();
8045 
8046   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8047   return true;
8048 }
8049 
8050 // Given the head of the old chain, ResChain, insert a token factor containing
8051 // it and NewResChain, and make users of ResChain now be users of that token
8052 // factor.
8053 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8054 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8055                                         SDValue NewResChain,
8056                                         SelectionDAG &DAG) const {
8057   if (!ResChain)
8058     return;
8059 
8060   SDLoc dl(NewResChain);
8061 
8062   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8063                            NewResChain, DAG.getUNDEF(MVT::Other));
8064   assert(TF.getNode() != NewResChain.getNode() &&
8065          "A new TF really is required here");
8066 
8067   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8068   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8069 }
8070 
8071 /// Analyze profitability of direct move
8072 /// prefer float load to int load plus direct move
8073 /// when there is no integer use of int load
8074 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8075   SDNode *Origin = Op.getOperand(0).getNode();
8076   if (Origin->getOpcode() != ISD::LOAD)
8077     return true;
8078 
8079   // If there is no LXSIBZX/LXSIHZX, like Power8,
8080   // prefer direct move if the memory size is 1 or 2 bytes.
8081   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8082   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8083     return true;
8084 
8085   for (SDNode::use_iterator UI = Origin->use_begin(),
8086                             UE = Origin->use_end();
8087        UI != UE; ++UI) {
8088 
8089     // Only look at the users of the loaded value.
8090     if (UI.getUse().get().getResNo() != 0)
8091       continue;
8092 
8093     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8094         UI->getOpcode() != ISD::UINT_TO_FP &&
8095         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8096         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8097       return true;
8098   }
8099 
8100   return false;
8101 }
8102 
8103 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8104                               const PPCSubtarget &Subtarget,
8105                               SDValue Chain = SDValue()) {
8106   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8107                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8108   SDLoc dl(Op);
8109 
8110   // TODO: Any other flags to propagate?
8111   SDNodeFlags Flags;
8112   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8113 
8114   // If we have FCFIDS, then use it when converting to single-precision.
8115   // Otherwise, convert to double-precision and then round.
8116   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8117   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8118                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8119   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8120   if (Op->isStrictFPOpcode()) {
8121     if (!Chain)
8122       Chain = Op.getOperand(0);
8123     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8124                        DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8125   } else
8126     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8127 }
8128 
8129 /// Custom lowers integer to floating point conversions to use
8130 /// the direct move instructions available in ISA 2.07 to avoid the
8131 /// need for load/store combinations.
8132 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8133                                                     SelectionDAG &DAG,
8134                                                     const SDLoc &dl) const {
8135   assert((Op.getValueType() == MVT::f32 ||
8136           Op.getValueType() == MVT::f64) &&
8137          "Invalid floating point type as target of conversion");
8138   assert(Subtarget.hasFPCVT() &&
8139          "Int to FP conversions with direct moves require FPCVT");
8140   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8141   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8142   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8143                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8144   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8145   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8146   return convertIntToFP(Op, Mov, DAG, Subtarget);
8147 }
8148 
8149 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8150 
8151   EVT VecVT = Vec.getValueType();
8152   assert(VecVT.isVector() && "Expected a vector type.");
8153   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8154 
8155   EVT EltVT = VecVT.getVectorElementType();
8156   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8157   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8158 
8159   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8160   SmallVector<SDValue, 16> Ops(NumConcat);
8161   Ops[0] = Vec;
8162   SDValue UndefVec = DAG.getUNDEF(VecVT);
8163   for (unsigned i = 1; i < NumConcat; ++i)
8164     Ops[i] = UndefVec;
8165 
8166   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8167 }
8168 
8169 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8170                                                 const SDLoc &dl) const {
8171   bool IsStrict = Op->isStrictFPOpcode();
8172   unsigned Opc = Op.getOpcode();
8173   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8174   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8175           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8176          "Unexpected conversion type");
8177   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8178          "Supports conversions to v2f64/v4f32 only.");
8179 
8180   // TODO: Any other flags to propagate?
8181   SDNodeFlags Flags;
8182   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8183 
8184   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8185   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8186 
8187   SDValue Wide = widenVec(DAG, Src, dl);
8188   EVT WideVT = Wide.getValueType();
8189   unsigned WideNumElts = WideVT.getVectorNumElements();
8190   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8191 
8192   SmallVector<int, 16> ShuffV;
8193   for (unsigned i = 0; i < WideNumElts; ++i)
8194     ShuffV.push_back(i + WideNumElts);
8195 
8196   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8197   int SaveElts = FourEltRes ? 4 : 2;
8198   if (Subtarget.isLittleEndian())
8199     for (int i = 0; i < SaveElts; i++)
8200       ShuffV[i * Stride] = i;
8201   else
8202     for (int i = 1; i <= SaveElts; i++)
8203       ShuffV[i * Stride - 1] = i - 1;
8204 
8205   SDValue ShuffleSrc2 =
8206       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8207   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8208 
8209   SDValue Extend;
8210   if (SignedConv) {
8211     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8212     EVT ExtVT = Src.getValueType();
8213     if (Subtarget.hasP9Altivec())
8214       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8215                                IntermediateVT.getVectorNumElements());
8216 
8217     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8218                          DAG.getValueType(ExtVT));
8219   } else
8220     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8221 
8222   if (IsStrict)
8223     return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8224                        {Op.getOperand(0), Extend}, Flags);
8225 
8226   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8227 }
8228 
8229 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8230                                           SelectionDAG &DAG) const {
8231   SDLoc dl(Op);
8232   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8233                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8234   bool IsStrict = Op->isStrictFPOpcode();
8235   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8236   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8237 
8238   // TODO: Any other flags to propagate?
8239   SDNodeFlags Flags;
8240   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8241 
8242   EVT InVT = Src.getValueType();
8243   EVT OutVT = Op.getValueType();
8244   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8245       isOperationCustom(Op.getOpcode(), InVT))
8246     return LowerINT_TO_FPVector(Op, DAG, dl);
8247 
8248   // Conversions to f128 are legal.
8249   if (Op.getValueType() == MVT::f128)
8250     return Subtarget.hasP9Vector() ? Op : SDValue();
8251 
8252   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8253   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8254     return SDValue();
8255 
8256   if (Src.getValueType() == MVT::i1) {
8257     SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8258                               DAG.getConstantFP(1.0, dl, Op.getValueType()),
8259                               DAG.getConstantFP(0.0, dl, Op.getValueType()));
8260     if (IsStrict)
8261       return DAG.getMergeValues({Sel, Chain}, dl);
8262     else
8263       return Sel;
8264   }
8265 
8266   // If we have direct moves, we can do all the conversion, skip the store/load
8267   // however, without FPCVT we can't do most conversions.
8268   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8269       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8270     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8271 
8272   assert((IsSigned || Subtarget.hasFPCVT()) &&
8273          "UINT_TO_FP is supported only with FPCVT");
8274 
8275   if (Src.getValueType() == MVT::i64) {
8276     SDValue SINT = Src;
8277     // When converting to single-precision, we actually need to convert
8278     // to double-precision first and then round to single-precision.
8279     // To avoid double-rounding effects during that operation, we have
8280     // to prepare the input operand.  Bits that might be truncated when
8281     // converting to double-precision are replaced by a bit that won't
8282     // be lost at this stage, but is below the single-precision rounding
8283     // position.
8284     //
8285     // However, if -enable-unsafe-fp-math is in effect, accept double
8286     // rounding to avoid the extra overhead.
8287     if (Op.getValueType() == MVT::f32 &&
8288         !Subtarget.hasFPCVT() &&
8289         !DAG.getTarget().Options.UnsafeFPMath) {
8290 
8291       // Twiddle input to make sure the low 11 bits are zero.  (If this
8292       // is the case, we are guaranteed the value will fit into the 53 bit
8293       // mantissa of an IEEE double-precision value without rounding.)
8294       // If any of those low 11 bits were not zero originally, make sure
8295       // bit 12 (value 2048) is set instead, so that the final rounding
8296       // to single-precision gets the correct result.
8297       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8298                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8299       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8300                           Round, DAG.getConstant(2047, dl, MVT::i64));
8301       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8302       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8303                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8304 
8305       // However, we cannot use that value unconditionally: if the magnitude
8306       // of the input value is small, the bit-twiddling we did above might
8307       // end up visibly changing the output.  Fortunately, in that case, we
8308       // don't need to twiddle bits since the original input will convert
8309       // exactly to double-precision floating-point already.  Therefore,
8310       // construct a conditional to use the original value if the top 11
8311       // bits are all sign-bit copies, and use the rounded value computed
8312       // above otherwise.
8313       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8314                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8315       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8316                          Cond, DAG.getConstant(1, dl, MVT::i64));
8317       Cond = DAG.getSetCC(
8318           dl,
8319           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8320           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8321 
8322       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8323     }
8324 
8325     ReuseLoadInfo RLI;
8326     SDValue Bits;
8327 
8328     MachineFunction &MF = DAG.getMachineFunction();
8329     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8330       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8331                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8332       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8333     } else if (Subtarget.hasLFIWAX() &&
8334                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8335       MachineMemOperand *MMO =
8336         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8337                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8338       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8339       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8340                                      DAG.getVTList(MVT::f64, MVT::Other),
8341                                      Ops, MVT::i32, MMO);
8342       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8343     } else if (Subtarget.hasFPCVT() &&
8344                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8345       MachineMemOperand *MMO =
8346         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8347                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8348       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8349       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8350                                      DAG.getVTList(MVT::f64, MVT::Other),
8351                                      Ops, MVT::i32, MMO);
8352       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8353     } else if (((Subtarget.hasLFIWAX() &&
8354                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8355                 (Subtarget.hasFPCVT() &&
8356                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8357                SINT.getOperand(0).getValueType() == MVT::i32) {
8358       MachineFrameInfo &MFI = MF.getFrameInfo();
8359       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8360 
8361       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8362       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8363 
8364       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8365                                    MachinePointerInfo::getFixedStack(
8366                                        DAG.getMachineFunction(), FrameIdx));
8367       Chain = Store;
8368 
8369       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8370              "Expected an i32 store");
8371 
8372       RLI.Ptr = FIdx;
8373       RLI.Chain = Chain;
8374       RLI.MPI =
8375           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8376       RLI.Alignment = Align(4);
8377 
8378       MachineMemOperand *MMO =
8379         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8380                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8381       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8382       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8383                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8384                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8385                                      Ops, MVT::i32, MMO);
8386       Chain = Bits.getValue(1);
8387     } else
8388       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8389 
8390     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8391     if (IsStrict)
8392       Chain = FP.getValue(1);
8393 
8394     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8395       if (IsStrict)
8396         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8397                          DAG.getVTList(MVT::f32, MVT::Other),
8398                          {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8399       else
8400         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8401                          DAG.getIntPtrConstant(0, dl));
8402     }
8403     return FP;
8404   }
8405 
8406   assert(Src.getValueType() == MVT::i32 &&
8407          "Unhandled INT_TO_FP type in custom expander!");
8408   // Since we only generate this in 64-bit mode, we can take advantage of
8409   // 64-bit registers.  In particular, sign extend the input value into the
8410   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8411   // then lfd it and fcfid it.
8412   MachineFunction &MF = DAG.getMachineFunction();
8413   MachineFrameInfo &MFI = MF.getFrameInfo();
8414   EVT PtrVT = getPointerTy(MF.getDataLayout());
8415 
8416   SDValue Ld;
8417   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8418     ReuseLoadInfo RLI;
8419     bool ReusingLoad;
8420     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8421       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8422       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8423 
8424       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8425                                    MachinePointerInfo::getFixedStack(
8426                                        DAG.getMachineFunction(), FrameIdx));
8427       Chain = Store;
8428 
8429       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8430              "Expected an i32 store");
8431 
8432       RLI.Ptr = FIdx;
8433       RLI.Chain = Chain;
8434       RLI.MPI =
8435           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8436       RLI.Alignment = Align(4);
8437     }
8438 
8439     MachineMemOperand *MMO =
8440       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8441                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8442     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8443     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8444                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8445                                  MVT::i32, MMO);
8446     Chain = Ld.getValue(1);
8447     if (ReusingLoad)
8448       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8449   } else {
8450     assert(Subtarget.isPPC64() &&
8451            "i32->FP without LFIWAX supported only on PPC64");
8452 
8453     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8454     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8455 
8456     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8457 
8458     // STD the extended value into the stack slot.
8459     SDValue Store = DAG.getStore(
8460         Chain, dl, Ext64, FIdx,
8461         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8462     Chain = Store;
8463 
8464     // Load the value as a double.
8465     Ld = DAG.getLoad(
8466         MVT::f64, dl, Chain, FIdx,
8467         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8468     Chain = Ld.getValue(1);
8469   }
8470 
8471   // FCFID it and return it.
8472   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8473   if (IsStrict)
8474     Chain = FP.getValue(1);
8475   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8476     if (IsStrict)
8477       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8478                        DAG.getVTList(MVT::f32, MVT::Other),
8479                        {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8480     else
8481       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8482                        DAG.getIntPtrConstant(0, dl));
8483   }
8484   return FP;
8485 }
8486 
8487 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8488                                             SelectionDAG &DAG) const {
8489   SDLoc dl(Op);
8490   /*
8491    The rounding mode is in bits 30:31 of FPSR, and has the following
8492    settings:
8493      00 Round to nearest
8494      01 Round to 0
8495      10 Round to +inf
8496      11 Round to -inf
8497 
8498   FLT_ROUNDS, on the other hand, expects the following:
8499     -1 Undefined
8500      0 Round to 0
8501      1 Round to nearest
8502      2 Round to +inf
8503      3 Round to -inf
8504 
8505   To perform the conversion, we do:
8506     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8507   */
8508 
8509   MachineFunction &MF = DAG.getMachineFunction();
8510   EVT VT = Op.getValueType();
8511   EVT PtrVT = getPointerTy(MF.getDataLayout());
8512 
8513   // Save FP Control Word to register
8514   SDValue Chain = Op.getOperand(0);
8515   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8516   Chain = MFFS.getValue(1);
8517 
8518   SDValue CWD;
8519   if (isTypeLegal(MVT::i64)) {
8520     CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
8521                       DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
8522   } else {
8523     // Save FP register to stack slot
8524     int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8525     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8526     Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8527 
8528     // Load FP Control Word from low 32 bits of stack slot.
8529     assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) &&
8530            "Stack slot adjustment is valid only on big endian subtargets!");
8531     SDValue Four = DAG.getConstant(4, dl, PtrVT);
8532     SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8533     CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8534     Chain = CWD.getValue(1);
8535   }
8536 
8537   // Transform as necessary
8538   SDValue CWD1 =
8539     DAG.getNode(ISD::AND, dl, MVT::i32,
8540                 CWD, DAG.getConstant(3, dl, MVT::i32));
8541   SDValue CWD2 =
8542     DAG.getNode(ISD::SRL, dl, MVT::i32,
8543                 DAG.getNode(ISD::AND, dl, MVT::i32,
8544                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8545                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8546                             DAG.getConstant(3, dl, MVT::i32)),
8547                 DAG.getConstant(1, dl, MVT::i32));
8548 
8549   SDValue RetVal =
8550     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8551 
8552   RetVal =
8553       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8554                   dl, VT, RetVal);
8555 
8556   return DAG.getMergeValues({RetVal, Chain}, dl);
8557 }
8558 
8559 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8560   EVT VT = Op.getValueType();
8561   unsigned BitWidth = VT.getSizeInBits();
8562   SDLoc dl(Op);
8563   assert(Op.getNumOperands() == 3 &&
8564          VT == Op.getOperand(1).getValueType() &&
8565          "Unexpected SHL!");
8566 
8567   // Expand into a bunch of logical ops.  Note that these ops
8568   // depend on the PPC behavior for oversized shift amounts.
8569   SDValue Lo = Op.getOperand(0);
8570   SDValue Hi = Op.getOperand(1);
8571   SDValue Amt = Op.getOperand(2);
8572   EVT AmtVT = Amt.getValueType();
8573 
8574   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8575                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8576   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8577   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8578   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8579   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8580                              DAG.getConstant(-BitWidth, dl, AmtVT));
8581   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8582   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8583   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8584   SDValue OutOps[] = { OutLo, OutHi };
8585   return DAG.getMergeValues(OutOps, dl);
8586 }
8587 
8588 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8589   EVT VT = Op.getValueType();
8590   SDLoc dl(Op);
8591   unsigned BitWidth = VT.getSizeInBits();
8592   assert(Op.getNumOperands() == 3 &&
8593          VT == Op.getOperand(1).getValueType() &&
8594          "Unexpected SRL!");
8595 
8596   // Expand into a bunch of logical ops.  Note that these ops
8597   // depend on the PPC behavior for oversized shift amounts.
8598   SDValue Lo = Op.getOperand(0);
8599   SDValue Hi = Op.getOperand(1);
8600   SDValue Amt = Op.getOperand(2);
8601   EVT AmtVT = Amt.getValueType();
8602 
8603   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8604                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8605   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8606   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8607   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8608   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8609                              DAG.getConstant(-BitWidth, dl, AmtVT));
8610   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8611   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8612   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8613   SDValue OutOps[] = { OutLo, OutHi };
8614   return DAG.getMergeValues(OutOps, dl);
8615 }
8616 
8617 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8618   SDLoc dl(Op);
8619   EVT VT = Op.getValueType();
8620   unsigned BitWidth = VT.getSizeInBits();
8621   assert(Op.getNumOperands() == 3 &&
8622          VT == Op.getOperand(1).getValueType() &&
8623          "Unexpected SRA!");
8624 
8625   // Expand into a bunch of logical ops, followed by a select_cc.
8626   SDValue Lo = Op.getOperand(0);
8627   SDValue Hi = Op.getOperand(1);
8628   SDValue Amt = Op.getOperand(2);
8629   EVT AmtVT = Amt.getValueType();
8630 
8631   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8632                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8633   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8634   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8635   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8636   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8637                              DAG.getConstant(-BitWidth, dl, AmtVT));
8638   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8639   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8640   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8641                                   Tmp4, Tmp6, ISD::SETLE);
8642   SDValue OutOps[] = { OutLo, OutHi };
8643   return DAG.getMergeValues(OutOps, dl);
8644 }
8645 
8646 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8647                                             SelectionDAG &DAG) const {
8648   SDLoc dl(Op);
8649   EVT VT = Op.getValueType();
8650   unsigned BitWidth = VT.getSizeInBits();
8651 
8652   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8653   SDValue X = Op.getOperand(0);
8654   SDValue Y = Op.getOperand(1);
8655   SDValue Z = Op.getOperand(2);
8656   EVT AmtVT = Z.getValueType();
8657 
8658   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8659   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8660   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8661   // on PowerPC shift by BW being well defined.
8662   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8663                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8664   SDValue SubZ =
8665       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8666   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8667   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8668   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8669 }
8670 
8671 //===----------------------------------------------------------------------===//
8672 // Vector related lowering.
8673 //
8674 
8675 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8676 /// element size of SplatSize. Cast the result to VT.
8677 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8678                                       SelectionDAG &DAG, const SDLoc &dl) {
8679   static const MVT VTys[] = { // canonical VT to use for each size.
8680     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8681   };
8682 
8683   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8684 
8685   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8686   if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
8687     SplatSize = 1;
8688     Val = 0xFF;
8689   }
8690 
8691   EVT CanonicalVT = VTys[SplatSize-1];
8692 
8693   // Build a canonical splat for this value.
8694   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8695 }
8696 
8697 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8698 /// specified intrinsic ID.
8699 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8700                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8701   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8702   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8703                      DAG.getConstant(IID, dl, MVT::i32), Op);
8704 }
8705 
8706 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8707 /// specified intrinsic ID.
8708 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8709                                 SelectionDAG &DAG, const SDLoc &dl,
8710                                 EVT DestVT = MVT::Other) {
8711   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8712   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8713                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8714 }
8715 
8716 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8717 /// specified intrinsic ID.
8718 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8719                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8720                                 EVT DestVT = MVT::Other) {
8721   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8722   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8723                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8724 }
8725 
8726 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8727 /// amount.  The result has the specified value type.
8728 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8729                            SelectionDAG &DAG, const SDLoc &dl) {
8730   // Force LHS/RHS to be the right type.
8731   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8732   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8733 
8734   int Ops[16];
8735   for (unsigned i = 0; i != 16; ++i)
8736     Ops[i] = i + Amt;
8737   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8738   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8739 }
8740 
8741 /// Do we have an efficient pattern in a .td file for this node?
8742 ///
8743 /// \param V - pointer to the BuildVectorSDNode being matched
8744 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8745 ///
8746 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8747 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8748 /// the opposite is true (expansion is beneficial) are:
8749 /// - The node builds a vector out of integers that are not 32 or 64-bits
8750 /// - The node builds a vector out of constants
8751 /// - The node is a "load-and-splat"
8752 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8753 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8754                                             bool HasDirectMove,
8755                                             bool HasP8Vector) {
8756   EVT VecVT = V->getValueType(0);
8757   bool RightType = VecVT == MVT::v2f64 ||
8758     (HasP8Vector && VecVT == MVT::v4f32) ||
8759     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8760   if (!RightType)
8761     return false;
8762 
8763   bool IsSplat = true;
8764   bool IsLoad = false;
8765   SDValue Op0 = V->getOperand(0);
8766 
8767   // This function is called in a block that confirms the node is not a constant
8768   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8769   // different constants.
8770   if (V->isConstant())
8771     return false;
8772   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8773     if (V->getOperand(i).isUndef())
8774       return false;
8775     // We want to expand nodes that represent load-and-splat even if the
8776     // loaded value is a floating point truncation or conversion to int.
8777     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8778         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8779          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8780         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8781          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8782         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8783          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8784       IsLoad = true;
8785     // If the operands are different or the input is not a load and has more
8786     // uses than just this BV node, then it isn't a splat.
8787     if (V->getOperand(i) != Op0 ||
8788         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8789       IsSplat = false;
8790   }
8791   return !(IsSplat && IsLoad);
8792 }
8793 
8794 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8795 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8796 
8797   SDLoc dl(Op);
8798   SDValue Op0 = Op->getOperand(0);
8799 
8800   if ((Op.getValueType() != MVT::f128) ||
8801       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8802       (Op0.getOperand(0).getValueType() != MVT::i64) ||
8803       (Op0.getOperand(1).getValueType() != MVT::i64))
8804     return SDValue();
8805 
8806   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8807                      Op0.getOperand(1));
8808 }
8809 
8810 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
8811   const SDValue *InputLoad = &Op;
8812   if (InputLoad->getOpcode() == ISD::BITCAST)
8813     InputLoad = &InputLoad->getOperand(0);
8814   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
8815       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
8816     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
8817     InputLoad = &InputLoad->getOperand(0);
8818   }
8819   if (InputLoad->getOpcode() != ISD::LOAD)
8820     return nullptr;
8821   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8822   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8823 }
8824 
8825 // Convert the argument APFloat to a single precision APFloat if there is no
8826 // loss in information during the conversion to single precision APFloat and the
8827 // resulting number is not a denormal number. Return true if successful.
8828 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
8829   APFloat APFloatToConvert = ArgAPFloat;
8830   bool LosesInfo = true;
8831   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
8832                            &LosesInfo);
8833   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
8834   if (Success)
8835     ArgAPFloat = APFloatToConvert;
8836   return Success;
8837 }
8838 
8839 // Bitcast the argument APInt to a double and convert it to a single precision
8840 // APFloat, bitcast the APFloat to an APInt and assign it to the original
8841 // argument if there is no loss in information during the conversion from
8842 // double to single precision APFloat and the resulting number is not a denormal
8843 // number. Return true if successful.
8844 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
8845   double DpValue = ArgAPInt.bitsToDouble();
8846   APFloat APFloatDp(DpValue);
8847   bool Success = convertToNonDenormSingle(APFloatDp);
8848   if (Success)
8849     ArgAPInt = APFloatDp.bitcastToAPInt();
8850   return Success;
8851 }
8852 
8853 // Nondestructive check for convertTonNonDenormSingle.
8854 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) {
8855   // Only convert if it loses info, since XXSPLTIDP should
8856   // handle the other case.
8857   APFloat APFloatToConvert = ArgAPFloat;
8858   bool LosesInfo = true;
8859   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
8860                            &LosesInfo);
8861 
8862   return (!LosesInfo && !APFloatToConvert.isDenormal());
8863 }
8864 
8865 // If this is a case we can't handle, return null and let the default
8866 // expansion code take care of it.  If we CAN select this case, and if it
8867 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8868 // this case more efficiently than a constant pool load, lower it to the
8869 // sequence of ops that should be used.
8870 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8871                                              SelectionDAG &DAG) const {
8872   SDLoc dl(Op);
8873   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8874   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8875 
8876   // Check if this is a splat of a constant value.
8877   APInt APSplatBits, APSplatUndef;
8878   unsigned SplatBitSize;
8879   bool HasAnyUndefs;
8880   bool BVNIsConstantSplat =
8881       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8882                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
8883 
8884   // If it is a splat of a double, check if we can shrink it to a 32 bit
8885   // non-denormal float which when converted back to double gives us the same
8886   // double. This is to exploit the XXSPLTIDP instruction.
8887   // If we lose precision, we use XXSPLTI32DX.
8888   if (BVNIsConstantSplat && (SplatBitSize == 64) &&
8889       Subtarget.hasPrefixInstrs()) {
8890     // Check the type first to short-circuit so we don't modify APSplatBits if
8891     // this block isn't executed.
8892     if ((Op->getValueType(0) == MVT::v2f64) &&
8893         convertToNonDenormSingle(APSplatBits)) {
8894       SDValue SplatNode = DAG.getNode(
8895           PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
8896           DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
8897       return DAG.getBitcast(Op.getValueType(), SplatNode);
8898     } else {
8899       // We may lose precision, so we have to use XXSPLTI32DX.
8900 
8901       uint32_t Hi =
8902           (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32);
8903       uint32_t Lo =
8904           (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF);
8905       SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
8906 
8907       if (!Hi || !Lo)
8908         // If either load is 0, then we should generate XXLXOR to set to 0.
8909         SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
8910 
8911       if (Hi)
8912         SplatNode = DAG.getNode(
8913             PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
8914             DAG.getTargetConstant(0, dl, MVT::i32),
8915             DAG.getTargetConstant(Hi, dl, MVT::i32));
8916 
8917       if (Lo)
8918         SplatNode =
8919             DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
8920                         DAG.getTargetConstant(1, dl, MVT::i32),
8921                         DAG.getTargetConstant(Lo, dl, MVT::i32));
8922 
8923       return DAG.getBitcast(Op.getValueType(), SplatNode);
8924     }
8925   }
8926 
8927   if (!BVNIsConstantSplat || SplatBitSize > 32) {
8928 
8929     bool IsPermutedLoad = false;
8930     const SDValue *InputLoad =
8931         getNormalLoadInput(Op.getOperand(0), IsPermutedLoad);
8932     // Handle load-and-splat patterns as we have instructions that will do this
8933     // in one go.
8934     if (InputLoad && DAG.isSplatValue(Op, true)) {
8935       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8936 
8937       // We have handling for 4 and 8 byte elements.
8938       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
8939 
8940       // Checking for a single use of this load, we have to check for vector
8941       // width (128 bits) / ElementSize uses (since each operand of the
8942       // BUILD_VECTOR is a separate use of the value.
8943       unsigned NumUsesOfInputLD = 128 / ElementSize;
8944       for (SDValue BVInOp : Op->ops())
8945         if (BVInOp.isUndef())
8946           NumUsesOfInputLD--;
8947       assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
8948       if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
8949           ((Subtarget.hasVSX() && ElementSize == 64) ||
8950            (Subtarget.hasP9Vector() && ElementSize == 32))) {
8951         SDValue Ops[] = {
8952           LD->getChain(),    // Chain
8953           LD->getBasePtr(),  // Ptr
8954           DAG.getValueType(Op.getValueType()) // VT
8955         };
8956         SDValue LdSplt = DAG.getMemIntrinsicNode(
8957             PPCISD::LD_SPLAT, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8958             Ops, LD->getMemoryVT(), LD->getMemOperand());
8959         // Replace all uses of the output chain of the original load with the
8960         // output chain of the new load.
8961         DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
8962                                       LdSplt.getValue(1));
8963         return LdSplt;
8964       }
8965     }
8966 
8967     // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
8968     // 32-bits can be lowered to VSX instructions under certain conditions.
8969     // Without VSX, there is no pattern more efficient than expanding the node.
8970     if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
8971         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8972                                         Subtarget.hasP8Vector()))
8973       return Op;
8974     return SDValue();
8975   }
8976 
8977   uint64_t SplatBits = APSplatBits.getZExtValue();
8978   uint64_t SplatUndef = APSplatUndef.getZExtValue();
8979   unsigned SplatSize = SplatBitSize / 8;
8980 
8981   // First, handle single instruction cases.
8982 
8983   // All zeros?
8984   if (SplatBits == 0) {
8985     // Canonicalize all zero vectors to be v4i32.
8986     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8987       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8988       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8989     }
8990     return Op;
8991   }
8992 
8993   // We have XXSPLTIW for constant splats four bytes wide.
8994   // Given vector length is a multiple of 4, 2-byte splats can be replaced
8995   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
8996   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
8997   // turned into a 4-byte splat of 0xABABABAB.
8998   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
8999     return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
9000                                   Op.getValueType(), DAG, dl);
9001 
9002   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9003     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9004                                   dl);
9005 
9006   // We have XXSPLTIB for constant splats one byte wide.
9007   if (Subtarget.hasP9Vector() && SplatSize == 1)
9008     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9009                                   dl);
9010 
9011   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9012   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9013                     (32-SplatBitSize));
9014   if (SextVal >= -16 && SextVal <= 15)
9015     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9016                                   dl);
9017 
9018   // Two instruction sequences.
9019 
9020   // If this value is in the range [-32,30] and is even, use:
9021   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9022   // If this value is in the range [17,31] and is odd, use:
9023   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9024   // If this value is in the range [-31,-17] and is odd, use:
9025   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9026   // Note the last two are three-instruction sequences.
9027   if (SextVal >= -32 && SextVal <= 31) {
9028     // To avoid having these optimizations undone by constant folding,
9029     // we convert to a pseudo that will be expanded later into one of
9030     // the above forms.
9031     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9032     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9033               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9034     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9035     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9036     if (VT == Op.getValueType())
9037       return RetVal;
9038     else
9039       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9040   }
9041 
9042   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9043   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9044   // for fneg/fabs.
9045   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9046     // Make -1 and vspltisw -1:
9047     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9048 
9049     // Make the VSLW intrinsic, computing 0x8000_0000.
9050     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9051                                    OnesV, DAG, dl);
9052 
9053     // xor by OnesV to invert it.
9054     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9055     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9056   }
9057 
9058   // Check to see if this is a wide variety of vsplti*, binop self cases.
9059   static const signed char SplatCsts[] = {
9060     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9061     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9062   };
9063 
9064   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9065     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9066     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9067     int i = SplatCsts[idx];
9068 
9069     // Figure out what shift amount will be used by altivec if shifted by i in
9070     // this splat size.
9071     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9072 
9073     // vsplti + shl self.
9074     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9075       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9076       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9077         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9078         Intrinsic::ppc_altivec_vslw
9079       };
9080       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9081       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9082     }
9083 
9084     // vsplti + srl self.
9085     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9086       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9087       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9088         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9089         Intrinsic::ppc_altivec_vsrw
9090       };
9091       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9092       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9093     }
9094 
9095     // vsplti + rol self.
9096     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9097                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9098       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9099       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9100         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9101         Intrinsic::ppc_altivec_vrlw
9102       };
9103       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9104       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9105     }
9106 
9107     // t = vsplti c, result = vsldoi t, t, 1
9108     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9109       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9110       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9111       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9112     }
9113     // t = vsplti c, result = vsldoi t, t, 2
9114     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9115       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9116       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9117       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9118     }
9119     // t = vsplti c, result = vsldoi t, t, 3
9120     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9121       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9122       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9123       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9124     }
9125   }
9126 
9127   return SDValue();
9128 }
9129 
9130 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9131 /// the specified operations to build the shuffle.
9132 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9133                                       SDValue RHS, SelectionDAG &DAG,
9134                                       const SDLoc &dl) {
9135   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9136   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9137   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9138 
9139   enum {
9140     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9141     OP_VMRGHW,
9142     OP_VMRGLW,
9143     OP_VSPLTISW0,
9144     OP_VSPLTISW1,
9145     OP_VSPLTISW2,
9146     OP_VSPLTISW3,
9147     OP_VSLDOI4,
9148     OP_VSLDOI8,
9149     OP_VSLDOI12
9150   };
9151 
9152   if (OpNum == OP_COPY) {
9153     if (LHSID == (1*9+2)*9+3) return LHS;
9154     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9155     return RHS;
9156   }
9157 
9158   SDValue OpLHS, OpRHS;
9159   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9160   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9161 
9162   int ShufIdxs[16];
9163   switch (OpNum) {
9164   default: llvm_unreachable("Unknown i32 permute!");
9165   case OP_VMRGHW:
9166     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9167     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9168     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9169     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9170     break;
9171   case OP_VMRGLW:
9172     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9173     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9174     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9175     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9176     break;
9177   case OP_VSPLTISW0:
9178     for (unsigned i = 0; i != 16; ++i)
9179       ShufIdxs[i] = (i&3)+0;
9180     break;
9181   case OP_VSPLTISW1:
9182     for (unsigned i = 0; i != 16; ++i)
9183       ShufIdxs[i] = (i&3)+4;
9184     break;
9185   case OP_VSPLTISW2:
9186     for (unsigned i = 0; i != 16; ++i)
9187       ShufIdxs[i] = (i&3)+8;
9188     break;
9189   case OP_VSPLTISW3:
9190     for (unsigned i = 0; i != 16; ++i)
9191       ShufIdxs[i] = (i&3)+12;
9192     break;
9193   case OP_VSLDOI4:
9194     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9195   case OP_VSLDOI8:
9196     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9197   case OP_VSLDOI12:
9198     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9199   }
9200   EVT VT = OpLHS.getValueType();
9201   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9202   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9203   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9204   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9205 }
9206 
9207 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9208 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9209 /// SDValue.
9210 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9211                                            SelectionDAG &DAG) const {
9212   const unsigned BytesInVector = 16;
9213   bool IsLE = Subtarget.isLittleEndian();
9214   SDLoc dl(N);
9215   SDValue V1 = N->getOperand(0);
9216   SDValue V2 = N->getOperand(1);
9217   unsigned ShiftElts = 0, InsertAtByte = 0;
9218   bool Swap = false;
9219 
9220   // Shifts required to get the byte we want at element 7.
9221   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9222                                    0, 15, 14, 13, 12, 11, 10, 9};
9223   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9224                                 1, 2,  3,  4,  5,  6,  7,  8};
9225 
9226   ArrayRef<int> Mask = N->getMask();
9227   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9228 
9229   // For each mask element, find out if we're just inserting something
9230   // from V2 into V1 or vice versa.
9231   // Possible permutations inserting an element from V2 into V1:
9232   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9233   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9234   //   ...
9235   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9236   // Inserting from V1 into V2 will be similar, except mask range will be
9237   // [16,31].
9238 
9239   bool FoundCandidate = false;
9240   // If both vector operands for the shuffle are the same vector, the mask
9241   // will contain only elements from the first one and the second one will be
9242   // undef.
9243   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9244   // Go through the mask of half-words to find an element that's being moved
9245   // from one vector to the other.
9246   for (unsigned i = 0; i < BytesInVector; ++i) {
9247     unsigned CurrentElement = Mask[i];
9248     // If 2nd operand is undefined, we should only look for element 7 in the
9249     // Mask.
9250     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9251       continue;
9252 
9253     bool OtherElementsInOrder = true;
9254     // Examine the other elements in the Mask to see if they're in original
9255     // order.
9256     for (unsigned j = 0; j < BytesInVector; ++j) {
9257       if (j == i)
9258         continue;
9259       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9260       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9261       // in which we always assume we're always picking from the 1st operand.
9262       int MaskOffset =
9263           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9264       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9265         OtherElementsInOrder = false;
9266         break;
9267       }
9268     }
9269     // If other elements are in original order, we record the number of shifts
9270     // we need to get the element we want into element 7. Also record which byte
9271     // in the vector we should insert into.
9272     if (OtherElementsInOrder) {
9273       // If 2nd operand is undefined, we assume no shifts and no swapping.
9274       if (V2.isUndef()) {
9275         ShiftElts = 0;
9276         Swap = false;
9277       } else {
9278         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9279         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9280                          : BigEndianShifts[CurrentElement & 0xF];
9281         Swap = CurrentElement < BytesInVector;
9282       }
9283       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9284       FoundCandidate = true;
9285       break;
9286     }
9287   }
9288 
9289   if (!FoundCandidate)
9290     return SDValue();
9291 
9292   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9293   // optionally with VECSHL if shift is required.
9294   if (Swap)
9295     std::swap(V1, V2);
9296   if (V2.isUndef())
9297     V2 = V1;
9298   if (ShiftElts) {
9299     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9300                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9301     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9302                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9303   }
9304   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9305                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9306 }
9307 
9308 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9309 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9310 /// SDValue.
9311 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9312                                            SelectionDAG &DAG) const {
9313   const unsigned NumHalfWords = 8;
9314   const unsigned BytesInVector = NumHalfWords * 2;
9315   // Check that the shuffle is on half-words.
9316   if (!isNByteElemShuffleMask(N, 2, 1))
9317     return SDValue();
9318 
9319   bool IsLE = Subtarget.isLittleEndian();
9320   SDLoc dl(N);
9321   SDValue V1 = N->getOperand(0);
9322   SDValue V2 = N->getOperand(1);
9323   unsigned ShiftElts = 0, InsertAtByte = 0;
9324   bool Swap = false;
9325 
9326   // Shifts required to get the half-word we want at element 3.
9327   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9328   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9329 
9330   uint32_t Mask = 0;
9331   uint32_t OriginalOrderLow = 0x1234567;
9332   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9333   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9334   // 32-bit space, only need 4-bit nibbles per element.
9335   for (unsigned i = 0; i < NumHalfWords; ++i) {
9336     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9337     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9338   }
9339 
9340   // For each mask element, find out if we're just inserting something
9341   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9342   // from V2 into V1:
9343   //   X, 1, 2, 3, 4, 5, 6, 7
9344   //   0, X, 2, 3, 4, 5, 6, 7
9345   //   0, 1, X, 3, 4, 5, 6, 7
9346   //   0, 1, 2, X, 4, 5, 6, 7
9347   //   0, 1, 2, 3, X, 5, 6, 7
9348   //   0, 1, 2, 3, 4, X, 6, 7
9349   //   0, 1, 2, 3, 4, 5, X, 7
9350   //   0, 1, 2, 3, 4, 5, 6, X
9351   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9352 
9353   bool FoundCandidate = false;
9354   // Go through the mask of half-words to find an element that's being moved
9355   // from one vector to the other.
9356   for (unsigned i = 0; i < NumHalfWords; ++i) {
9357     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9358     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9359     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9360     uint32_t TargetOrder = 0x0;
9361 
9362     // If both vector operands for the shuffle are the same vector, the mask
9363     // will contain only elements from the first one and the second one will be
9364     // undef.
9365     if (V2.isUndef()) {
9366       ShiftElts = 0;
9367       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9368       TargetOrder = OriginalOrderLow;
9369       Swap = false;
9370       // Skip if not the correct element or mask of other elements don't equal
9371       // to our expected order.
9372       if (MaskOneElt == VINSERTHSrcElem &&
9373           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9374         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9375         FoundCandidate = true;
9376         break;
9377       }
9378     } else { // If both operands are defined.
9379       // Target order is [8,15] if the current mask is between [0,7].
9380       TargetOrder =
9381           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9382       // Skip if mask of other elements don't equal our expected order.
9383       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9384         // We only need the last 3 bits for the number of shifts.
9385         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9386                          : BigEndianShifts[MaskOneElt & 0x7];
9387         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9388         Swap = MaskOneElt < NumHalfWords;
9389         FoundCandidate = true;
9390         break;
9391       }
9392     }
9393   }
9394 
9395   if (!FoundCandidate)
9396     return SDValue();
9397 
9398   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9399   // optionally with VECSHL if shift is required.
9400   if (Swap)
9401     std::swap(V1, V2);
9402   if (V2.isUndef())
9403     V2 = V1;
9404   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9405   if (ShiftElts) {
9406     // Double ShiftElts because we're left shifting on v16i8 type.
9407     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9408                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9409     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9410     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9411                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9412     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9413   }
9414   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9415   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9416                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9417   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9418 }
9419 
9420 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9421 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9422 /// return the default SDValue.
9423 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9424                                               SelectionDAG &DAG) const {
9425   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9426   // to v16i8. Peek through the bitcasts to get the actual operands.
9427   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9428   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9429 
9430   auto ShuffleMask = SVN->getMask();
9431   SDValue VecShuffle(SVN, 0);
9432   SDLoc DL(SVN);
9433 
9434   // Check that we have a four byte shuffle.
9435   if (!isNByteElemShuffleMask(SVN, 4, 1))
9436     return SDValue();
9437 
9438   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9439   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9440     std::swap(LHS, RHS);
9441     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9442     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9443   }
9444 
9445   // Ensure that the RHS is a vector of constants.
9446   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9447   if (!BVN)
9448     return SDValue();
9449 
9450   // Check if RHS is a splat of 4-bytes (or smaller).
9451   APInt APSplatValue, APSplatUndef;
9452   unsigned SplatBitSize;
9453   bool HasAnyUndefs;
9454   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9455                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9456       SplatBitSize > 32)
9457     return SDValue();
9458 
9459   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9460   // The instruction splats a constant C into two words of the source vector
9461   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9462   // Thus we check that the shuffle mask is the equivalent  of
9463   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9464   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9465   // within each word are consecutive, so we only need to check the first byte.
9466   SDValue Index;
9467   bool IsLE = Subtarget.isLittleEndian();
9468   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9469       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9470        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9471     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9472   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9473            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9474             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9475     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9476   else
9477     return SDValue();
9478 
9479   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9480   // for XXSPLTI32DX.
9481   unsigned SplatVal = APSplatValue.getZExtValue();
9482   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9483     SplatVal |= (SplatVal << SplatBitSize);
9484 
9485   SDValue SplatNode = DAG.getNode(
9486       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9487       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9488   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9489 }
9490 
9491 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9492 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9493 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9494 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9495 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9496   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9497   assert(Op.getValueType() == MVT::v1i128 &&
9498          "Only set v1i128 as custom, other type shouldn't reach here!");
9499   SDLoc dl(Op);
9500   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9501   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9502   unsigned SHLAmt = N1.getConstantOperandVal(0);
9503   if (SHLAmt % 8 == 0) {
9504     SmallVector<int, 16> Mask(16, 0);
9505     std::iota(Mask.begin(), Mask.end(), 0);
9506     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9507     if (SDValue Shuffle =
9508             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9509                                  DAG.getUNDEF(MVT::v16i8), Mask))
9510       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9511   }
9512   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9513   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9514                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9515   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9516                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9517   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9518   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9519 }
9520 
9521 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9522 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9523 /// return the code it can be lowered into.  Worst case, it can always be
9524 /// lowered into a vperm.
9525 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9526                                                SelectionDAG &DAG) const {
9527   SDLoc dl(Op);
9528   SDValue V1 = Op.getOperand(0);
9529   SDValue V2 = Op.getOperand(1);
9530   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9531 
9532   // Any nodes that were combined in the target-independent combiner prior
9533   // to vector legalization will not be sent to the target combine. Try to
9534   // combine it here.
9535   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9536     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9537       return NewShuffle;
9538     Op = NewShuffle;
9539     SVOp = cast<ShuffleVectorSDNode>(Op);
9540     V1 = Op.getOperand(0);
9541     V2 = Op.getOperand(1);
9542   }
9543   EVT VT = Op.getValueType();
9544   bool isLittleEndian = Subtarget.isLittleEndian();
9545 
9546   unsigned ShiftElts, InsertAtByte;
9547   bool Swap = false;
9548 
9549   // If this is a load-and-splat, we can do that with a single instruction
9550   // in some cases. However if the load has multiple uses, we don't want to
9551   // combine it because that will just produce multiple loads.
9552   bool IsPermutedLoad = false;
9553   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9554   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9555       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9556       InputLoad->hasOneUse()) {
9557     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9558     int SplatIdx =
9559       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9560 
9561     // The splat index for permuted loads will be in the left half of the vector
9562     // which is strictly wider than the loaded value by 8 bytes. So we need to
9563     // adjust the splat index to point to the correct address in memory.
9564     if (IsPermutedLoad) {
9565       assert(isLittleEndian && "Unexpected permuted load on big endian target");
9566       SplatIdx += IsFourByte ? 2 : 1;
9567       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9568              "Splat of a value outside of the loaded memory");
9569     }
9570 
9571     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9572     // For 4-byte load-and-splat, we need Power9.
9573     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9574       uint64_t Offset = 0;
9575       if (IsFourByte)
9576         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9577       else
9578         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9579 
9580       SDValue BasePtr = LD->getBasePtr();
9581       if (Offset != 0)
9582         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9583                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9584       SDValue Ops[] = {
9585         LD->getChain(),    // Chain
9586         BasePtr,           // BasePtr
9587         DAG.getValueType(Op.getValueType()) // VT
9588       };
9589       SDVTList VTL =
9590         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9591       SDValue LdSplt =
9592         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9593                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9594       DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
9595       if (LdSplt.getValueType() != SVOp->getValueType(0))
9596         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9597       return LdSplt;
9598     }
9599   }
9600   if (Subtarget.hasP9Vector() &&
9601       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9602                            isLittleEndian)) {
9603     if (Swap)
9604       std::swap(V1, V2);
9605     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9606     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9607     if (ShiftElts) {
9608       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9609                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9610       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9611                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9612       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9613     }
9614     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9615                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9616     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9617   }
9618 
9619   if (Subtarget.hasPrefixInstrs()) {
9620     SDValue SplatInsertNode;
9621     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9622       return SplatInsertNode;
9623   }
9624 
9625   if (Subtarget.hasP9Altivec()) {
9626     SDValue NewISDNode;
9627     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9628       return NewISDNode;
9629 
9630     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9631       return NewISDNode;
9632   }
9633 
9634   if (Subtarget.hasVSX() &&
9635       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9636     if (Swap)
9637       std::swap(V1, V2);
9638     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9639     SDValue Conv2 =
9640         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9641 
9642     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9643                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9644     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9645   }
9646 
9647   if (Subtarget.hasVSX() &&
9648     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9649     if (Swap)
9650       std::swap(V1, V2);
9651     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9652     SDValue Conv2 =
9653         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9654 
9655     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9656                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9657     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9658   }
9659 
9660   if (Subtarget.hasP9Vector()) {
9661      if (PPC::isXXBRHShuffleMask(SVOp)) {
9662       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9663       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9664       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9665     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9666       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9667       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9668       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9669     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9670       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9671       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9672       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9673     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9674       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9675       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9676       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9677     }
9678   }
9679 
9680   if (Subtarget.hasVSX()) {
9681     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9682       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9683 
9684       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9685       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9686                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9687       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9688     }
9689 
9690     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9691     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9692       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9693       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9694       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9695     }
9696   }
9697 
9698   // Cases that are handled by instructions that take permute immediates
9699   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9700   // selected by the instruction selector.
9701   if (V2.isUndef()) {
9702     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9703         PPC::isSplatShuffleMask(SVOp, 2) ||
9704         PPC::isSplatShuffleMask(SVOp, 4) ||
9705         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9706         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9707         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9708         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9709         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9710         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9711         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9712         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9713         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9714         (Subtarget.hasP8Altivec() && (
9715          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9716          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9717          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9718       return Op;
9719     }
9720   }
9721 
9722   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9723   // and produce a fixed permutation.  If any of these match, do not lower to
9724   // VPERM.
9725   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9726   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9727       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9728       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9729       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9730       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9731       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9732       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9733       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9734       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9735       (Subtarget.hasP8Altivec() && (
9736        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9737        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9738        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9739     return Op;
9740 
9741   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9742   // perfect shuffle table to emit an optimal matching sequence.
9743   ArrayRef<int> PermMask = SVOp->getMask();
9744 
9745   unsigned PFIndexes[4];
9746   bool isFourElementShuffle = true;
9747   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9748     unsigned EltNo = 8;   // Start out undef.
9749     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9750       if (PermMask[i*4+j] < 0)
9751         continue;   // Undef, ignore it.
9752 
9753       unsigned ByteSource = PermMask[i*4+j];
9754       if ((ByteSource & 3) != j) {
9755         isFourElementShuffle = false;
9756         break;
9757       }
9758 
9759       if (EltNo == 8) {
9760         EltNo = ByteSource/4;
9761       } else if (EltNo != ByteSource/4) {
9762         isFourElementShuffle = false;
9763         break;
9764       }
9765     }
9766     PFIndexes[i] = EltNo;
9767   }
9768 
9769   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9770   // perfect shuffle vector to determine if it is cost effective to do this as
9771   // discrete instructions, or whether we should use a vperm.
9772   // For now, we skip this for little endian until such time as we have a
9773   // little-endian perfect shuffle table.
9774   if (isFourElementShuffle && !isLittleEndian) {
9775     // Compute the index in the perfect shuffle table.
9776     unsigned PFTableIndex =
9777       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9778 
9779     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9780     unsigned Cost  = (PFEntry >> 30);
9781 
9782     // Determining when to avoid vperm is tricky.  Many things affect the cost
9783     // of vperm, particularly how many times the perm mask needs to be computed.
9784     // For example, if the perm mask can be hoisted out of a loop or is already
9785     // used (perhaps because there are multiple permutes with the same shuffle
9786     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9787     // the loop requires an extra register.
9788     //
9789     // As a compromise, we only emit discrete instructions if the shuffle can be
9790     // generated in 3 or fewer operations.  When we have loop information
9791     // available, if this block is within a loop, we should avoid using vperm
9792     // for 3-operation perms and use a constant pool load instead.
9793     if (Cost < 3)
9794       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9795   }
9796 
9797   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9798   // vector that will get spilled to the constant pool.
9799   if (V2.isUndef()) V2 = V1;
9800 
9801   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9802   // that it is in input element units, not in bytes.  Convert now.
9803 
9804   // For little endian, the order of the input vectors is reversed, and
9805   // the permutation mask is complemented with respect to 31.  This is
9806   // necessary to produce proper semantics with the big-endian-biased vperm
9807   // instruction.
9808   EVT EltVT = V1.getValueType().getVectorElementType();
9809   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9810 
9811   SmallVector<SDValue, 16> ResultMask;
9812   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9813     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9814 
9815     for (unsigned j = 0; j != BytesPerElement; ++j)
9816       if (isLittleEndian)
9817         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9818                                              dl, MVT::i32));
9819       else
9820         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9821                                              MVT::i32));
9822   }
9823 
9824   ShufflesHandledWithVPERM++;
9825   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9826   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
9827   LLVM_DEBUG(SVOp->dump());
9828   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
9829   LLVM_DEBUG(VPermMask.dump());
9830 
9831   if (isLittleEndian)
9832     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9833                        V2, V1, VPermMask);
9834   else
9835     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9836                        V1, V2, VPermMask);
9837 }
9838 
9839 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9840 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9841 /// information about the intrinsic.
9842 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9843                                  bool &isDot, const PPCSubtarget &Subtarget) {
9844   unsigned IntrinsicID =
9845       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9846   CompareOpc = -1;
9847   isDot = false;
9848   switch (IntrinsicID) {
9849   default:
9850     return false;
9851   // Comparison predicates.
9852   case Intrinsic::ppc_altivec_vcmpbfp_p:
9853     CompareOpc = 966;
9854     isDot = true;
9855     break;
9856   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9857     CompareOpc = 198;
9858     isDot = true;
9859     break;
9860   case Intrinsic::ppc_altivec_vcmpequb_p:
9861     CompareOpc = 6;
9862     isDot = true;
9863     break;
9864   case Intrinsic::ppc_altivec_vcmpequh_p:
9865     CompareOpc = 70;
9866     isDot = true;
9867     break;
9868   case Intrinsic::ppc_altivec_vcmpequw_p:
9869     CompareOpc = 134;
9870     isDot = true;
9871     break;
9872   case Intrinsic::ppc_altivec_vcmpequd_p:
9873     if (Subtarget.hasP8Altivec()) {
9874       CompareOpc = 199;
9875       isDot = true;
9876     } else
9877       return false;
9878     break;
9879   case Intrinsic::ppc_altivec_vcmpneb_p:
9880   case Intrinsic::ppc_altivec_vcmpneh_p:
9881   case Intrinsic::ppc_altivec_vcmpnew_p:
9882   case Intrinsic::ppc_altivec_vcmpnezb_p:
9883   case Intrinsic::ppc_altivec_vcmpnezh_p:
9884   case Intrinsic::ppc_altivec_vcmpnezw_p:
9885     if (Subtarget.hasP9Altivec()) {
9886       switch (IntrinsicID) {
9887       default:
9888         llvm_unreachable("Unknown comparison intrinsic.");
9889       case Intrinsic::ppc_altivec_vcmpneb_p:
9890         CompareOpc = 7;
9891         break;
9892       case Intrinsic::ppc_altivec_vcmpneh_p:
9893         CompareOpc = 71;
9894         break;
9895       case Intrinsic::ppc_altivec_vcmpnew_p:
9896         CompareOpc = 135;
9897         break;
9898       case Intrinsic::ppc_altivec_vcmpnezb_p:
9899         CompareOpc = 263;
9900         break;
9901       case Intrinsic::ppc_altivec_vcmpnezh_p:
9902         CompareOpc = 327;
9903         break;
9904       case Intrinsic::ppc_altivec_vcmpnezw_p:
9905         CompareOpc = 391;
9906         break;
9907       }
9908       isDot = true;
9909     } else
9910       return false;
9911     break;
9912   case Intrinsic::ppc_altivec_vcmpgefp_p:
9913     CompareOpc = 454;
9914     isDot = true;
9915     break;
9916   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9917     CompareOpc = 710;
9918     isDot = true;
9919     break;
9920   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9921     CompareOpc = 774;
9922     isDot = true;
9923     break;
9924   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9925     CompareOpc = 838;
9926     isDot = true;
9927     break;
9928   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9929     CompareOpc = 902;
9930     isDot = true;
9931     break;
9932   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9933     if (Subtarget.hasP8Altivec()) {
9934       CompareOpc = 967;
9935       isDot = true;
9936     } else
9937       return false;
9938     break;
9939   case Intrinsic::ppc_altivec_vcmpgtub_p:
9940     CompareOpc = 518;
9941     isDot = true;
9942     break;
9943   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9944     CompareOpc = 582;
9945     isDot = true;
9946     break;
9947   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9948     CompareOpc = 646;
9949     isDot = true;
9950     break;
9951   case Intrinsic::ppc_altivec_vcmpgtud_p:
9952     if (Subtarget.hasP8Altivec()) {
9953       CompareOpc = 711;
9954       isDot = true;
9955     } else
9956       return false;
9957     break;
9958 
9959   case Intrinsic::ppc_altivec_vcmpequq:
9960   case Intrinsic::ppc_altivec_vcmpgtsq:
9961   case Intrinsic::ppc_altivec_vcmpgtuq:
9962     if (!Subtarget.isISA3_1())
9963       return false;
9964     switch (IntrinsicID) {
9965     default:
9966       llvm_unreachable("Unknown comparison intrinsic.");
9967     case Intrinsic::ppc_altivec_vcmpequq:
9968       CompareOpc = 455;
9969       break;
9970     case Intrinsic::ppc_altivec_vcmpgtsq:
9971       CompareOpc = 903;
9972       break;
9973     case Intrinsic::ppc_altivec_vcmpgtuq:
9974       CompareOpc = 647;
9975       break;
9976     }
9977     break;
9978 
9979   // VSX predicate comparisons use the same infrastructure
9980   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9981   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9982   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9983   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9984   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9985   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9986     if (Subtarget.hasVSX()) {
9987       switch (IntrinsicID) {
9988       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9989         CompareOpc = 99;
9990         break;
9991       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9992         CompareOpc = 115;
9993         break;
9994       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9995         CompareOpc = 107;
9996         break;
9997       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9998         CompareOpc = 67;
9999         break;
10000       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10001         CompareOpc = 83;
10002         break;
10003       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10004         CompareOpc = 75;
10005         break;
10006       }
10007       isDot = true;
10008     } else
10009       return false;
10010     break;
10011 
10012   // Normal Comparisons.
10013   case Intrinsic::ppc_altivec_vcmpbfp:
10014     CompareOpc = 966;
10015     break;
10016   case Intrinsic::ppc_altivec_vcmpeqfp:
10017     CompareOpc = 198;
10018     break;
10019   case Intrinsic::ppc_altivec_vcmpequb:
10020     CompareOpc = 6;
10021     break;
10022   case Intrinsic::ppc_altivec_vcmpequh:
10023     CompareOpc = 70;
10024     break;
10025   case Intrinsic::ppc_altivec_vcmpequw:
10026     CompareOpc = 134;
10027     break;
10028   case Intrinsic::ppc_altivec_vcmpequd:
10029     if (Subtarget.hasP8Altivec())
10030       CompareOpc = 199;
10031     else
10032       return false;
10033     break;
10034   case Intrinsic::ppc_altivec_vcmpneb:
10035   case Intrinsic::ppc_altivec_vcmpneh:
10036   case Intrinsic::ppc_altivec_vcmpnew:
10037   case Intrinsic::ppc_altivec_vcmpnezb:
10038   case Intrinsic::ppc_altivec_vcmpnezh:
10039   case Intrinsic::ppc_altivec_vcmpnezw:
10040     if (Subtarget.hasP9Altivec())
10041       switch (IntrinsicID) {
10042       default:
10043         llvm_unreachable("Unknown comparison intrinsic.");
10044       case Intrinsic::ppc_altivec_vcmpneb:
10045         CompareOpc = 7;
10046         break;
10047       case Intrinsic::ppc_altivec_vcmpneh:
10048         CompareOpc = 71;
10049         break;
10050       case Intrinsic::ppc_altivec_vcmpnew:
10051         CompareOpc = 135;
10052         break;
10053       case Intrinsic::ppc_altivec_vcmpnezb:
10054         CompareOpc = 263;
10055         break;
10056       case Intrinsic::ppc_altivec_vcmpnezh:
10057         CompareOpc = 327;
10058         break;
10059       case Intrinsic::ppc_altivec_vcmpnezw:
10060         CompareOpc = 391;
10061         break;
10062       }
10063     else
10064       return false;
10065     break;
10066   case Intrinsic::ppc_altivec_vcmpgefp:
10067     CompareOpc = 454;
10068     break;
10069   case Intrinsic::ppc_altivec_vcmpgtfp:
10070     CompareOpc = 710;
10071     break;
10072   case Intrinsic::ppc_altivec_vcmpgtsb:
10073     CompareOpc = 774;
10074     break;
10075   case Intrinsic::ppc_altivec_vcmpgtsh:
10076     CompareOpc = 838;
10077     break;
10078   case Intrinsic::ppc_altivec_vcmpgtsw:
10079     CompareOpc = 902;
10080     break;
10081   case Intrinsic::ppc_altivec_vcmpgtsd:
10082     if (Subtarget.hasP8Altivec())
10083       CompareOpc = 967;
10084     else
10085       return false;
10086     break;
10087   case Intrinsic::ppc_altivec_vcmpgtub:
10088     CompareOpc = 518;
10089     break;
10090   case Intrinsic::ppc_altivec_vcmpgtuh:
10091     CompareOpc = 582;
10092     break;
10093   case Intrinsic::ppc_altivec_vcmpgtuw:
10094     CompareOpc = 646;
10095     break;
10096   case Intrinsic::ppc_altivec_vcmpgtud:
10097     if (Subtarget.hasP8Altivec())
10098       CompareOpc = 711;
10099     else
10100       return false;
10101     break;
10102   case Intrinsic::ppc_altivec_vcmpequq_p:
10103   case Intrinsic::ppc_altivec_vcmpgtsq_p:
10104   case Intrinsic::ppc_altivec_vcmpgtuq_p:
10105     if (!Subtarget.isISA3_1())
10106       return false;
10107     switch (IntrinsicID) {
10108     default:
10109       llvm_unreachable("Unknown comparison intrinsic.");
10110     case Intrinsic::ppc_altivec_vcmpequq_p:
10111       CompareOpc = 455;
10112       break;
10113     case Intrinsic::ppc_altivec_vcmpgtsq_p:
10114       CompareOpc = 903;
10115       break;
10116     case Intrinsic::ppc_altivec_vcmpgtuq_p:
10117       CompareOpc = 647;
10118       break;
10119     }
10120     isDot = true;
10121     break;
10122   }
10123   return true;
10124 }
10125 
10126 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10127 /// lower, do it, otherwise return null.
10128 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10129                                                    SelectionDAG &DAG) const {
10130   unsigned IntrinsicID =
10131     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10132 
10133   SDLoc dl(Op);
10134 
10135   switch (IntrinsicID) {
10136   case Intrinsic::thread_pointer:
10137     // Reads the thread pointer register, used for __builtin_thread_pointer.
10138     if (Subtarget.isPPC64())
10139       return DAG.getRegister(PPC::X13, MVT::i64);
10140     return DAG.getRegister(PPC::R2, MVT::i32);
10141 
10142   case Intrinsic::ppc_mma_disassemble_acc:
10143   case Intrinsic::ppc_vsx_disassemble_pair: {
10144     int NumVecs = 2;
10145     SDValue WideVec = Op.getOperand(1);
10146     if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
10147       NumVecs = 4;
10148       WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
10149     }
10150     SmallVector<SDValue, 4> RetOps;
10151     for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
10152       SDValue Extract = DAG.getNode(
10153           PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
10154           DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
10155                                                      : VecNo,
10156                           dl, getPointerTy(DAG.getDataLayout())));
10157       RetOps.push_back(Extract);
10158     }
10159     return DAG.getMergeValues(RetOps, dl);
10160   }
10161   }
10162 
10163   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10164   // opcode number of the comparison.
10165   int CompareOpc;
10166   bool isDot;
10167   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10168     return SDValue();    // Don't custom lower most intrinsics.
10169 
10170   // If this is a non-dot comparison, make the VCMP node and we are done.
10171   if (!isDot) {
10172     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10173                               Op.getOperand(1), Op.getOperand(2),
10174                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10175     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10176   }
10177 
10178   // Create the PPCISD altivec 'dot' comparison node.
10179   SDValue Ops[] = {
10180     Op.getOperand(2),  // LHS
10181     Op.getOperand(3),  // RHS
10182     DAG.getConstant(CompareOpc, dl, MVT::i32)
10183   };
10184   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10185   SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
10186 
10187   // Now that we have the comparison, emit a copy from the CR to a GPR.
10188   // This is flagged to the above dot comparison.
10189   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10190                                 DAG.getRegister(PPC::CR6, MVT::i32),
10191                                 CompNode.getValue(1));
10192 
10193   // Unpack the result based on how the target uses it.
10194   unsigned BitNo;   // Bit # of CR6.
10195   bool InvertBit;   // Invert result?
10196   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10197   default:  // Can't happen, don't crash on invalid number though.
10198   case 0:   // Return the value of the EQ bit of CR6.
10199     BitNo = 0; InvertBit = false;
10200     break;
10201   case 1:   // Return the inverted value of the EQ bit of CR6.
10202     BitNo = 0; InvertBit = true;
10203     break;
10204   case 2:   // Return the value of the LT bit of CR6.
10205     BitNo = 2; InvertBit = false;
10206     break;
10207   case 3:   // Return the inverted value of the LT bit of CR6.
10208     BitNo = 2; InvertBit = true;
10209     break;
10210   }
10211 
10212   // Shift the bit into the low position.
10213   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10214                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10215   // Isolate the bit.
10216   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10217                       DAG.getConstant(1, dl, MVT::i32));
10218 
10219   // If we are supposed to, toggle the bit.
10220   if (InvertBit)
10221     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10222                         DAG.getConstant(1, dl, MVT::i32));
10223   return Flags;
10224 }
10225 
10226 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10227                                                SelectionDAG &DAG) const {
10228   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10229   // the beginning of the argument list.
10230   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10231   SDLoc DL(Op);
10232   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10233   case Intrinsic::ppc_cfence: {
10234     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10235     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10236     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10237                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10238                                                   Op.getOperand(ArgStart + 1)),
10239                                       Op.getOperand(0)),
10240                    0);
10241   }
10242   default:
10243     break;
10244   }
10245   return SDValue();
10246 }
10247 
10248 // Lower scalar BSWAP64 to xxbrd.
10249 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10250   SDLoc dl(Op);
10251   // MTVSRDD
10252   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10253                    Op.getOperand(0));
10254   // XXBRD
10255   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10256   // MFVSRD
10257   int VectorIndex = 0;
10258   if (Subtarget.isLittleEndian())
10259     VectorIndex = 1;
10260   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10261                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10262   return Op;
10263 }
10264 
10265 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10266 // compared to a value that is atomically loaded (atomic loads zero-extend).
10267 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10268                                                 SelectionDAG &DAG) const {
10269   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10270          "Expecting an atomic compare-and-swap here.");
10271   SDLoc dl(Op);
10272   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10273   EVT MemVT = AtomicNode->getMemoryVT();
10274   if (MemVT.getSizeInBits() >= 32)
10275     return Op;
10276 
10277   SDValue CmpOp = Op.getOperand(2);
10278   // If this is already correctly zero-extended, leave it alone.
10279   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10280   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10281     return Op;
10282 
10283   // Clear the high bits of the compare operand.
10284   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10285   SDValue NewCmpOp =
10286     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10287                 DAG.getConstant(MaskVal, dl, MVT::i32));
10288 
10289   // Replace the existing compare operand with the properly zero-extended one.
10290   SmallVector<SDValue, 4> Ops;
10291   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10292     Ops.push_back(AtomicNode->getOperand(i));
10293   Ops[2] = NewCmpOp;
10294   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10295   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10296   auto NodeTy =
10297     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10298   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10299 }
10300 
10301 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10302                                                  SelectionDAG &DAG) const {
10303   SDLoc dl(Op);
10304   // Create a stack slot that is 16-byte aligned.
10305   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10306   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10307   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10308   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10309 
10310   // Store the input value into Value#0 of the stack slot.
10311   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10312                                MachinePointerInfo());
10313   // Load it out.
10314   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10315 }
10316 
10317 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10318                                                   SelectionDAG &DAG) const {
10319   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10320          "Should only be called for ISD::INSERT_VECTOR_ELT");
10321 
10322   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10323 
10324   EVT VT = Op.getValueType();
10325   SDLoc dl(Op);
10326   SDValue V1 = Op.getOperand(0);
10327   SDValue V2 = Op.getOperand(1);
10328   SDValue V3 = Op.getOperand(2);
10329 
10330   if (VT == MVT::v2f64 && C)
10331     return Op;
10332 
10333   if (Subtarget.isISA3_1()) {
10334     // On P10, we have legal lowering for constant and variable indices for
10335     // integer vectors.
10336     if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
10337         VT == MVT::v2i64)
10338       return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3);
10339     // For f32 and f64 vectors, we have legal lowering for variable indices.
10340     // For f32 we also have legal lowering when the element is loaded from
10341     // memory.
10342     if (VT == MVT::v4f32 || VT == MVT::v2f64) {
10343       if (!C || (VT == MVT::v4f32 && dyn_cast<LoadSDNode>(V2)))
10344         return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3);
10345       return Op;
10346     }
10347   }
10348 
10349   // Before P10, we have legal lowering for constant indices but not for
10350   // variable ones.
10351   if (!C)
10352     return SDValue();
10353 
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::LowerVectorLoad(SDValue Op,
10370                                            SelectionDAG &DAG) const {
10371   SDLoc dl(Op);
10372   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10373   SDValue LoadChain = LN->getChain();
10374   SDValue BasePtr = LN->getBasePtr();
10375   EVT VT = Op.getValueType();
10376 
10377   if (VT != MVT::v256i1 && VT != MVT::v512i1)
10378     return Op;
10379 
10380   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10381   // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
10382   // 2 or 4 vsx registers.
10383   assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
10384          "Type unsupported without MMA");
10385   assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10386          "Type unsupported without paired vector support");
10387   Align Alignment = LN->getAlign();
10388   SmallVector<SDValue, 4> Loads;
10389   SmallVector<SDValue, 4> LoadChains;
10390   unsigned NumVecs = VT.getSizeInBits() / 128;
10391   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10392     SDValue Load =
10393         DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
10394                     LN->getPointerInfo().getWithOffset(Idx * 16),
10395                     commonAlignment(Alignment, Idx * 16),
10396                     LN->getMemOperand()->getFlags(), LN->getAAInfo());
10397     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10398                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10399     Loads.push_back(Load);
10400     LoadChains.push_back(Load.getValue(1));
10401   }
10402   if (Subtarget.isLittleEndian()) {
10403     std::reverse(Loads.begin(), Loads.end());
10404     std::reverse(LoadChains.begin(), LoadChains.end());
10405   }
10406   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10407   SDValue Value =
10408       DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
10409                   dl, VT, Loads);
10410   SDValue RetOps[] = {Value, TF};
10411   return DAG.getMergeValues(RetOps, dl);
10412 }
10413 
10414 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10415                                             SelectionDAG &DAG) const {
10416   SDLoc dl(Op);
10417   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10418   SDValue StoreChain = SN->getChain();
10419   SDValue BasePtr = SN->getBasePtr();
10420   SDValue Value = SN->getValue();
10421   EVT StoreVT = Value.getValueType();
10422 
10423   if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
10424     return Op;
10425 
10426   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10427   // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
10428   // underlying registers individually.
10429   assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
10430          "Type unsupported without MMA");
10431   assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10432          "Type unsupported without paired vector support");
10433   Align Alignment = SN->getAlign();
10434   SmallVector<SDValue, 4> Stores;
10435   unsigned NumVecs = 2;
10436   if (StoreVT == MVT::v512i1) {
10437     Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
10438     NumVecs = 4;
10439   }
10440   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10441     unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
10442     SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
10443                               DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
10444     SDValue Store =
10445         DAG.getStore(StoreChain, dl, Elt, BasePtr,
10446                      SN->getPointerInfo().getWithOffset(Idx * 16),
10447                      commonAlignment(Alignment, Idx * 16),
10448                      SN->getMemOperand()->getFlags(), SN->getAAInfo());
10449     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10450                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10451     Stores.push_back(Store);
10452   }
10453   SDValue TF = DAG.getTokenFactor(dl, Stores);
10454   return TF;
10455 }
10456 
10457 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10458   SDLoc dl(Op);
10459   if (Op.getValueType() == MVT::v4i32) {
10460     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10461 
10462     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10463     // +16 as shift amt.
10464     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10465     SDValue RHSSwap =   // = vrlw RHS, 16
10466       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10467 
10468     // Shrinkify inputs to v8i16.
10469     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10470     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10471     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10472 
10473     // Low parts multiplied together, generating 32-bit results (we ignore the
10474     // top parts).
10475     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10476                                         LHS, RHS, DAG, dl, MVT::v4i32);
10477 
10478     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10479                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10480     // Shift the high parts up 16 bits.
10481     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10482                               Neg16, DAG, dl);
10483     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10484   } else if (Op.getValueType() == MVT::v16i8) {
10485     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10486     bool isLittleEndian = Subtarget.isLittleEndian();
10487 
10488     // Multiply the even 8-bit parts, producing 16-bit sums.
10489     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10490                                            LHS, RHS, DAG, dl, MVT::v8i16);
10491     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10492 
10493     // Multiply the odd 8-bit parts, producing 16-bit sums.
10494     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10495                                           LHS, RHS, DAG, dl, MVT::v8i16);
10496     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10497 
10498     // Merge the results together.  Because vmuleub and vmuloub are
10499     // instructions with a big-endian bias, we must reverse the
10500     // element numbering and reverse the meaning of "odd" and "even"
10501     // when generating little endian code.
10502     int Ops[16];
10503     for (unsigned i = 0; i != 8; ++i) {
10504       if (isLittleEndian) {
10505         Ops[i*2  ] = 2*i;
10506         Ops[i*2+1] = 2*i+16;
10507       } else {
10508         Ops[i*2  ] = 2*i+1;
10509         Ops[i*2+1] = 2*i+1+16;
10510       }
10511     }
10512     if (isLittleEndian)
10513       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10514     else
10515       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10516   } else {
10517     llvm_unreachable("Unknown mul to lower!");
10518   }
10519 }
10520 
10521 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10522   bool IsStrict = Op->isStrictFPOpcode();
10523   if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
10524       !Subtarget.hasP9Vector())
10525     return SDValue();
10526 
10527   return Op;
10528 }
10529 
10530 // Custom lowering for fpext vf32 to v2f64
10531 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10532 
10533   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10534          "Should only be called for ISD::FP_EXTEND");
10535 
10536   // FIXME: handle extends from half precision float vectors on P9.
10537   // We only want to custom lower an extend from v2f32 to v2f64.
10538   if (Op.getValueType() != MVT::v2f64 ||
10539       Op.getOperand(0).getValueType() != MVT::v2f32)
10540     return SDValue();
10541 
10542   SDLoc dl(Op);
10543   SDValue Op0 = Op.getOperand(0);
10544 
10545   switch (Op0.getOpcode()) {
10546   default:
10547     return SDValue();
10548   case ISD::EXTRACT_SUBVECTOR: {
10549     assert(Op0.getNumOperands() == 2 &&
10550            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10551            "Node should have 2 operands with second one being a constant!");
10552 
10553     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10554       return SDValue();
10555 
10556     // Custom lower is only done for high or low doubleword.
10557     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10558     if (Idx % 2 != 0)
10559       return SDValue();
10560 
10561     // Since input is v4f32, at this point Idx is either 0 or 2.
10562     // Shift to get the doubleword position we want.
10563     int DWord = Idx >> 1;
10564 
10565     // High and low word positions are different on little endian.
10566     if (Subtarget.isLittleEndian())
10567       DWord ^= 0x1;
10568 
10569     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10570                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10571   }
10572   case ISD::FADD:
10573   case ISD::FMUL:
10574   case ISD::FSUB: {
10575     SDValue NewLoad[2];
10576     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10577       // Ensure both input are loads.
10578       SDValue LdOp = Op0.getOperand(i);
10579       if (LdOp.getOpcode() != ISD::LOAD)
10580         return SDValue();
10581       // Generate new load node.
10582       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10583       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10584       NewLoad[i] = DAG.getMemIntrinsicNode(
10585           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10586           LD->getMemoryVT(), LD->getMemOperand());
10587     }
10588     SDValue NewOp =
10589         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10590                     NewLoad[1], Op0.getNode()->getFlags());
10591     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10592                        DAG.getConstant(0, dl, MVT::i32));
10593   }
10594   case ISD::LOAD: {
10595     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10596     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10597     SDValue NewLd = DAG.getMemIntrinsicNode(
10598         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10599         LD->getMemoryVT(), LD->getMemOperand());
10600     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10601                        DAG.getConstant(0, dl, MVT::i32));
10602   }
10603   }
10604   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10605 }
10606 
10607 /// LowerOperation - Provide custom lowering hooks for some operations.
10608 ///
10609 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10610   switch (Op.getOpcode()) {
10611   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10612   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10613   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10614   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10615   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10616   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10617   case ISD::STRICT_FSETCC:
10618   case ISD::STRICT_FSETCCS:
10619   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10620   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10621   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10622 
10623   // Variable argument lowering.
10624   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10625   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10626   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10627 
10628   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10629   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10630   case ISD::GET_DYNAMIC_AREA_OFFSET:
10631     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10632 
10633   // Exception handling lowering.
10634   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10635   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10636   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10637 
10638   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10639   case ISD::STORE:              return LowerSTORE(Op, DAG);
10640   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10641   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10642   case ISD::STRICT_FP_TO_UINT:
10643   case ISD::STRICT_FP_TO_SINT:
10644   case ISD::FP_TO_UINT:
10645   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10646   case ISD::STRICT_UINT_TO_FP:
10647   case ISD::STRICT_SINT_TO_FP:
10648   case ISD::UINT_TO_FP:
10649   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10650   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10651 
10652   // Lower 64-bit shifts.
10653   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10654   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10655   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10656 
10657   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
10658   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
10659 
10660   // Vector-related lowering.
10661   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10662   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10663   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10664   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10665   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10666   case ISD::MUL:                return LowerMUL(Op, DAG);
10667   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10668   case ISD::STRICT_FP_ROUND:
10669   case ISD::FP_ROUND:
10670     return LowerFP_ROUND(Op, DAG);
10671   case ISD::ROTL:               return LowerROTL(Op, DAG);
10672 
10673   // For counter-based loop handling.
10674   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10675 
10676   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10677 
10678   // Frame & Return address.
10679   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10680   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10681 
10682   case ISD::INTRINSIC_VOID:
10683     return LowerINTRINSIC_VOID(Op, DAG);
10684   case ISD::BSWAP:
10685     return LowerBSWAP(Op, DAG);
10686   case ISD::ATOMIC_CMP_SWAP:
10687     return LowerATOMIC_CMP_SWAP(Op, DAG);
10688   }
10689 }
10690 
10691 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10692                                            SmallVectorImpl<SDValue>&Results,
10693                                            SelectionDAG &DAG) const {
10694   SDLoc dl(N);
10695   switch (N->getOpcode()) {
10696   default:
10697     llvm_unreachable("Do not know how to custom type legalize this operation!");
10698   case ISD::READCYCLECOUNTER: {
10699     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10700     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10701 
10702     Results.push_back(
10703         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10704     Results.push_back(RTB.getValue(2));
10705     break;
10706   }
10707   case ISD::INTRINSIC_W_CHAIN: {
10708     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10709         Intrinsic::loop_decrement)
10710       break;
10711 
10712     assert(N->getValueType(0) == MVT::i1 &&
10713            "Unexpected result type for CTR decrement intrinsic");
10714     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10715                                  N->getValueType(0));
10716     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10717     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10718                                  N->getOperand(1));
10719 
10720     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10721     Results.push_back(NewInt.getValue(1));
10722     break;
10723   }
10724   case ISD::VAARG: {
10725     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10726       return;
10727 
10728     EVT VT = N->getValueType(0);
10729 
10730     if (VT == MVT::i64) {
10731       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10732 
10733       Results.push_back(NewNode);
10734       Results.push_back(NewNode.getValue(1));
10735     }
10736     return;
10737   }
10738   case ISD::STRICT_FP_TO_SINT:
10739   case ISD::STRICT_FP_TO_UINT:
10740   case ISD::FP_TO_SINT:
10741   case ISD::FP_TO_UINT:
10742     // LowerFP_TO_INT() can only handle f32 and f64.
10743     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
10744         MVT::ppcf128)
10745       return;
10746     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10747     return;
10748   case ISD::TRUNCATE: {
10749     if (!N->getValueType(0).isVector())
10750       return;
10751     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
10752     if (Lowered)
10753       Results.push_back(Lowered);
10754     return;
10755   }
10756   case ISD::FSHL:
10757   case ISD::FSHR:
10758     // Don't handle funnel shifts here.
10759     return;
10760   case ISD::BITCAST:
10761     // Don't handle bitcast here.
10762     return;
10763   case ISD::FP_EXTEND:
10764     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
10765     if (Lowered)
10766       Results.push_back(Lowered);
10767     return;
10768   }
10769 }
10770 
10771 //===----------------------------------------------------------------------===//
10772 //  Other Lowering Code
10773 //===----------------------------------------------------------------------===//
10774 
10775 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10776   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10777   Function *Func = Intrinsic::getDeclaration(M, Id);
10778   return Builder.CreateCall(Func, {});
10779 }
10780 
10781 // The mappings for emitLeading/TrailingFence is taken from
10782 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10783 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10784                                                  Instruction *Inst,
10785                                                  AtomicOrdering Ord) const {
10786   if (Ord == AtomicOrdering::SequentiallyConsistent)
10787     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10788   if (isReleaseOrStronger(Ord))
10789     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10790   return nullptr;
10791 }
10792 
10793 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10794                                                   Instruction *Inst,
10795                                                   AtomicOrdering Ord) const {
10796   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10797     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10798     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10799     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10800     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10801       return Builder.CreateCall(
10802           Intrinsic::getDeclaration(
10803               Builder.GetInsertBlock()->getParent()->getParent(),
10804               Intrinsic::ppc_cfence, {Inst->getType()}),
10805           {Inst});
10806     // FIXME: Can use isync for rmw operation.
10807     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10808   }
10809   return nullptr;
10810 }
10811 
10812 MachineBasicBlock *
10813 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10814                                     unsigned AtomicSize,
10815                                     unsigned BinOpcode,
10816                                     unsigned CmpOpcode,
10817                                     unsigned CmpPred) const {
10818   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10819   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10820 
10821   auto LoadMnemonic = PPC::LDARX;
10822   auto StoreMnemonic = PPC::STDCX;
10823   switch (AtomicSize) {
10824   default:
10825     llvm_unreachable("Unexpected size of atomic entity");
10826   case 1:
10827     LoadMnemonic = PPC::LBARX;
10828     StoreMnemonic = PPC::STBCX;
10829     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10830     break;
10831   case 2:
10832     LoadMnemonic = PPC::LHARX;
10833     StoreMnemonic = PPC::STHCX;
10834     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10835     break;
10836   case 4:
10837     LoadMnemonic = PPC::LWARX;
10838     StoreMnemonic = PPC::STWCX;
10839     break;
10840   case 8:
10841     LoadMnemonic = PPC::LDARX;
10842     StoreMnemonic = PPC::STDCX;
10843     break;
10844   }
10845 
10846   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10847   MachineFunction *F = BB->getParent();
10848   MachineFunction::iterator It = ++BB->getIterator();
10849 
10850   Register dest = MI.getOperand(0).getReg();
10851   Register ptrA = MI.getOperand(1).getReg();
10852   Register ptrB = MI.getOperand(2).getReg();
10853   Register incr = MI.getOperand(3).getReg();
10854   DebugLoc dl = MI.getDebugLoc();
10855 
10856   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10857   MachineBasicBlock *loop2MBB =
10858     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10859   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10860   F->insert(It, loopMBB);
10861   if (CmpOpcode)
10862     F->insert(It, loop2MBB);
10863   F->insert(It, exitMBB);
10864   exitMBB->splice(exitMBB->begin(), BB,
10865                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10866   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10867 
10868   MachineRegisterInfo &RegInfo = F->getRegInfo();
10869   Register TmpReg = (!BinOpcode) ? incr :
10870     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10871                                            : &PPC::GPRCRegClass);
10872 
10873   //  thisMBB:
10874   //   ...
10875   //   fallthrough --> loopMBB
10876   BB->addSuccessor(loopMBB);
10877 
10878   //  loopMBB:
10879   //   l[wd]arx dest, ptr
10880   //   add r0, dest, incr
10881   //   st[wd]cx. r0, ptr
10882   //   bne- loopMBB
10883   //   fallthrough --> exitMBB
10884 
10885   // For max/min...
10886   //  loopMBB:
10887   //   l[wd]arx dest, ptr
10888   //   cmpl?[wd] incr, dest
10889   //   bgt exitMBB
10890   //  loop2MBB:
10891   //   st[wd]cx. dest, ptr
10892   //   bne- loopMBB
10893   //   fallthrough --> exitMBB
10894 
10895   BB = loopMBB;
10896   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10897     .addReg(ptrA).addReg(ptrB);
10898   if (BinOpcode)
10899     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10900   if (CmpOpcode) {
10901     // Signed comparisons of byte or halfword values must be sign-extended.
10902     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10903       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10904       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10905               ExtReg).addReg(dest);
10906       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10907         .addReg(incr).addReg(ExtReg);
10908     } else
10909       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10910         .addReg(incr).addReg(dest);
10911 
10912     BuildMI(BB, dl, TII->get(PPC::BCC))
10913       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10914     BB->addSuccessor(loop2MBB);
10915     BB->addSuccessor(exitMBB);
10916     BB = loop2MBB;
10917   }
10918   BuildMI(BB, dl, TII->get(StoreMnemonic))
10919     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10920   BuildMI(BB, dl, TII->get(PPC::BCC))
10921     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10922   BB->addSuccessor(loopMBB);
10923   BB->addSuccessor(exitMBB);
10924 
10925   //  exitMBB:
10926   //   ...
10927   BB = exitMBB;
10928   return BB;
10929 }
10930 
10931 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) {
10932   switch(MI.getOpcode()) {
10933   default:
10934     return false;
10935   case PPC::COPY:
10936     return TII->isSignExtended(MI);
10937   case PPC::LHA:
10938   case PPC::LHA8:
10939   case PPC::LHAU:
10940   case PPC::LHAU8:
10941   case PPC::LHAUX:
10942   case PPC::LHAUX8:
10943   case PPC::LHAX:
10944   case PPC::LHAX8:
10945   case PPC::LWA:
10946   case PPC::LWAUX:
10947   case PPC::LWAX:
10948   case PPC::LWAX_32:
10949   case PPC::LWA_32:
10950   case PPC::PLHA:
10951   case PPC::PLHA8:
10952   case PPC::PLHA8pc:
10953   case PPC::PLHApc:
10954   case PPC::PLWA:
10955   case PPC::PLWA8:
10956   case PPC::PLWA8pc:
10957   case PPC::PLWApc:
10958   case PPC::EXTSB:
10959   case PPC::EXTSB8:
10960   case PPC::EXTSB8_32_64:
10961   case PPC::EXTSB8_rec:
10962   case PPC::EXTSB_rec:
10963   case PPC::EXTSH:
10964   case PPC::EXTSH8:
10965   case PPC::EXTSH8_32_64:
10966   case PPC::EXTSH8_rec:
10967   case PPC::EXTSH_rec:
10968   case PPC::EXTSW:
10969   case PPC::EXTSWSLI:
10970   case PPC::EXTSWSLI_32_64:
10971   case PPC::EXTSWSLI_32_64_rec:
10972   case PPC::EXTSWSLI_rec:
10973   case PPC::EXTSW_32:
10974   case PPC::EXTSW_32_64:
10975   case PPC::EXTSW_32_64_rec:
10976   case PPC::EXTSW_rec:
10977   case PPC::SRAW:
10978   case PPC::SRAWI:
10979   case PPC::SRAWI_rec:
10980   case PPC::SRAW_rec:
10981     return true;
10982   }
10983   return false;
10984 }
10985 
10986 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10987     MachineInstr &MI, MachineBasicBlock *BB,
10988     bool is8bit, // operation
10989     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10990   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10991   const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10992 
10993   // If this is a signed comparison and the value being compared is not known
10994   // to be sign extended, sign extend it here.
10995   DebugLoc dl = MI.getDebugLoc();
10996   MachineFunction *F = BB->getParent();
10997   MachineRegisterInfo &RegInfo = F->getRegInfo();
10998   Register incr = MI.getOperand(3).getReg();
10999   bool IsSignExtended = Register::isVirtualRegister(incr) &&
11000     isSignExtended(*RegInfo.getVRegDef(incr), TII);
11001 
11002   if (CmpOpcode == PPC::CMPW && !IsSignExtended) {
11003     Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11004     BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg)
11005         .addReg(MI.getOperand(3).getReg());
11006     MI.getOperand(3).setReg(ValueReg);
11007   }
11008   // If we support part-word atomic mnemonics, just use them
11009   if (Subtarget.hasPartwordAtomics())
11010     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11011                             CmpPred);
11012 
11013   // In 64 bit mode we have to use 64 bits for addresses, even though the
11014   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11015   // registers without caring whether they're 32 or 64, but here we're
11016   // doing actual arithmetic on the addresses.
11017   bool is64bit = Subtarget.isPPC64();
11018   bool isLittleEndian = Subtarget.isLittleEndian();
11019   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11020 
11021   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11022   MachineFunction::iterator It = ++BB->getIterator();
11023 
11024   Register dest = MI.getOperand(0).getReg();
11025   Register ptrA = MI.getOperand(1).getReg();
11026   Register ptrB = MI.getOperand(2).getReg();
11027 
11028   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11029   MachineBasicBlock *loop2MBB =
11030       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11031   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11032   F->insert(It, loopMBB);
11033   if (CmpOpcode)
11034     F->insert(It, loop2MBB);
11035   F->insert(It, exitMBB);
11036   exitMBB->splice(exitMBB->begin(), BB,
11037                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11038   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11039 
11040   const TargetRegisterClass *RC =
11041       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11042   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11043 
11044   Register PtrReg = RegInfo.createVirtualRegister(RC);
11045   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11046   Register ShiftReg =
11047       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11048   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11049   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11050   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11051   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11052   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11053   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11054   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11055   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11056   Register Ptr1Reg;
11057   Register TmpReg =
11058       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11059 
11060   //  thisMBB:
11061   //   ...
11062   //   fallthrough --> loopMBB
11063   BB->addSuccessor(loopMBB);
11064 
11065   // The 4-byte load must be aligned, while a char or short may be
11066   // anywhere in the word.  Hence all this nasty bookkeeping code.
11067   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11068   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11069   //   xori shift, shift1, 24 [16]
11070   //   rlwinm ptr, ptr1, 0, 0, 29
11071   //   slw incr2, incr, shift
11072   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11073   //   slw mask, mask2, shift
11074   //  loopMBB:
11075   //   lwarx tmpDest, ptr
11076   //   add tmp, tmpDest, incr2
11077   //   andc tmp2, tmpDest, mask
11078   //   and tmp3, tmp, mask
11079   //   or tmp4, tmp3, tmp2
11080   //   stwcx. tmp4, ptr
11081   //   bne- loopMBB
11082   //   fallthrough --> exitMBB
11083   //   srw dest, tmpDest, shift
11084   if (ptrA != ZeroReg) {
11085     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11086     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11087         .addReg(ptrA)
11088         .addReg(ptrB);
11089   } else {
11090     Ptr1Reg = ptrB;
11091   }
11092   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11093   // mode.
11094   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11095       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11096       .addImm(3)
11097       .addImm(27)
11098       .addImm(is8bit ? 28 : 27);
11099   if (!isLittleEndian)
11100     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11101         .addReg(Shift1Reg)
11102         .addImm(is8bit ? 24 : 16);
11103   if (is64bit)
11104     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11105         .addReg(Ptr1Reg)
11106         .addImm(0)
11107         .addImm(61);
11108   else
11109     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11110         .addReg(Ptr1Reg)
11111         .addImm(0)
11112         .addImm(0)
11113         .addImm(29);
11114   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11115   if (is8bit)
11116     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11117   else {
11118     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11119     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11120         .addReg(Mask3Reg)
11121         .addImm(65535);
11122   }
11123   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11124       .addReg(Mask2Reg)
11125       .addReg(ShiftReg);
11126 
11127   BB = loopMBB;
11128   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11129       .addReg(ZeroReg)
11130       .addReg(PtrReg);
11131   if (BinOpcode)
11132     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11133         .addReg(Incr2Reg)
11134         .addReg(TmpDestReg);
11135   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11136       .addReg(TmpDestReg)
11137       .addReg(MaskReg);
11138   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11139   if (CmpOpcode) {
11140     // For unsigned comparisons, we can directly compare the shifted values.
11141     // For signed comparisons we shift and sign extend.
11142     Register SReg = RegInfo.createVirtualRegister(GPRC);
11143     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11144         .addReg(TmpDestReg)
11145         .addReg(MaskReg);
11146     unsigned ValueReg = SReg;
11147     unsigned CmpReg = Incr2Reg;
11148     if (CmpOpcode == PPC::CMPW) {
11149       ValueReg = RegInfo.createVirtualRegister(GPRC);
11150       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11151           .addReg(SReg)
11152           .addReg(ShiftReg);
11153       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11154       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11155           .addReg(ValueReg);
11156       ValueReg = ValueSReg;
11157       CmpReg = incr;
11158     }
11159     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11160         .addReg(CmpReg)
11161         .addReg(ValueReg);
11162     BuildMI(BB, dl, TII->get(PPC::BCC))
11163         .addImm(CmpPred)
11164         .addReg(PPC::CR0)
11165         .addMBB(exitMBB);
11166     BB->addSuccessor(loop2MBB);
11167     BB->addSuccessor(exitMBB);
11168     BB = loop2MBB;
11169   }
11170   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11171   BuildMI(BB, dl, TII->get(PPC::STWCX))
11172       .addReg(Tmp4Reg)
11173       .addReg(ZeroReg)
11174       .addReg(PtrReg);
11175   BuildMI(BB, dl, TII->get(PPC::BCC))
11176       .addImm(PPC::PRED_NE)
11177       .addReg(PPC::CR0)
11178       .addMBB(loopMBB);
11179   BB->addSuccessor(loopMBB);
11180   BB->addSuccessor(exitMBB);
11181 
11182   //  exitMBB:
11183   //   ...
11184   BB = exitMBB;
11185   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11186       .addReg(TmpDestReg)
11187       .addReg(ShiftReg);
11188   return BB;
11189 }
11190 
11191 llvm::MachineBasicBlock *
11192 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11193                                     MachineBasicBlock *MBB) const {
11194   DebugLoc DL = MI.getDebugLoc();
11195   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11196   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11197 
11198   MachineFunction *MF = MBB->getParent();
11199   MachineRegisterInfo &MRI = MF->getRegInfo();
11200 
11201   const BasicBlock *BB = MBB->getBasicBlock();
11202   MachineFunction::iterator I = ++MBB->getIterator();
11203 
11204   Register DstReg = MI.getOperand(0).getReg();
11205   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11206   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11207   Register mainDstReg = MRI.createVirtualRegister(RC);
11208   Register restoreDstReg = MRI.createVirtualRegister(RC);
11209 
11210   MVT PVT = getPointerTy(MF->getDataLayout());
11211   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11212          "Invalid Pointer Size!");
11213   // For v = setjmp(buf), we generate
11214   //
11215   // thisMBB:
11216   //  SjLjSetup mainMBB
11217   //  bl mainMBB
11218   //  v_restore = 1
11219   //  b sinkMBB
11220   //
11221   // mainMBB:
11222   //  buf[LabelOffset] = LR
11223   //  v_main = 0
11224   //
11225   // sinkMBB:
11226   //  v = phi(main, restore)
11227   //
11228 
11229   MachineBasicBlock *thisMBB = MBB;
11230   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11231   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11232   MF->insert(I, mainMBB);
11233   MF->insert(I, sinkMBB);
11234 
11235   MachineInstrBuilder MIB;
11236 
11237   // Transfer the remainder of BB and its successor edges to sinkMBB.
11238   sinkMBB->splice(sinkMBB->begin(), MBB,
11239                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11240   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11241 
11242   // Note that the structure of the jmp_buf used here is not compatible
11243   // with that used by libc, and is not designed to be. Specifically, it
11244   // stores only those 'reserved' registers that LLVM does not otherwise
11245   // understand how to spill. Also, by convention, by the time this
11246   // intrinsic is called, Clang has already stored the frame address in the
11247   // first slot of the buffer and stack address in the third. Following the
11248   // X86 target code, we'll store the jump address in the second slot. We also
11249   // need to save the TOC pointer (R2) to handle jumps between shared
11250   // libraries, and that will be stored in the fourth slot. The thread
11251   // identifier (R13) is not affected.
11252 
11253   // thisMBB:
11254   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11255   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11256   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11257 
11258   // Prepare IP either in reg.
11259   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11260   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11261   Register BufReg = MI.getOperand(1).getReg();
11262 
11263   if (Subtarget.is64BitELFABI()) {
11264     setUsesTOCBasePtr(*MBB->getParent());
11265     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11266               .addReg(PPC::X2)
11267               .addImm(TOCOffset)
11268               .addReg(BufReg)
11269               .cloneMemRefs(MI);
11270   }
11271 
11272   // Naked functions never have a base pointer, and so we use r1. For all
11273   // other functions, this decision must be delayed until during PEI.
11274   unsigned BaseReg;
11275   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11276     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11277   else
11278     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11279 
11280   MIB = BuildMI(*thisMBB, MI, DL,
11281                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11282             .addReg(BaseReg)
11283             .addImm(BPOffset)
11284             .addReg(BufReg)
11285             .cloneMemRefs(MI);
11286 
11287   // Setup
11288   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11289   MIB.addRegMask(TRI->getNoPreservedMask());
11290 
11291   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11292 
11293   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11294           .addMBB(mainMBB);
11295   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11296 
11297   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11298   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11299 
11300   // mainMBB:
11301   //  mainDstReg = 0
11302   MIB =
11303       BuildMI(mainMBB, DL,
11304               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11305 
11306   // Store IP
11307   if (Subtarget.isPPC64()) {
11308     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11309             .addReg(LabelReg)
11310             .addImm(LabelOffset)
11311             .addReg(BufReg);
11312   } else {
11313     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11314             .addReg(LabelReg)
11315             .addImm(LabelOffset)
11316             .addReg(BufReg);
11317   }
11318   MIB.cloneMemRefs(MI);
11319 
11320   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11321   mainMBB->addSuccessor(sinkMBB);
11322 
11323   // sinkMBB:
11324   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11325           TII->get(PPC::PHI), DstReg)
11326     .addReg(mainDstReg).addMBB(mainMBB)
11327     .addReg(restoreDstReg).addMBB(thisMBB);
11328 
11329   MI.eraseFromParent();
11330   return sinkMBB;
11331 }
11332 
11333 MachineBasicBlock *
11334 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11335                                      MachineBasicBlock *MBB) const {
11336   DebugLoc DL = MI.getDebugLoc();
11337   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11338 
11339   MachineFunction *MF = MBB->getParent();
11340   MachineRegisterInfo &MRI = MF->getRegInfo();
11341 
11342   MVT PVT = getPointerTy(MF->getDataLayout());
11343   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11344          "Invalid Pointer Size!");
11345 
11346   const TargetRegisterClass *RC =
11347     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11348   Register Tmp = MRI.createVirtualRegister(RC);
11349   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11350   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11351   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11352   unsigned BP =
11353       (PVT == MVT::i64)
11354           ? PPC::X30
11355           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11356                                                               : PPC::R30);
11357 
11358   MachineInstrBuilder MIB;
11359 
11360   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11361   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11362   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11363   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11364 
11365   Register BufReg = MI.getOperand(0).getReg();
11366 
11367   // Reload FP (the jumped-to function may not have had a
11368   // frame pointer, and if so, then its r31 will be restored
11369   // as necessary).
11370   if (PVT == MVT::i64) {
11371     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11372             .addImm(0)
11373             .addReg(BufReg);
11374   } else {
11375     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11376             .addImm(0)
11377             .addReg(BufReg);
11378   }
11379   MIB.cloneMemRefs(MI);
11380 
11381   // Reload IP
11382   if (PVT == MVT::i64) {
11383     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11384             .addImm(LabelOffset)
11385             .addReg(BufReg);
11386   } else {
11387     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11388             .addImm(LabelOffset)
11389             .addReg(BufReg);
11390   }
11391   MIB.cloneMemRefs(MI);
11392 
11393   // Reload SP
11394   if (PVT == MVT::i64) {
11395     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11396             .addImm(SPOffset)
11397             .addReg(BufReg);
11398   } else {
11399     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11400             .addImm(SPOffset)
11401             .addReg(BufReg);
11402   }
11403   MIB.cloneMemRefs(MI);
11404 
11405   // Reload BP
11406   if (PVT == MVT::i64) {
11407     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11408             .addImm(BPOffset)
11409             .addReg(BufReg);
11410   } else {
11411     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11412             .addImm(BPOffset)
11413             .addReg(BufReg);
11414   }
11415   MIB.cloneMemRefs(MI);
11416 
11417   // Reload TOC
11418   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11419     setUsesTOCBasePtr(*MBB->getParent());
11420     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11421               .addImm(TOCOffset)
11422               .addReg(BufReg)
11423               .cloneMemRefs(MI);
11424   }
11425 
11426   // Jump
11427   BuildMI(*MBB, MI, DL,
11428           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11429   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11430 
11431   MI.eraseFromParent();
11432   return MBB;
11433 }
11434 
11435 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11436   // If the function specifically requests inline stack probes, emit them.
11437   if (MF.getFunction().hasFnAttribute("probe-stack"))
11438     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11439            "inline-asm";
11440   return false;
11441 }
11442 
11443 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11444   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11445   unsigned StackAlign = TFI->getStackAlignment();
11446   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11447          "Unexpected stack alignment");
11448   // The default stack probe size is 4096 if the function has no
11449   // stack-probe-size attribute.
11450   unsigned StackProbeSize = 4096;
11451   const Function &Fn = MF.getFunction();
11452   if (Fn.hasFnAttribute("stack-probe-size"))
11453     Fn.getFnAttribute("stack-probe-size")
11454         .getValueAsString()
11455         .getAsInteger(0, StackProbeSize);
11456   // Round down to the stack alignment.
11457   StackProbeSize &= ~(StackAlign - 1);
11458   return StackProbeSize ? StackProbeSize : StackAlign;
11459 }
11460 
11461 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11462 // into three phases. In the first phase, it uses pseudo instruction
11463 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11464 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11465 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11466 // MaxCallFrameSize so that it can calculate correct data area pointer.
11467 MachineBasicBlock *
11468 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11469                                     MachineBasicBlock *MBB) const {
11470   const bool isPPC64 = Subtarget.isPPC64();
11471   MachineFunction *MF = MBB->getParent();
11472   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11473   DebugLoc DL = MI.getDebugLoc();
11474   const unsigned ProbeSize = getStackProbeSize(*MF);
11475   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11476   MachineRegisterInfo &MRI = MF->getRegInfo();
11477   // The CFG of probing stack looks as
11478   //         +-----+
11479   //         | MBB |
11480   //         +--+--+
11481   //            |
11482   //       +----v----+
11483   //  +--->+ TestMBB +---+
11484   //  |    +----+----+   |
11485   //  |         |        |
11486   //  |   +-----v----+   |
11487   //  +---+ BlockMBB |   |
11488   //      +----------+   |
11489   //                     |
11490   //       +---------+   |
11491   //       | TailMBB +<--+
11492   //       +---------+
11493   // In MBB, calculate previous frame pointer and final stack pointer.
11494   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11495   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11496   // TailMBB is spliced via \p MI.
11497   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11498   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11499   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11500 
11501   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11502   MF->insert(MBBIter, TestMBB);
11503   MF->insert(MBBIter, BlockMBB);
11504   MF->insert(MBBIter, TailMBB);
11505 
11506   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11507   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11508 
11509   Register DstReg = MI.getOperand(0).getReg();
11510   Register NegSizeReg = MI.getOperand(1).getReg();
11511   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11512   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11513   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11514   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11515 
11516   // Since value of NegSizeReg might be realigned in prologepilog, insert a
11517   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
11518   // NegSize.
11519   unsigned ProbeOpc;
11520   if (!MRI.hasOneNonDBGUse(NegSizeReg))
11521     ProbeOpc =
11522         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
11523   else
11524     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
11525     // and NegSizeReg will be allocated in the same phyreg to avoid
11526     // redundant copy when NegSizeReg has only one use which is current MI and
11527     // will be replaced by PREPARE_PROBED_ALLOCA then.
11528     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
11529                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
11530   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
11531       .addDef(ActualNegSizeReg)
11532       .addReg(NegSizeReg)
11533       .add(MI.getOperand(2))
11534       .add(MI.getOperand(3));
11535 
11536   // Calculate final stack pointer, which equals to SP + ActualNegSize.
11537   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
11538           FinalStackPtr)
11539       .addReg(SPReg)
11540       .addReg(ActualNegSizeReg);
11541 
11542   // Materialize a scratch register for update.
11543   int64_t NegProbeSize = -(int64_t)ProbeSize;
11544   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
11545   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11546   if (!isInt<16>(NegProbeSize)) {
11547     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11548     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
11549         .addImm(NegProbeSize >> 16);
11550     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
11551             ScratchReg)
11552         .addReg(TempReg)
11553         .addImm(NegProbeSize & 0xFFFF);
11554   } else
11555     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
11556         .addImm(NegProbeSize);
11557 
11558   {
11559     // Probing leading residual part.
11560     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11561     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
11562         .addReg(ActualNegSizeReg)
11563         .addReg(ScratchReg);
11564     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11565     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
11566         .addReg(Div)
11567         .addReg(ScratchReg);
11568     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11569     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
11570         .addReg(Mul)
11571         .addReg(ActualNegSizeReg);
11572     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11573         .addReg(FramePointer)
11574         .addReg(SPReg)
11575         .addReg(NegMod);
11576   }
11577 
11578   {
11579     // Remaining part should be multiple of ProbeSize.
11580     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
11581     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
11582         .addReg(SPReg)
11583         .addReg(FinalStackPtr);
11584     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
11585         .addImm(PPC::PRED_EQ)
11586         .addReg(CmpResult)
11587         .addMBB(TailMBB);
11588     TestMBB->addSuccessor(BlockMBB);
11589     TestMBB->addSuccessor(TailMBB);
11590   }
11591 
11592   {
11593     // Touch the block.
11594     // |P...|P...|P...
11595     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11596         .addReg(FramePointer)
11597         .addReg(SPReg)
11598         .addReg(ScratchReg);
11599     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
11600     BlockMBB->addSuccessor(TestMBB);
11601   }
11602 
11603   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
11604   // DYNAREAOFFSET pseudo instruction to get the future result.
11605   Register MaxCallFrameSizeReg =
11606       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11607   BuildMI(TailMBB, DL,
11608           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
11609           MaxCallFrameSizeReg)
11610       .add(MI.getOperand(2))
11611       .add(MI.getOperand(3));
11612   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
11613       .addReg(SPReg)
11614       .addReg(MaxCallFrameSizeReg);
11615 
11616   // Splice instructions after MI to TailMBB.
11617   TailMBB->splice(TailMBB->end(), MBB,
11618                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11619   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
11620   MBB->addSuccessor(TestMBB);
11621 
11622   // Delete the pseudo instruction.
11623   MI.eraseFromParent();
11624 
11625   ++NumDynamicAllocaProbed;
11626   return TailMBB;
11627 }
11628 
11629 MachineBasicBlock *
11630 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11631                                                MachineBasicBlock *BB) const {
11632   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11633       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11634     if (Subtarget.is64BitELFABI() &&
11635         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11636         !Subtarget.isUsingPCRelativeCalls()) {
11637       // Call lowering should have added an r2 operand to indicate a dependence
11638       // on the TOC base pointer value. It can't however, because there is no
11639       // way to mark the dependence as implicit there, and so the stackmap code
11640       // will confuse it with a regular operand. Instead, add the dependence
11641       // here.
11642       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11643     }
11644 
11645     return emitPatchPoint(MI, BB);
11646   }
11647 
11648   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11649       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11650     return emitEHSjLjSetJmp(MI, BB);
11651   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11652              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11653     return emitEHSjLjLongJmp(MI, BB);
11654   }
11655 
11656   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11657 
11658   // To "insert" these instructions we actually have to insert their
11659   // control-flow patterns.
11660   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11661   MachineFunction::iterator It = ++BB->getIterator();
11662 
11663   MachineFunction *F = BB->getParent();
11664 
11665   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11666       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11667       MI.getOpcode() == PPC::SELECT_I8) {
11668     SmallVector<MachineOperand, 2> Cond;
11669     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11670         MI.getOpcode() == PPC::SELECT_CC_I8)
11671       Cond.push_back(MI.getOperand(4));
11672     else
11673       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11674     Cond.push_back(MI.getOperand(1));
11675 
11676     DebugLoc dl = MI.getDebugLoc();
11677     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11678                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11679   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11680              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11681              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11682              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11683              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11684              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11685              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11686              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11687              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11688              MI.getOpcode() == PPC::SELECT_F4 ||
11689              MI.getOpcode() == PPC::SELECT_F8 ||
11690              MI.getOpcode() == PPC::SELECT_F16 ||
11691              MI.getOpcode() == PPC::SELECT_SPE ||
11692              MI.getOpcode() == PPC::SELECT_SPE4 ||
11693              MI.getOpcode() == PPC::SELECT_VRRC ||
11694              MI.getOpcode() == PPC::SELECT_VSFRC ||
11695              MI.getOpcode() == PPC::SELECT_VSSRC ||
11696              MI.getOpcode() == PPC::SELECT_VSRC) {
11697     // The incoming instruction knows the destination vreg to set, the
11698     // condition code register to branch on, the true/false values to
11699     // select between, and a branch opcode to use.
11700 
11701     //  thisMBB:
11702     //  ...
11703     //   TrueVal = ...
11704     //   cmpTY ccX, r1, r2
11705     //   bCC copy1MBB
11706     //   fallthrough --> copy0MBB
11707     MachineBasicBlock *thisMBB = BB;
11708     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11709     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11710     DebugLoc dl = MI.getDebugLoc();
11711     F->insert(It, copy0MBB);
11712     F->insert(It, sinkMBB);
11713 
11714     // Transfer the remainder of BB and its successor edges to sinkMBB.
11715     sinkMBB->splice(sinkMBB->begin(), BB,
11716                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11717     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11718 
11719     // Next, add the true and fallthrough blocks as its successors.
11720     BB->addSuccessor(copy0MBB);
11721     BB->addSuccessor(sinkMBB);
11722 
11723     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11724         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11725         MI.getOpcode() == PPC::SELECT_F16 ||
11726         MI.getOpcode() == PPC::SELECT_SPE4 ||
11727         MI.getOpcode() == PPC::SELECT_SPE ||
11728         MI.getOpcode() == PPC::SELECT_VRRC ||
11729         MI.getOpcode() == PPC::SELECT_VSFRC ||
11730         MI.getOpcode() == PPC::SELECT_VSSRC ||
11731         MI.getOpcode() == PPC::SELECT_VSRC) {
11732       BuildMI(BB, dl, TII->get(PPC::BC))
11733           .addReg(MI.getOperand(1).getReg())
11734           .addMBB(sinkMBB);
11735     } else {
11736       unsigned SelectPred = MI.getOperand(4).getImm();
11737       BuildMI(BB, dl, TII->get(PPC::BCC))
11738           .addImm(SelectPred)
11739           .addReg(MI.getOperand(1).getReg())
11740           .addMBB(sinkMBB);
11741     }
11742 
11743     //  copy0MBB:
11744     //   %FalseValue = ...
11745     //   # fallthrough to sinkMBB
11746     BB = copy0MBB;
11747 
11748     // Update machine-CFG edges
11749     BB->addSuccessor(sinkMBB);
11750 
11751     //  sinkMBB:
11752     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11753     //  ...
11754     BB = sinkMBB;
11755     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11756         .addReg(MI.getOperand(3).getReg())
11757         .addMBB(copy0MBB)
11758         .addReg(MI.getOperand(2).getReg())
11759         .addMBB(thisMBB);
11760   } else if (MI.getOpcode() == PPC::ReadTB) {
11761     // To read the 64-bit time-base register on a 32-bit target, we read the
11762     // two halves. Should the counter have wrapped while it was being read, we
11763     // need to try again.
11764     // ...
11765     // readLoop:
11766     // mfspr Rx,TBU # load from TBU
11767     // mfspr Ry,TB  # load from TB
11768     // mfspr Rz,TBU # load from TBU
11769     // cmpw crX,Rx,Rz # check if 'old'='new'
11770     // bne readLoop   # branch if they're not equal
11771     // ...
11772 
11773     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11774     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11775     DebugLoc dl = MI.getDebugLoc();
11776     F->insert(It, readMBB);
11777     F->insert(It, sinkMBB);
11778 
11779     // Transfer the remainder of BB and its successor edges to sinkMBB.
11780     sinkMBB->splice(sinkMBB->begin(), BB,
11781                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11782     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11783 
11784     BB->addSuccessor(readMBB);
11785     BB = readMBB;
11786 
11787     MachineRegisterInfo &RegInfo = F->getRegInfo();
11788     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11789     Register LoReg = MI.getOperand(0).getReg();
11790     Register HiReg = MI.getOperand(1).getReg();
11791 
11792     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11793     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11794     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11795 
11796     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11797 
11798     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11799         .addReg(HiReg)
11800         .addReg(ReadAgainReg);
11801     BuildMI(BB, dl, TII->get(PPC::BCC))
11802         .addImm(PPC::PRED_NE)
11803         .addReg(CmpReg)
11804         .addMBB(readMBB);
11805 
11806     BB->addSuccessor(readMBB);
11807     BB->addSuccessor(sinkMBB);
11808   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11809     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11810   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11811     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11812   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11813     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11814   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11815     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11816 
11817   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11818     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11819   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11820     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11821   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11822     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11823   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11824     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11825 
11826   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11827     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11828   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11829     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11830   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11831     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11832   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11833     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11834 
11835   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11836     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11837   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11838     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11839   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11840     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11841   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11842     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11843 
11844   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11845     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11846   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11847     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11848   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11849     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11850   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11851     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11852 
11853   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11854     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11855   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11856     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11857   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11858     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11859   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11860     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11861 
11862   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11863     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11864   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11865     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11866   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11867     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11868   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11869     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11870 
11871   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11872     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11873   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11874     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11875   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11876     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11877   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11878     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11879 
11880   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11881     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11882   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11883     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11884   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11885     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11886   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11887     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11888 
11889   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11890     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11891   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11892     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11893   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11894     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11895   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11896     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11897 
11898   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11899     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11900   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11901     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11902   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11903     BB = EmitAtomicBinary(MI, BB, 4, 0);
11904   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11905     BB = EmitAtomicBinary(MI, BB, 8, 0);
11906   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11907            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11908            (Subtarget.hasPartwordAtomics() &&
11909             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11910            (Subtarget.hasPartwordAtomics() &&
11911             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11912     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11913 
11914     auto LoadMnemonic = PPC::LDARX;
11915     auto StoreMnemonic = PPC::STDCX;
11916     switch (MI.getOpcode()) {
11917     default:
11918       llvm_unreachable("Compare and swap of unknown size");
11919     case PPC::ATOMIC_CMP_SWAP_I8:
11920       LoadMnemonic = PPC::LBARX;
11921       StoreMnemonic = PPC::STBCX;
11922       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11923       break;
11924     case PPC::ATOMIC_CMP_SWAP_I16:
11925       LoadMnemonic = PPC::LHARX;
11926       StoreMnemonic = PPC::STHCX;
11927       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11928       break;
11929     case PPC::ATOMIC_CMP_SWAP_I32:
11930       LoadMnemonic = PPC::LWARX;
11931       StoreMnemonic = PPC::STWCX;
11932       break;
11933     case PPC::ATOMIC_CMP_SWAP_I64:
11934       LoadMnemonic = PPC::LDARX;
11935       StoreMnemonic = PPC::STDCX;
11936       break;
11937     }
11938     Register dest = MI.getOperand(0).getReg();
11939     Register ptrA = MI.getOperand(1).getReg();
11940     Register ptrB = MI.getOperand(2).getReg();
11941     Register oldval = MI.getOperand(3).getReg();
11942     Register newval = MI.getOperand(4).getReg();
11943     DebugLoc dl = MI.getDebugLoc();
11944 
11945     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11946     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11947     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11948     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11949     F->insert(It, loop1MBB);
11950     F->insert(It, loop2MBB);
11951     F->insert(It, midMBB);
11952     F->insert(It, exitMBB);
11953     exitMBB->splice(exitMBB->begin(), BB,
11954                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11955     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11956 
11957     //  thisMBB:
11958     //   ...
11959     //   fallthrough --> loopMBB
11960     BB->addSuccessor(loop1MBB);
11961 
11962     // loop1MBB:
11963     //   l[bhwd]arx dest, ptr
11964     //   cmp[wd] dest, oldval
11965     //   bne- midMBB
11966     // loop2MBB:
11967     //   st[bhwd]cx. newval, ptr
11968     //   bne- loopMBB
11969     //   b exitBB
11970     // midMBB:
11971     //   st[bhwd]cx. dest, ptr
11972     // exitBB:
11973     BB = loop1MBB;
11974     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11975     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11976         .addReg(oldval)
11977         .addReg(dest);
11978     BuildMI(BB, dl, TII->get(PPC::BCC))
11979         .addImm(PPC::PRED_NE)
11980         .addReg(PPC::CR0)
11981         .addMBB(midMBB);
11982     BB->addSuccessor(loop2MBB);
11983     BB->addSuccessor(midMBB);
11984 
11985     BB = loop2MBB;
11986     BuildMI(BB, dl, TII->get(StoreMnemonic))
11987         .addReg(newval)
11988         .addReg(ptrA)
11989         .addReg(ptrB);
11990     BuildMI(BB, dl, TII->get(PPC::BCC))
11991         .addImm(PPC::PRED_NE)
11992         .addReg(PPC::CR0)
11993         .addMBB(loop1MBB);
11994     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11995     BB->addSuccessor(loop1MBB);
11996     BB->addSuccessor(exitMBB);
11997 
11998     BB = midMBB;
11999     BuildMI(BB, dl, TII->get(StoreMnemonic))
12000         .addReg(dest)
12001         .addReg(ptrA)
12002         .addReg(ptrB);
12003     BB->addSuccessor(exitMBB);
12004 
12005     //  exitMBB:
12006     //   ...
12007     BB = exitMBB;
12008   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12009              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12010     // We must use 64-bit registers for addresses when targeting 64-bit,
12011     // since we're actually doing arithmetic on them.  Other registers
12012     // can be 32-bit.
12013     bool is64bit = Subtarget.isPPC64();
12014     bool isLittleEndian = Subtarget.isLittleEndian();
12015     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12016 
12017     Register dest = MI.getOperand(0).getReg();
12018     Register ptrA = MI.getOperand(1).getReg();
12019     Register ptrB = MI.getOperand(2).getReg();
12020     Register oldval = MI.getOperand(3).getReg();
12021     Register newval = MI.getOperand(4).getReg();
12022     DebugLoc dl = MI.getDebugLoc();
12023 
12024     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12025     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12026     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12027     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12028     F->insert(It, loop1MBB);
12029     F->insert(It, loop2MBB);
12030     F->insert(It, midMBB);
12031     F->insert(It, exitMBB);
12032     exitMBB->splice(exitMBB->begin(), BB,
12033                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12034     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12035 
12036     MachineRegisterInfo &RegInfo = F->getRegInfo();
12037     const TargetRegisterClass *RC =
12038         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12039     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12040 
12041     Register PtrReg = RegInfo.createVirtualRegister(RC);
12042     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12043     Register ShiftReg =
12044         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12045     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12046     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12047     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12048     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12049     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12050     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12051     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12052     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12053     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12054     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12055     Register Ptr1Reg;
12056     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12057     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12058     //  thisMBB:
12059     //   ...
12060     //   fallthrough --> loopMBB
12061     BB->addSuccessor(loop1MBB);
12062 
12063     // The 4-byte load must be aligned, while a char or short may be
12064     // anywhere in the word.  Hence all this nasty bookkeeping code.
12065     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12066     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12067     //   xori shift, shift1, 24 [16]
12068     //   rlwinm ptr, ptr1, 0, 0, 29
12069     //   slw newval2, newval, shift
12070     //   slw oldval2, oldval,shift
12071     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12072     //   slw mask, mask2, shift
12073     //   and newval3, newval2, mask
12074     //   and oldval3, oldval2, mask
12075     // loop1MBB:
12076     //   lwarx tmpDest, ptr
12077     //   and tmp, tmpDest, mask
12078     //   cmpw tmp, oldval3
12079     //   bne- midMBB
12080     // loop2MBB:
12081     //   andc tmp2, tmpDest, mask
12082     //   or tmp4, tmp2, newval3
12083     //   stwcx. tmp4, ptr
12084     //   bne- loop1MBB
12085     //   b exitBB
12086     // midMBB:
12087     //   stwcx. tmpDest, ptr
12088     // exitBB:
12089     //   srw dest, tmpDest, shift
12090     if (ptrA != ZeroReg) {
12091       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12092       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12093           .addReg(ptrA)
12094           .addReg(ptrB);
12095     } else {
12096       Ptr1Reg = ptrB;
12097     }
12098 
12099     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12100     // mode.
12101     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12102         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12103         .addImm(3)
12104         .addImm(27)
12105         .addImm(is8bit ? 28 : 27);
12106     if (!isLittleEndian)
12107       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12108           .addReg(Shift1Reg)
12109           .addImm(is8bit ? 24 : 16);
12110     if (is64bit)
12111       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12112           .addReg(Ptr1Reg)
12113           .addImm(0)
12114           .addImm(61);
12115     else
12116       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12117           .addReg(Ptr1Reg)
12118           .addImm(0)
12119           .addImm(0)
12120           .addImm(29);
12121     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12122         .addReg(newval)
12123         .addReg(ShiftReg);
12124     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12125         .addReg(oldval)
12126         .addReg(ShiftReg);
12127     if (is8bit)
12128       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12129     else {
12130       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12131       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12132           .addReg(Mask3Reg)
12133           .addImm(65535);
12134     }
12135     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12136         .addReg(Mask2Reg)
12137         .addReg(ShiftReg);
12138     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12139         .addReg(NewVal2Reg)
12140         .addReg(MaskReg);
12141     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12142         .addReg(OldVal2Reg)
12143         .addReg(MaskReg);
12144 
12145     BB = loop1MBB;
12146     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12147         .addReg(ZeroReg)
12148         .addReg(PtrReg);
12149     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12150         .addReg(TmpDestReg)
12151         .addReg(MaskReg);
12152     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12153         .addReg(TmpReg)
12154         .addReg(OldVal3Reg);
12155     BuildMI(BB, dl, TII->get(PPC::BCC))
12156         .addImm(PPC::PRED_NE)
12157         .addReg(PPC::CR0)
12158         .addMBB(midMBB);
12159     BB->addSuccessor(loop2MBB);
12160     BB->addSuccessor(midMBB);
12161 
12162     BB = loop2MBB;
12163     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12164         .addReg(TmpDestReg)
12165         .addReg(MaskReg);
12166     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12167         .addReg(Tmp2Reg)
12168         .addReg(NewVal3Reg);
12169     BuildMI(BB, dl, TII->get(PPC::STWCX))
12170         .addReg(Tmp4Reg)
12171         .addReg(ZeroReg)
12172         .addReg(PtrReg);
12173     BuildMI(BB, dl, TII->get(PPC::BCC))
12174         .addImm(PPC::PRED_NE)
12175         .addReg(PPC::CR0)
12176         .addMBB(loop1MBB);
12177     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12178     BB->addSuccessor(loop1MBB);
12179     BB->addSuccessor(exitMBB);
12180 
12181     BB = midMBB;
12182     BuildMI(BB, dl, TII->get(PPC::STWCX))
12183         .addReg(TmpDestReg)
12184         .addReg(ZeroReg)
12185         .addReg(PtrReg);
12186     BB->addSuccessor(exitMBB);
12187 
12188     //  exitMBB:
12189     //   ...
12190     BB = exitMBB;
12191     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12192         .addReg(TmpReg)
12193         .addReg(ShiftReg);
12194   } else if (MI.getOpcode() == PPC::FADDrtz) {
12195     // This pseudo performs an FADD with rounding mode temporarily forced
12196     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12197     // is not modeled at the SelectionDAG level.
12198     Register Dest = MI.getOperand(0).getReg();
12199     Register Src1 = MI.getOperand(1).getReg();
12200     Register Src2 = MI.getOperand(2).getReg();
12201     DebugLoc dl = MI.getDebugLoc();
12202 
12203     MachineRegisterInfo &RegInfo = F->getRegInfo();
12204     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12205 
12206     // Save FPSCR value.
12207     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12208 
12209     // Set rounding mode to round-to-zero.
12210     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12211         .addImm(31)
12212         .addReg(PPC::RM, RegState::ImplicitDefine);
12213 
12214     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12215         .addImm(30)
12216         .addReg(PPC::RM, RegState::ImplicitDefine);
12217 
12218     // Perform addition.
12219     auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
12220                    .addReg(Src1)
12221                    .addReg(Src2);
12222     if (MI.getFlag(MachineInstr::NoFPExcept))
12223       MIB.setMIFlag(MachineInstr::NoFPExcept);
12224 
12225     // Restore FPSCR value.
12226     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12227   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12228              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12229              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12230              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12231     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12232                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12233                           ? PPC::ANDI8_rec
12234                           : PPC::ANDI_rec;
12235     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12236                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12237 
12238     MachineRegisterInfo &RegInfo = F->getRegInfo();
12239     Register Dest = RegInfo.createVirtualRegister(
12240         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12241 
12242     DebugLoc Dl = MI.getDebugLoc();
12243     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12244         .addReg(MI.getOperand(1).getReg())
12245         .addImm(1);
12246     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12247             MI.getOperand(0).getReg())
12248         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12249   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12250     DebugLoc Dl = MI.getDebugLoc();
12251     MachineRegisterInfo &RegInfo = F->getRegInfo();
12252     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12253     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12254     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12255             MI.getOperand(0).getReg())
12256         .addReg(CRReg);
12257   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12258     DebugLoc Dl = MI.getDebugLoc();
12259     unsigned Imm = MI.getOperand(1).getImm();
12260     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12261     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12262             MI.getOperand(0).getReg())
12263         .addReg(PPC::CR0EQ);
12264   } else if (MI.getOpcode() == PPC::SETRNDi) {
12265     DebugLoc dl = MI.getDebugLoc();
12266     Register OldFPSCRReg = MI.getOperand(0).getReg();
12267 
12268     // Save FPSCR value.
12269     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12270 
12271     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12272     // the following settings:
12273     //   00 Round to nearest
12274     //   01 Round to 0
12275     //   10 Round to +inf
12276     //   11 Round to -inf
12277 
12278     // When the operand is immediate, using the two least significant bits of
12279     // the immediate to set the bits 62:63 of FPSCR.
12280     unsigned Mode = MI.getOperand(1).getImm();
12281     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12282         .addImm(31)
12283         .addReg(PPC::RM, RegState::ImplicitDefine);
12284 
12285     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12286         .addImm(30)
12287         .addReg(PPC::RM, RegState::ImplicitDefine);
12288   } else if (MI.getOpcode() == PPC::SETRND) {
12289     DebugLoc dl = MI.getDebugLoc();
12290 
12291     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12292     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12293     // If the target doesn't have DirectMove, we should use stack to do the
12294     // conversion, because the target doesn't have the instructions like mtvsrd
12295     // or mfvsrd to do this conversion directly.
12296     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12297       if (Subtarget.hasDirectMove()) {
12298         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12299           .addReg(SrcReg);
12300       } else {
12301         // Use stack to do the register copy.
12302         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12303         MachineRegisterInfo &RegInfo = F->getRegInfo();
12304         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12305         if (RC == &PPC::F8RCRegClass) {
12306           // Copy register from F8RCRegClass to G8RCRegclass.
12307           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12308                  "Unsupported RegClass.");
12309 
12310           StoreOp = PPC::STFD;
12311           LoadOp = PPC::LD;
12312         } else {
12313           // Copy register from G8RCRegClass to F8RCRegclass.
12314           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12315                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12316                  "Unsupported RegClass.");
12317         }
12318 
12319         MachineFrameInfo &MFI = F->getFrameInfo();
12320         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12321 
12322         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12323             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12324             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12325             MFI.getObjectAlign(FrameIdx));
12326 
12327         // Store the SrcReg into the stack.
12328         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12329           .addReg(SrcReg)
12330           .addImm(0)
12331           .addFrameIndex(FrameIdx)
12332           .addMemOperand(MMOStore);
12333 
12334         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12335             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12336             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12337             MFI.getObjectAlign(FrameIdx));
12338 
12339         // Load from the stack where SrcReg is stored, and save to DestReg,
12340         // so we have done the RegClass conversion from RegClass::SrcReg to
12341         // RegClass::DestReg.
12342         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12343           .addImm(0)
12344           .addFrameIndex(FrameIdx)
12345           .addMemOperand(MMOLoad);
12346       }
12347     };
12348 
12349     Register OldFPSCRReg = MI.getOperand(0).getReg();
12350 
12351     // Save FPSCR value.
12352     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12353 
12354     // When the operand is gprc register, use two least significant bits of the
12355     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12356     //
12357     // copy OldFPSCRTmpReg, OldFPSCRReg
12358     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12359     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12360     // copy NewFPSCRReg, NewFPSCRTmpReg
12361     // mtfsf 255, NewFPSCRReg
12362     MachineOperand SrcOp = MI.getOperand(1);
12363     MachineRegisterInfo &RegInfo = F->getRegInfo();
12364     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12365 
12366     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12367 
12368     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12369     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12370 
12371     // The first operand of INSERT_SUBREG should be a register which has
12372     // subregisters, we only care about its RegClass, so we should use an
12373     // IMPLICIT_DEF register.
12374     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12375     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12376       .addReg(ImDefReg)
12377       .add(SrcOp)
12378       .addImm(1);
12379 
12380     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12381     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12382       .addReg(OldFPSCRTmpReg)
12383       .addReg(ExtSrcReg)
12384       .addImm(0)
12385       .addImm(62);
12386 
12387     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12388     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12389 
12390     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12391     // bits of FPSCR.
12392     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12393       .addImm(255)
12394       .addReg(NewFPSCRReg)
12395       .addImm(0)
12396       .addImm(0);
12397   } else if (MI.getOpcode() == PPC::SETFLM) {
12398     DebugLoc Dl = MI.getDebugLoc();
12399 
12400     // Result of setflm is previous FPSCR content, so we need to save it first.
12401     Register OldFPSCRReg = MI.getOperand(0).getReg();
12402     BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12403 
12404     // Put bits in 32:63 to FPSCR.
12405     Register NewFPSCRReg = MI.getOperand(1).getReg();
12406     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12407         .addImm(255)
12408         .addReg(NewFPSCRReg)
12409         .addImm(0)
12410         .addImm(0);
12411   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12412              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12413     return emitProbedAlloca(MI, BB);
12414   } else {
12415     llvm_unreachable("Unexpected instr type to insert");
12416   }
12417 
12418   MI.eraseFromParent(); // The pseudo instruction is gone now.
12419   return BB;
12420 }
12421 
12422 //===----------------------------------------------------------------------===//
12423 // Target Optimization Hooks
12424 //===----------------------------------------------------------------------===//
12425 
12426 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12427   // For the estimates, convergence is quadratic, so we essentially double the
12428   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12429   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12430   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12431   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12432   if (VT.getScalarType() == MVT::f64)
12433     RefinementSteps++;
12434   return RefinementSteps;
12435 }
12436 
12437 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
12438                                             const DenormalMode &Mode) const {
12439   // We only have VSX Vector Test for software Square Root.
12440   EVT VT = Op.getValueType();
12441   if (!isTypeLegal(MVT::i1) ||
12442       (VT != MVT::f64 &&
12443        ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
12444     return TargetLowering::getSqrtInputTest(Op, DAG, Mode);
12445 
12446   SDLoc DL(Op);
12447   // The output register of FTSQRT is CR field.
12448   SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
12449   // ftsqrt BF,FRB
12450   // Let e_b be the unbiased exponent of the double-precision
12451   // floating-point operand in register FRB.
12452   // fe_flag is set to 1 if either of the following conditions occurs.
12453   //   - The double-precision floating-point operand in register FRB is a zero,
12454   //     a NaN, or an infinity, or a negative value.
12455   //   - e_b is less than or equal to -970.
12456   // Otherwise fe_flag is set to 0.
12457   // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
12458   // not eligible for iteration. (zero/negative/infinity/nan or unbiased
12459   // exponent is less than -970)
12460   SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
12461   return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
12462                                     FTSQRT, SRIdxVal),
12463                  0);
12464 }
12465 
12466 SDValue
12467 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
12468                                                SelectionDAG &DAG) const {
12469   // We only have VSX Vector Square Root.
12470   EVT VT = Op.getValueType();
12471   if (VT != MVT::f64 &&
12472       ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
12473     return TargetLowering::getSqrtResultForDenormInput(Op, DAG);
12474 
12475   return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
12476 }
12477 
12478 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12479                                            int Enabled, int &RefinementSteps,
12480                                            bool &UseOneConstNR,
12481                                            bool Reciprocal) const {
12482   EVT VT = Operand.getValueType();
12483   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12484       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12485       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12486       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12487     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12488       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12489 
12490     // The Newton-Raphson computation with a single constant does not provide
12491     // enough accuracy on some CPUs.
12492     UseOneConstNR = !Subtarget.needsTwoConstNR();
12493     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12494   }
12495   return SDValue();
12496 }
12497 
12498 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12499                                             int Enabled,
12500                                             int &RefinementSteps) const {
12501   EVT VT = Operand.getValueType();
12502   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12503       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12504       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12505       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12506     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12507       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12508     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12509   }
12510   return SDValue();
12511 }
12512 
12513 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12514   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12515   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12516   // enabled for division), this functionality is redundant with the default
12517   // combiner logic (once the division -> reciprocal/multiply transformation
12518   // has taken place). As a result, this matters more for older cores than for
12519   // newer ones.
12520 
12521   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12522   // reciprocal if there are two or more FDIVs (for embedded cores with only
12523   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12524   switch (Subtarget.getCPUDirective()) {
12525   default:
12526     return 3;
12527   case PPC::DIR_440:
12528   case PPC::DIR_A2:
12529   case PPC::DIR_E500:
12530   case PPC::DIR_E500mc:
12531   case PPC::DIR_E5500:
12532     return 2;
12533   }
12534 }
12535 
12536 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12537 // collapsed, and so we need to look through chains of them.
12538 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12539                                      int64_t& Offset, SelectionDAG &DAG) {
12540   if (DAG.isBaseWithConstantOffset(Loc)) {
12541     Base = Loc.getOperand(0);
12542     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12543 
12544     // The base might itself be a base plus an offset, and if so, accumulate
12545     // that as well.
12546     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12547   }
12548 }
12549 
12550 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12551                             unsigned Bytes, int Dist,
12552                             SelectionDAG &DAG) {
12553   if (VT.getSizeInBits() / 8 != Bytes)
12554     return false;
12555 
12556   SDValue BaseLoc = Base->getBasePtr();
12557   if (Loc.getOpcode() == ISD::FrameIndex) {
12558     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12559       return false;
12560     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12561     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12562     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12563     int FS  = MFI.getObjectSize(FI);
12564     int BFS = MFI.getObjectSize(BFI);
12565     if (FS != BFS || FS != (int)Bytes) return false;
12566     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12567   }
12568 
12569   SDValue Base1 = Loc, Base2 = BaseLoc;
12570   int64_t Offset1 = 0, Offset2 = 0;
12571   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12572   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12573   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12574     return true;
12575 
12576   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12577   const GlobalValue *GV1 = nullptr;
12578   const GlobalValue *GV2 = nullptr;
12579   Offset1 = 0;
12580   Offset2 = 0;
12581   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12582   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12583   if (isGA1 && isGA2 && GV1 == GV2)
12584     return Offset1 == (Offset2 + Dist*Bytes);
12585   return false;
12586 }
12587 
12588 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12589 // not enforce equality of the chain operands.
12590 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12591                             unsigned Bytes, int Dist,
12592                             SelectionDAG &DAG) {
12593   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12594     EVT VT = LS->getMemoryVT();
12595     SDValue Loc = LS->getBasePtr();
12596     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12597   }
12598 
12599   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12600     EVT VT;
12601     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12602     default: return false;
12603     case Intrinsic::ppc_altivec_lvx:
12604     case Intrinsic::ppc_altivec_lvxl:
12605     case Intrinsic::ppc_vsx_lxvw4x:
12606     case Intrinsic::ppc_vsx_lxvw4x_be:
12607       VT = MVT::v4i32;
12608       break;
12609     case Intrinsic::ppc_vsx_lxvd2x:
12610     case Intrinsic::ppc_vsx_lxvd2x_be:
12611       VT = MVT::v2f64;
12612       break;
12613     case Intrinsic::ppc_altivec_lvebx:
12614       VT = MVT::i8;
12615       break;
12616     case Intrinsic::ppc_altivec_lvehx:
12617       VT = MVT::i16;
12618       break;
12619     case Intrinsic::ppc_altivec_lvewx:
12620       VT = MVT::i32;
12621       break;
12622     }
12623 
12624     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12625   }
12626 
12627   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12628     EVT VT;
12629     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12630     default: return false;
12631     case Intrinsic::ppc_altivec_stvx:
12632     case Intrinsic::ppc_altivec_stvxl:
12633     case Intrinsic::ppc_vsx_stxvw4x:
12634       VT = MVT::v4i32;
12635       break;
12636     case Intrinsic::ppc_vsx_stxvd2x:
12637       VT = MVT::v2f64;
12638       break;
12639     case Intrinsic::ppc_vsx_stxvw4x_be:
12640       VT = MVT::v4i32;
12641       break;
12642     case Intrinsic::ppc_vsx_stxvd2x_be:
12643       VT = MVT::v2f64;
12644       break;
12645     case Intrinsic::ppc_altivec_stvebx:
12646       VT = MVT::i8;
12647       break;
12648     case Intrinsic::ppc_altivec_stvehx:
12649       VT = MVT::i16;
12650       break;
12651     case Intrinsic::ppc_altivec_stvewx:
12652       VT = MVT::i32;
12653       break;
12654     }
12655 
12656     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12657   }
12658 
12659   return false;
12660 }
12661 
12662 // Return true is there is a nearyby consecutive load to the one provided
12663 // (regardless of alignment). We search up and down the chain, looking though
12664 // token factors and other loads (but nothing else). As a result, a true result
12665 // indicates that it is safe to create a new consecutive load adjacent to the
12666 // load provided.
12667 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12668   SDValue Chain = LD->getChain();
12669   EVT VT = LD->getMemoryVT();
12670 
12671   SmallSet<SDNode *, 16> LoadRoots;
12672   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12673   SmallSet<SDNode *, 16> Visited;
12674 
12675   // First, search up the chain, branching to follow all token-factor operands.
12676   // If we find a consecutive load, then we're done, otherwise, record all
12677   // nodes just above the top-level loads and token factors.
12678   while (!Queue.empty()) {
12679     SDNode *ChainNext = Queue.pop_back_val();
12680     if (!Visited.insert(ChainNext).second)
12681       continue;
12682 
12683     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12684       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12685         return true;
12686 
12687       if (!Visited.count(ChainLD->getChain().getNode()))
12688         Queue.push_back(ChainLD->getChain().getNode());
12689     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12690       for (const SDUse &O : ChainNext->ops())
12691         if (!Visited.count(O.getNode()))
12692           Queue.push_back(O.getNode());
12693     } else
12694       LoadRoots.insert(ChainNext);
12695   }
12696 
12697   // Second, search down the chain, starting from the top-level nodes recorded
12698   // in the first phase. These top-level nodes are the nodes just above all
12699   // loads and token factors. Starting with their uses, recursively look though
12700   // all loads (just the chain uses) and token factors to find a consecutive
12701   // load.
12702   Visited.clear();
12703   Queue.clear();
12704 
12705   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12706        IE = LoadRoots.end(); I != IE; ++I) {
12707     Queue.push_back(*I);
12708 
12709     while (!Queue.empty()) {
12710       SDNode *LoadRoot = Queue.pop_back_val();
12711       if (!Visited.insert(LoadRoot).second)
12712         continue;
12713 
12714       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12715         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12716           return true;
12717 
12718       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12719            UE = LoadRoot->use_end(); UI != UE; ++UI)
12720         if (((isa<MemSDNode>(*UI) &&
12721             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12722             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12723           Queue.push_back(*UI);
12724     }
12725   }
12726 
12727   return false;
12728 }
12729 
12730 /// This function is called when we have proved that a SETCC node can be replaced
12731 /// by subtraction (and other supporting instructions) so that the result of
12732 /// comparison is kept in a GPR instead of CR. This function is purely for
12733 /// codegen purposes and has some flags to guide the codegen process.
12734 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12735                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12736   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12737 
12738   // Zero extend the operands to the largest legal integer. Originally, they
12739   // must be of a strictly smaller size.
12740   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12741                          DAG.getConstant(Size, DL, MVT::i32));
12742   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12743                          DAG.getConstant(Size, DL, MVT::i32));
12744 
12745   // Swap if needed. Depends on the condition code.
12746   if (Swap)
12747     std::swap(Op0, Op1);
12748 
12749   // Subtract extended integers.
12750   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12751 
12752   // Move the sign bit to the least significant position and zero out the rest.
12753   // Now the least significant bit carries the result of original comparison.
12754   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12755                              DAG.getConstant(Size - 1, DL, MVT::i32));
12756   auto Final = Shifted;
12757 
12758   // Complement the result if needed. Based on the condition code.
12759   if (Complement)
12760     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12761                         DAG.getConstant(1, DL, MVT::i64));
12762 
12763   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12764 }
12765 
12766 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12767                                                   DAGCombinerInfo &DCI) const {
12768   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12769 
12770   SelectionDAG &DAG = DCI.DAG;
12771   SDLoc DL(N);
12772 
12773   // Size of integers being compared has a critical role in the following
12774   // analysis, so we prefer to do this when all types are legal.
12775   if (!DCI.isAfterLegalizeDAG())
12776     return SDValue();
12777 
12778   // If all users of SETCC extend its value to a legal integer type
12779   // then we replace SETCC with a subtraction
12780   for (SDNode::use_iterator UI = N->use_begin(),
12781        UE = N->use_end(); UI != UE; ++UI) {
12782     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12783       return SDValue();
12784   }
12785 
12786   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12787   auto OpSize = N->getOperand(0).getValueSizeInBits();
12788 
12789   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12790 
12791   if (OpSize < Size) {
12792     switch (CC) {
12793     default: break;
12794     case ISD::SETULT:
12795       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12796     case ISD::SETULE:
12797       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12798     case ISD::SETUGT:
12799       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12800     case ISD::SETUGE:
12801       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12802     }
12803   }
12804 
12805   return SDValue();
12806 }
12807 
12808 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12809                                                   DAGCombinerInfo &DCI) const {
12810   SelectionDAG &DAG = DCI.DAG;
12811   SDLoc dl(N);
12812 
12813   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12814   // If we're tracking CR bits, we need to be careful that we don't have:
12815   //   trunc(binary-ops(zext(x), zext(y)))
12816   // or
12817   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12818   // such that we're unnecessarily moving things into GPRs when it would be
12819   // better to keep them in CR bits.
12820 
12821   // Note that trunc here can be an actual i1 trunc, or can be the effective
12822   // truncation that comes from a setcc or select_cc.
12823   if (N->getOpcode() == ISD::TRUNCATE &&
12824       N->getValueType(0) != MVT::i1)
12825     return SDValue();
12826 
12827   if (N->getOperand(0).getValueType() != MVT::i32 &&
12828       N->getOperand(0).getValueType() != MVT::i64)
12829     return SDValue();
12830 
12831   if (N->getOpcode() == ISD::SETCC ||
12832       N->getOpcode() == ISD::SELECT_CC) {
12833     // If we're looking at a comparison, then we need to make sure that the
12834     // high bits (all except for the first) don't matter the result.
12835     ISD::CondCode CC =
12836       cast<CondCodeSDNode>(N->getOperand(
12837         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12838     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12839 
12840     if (ISD::isSignedIntSetCC(CC)) {
12841       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12842           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12843         return SDValue();
12844     } else if (ISD::isUnsignedIntSetCC(CC)) {
12845       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12846                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12847           !DAG.MaskedValueIsZero(N->getOperand(1),
12848                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12849         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12850                                              : SDValue());
12851     } else {
12852       // This is neither a signed nor an unsigned comparison, just make sure
12853       // that the high bits are equal.
12854       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12855       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12856 
12857       // We don't really care about what is known about the first bit (if
12858       // anything), so pretend that it is known zero for both to ensure they can
12859       // be compared as constants.
12860       Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
12861       Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
12862 
12863       if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
12864           Op1Known.getConstant() != Op2Known.getConstant())
12865         return SDValue();
12866     }
12867   }
12868 
12869   // We now know that the higher-order bits are irrelevant, we just need to
12870   // make sure that all of the intermediate operations are bit operations, and
12871   // all inputs are extensions.
12872   if (N->getOperand(0).getOpcode() != ISD::AND &&
12873       N->getOperand(0).getOpcode() != ISD::OR  &&
12874       N->getOperand(0).getOpcode() != ISD::XOR &&
12875       N->getOperand(0).getOpcode() != ISD::SELECT &&
12876       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12877       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12878       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12879       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12880       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12881     return SDValue();
12882 
12883   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12884       N->getOperand(1).getOpcode() != ISD::AND &&
12885       N->getOperand(1).getOpcode() != ISD::OR  &&
12886       N->getOperand(1).getOpcode() != ISD::XOR &&
12887       N->getOperand(1).getOpcode() != ISD::SELECT &&
12888       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12889       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12890       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12891       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12892       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12893     return SDValue();
12894 
12895   SmallVector<SDValue, 4> Inputs;
12896   SmallVector<SDValue, 8> BinOps, PromOps;
12897   SmallPtrSet<SDNode *, 16> Visited;
12898 
12899   for (unsigned i = 0; i < 2; ++i) {
12900     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12901           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12902           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12903           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12904         isa<ConstantSDNode>(N->getOperand(i)))
12905       Inputs.push_back(N->getOperand(i));
12906     else
12907       BinOps.push_back(N->getOperand(i));
12908 
12909     if (N->getOpcode() == ISD::TRUNCATE)
12910       break;
12911   }
12912 
12913   // Visit all inputs, collect all binary operations (and, or, xor and
12914   // select) that are all fed by extensions.
12915   while (!BinOps.empty()) {
12916     SDValue BinOp = BinOps.pop_back_val();
12917 
12918     if (!Visited.insert(BinOp.getNode()).second)
12919       continue;
12920 
12921     PromOps.push_back(BinOp);
12922 
12923     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12924       // The condition of the select is not promoted.
12925       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12926         continue;
12927       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12928         continue;
12929 
12930       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12931             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12932             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12933            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12934           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12935         Inputs.push_back(BinOp.getOperand(i));
12936       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12937                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12938                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12939                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12940                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12941                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12942                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12943                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12944                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12945         BinOps.push_back(BinOp.getOperand(i));
12946       } else {
12947         // We have an input that is not an extension or another binary
12948         // operation; we'll abort this transformation.
12949         return SDValue();
12950       }
12951     }
12952   }
12953 
12954   // Make sure that this is a self-contained cluster of operations (which
12955   // is not quite the same thing as saying that everything has only one
12956   // use).
12957   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12958     if (isa<ConstantSDNode>(Inputs[i]))
12959       continue;
12960 
12961     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12962                               UE = Inputs[i].getNode()->use_end();
12963          UI != UE; ++UI) {
12964       SDNode *User = *UI;
12965       if (User != N && !Visited.count(User))
12966         return SDValue();
12967 
12968       // Make sure that we're not going to promote the non-output-value
12969       // operand(s) or SELECT or SELECT_CC.
12970       // FIXME: Although we could sometimes handle this, and it does occur in
12971       // practice that one of the condition inputs to the select is also one of
12972       // the outputs, we currently can't deal with this.
12973       if (User->getOpcode() == ISD::SELECT) {
12974         if (User->getOperand(0) == Inputs[i])
12975           return SDValue();
12976       } else if (User->getOpcode() == ISD::SELECT_CC) {
12977         if (User->getOperand(0) == Inputs[i] ||
12978             User->getOperand(1) == Inputs[i])
12979           return SDValue();
12980       }
12981     }
12982   }
12983 
12984   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12985     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12986                               UE = PromOps[i].getNode()->use_end();
12987          UI != UE; ++UI) {
12988       SDNode *User = *UI;
12989       if (User != N && !Visited.count(User))
12990         return SDValue();
12991 
12992       // Make sure that we're not going to promote the non-output-value
12993       // operand(s) or SELECT or SELECT_CC.
12994       // FIXME: Although we could sometimes handle this, and it does occur in
12995       // practice that one of the condition inputs to the select is also one of
12996       // the outputs, we currently can't deal with this.
12997       if (User->getOpcode() == ISD::SELECT) {
12998         if (User->getOperand(0) == PromOps[i])
12999           return SDValue();
13000       } else if (User->getOpcode() == ISD::SELECT_CC) {
13001         if (User->getOperand(0) == PromOps[i] ||
13002             User->getOperand(1) == PromOps[i])
13003           return SDValue();
13004       }
13005     }
13006   }
13007 
13008   // Replace all inputs with the extension operand.
13009   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13010     // Constants may have users outside the cluster of to-be-promoted nodes,
13011     // and so we need to replace those as we do the promotions.
13012     if (isa<ConstantSDNode>(Inputs[i]))
13013       continue;
13014     else
13015       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13016   }
13017 
13018   std::list<HandleSDNode> PromOpHandles;
13019   for (auto &PromOp : PromOps)
13020     PromOpHandles.emplace_back(PromOp);
13021 
13022   // Replace all operations (these are all the same, but have a different
13023   // (i1) return type). DAG.getNode will validate that the types of
13024   // a binary operator match, so go through the list in reverse so that
13025   // we've likely promoted both operands first. Any intermediate truncations or
13026   // extensions disappear.
13027   while (!PromOpHandles.empty()) {
13028     SDValue PromOp = PromOpHandles.back().getValue();
13029     PromOpHandles.pop_back();
13030 
13031     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13032         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13033         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13034         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13035       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13036           PromOp.getOperand(0).getValueType() != MVT::i1) {
13037         // The operand is not yet ready (see comment below).
13038         PromOpHandles.emplace_front(PromOp);
13039         continue;
13040       }
13041 
13042       SDValue RepValue = PromOp.getOperand(0);
13043       if (isa<ConstantSDNode>(RepValue))
13044         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13045 
13046       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13047       continue;
13048     }
13049 
13050     unsigned C;
13051     switch (PromOp.getOpcode()) {
13052     default:             C = 0; break;
13053     case ISD::SELECT:    C = 1; break;
13054     case ISD::SELECT_CC: C = 2; break;
13055     }
13056 
13057     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13058          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13059         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13060          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13061       // The to-be-promoted operands of this node have not yet been
13062       // promoted (this should be rare because we're going through the
13063       // list backward, but if one of the operands has several users in
13064       // this cluster of to-be-promoted nodes, it is possible).
13065       PromOpHandles.emplace_front(PromOp);
13066       continue;
13067     }
13068 
13069     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13070                                 PromOp.getNode()->op_end());
13071 
13072     // If there are any constant inputs, make sure they're replaced now.
13073     for (unsigned i = 0; i < 2; ++i)
13074       if (isa<ConstantSDNode>(Ops[C+i]))
13075         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13076 
13077     DAG.ReplaceAllUsesOfValueWith(PromOp,
13078       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13079   }
13080 
13081   // Now we're left with the initial truncation itself.
13082   if (N->getOpcode() == ISD::TRUNCATE)
13083     return N->getOperand(0);
13084 
13085   // Otherwise, this is a comparison. The operands to be compared have just
13086   // changed type (to i1), but everything else is the same.
13087   return SDValue(N, 0);
13088 }
13089 
13090 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13091                                                   DAGCombinerInfo &DCI) const {
13092   SelectionDAG &DAG = DCI.DAG;
13093   SDLoc dl(N);
13094 
13095   // If we're tracking CR bits, we need to be careful that we don't have:
13096   //   zext(binary-ops(trunc(x), trunc(y)))
13097   // or
13098   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13099   // such that we're unnecessarily moving things into CR bits that can more
13100   // efficiently stay in GPRs. Note that if we're not certain that the high
13101   // bits are set as required by the final extension, we still may need to do
13102   // some masking to get the proper behavior.
13103 
13104   // This same functionality is important on PPC64 when dealing with
13105   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13106   // the return values of functions. Because it is so similar, it is handled
13107   // here as well.
13108 
13109   if (N->getValueType(0) != MVT::i32 &&
13110       N->getValueType(0) != MVT::i64)
13111     return SDValue();
13112 
13113   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13114         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13115     return SDValue();
13116 
13117   if (N->getOperand(0).getOpcode() != ISD::AND &&
13118       N->getOperand(0).getOpcode() != ISD::OR  &&
13119       N->getOperand(0).getOpcode() != ISD::XOR &&
13120       N->getOperand(0).getOpcode() != ISD::SELECT &&
13121       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13122     return SDValue();
13123 
13124   SmallVector<SDValue, 4> Inputs;
13125   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13126   SmallPtrSet<SDNode *, 16> Visited;
13127 
13128   // Visit all inputs, collect all binary operations (and, or, xor and
13129   // select) that are all fed by truncations.
13130   while (!BinOps.empty()) {
13131     SDValue BinOp = BinOps.pop_back_val();
13132 
13133     if (!Visited.insert(BinOp.getNode()).second)
13134       continue;
13135 
13136     PromOps.push_back(BinOp);
13137 
13138     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13139       // The condition of the select is not promoted.
13140       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13141         continue;
13142       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13143         continue;
13144 
13145       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13146           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13147         Inputs.push_back(BinOp.getOperand(i));
13148       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13149                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13150                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13151                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13152                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13153         BinOps.push_back(BinOp.getOperand(i));
13154       } else {
13155         // We have an input that is not a truncation or another binary
13156         // operation; we'll abort this transformation.
13157         return SDValue();
13158       }
13159     }
13160   }
13161 
13162   // The operands of a select that must be truncated when the select is
13163   // promoted because the operand is actually part of the to-be-promoted set.
13164   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13165 
13166   // Make sure that this is a self-contained cluster of operations (which
13167   // is not quite the same thing as saying that everything has only one
13168   // use).
13169   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13170     if (isa<ConstantSDNode>(Inputs[i]))
13171       continue;
13172 
13173     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13174                               UE = Inputs[i].getNode()->use_end();
13175          UI != UE; ++UI) {
13176       SDNode *User = *UI;
13177       if (User != N && !Visited.count(User))
13178         return SDValue();
13179 
13180       // If we're going to promote the non-output-value operand(s) or SELECT or
13181       // SELECT_CC, record them for truncation.
13182       if (User->getOpcode() == ISD::SELECT) {
13183         if (User->getOperand(0) == Inputs[i])
13184           SelectTruncOp[0].insert(std::make_pair(User,
13185                                     User->getOperand(0).getValueType()));
13186       } else if (User->getOpcode() == ISD::SELECT_CC) {
13187         if (User->getOperand(0) == Inputs[i])
13188           SelectTruncOp[0].insert(std::make_pair(User,
13189                                     User->getOperand(0).getValueType()));
13190         if (User->getOperand(1) == Inputs[i])
13191           SelectTruncOp[1].insert(std::make_pair(User,
13192                                     User->getOperand(1).getValueType()));
13193       }
13194     }
13195   }
13196 
13197   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13198     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13199                               UE = PromOps[i].getNode()->use_end();
13200          UI != UE; ++UI) {
13201       SDNode *User = *UI;
13202       if (User != N && !Visited.count(User))
13203         return SDValue();
13204 
13205       // If we're going to promote the non-output-value operand(s) or SELECT or
13206       // SELECT_CC, record them for truncation.
13207       if (User->getOpcode() == ISD::SELECT) {
13208         if (User->getOperand(0) == PromOps[i])
13209           SelectTruncOp[0].insert(std::make_pair(User,
13210                                     User->getOperand(0).getValueType()));
13211       } else if (User->getOpcode() == ISD::SELECT_CC) {
13212         if (User->getOperand(0) == PromOps[i])
13213           SelectTruncOp[0].insert(std::make_pair(User,
13214                                     User->getOperand(0).getValueType()));
13215         if (User->getOperand(1) == PromOps[i])
13216           SelectTruncOp[1].insert(std::make_pair(User,
13217                                     User->getOperand(1).getValueType()));
13218       }
13219     }
13220   }
13221 
13222   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13223   bool ReallyNeedsExt = false;
13224   if (N->getOpcode() != ISD::ANY_EXTEND) {
13225     // If all of the inputs are not already sign/zero extended, then
13226     // we'll still need to do that at the end.
13227     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13228       if (isa<ConstantSDNode>(Inputs[i]))
13229         continue;
13230 
13231       unsigned OpBits =
13232         Inputs[i].getOperand(0).getValueSizeInBits();
13233       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13234 
13235       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13236            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13237                                   APInt::getHighBitsSet(OpBits,
13238                                                         OpBits-PromBits))) ||
13239           (N->getOpcode() == ISD::SIGN_EXTEND &&
13240            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13241              (OpBits-(PromBits-1)))) {
13242         ReallyNeedsExt = true;
13243         break;
13244       }
13245     }
13246   }
13247 
13248   // Replace all inputs, either with the truncation operand, or a
13249   // truncation or extension to the final output type.
13250   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13251     // Constant inputs need to be replaced with the to-be-promoted nodes that
13252     // use them because they might have users outside of the cluster of
13253     // promoted nodes.
13254     if (isa<ConstantSDNode>(Inputs[i]))
13255       continue;
13256 
13257     SDValue InSrc = Inputs[i].getOperand(0);
13258     if (Inputs[i].getValueType() == N->getValueType(0))
13259       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13260     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13261       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13262         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13263     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13264       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13265         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13266     else
13267       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13268         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13269   }
13270 
13271   std::list<HandleSDNode> PromOpHandles;
13272   for (auto &PromOp : PromOps)
13273     PromOpHandles.emplace_back(PromOp);
13274 
13275   // Replace all operations (these are all the same, but have a different
13276   // (promoted) return type). DAG.getNode will validate that the types of
13277   // a binary operator match, so go through the list in reverse so that
13278   // we've likely promoted both operands first.
13279   while (!PromOpHandles.empty()) {
13280     SDValue PromOp = PromOpHandles.back().getValue();
13281     PromOpHandles.pop_back();
13282 
13283     unsigned C;
13284     switch (PromOp.getOpcode()) {
13285     default:             C = 0; break;
13286     case ISD::SELECT:    C = 1; break;
13287     case ISD::SELECT_CC: C = 2; break;
13288     }
13289 
13290     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13291          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13292         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13293          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13294       // The to-be-promoted operands of this node have not yet been
13295       // promoted (this should be rare because we're going through the
13296       // list backward, but if one of the operands has several users in
13297       // this cluster of to-be-promoted nodes, it is possible).
13298       PromOpHandles.emplace_front(PromOp);
13299       continue;
13300     }
13301 
13302     // For SELECT and SELECT_CC nodes, we do a similar check for any
13303     // to-be-promoted comparison inputs.
13304     if (PromOp.getOpcode() == ISD::SELECT ||
13305         PromOp.getOpcode() == ISD::SELECT_CC) {
13306       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13307            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13308           (SelectTruncOp[1].count(PromOp.getNode()) &&
13309            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13310         PromOpHandles.emplace_front(PromOp);
13311         continue;
13312       }
13313     }
13314 
13315     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13316                                 PromOp.getNode()->op_end());
13317 
13318     // If this node has constant inputs, then they'll need to be promoted here.
13319     for (unsigned i = 0; i < 2; ++i) {
13320       if (!isa<ConstantSDNode>(Ops[C+i]))
13321         continue;
13322       if (Ops[C+i].getValueType() == N->getValueType(0))
13323         continue;
13324 
13325       if (N->getOpcode() == ISD::SIGN_EXTEND)
13326         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13327       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13328         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13329       else
13330         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13331     }
13332 
13333     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13334     // truncate them again to the original value type.
13335     if (PromOp.getOpcode() == ISD::SELECT ||
13336         PromOp.getOpcode() == ISD::SELECT_CC) {
13337       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13338       if (SI0 != SelectTruncOp[0].end())
13339         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13340       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13341       if (SI1 != SelectTruncOp[1].end())
13342         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13343     }
13344 
13345     DAG.ReplaceAllUsesOfValueWith(PromOp,
13346       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13347   }
13348 
13349   // Now we're left with the initial extension itself.
13350   if (!ReallyNeedsExt)
13351     return N->getOperand(0);
13352 
13353   // To zero extend, just mask off everything except for the first bit (in the
13354   // i1 case).
13355   if (N->getOpcode() == ISD::ZERO_EXTEND)
13356     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13357                        DAG.getConstant(APInt::getLowBitsSet(
13358                                          N->getValueSizeInBits(0), PromBits),
13359                                        dl, N->getValueType(0)));
13360 
13361   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13362          "Invalid extension type");
13363   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13364   SDValue ShiftCst =
13365       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13366   return DAG.getNode(
13367       ISD::SRA, dl, N->getValueType(0),
13368       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13369       ShiftCst);
13370 }
13371 
13372 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13373                                         DAGCombinerInfo &DCI) const {
13374   assert(N->getOpcode() == ISD::SETCC &&
13375          "Should be called with a SETCC node");
13376 
13377   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13378   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13379     SDValue LHS = N->getOperand(0);
13380     SDValue RHS = N->getOperand(1);
13381 
13382     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13383     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13384         LHS.hasOneUse())
13385       std::swap(LHS, RHS);
13386 
13387     // x == 0-y --> x+y == 0
13388     // x != 0-y --> x+y != 0
13389     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13390         RHS.hasOneUse()) {
13391       SDLoc DL(N);
13392       SelectionDAG &DAG = DCI.DAG;
13393       EVT VT = N->getValueType(0);
13394       EVT OpVT = LHS.getValueType();
13395       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13396       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13397     }
13398   }
13399 
13400   return DAGCombineTruncBoolExt(N, DCI);
13401 }
13402 
13403 // Is this an extending load from an f32 to an f64?
13404 static bool isFPExtLoad(SDValue Op) {
13405   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13406     return LD->getExtensionType() == ISD::EXTLOAD &&
13407       Op.getValueType() == MVT::f64;
13408   return false;
13409 }
13410 
13411 /// Reduces the number of fp-to-int conversion when building a vector.
13412 ///
13413 /// If this vector is built out of floating to integer conversions,
13414 /// transform it to a vector built out of floating point values followed by a
13415 /// single floating to integer conversion of the vector.
13416 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13417 /// becomes (fptosi (build_vector ($A, $B, ...)))
13418 SDValue PPCTargetLowering::
13419 combineElementTruncationToVectorTruncation(SDNode *N,
13420                                            DAGCombinerInfo &DCI) const {
13421   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13422          "Should be called with a BUILD_VECTOR node");
13423 
13424   SelectionDAG &DAG = DCI.DAG;
13425   SDLoc dl(N);
13426 
13427   SDValue FirstInput = N->getOperand(0);
13428   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13429          "The input operand must be an fp-to-int conversion.");
13430 
13431   // This combine happens after legalization so the fp_to_[su]i nodes are
13432   // already converted to PPCSISD nodes.
13433   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13434   if (FirstConversion == PPCISD::FCTIDZ ||
13435       FirstConversion == PPCISD::FCTIDUZ ||
13436       FirstConversion == PPCISD::FCTIWZ ||
13437       FirstConversion == PPCISD::FCTIWUZ) {
13438     bool IsSplat = true;
13439     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13440       FirstConversion == PPCISD::FCTIWUZ;
13441     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13442     SmallVector<SDValue, 4> Ops;
13443     EVT TargetVT = N->getValueType(0);
13444     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13445       SDValue NextOp = N->getOperand(i);
13446       if (NextOp.getOpcode() != PPCISD::MFVSR)
13447         return SDValue();
13448       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13449       if (NextConversion != FirstConversion)
13450         return SDValue();
13451       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13452       // This is not valid if the input was originally double precision. It is
13453       // also not profitable to do unless this is an extending load in which
13454       // case doing this combine will allow us to combine consecutive loads.
13455       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13456         return SDValue();
13457       if (N->getOperand(i) != FirstInput)
13458         IsSplat = false;
13459     }
13460 
13461     // If this is a splat, we leave it as-is since there will be only a single
13462     // fp-to-int conversion followed by a splat of the integer. This is better
13463     // for 32-bit and smaller ints and neutral for 64-bit ints.
13464     if (IsSplat)
13465       return SDValue();
13466 
13467     // Now that we know we have the right type of node, get its operands
13468     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13469       SDValue In = N->getOperand(i).getOperand(0);
13470       if (Is32Bit) {
13471         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13472         // here, we know that all inputs are extending loads so this is safe).
13473         if (In.isUndef())
13474           Ops.push_back(DAG.getUNDEF(SrcVT));
13475         else {
13476           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13477                                       MVT::f32, In.getOperand(0),
13478                                       DAG.getIntPtrConstant(1, dl));
13479           Ops.push_back(Trunc);
13480         }
13481       } else
13482         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13483     }
13484 
13485     unsigned Opcode;
13486     if (FirstConversion == PPCISD::FCTIDZ ||
13487         FirstConversion == PPCISD::FCTIWZ)
13488       Opcode = ISD::FP_TO_SINT;
13489     else
13490       Opcode = ISD::FP_TO_UINT;
13491 
13492     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13493     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13494     return DAG.getNode(Opcode, dl, TargetVT, BV);
13495   }
13496   return SDValue();
13497 }
13498 
13499 /// Reduce the number of loads when building a vector.
13500 ///
13501 /// Building a vector out of multiple loads can be converted to a load
13502 /// of the vector type if the loads are consecutive. If the loads are
13503 /// consecutive but in descending order, a shuffle is added at the end
13504 /// to reorder the vector.
13505 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13506   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13507          "Should be called with a BUILD_VECTOR node");
13508 
13509   SDLoc dl(N);
13510 
13511   // Return early for non byte-sized type, as they can't be consecutive.
13512   if (!N->getValueType(0).getVectorElementType().isByteSized())
13513     return SDValue();
13514 
13515   bool InputsAreConsecutiveLoads = true;
13516   bool InputsAreReverseConsecutive = true;
13517   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13518   SDValue FirstInput = N->getOperand(0);
13519   bool IsRoundOfExtLoad = false;
13520 
13521   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13522       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13523     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13524     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13525   }
13526   // Not a build vector of (possibly fp_rounded) loads.
13527   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13528       N->getNumOperands() == 1)
13529     return SDValue();
13530 
13531   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13532     // If any inputs are fp_round(extload), they all must be.
13533     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13534       return SDValue();
13535 
13536     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13537       N->getOperand(i);
13538     if (NextInput.getOpcode() != ISD::LOAD)
13539       return SDValue();
13540 
13541     SDValue PreviousInput =
13542       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13543     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13544     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13545 
13546     // If any inputs are fp_round(extload), they all must be.
13547     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13548       return SDValue();
13549 
13550     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13551       InputsAreConsecutiveLoads = false;
13552     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13553       InputsAreReverseConsecutive = false;
13554 
13555     // Exit early if the loads are neither consecutive nor reverse consecutive.
13556     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13557       return SDValue();
13558   }
13559 
13560   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13561          "The loads cannot be both consecutive and reverse consecutive.");
13562 
13563   SDValue FirstLoadOp =
13564     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13565   SDValue LastLoadOp =
13566     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13567                        N->getOperand(N->getNumOperands()-1);
13568 
13569   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13570   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13571   if (InputsAreConsecutiveLoads) {
13572     assert(LD1 && "Input needs to be a LoadSDNode.");
13573     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13574                        LD1->getBasePtr(), LD1->getPointerInfo(),
13575                        LD1->getAlignment());
13576   }
13577   if (InputsAreReverseConsecutive) {
13578     assert(LDL && "Input needs to be a LoadSDNode.");
13579     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13580                                LDL->getBasePtr(), LDL->getPointerInfo(),
13581                                LDL->getAlignment());
13582     SmallVector<int, 16> Ops;
13583     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13584       Ops.push_back(i);
13585 
13586     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13587                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13588   }
13589   return SDValue();
13590 }
13591 
13592 // This function adds the required vector_shuffle needed to get
13593 // the elements of the vector extract in the correct position
13594 // as specified by the CorrectElems encoding.
13595 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13596                                       SDValue Input, uint64_t Elems,
13597                                       uint64_t CorrectElems) {
13598   SDLoc dl(N);
13599 
13600   unsigned NumElems = Input.getValueType().getVectorNumElements();
13601   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13602 
13603   // Knowing the element indices being extracted from the original
13604   // vector and the order in which they're being inserted, just put
13605   // them at element indices required for the instruction.
13606   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13607     if (DAG.getDataLayout().isLittleEndian())
13608       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13609     else
13610       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13611     CorrectElems = CorrectElems >> 8;
13612     Elems = Elems >> 8;
13613   }
13614 
13615   SDValue Shuffle =
13616       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13617                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13618 
13619   EVT VT = N->getValueType(0);
13620   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13621 
13622   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13623                                Input.getValueType().getVectorElementType(),
13624                                VT.getVectorNumElements());
13625   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13626                      DAG.getValueType(ExtVT));
13627 }
13628 
13629 // Look for build vector patterns where input operands come from sign
13630 // extended vector_extract elements of specific indices. If the correct indices
13631 // aren't used, add a vector shuffle to fix up the indices and create
13632 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13633 // during instruction selection.
13634 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13635   // This array encodes the indices that the vector sign extend instructions
13636   // extract from when extending from one type to another for both BE and LE.
13637   // The right nibble of each byte corresponds to the LE incides.
13638   // and the left nibble of each byte corresponds to the BE incides.
13639   // For example: 0x3074B8FC  byte->word
13640   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13641   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13642   // For example: 0x000070F8  byte->double word
13643   // For LE: the allowed indices are: 0x0,0x8
13644   // For BE: the allowed indices are: 0x7,0xF
13645   uint64_t TargetElems[] = {
13646       0x3074B8FC, // b->w
13647       0x000070F8, // b->d
13648       0x10325476, // h->w
13649       0x00003074, // h->d
13650       0x00001032, // w->d
13651   };
13652 
13653   uint64_t Elems = 0;
13654   int Index;
13655   SDValue Input;
13656 
13657   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13658     if (!Op)
13659       return false;
13660     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13661         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13662       return false;
13663 
13664     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13665     // of the right width.
13666     SDValue Extract = Op.getOperand(0);
13667     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13668       Extract = Extract.getOperand(0);
13669     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13670       return false;
13671 
13672     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13673     if (!ExtOp)
13674       return false;
13675 
13676     Index = ExtOp->getZExtValue();
13677     if (Input && Input != Extract.getOperand(0))
13678       return false;
13679 
13680     if (!Input)
13681       Input = Extract.getOperand(0);
13682 
13683     Elems = Elems << 8;
13684     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13685     Elems |= Index;
13686 
13687     return true;
13688   };
13689 
13690   // If the build vector operands aren't sign extended vector extracts,
13691   // of the same input vector, then return.
13692   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13693     if (!isSExtOfVecExtract(N->getOperand(i))) {
13694       return SDValue();
13695     }
13696   }
13697 
13698   // If the vector extract indicies are not correct, add the appropriate
13699   // vector_shuffle.
13700   int TgtElemArrayIdx;
13701   int InputSize = Input.getValueType().getScalarSizeInBits();
13702   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13703   if (InputSize + OutputSize == 40)
13704     TgtElemArrayIdx = 0;
13705   else if (InputSize + OutputSize == 72)
13706     TgtElemArrayIdx = 1;
13707   else if (InputSize + OutputSize == 48)
13708     TgtElemArrayIdx = 2;
13709   else if (InputSize + OutputSize == 80)
13710     TgtElemArrayIdx = 3;
13711   else if (InputSize + OutputSize == 96)
13712     TgtElemArrayIdx = 4;
13713   else
13714     return SDValue();
13715 
13716   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13717   CorrectElems = DAG.getDataLayout().isLittleEndian()
13718                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13719                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13720   if (Elems != CorrectElems) {
13721     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13722   }
13723 
13724   // Regular lowering will catch cases where a shuffle is not needed.
13725   return SDValue();
13726 }
13727 
13728 // Look for the pattern of a load from a narrow width to i128, feeding
13729 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
13730 // (LXVRZX). This node represents a zero extending load that will be matched
13731 // to the Load VSX Vector Rightmost instructions.
13732 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
13733   SDLoc DL(N);
13734 
13735   // This combine is only eligible for a BUILD_VECTOR of v1i128.
13736   if (N->getValueType(0) != MVT::v1i128)
13737     return SDValue();
13738 
13739   SDValue Operand = N->getOperand(0);
13740   // Proceed with the transformation if the operand to the BUILD_VECTOR
13741   // is a load instruction.
13742   if (Operand.getOpcode() != ISD::LOAD)
13743     return SDValue();
13744 
13745   LoadSDNode *LD = dyn_cast<LoadSDNode>(Operand);
13746   EVT MemoryType = LD->getMemoryVT();
13747 
13748   // This transformation is only valid if the we are loading either a byte,
13749   // halfword, word, or doubleword.
13750   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
13751                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
13752 
13753   // Ensure that the load from the narrow width is being zero extended to i128.
13754   if (!ValidLDType ||
13755       (LD->getExtensionType() != ISD::ZEXTLOAD &&
13756        LD->getExtensionType() != ISD::EXTLOAD))
13757     return SDValue();
13758 
13759   SDValue LoadOps[] = {
13760       LD->getChain(), LD->getBasePtr(),
13761       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
13762 
13763   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
13764                                  DAG.getVTList(MVT::v1i128, MVT::Other),
13765                                  LoadOps, MemoryType, LD->getMemOperand());
13766 }
13767 
13768 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13769                                                  DAGCombinerInfo &DCI) const {
13770   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13771          "Should be called with a BUILD_VECTOR node");
13772 
13773   SelectionDAG &DAG = DCI.DAG;
13774   SDLoc dl(N);
13775 
13776   if (!Subtarget.hasVSX())
13777     return SDValue();
13778 
13779   // The target independent DAG combiner will leave a build_vector of
13780   // float-to-int conversions intact. We can generate MUCH better code for
13781   // a float-to-int conversion of a vector of floats.
13782   SDValue FirstInput = N->getOperand(0);
13783   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13784     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13785     if (Reduced)
13786       return Reduced;
13787   }
13788 
13789   // If we're building a vector out of consecutive loads, just load that
13790   // vector type.
13791   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13792   if (Reduced)
13793     return Reduced;
13794 
13795   // If we're building a vector out of extended elements from another vector
13796   // we have P9 vector integer extend instructions. The code assumes legal
13797   // input types (i.e. it can't handle things like v4i16) so do not run before
13798   // legalization.
13799   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13800     Reduced = combineBVOfVecSExt(N, DAG);
13801     if (Reduced)
13802       return Reduced;
13803   }
13804 
13805   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
13806   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
13807   // is a load from <valid narrow width> to i128.
13808   if (Subtarget.isISA3_1()) {
13809     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
13810     if (BVOfZLoad)
13811       return BVOfZLoad;
13812   }
13813 
13814   if (N->getValueType(0) != MVT::v2f64)
13815     return SDValue();
13816 
13817   // Looking for:
13818   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13819   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13820       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13821     return SDValue();
13822   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13823       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13824     return SDValue();
13825   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13826     return SDValue();
13827 
13828   SDValue Ext1 = FirstInput.getOperand(0);
13829   SDValue Ext2 = N->getOperand(1).getOperand(0);
13830   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13831      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13832     return SDValue();
13833 
13834   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13835   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13836   if (!Ext1Op || !Ext2Op)
13837     return SDValue();
13838   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13839       Ext1.getOperand(0) != Ext2.getOperand(0))
13840     return SDValue();
13841 
13842   int FirstElem = Ext1Op->getZExtValue();
13843   int SecondElem = Ext2Op->getZExtValue();
13844   int SubvecIdx;
13845   if (FirstElem == 0 && SecondElem == 1)
13846     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13847   else if (FirstElem == 2 && SecondElem == 3)
13848     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13849   else
13850     return SDValue();
13851 
13852   SDValue SrcVec = Ext1.getOperand(0);
13853   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13854     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13855   return DAG.getNode(NodeType, dl, MVT::v2f64,
13856                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13857 }
13858 
13859 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13860                                               DAGCombinerInfo &DCI) const {
13861   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13862           N->getOpcode() == ISD::UINT_TO_FP) &&
13863          "Need an int -> FP conversion node here");
13864 
13865   if (useSoftFloat() || !Subtarget.has64BitSupport())
13866     return SDValue();
13867 
13868   SelectionDAG &DAG = DCI.DAG;
13869   SDLoc dl(N);
13870   SDValue Op(N, 0);
13871 
13872   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13873   // from the hardware.
13874   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13875     return SDValue();
13876   if (!Op.getOperand(0).getValueType().isSimple())
13877     return SDValue();
13878   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13879       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13880     return SDValue();
13881 
13882   SDValue FirstOperand(Op.getOperand(0));
13883   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13884     (FirstOperand.getValueType() == MVT::i8 ||
13885      FirstOperand.getValueType() == MVT::i16);
13886   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13887     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13888     bool DstDouble = Op.getValueType() == MVT::f64;
13889     unsigned ConvOp = Signed ?
13890       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13891       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13892     SDValue WidthConst =
13893       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13894                             dl, false);
13895     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13896     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13897     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13898                                          DAG.getVTList(MVT::f64, MVT::Other),
13899                                          Ops, MVT::i8, LDN->getMemOperand());
13900 
13901     // For signed conversion, we need to sign-extend the value in the VSR
13902     if (Signed) {
13903       SDValue ExtOps[] = { Ld, WidthConst };
13904       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13905       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13906     } else
13907       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13908   }
13909 
13910 
13911   // For i32 intermediate values, unfortunately, the conversion functions
13912   // leave the upper 32 bits of the value are undefined. Within the set of
13913   // scalar instructions, we have no method for zero- or sign-extending the
13914   // value. Thus, we cannot handle i32 intermediate values here.
13915   if (Op.getOperand(0).getValueType() == MVT::i32)
13916     return SDValue();
13917 
13918   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13919          "UINT_TO_FP is supported only with FPCVT");
13920 
13921   // If we have FCFIDS, then use it when converting to single-precision.
13922   // Otherwise, convert to double-precision and then round.
13923   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13924                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13925                                                             : PPCISD::FCFIDS)
13926                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13927                                                             : PPCISD::FCFID);
13928   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13929                   ? MVT::f32
13930                   : MVT::f64;
13931 
13932   // If we're converting from a float, to an int, and back to a float again,
13933   // then we don't need the store/load pair at all.
13934   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13935        Subtarget.hasFPCVT()) ||
13936       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13937     SDValue Src = Op.getOperand(0).getOperand(0);
13938     if (Src.getValueType() == MVT::f32) {
13939       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13940       DCI.AddToWorklist(Src.getNode());
13941     } else if (Src.getValueType() != MVT::f64) {
13942       // Make sure that we don't pick up a ppc_fp128 source value.
13943       return SDValue();
13944     }
13945 
13946     unsigned FCTOp =
13947       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13948                                                         PPCISD::FCTIDUZ;
13949 
13950     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13951     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13952 
13953     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13954       FP = DAG.getNode(ISD::FP_ROUND, dl,
13955                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13956       DCI.AddToWorklist(FP.getNode());
13957     }
13958 
13959     return FP;
13960   }
13961 
13962   return SDValue();
13963 }
13964 
13965 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13966 // builtins) into loads with swaps.
13967 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13968                                               DAGCombinerInfo &DCI) const {
13969   SelectionDAG &DAG = DCI.DAG;
13970   SDLoc dl(N);
13971   SDValue Chain;
13972   SDValue Base;
13973   MachineMemOperand *MMO;
13974 
13975   switch (N->getOpcode()) {
13976   default:
13977     llvm_unreachable("Unexpected opcode for little endian VSX load");
13978   case ISD::LOAD: {
13979     LoadSDNode *LD = cast<LoadSDNode>(N);
13980     Chain = LD->getChain();
13981     Base = LD->getBasePtr();
13982     MMO = LD->getMemOperand();
13983     // If the MMO suggests this isn't a load of a full vector, leave
13984     // things alone.  For a built-in, we have to make the change for
13985     // correctness, so if there is a size problem that will be a bug.
13986     if (MMO->getSize() < 16)
13987       return SDValue();
13988     break;
13989   }
13990   case ISD::INTRINSIC_W_CHAIN: {
13991     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13992     Chain = Intrin->getChain();
13993     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13994     // us what we want. Get operand 2 instead.
13995     Base = Intrin->getOperand(2);
13996     MMO = Intrin->getMemOperand();
13997     break;
13998   }
13999   }
14000 
14001   MVT VecTy = N->getValueType(0).getSimpleVT();
14002 
14003   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
14004   // aligned and the type is a vector with elements up to 4 bytes
14005   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14006       VecTy.getScalarSizeInBits() <= 32) {
14007     return SDValue();
14008   }
14009 
14010   SDValue LoadOps[] = { Chain, Base };
14011   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14012                                          DAG.getVTList(MVT::v2f64, MVT::Other),
14013                                          LoadOps, MVT::v2f64, MMO);
14014 
14015   DCI.AddToWorklist(Load.getNode());
14016   Chain = Load.getValue(1);
14017   SDValue Swap = DAG.getNode(
14018       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14019   DCI.AddToWorklist(Swap.getNode());
14020 
14021   // Add a bitcast if the resulting load type doesn't match v2f64.
14022   if (VecTy != MVT::v2f64) {
14023     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14024     DCI.AddToWorklist(N.getNode());
14025     // Package {bitcast value, swap's chain} to match Load's shape.
14026     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14027                        N, Swap.getValue(1));
14028   }
14029 
14030   return Swap;
14031 }
14032 
14033 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14034 // builtins) into stores with swaps.
14035 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14036                                                DAGCombinerInfo &DCI) const {
14037   SelectionDAG &DAG = DCI.DAG;
14038   SDLoc dl(N);
14039   SDValue Chain;
14040   SDValue Base;
14041   unsigned SrcOpnd;
14042   MachineMemOperand *MMO;
14043 
14044   switch (N->getOpcode()) {
14045   default:
14046     llvm_unreachable("Unexpected opcode for little endian VSX store");
14047   case ISD::STORE: {
14048     StoreSDNode *ST = cast<StoreSDNode>(N);
14049     Chain = ST->getChain();
14050     Base = ST->getBasePtr();
14051     MMO = ST->getMemOperand();
14052     SrcOpnd = 1;
14053     // If the MMO suggests this isn't a store of a full vector, leave
14054     // things alone.  For a built-in, we have to make the change for
14055     // correctness, so if there is a size problem that will be a bug.
14056     if (MMO->getSize() < 16)
14057       return SDValue();
14058     break;
14059   }
14060   case ISD::INTRINSIC_VOID: {
14061     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14062     Chain = Intrin->getChain();
14063     // Intrin->getBasePtr() oddly does not get what we want.
14064     Base = Intrin->getOperand(3);
14065     MMO = Intrin->getMemOperand();
14066     SrcOpnd = 2;
14067     break;
14068   }
14069   }
14070 
14071   SDValue Src = N->getOperand(SrcOpnd);
14072   MVT VecTy = Src.getValueType().getSimpleVT();
14073 
14074   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14075   // aligned and the type is a vector with elements up to 4 bytes
14076   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14077       VecTy.getScalarSizeInBits() <= 32) {
14078     return SDValue();
14079   }
14080 
14081   // All stores are done as v2f64 and possible bit cast.
14082   if (VecTy != MVT::v2f64) {
14083     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14084     DCI.AddToWorklist(Src.getNode());
14085   }
14086 
14087   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14088                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14089   DCI.AddToWorklist(Swap.getNode());
14090   Chain = Swap.getValue(1);
14091   SDValue StoreOps[] = { Chain, Swap, Base };
14092   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14093                                           DAG.getVTList(MVT::Other),
14094                                           StoreOps, VecTy, MMO);
14095   DCI.AddToWorklist(Store.getNode());
14096   return Store;
14097 }
14098 
14099 // Handle DAG combine for STORE (FP_TO_INT F).
14100 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14101                                                DAGCombinerInfo &DCI) const {
14102 
14103   SelectionDAG &DAG = DCI.DAG;
14104   SDLoc dl(N);
14105   unsigned Opcode = N->getOperand(1).getOpcode();
14106 
14107   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14108          && "Not a FP_TO_INT Instruction!");
14109 
14110   SDValue Val = N->getOperand(1).getOperand(0);
14111   EVT Op1VT = N->getOperand(1).getValueType();
14112   EVT ResVT = Val.getValueType();
14113 
14114   if (!isTypeLegal(ResVT))
14115     return SDValue();
14116 
14117   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14118   bool ValidTypeForStoreFltAsInt =
14119         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14120          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14121 
14122   if (ResVT == MVT::f128 && !Subtarget.hasP9Vector())
14123     return SDValue();
14124 
14125   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14126       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14127     return SDValue();
14128 
14129   // Extend f32 values to f64
14130   if (ResVT.getScalarSizeInBits() == 32) {
14131     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14132     DCI.AddToWorklist(Val.getNode());
14133   }
14134 
14135   // Set signed or unsigned conversion opcode.
14136   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14137                           PPCISD::FP_TO_SINT_IN_VSR :
14138                           PPCISD::FP_TO_UINT_IN_VSR;
14139 
14140   Val = DAG.getNode(ConvOpcode,
14141                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14142   DCI.AddToWorklist(Val.getNode());
14143 
14144   // Set number of bytes being converted.
14145   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14146   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14147                     DAG.getIntPtrConstant(ByteSize, dl, false),
14148                     DAG.getValueType(Op1VT) };
14149 
14150   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14151           DAG.getVTList(MVT::Other), Ops,
14152           cast<StoreSDNode>(N)->getMemoryVT(),
14153           cast<StoreSDNode>(N)->getMemOperand());
14154 
14155   DCI.AddToWorklist(Val.getNode());
14156   return Val;
14157 }
14158 
14159 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14160   // Check that the source of the element keeps flipping
14161   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14162   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14163   for (int i = 1, e = Mask.size(); i < e; i++) {
14164     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14165       return false;
14166     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14167       return false;
14168     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14169   }
14170   return true;
14171 }
14172 
14173 static bool isSplatBV(SDValue Op) {
14174   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14175     return false;
14176   SDValue FirstOp;
14177 
14178   // Find first non-undef input.
14179   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14180     FirstOp = Op.getOperand(i);
14181     if (!FirstOp.isUndef())
14182       break;
14183   }
14184 
14185   // All inputs are undef or the same as the first non-undef input.
14186   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14187     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14188       return false;
14189   return true;
14190 }
14191 
14192 static SDValue isScalarToVec(SDValue Op) {
14193   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14194     return Op;
14195   if (Op.getOpcode() != ISD::BITCAST)
14196     return SDValue();
14197   Op = Op.getOperand(0);
14198   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14199     return Op;
14200   return SDValue();
14201 }
14202 
14203 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14204                                             int LHSMaxIdx, int RHSMinIdx,
14205                                             int RHSMaxIdx, int HalfVec) {
14206   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14207     int Idx = ShuffV[i];
14208     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14209       ShuffV[i] += HalfVec;
14210   }
14211 }
14212 
14213 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14214 // the original is:
14215 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14216 // In such a case, just change the shuffle mask to extract the element
14217 // from the permuted index.
14218 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) {
14219   SDLoc dl(OrigSToV);
14220   EVT VT = OrigSToV.getValueType();
14221   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14222          "Expecting a SCALAR_TO_VECTOR here");
14223   SDValue Input = OrigSToV.getOperand(0);
14224 
14225   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14226     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14227     SDValue OrigVector = Input.getOperand(0);
14228 
14229     // Can't handle non-const element indices or different vector types
14230     // for the input to the extract and the output of the scalar_to_vector.
14231     if (Idx && VT == OrigVector.getValueType()) {
14232       SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1);
14233       NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue();
14234       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14235     }
14236   }
14237   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14238                      OrigSToV.getOperand(0));
14239 }
14240 
14241 // On little endian subtargets, combine shuffles such as:
14242 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14243 // into:
14244 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14245 // because the latter can be matched to a single instruction merge.
14246 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14247 // to put the value into element zero. Adjust the shuffle mask so that the
14248 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14249 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14250                                                 SelectionDAG &DAG) const {
14251   SDValue LHS = SVN->getOperand(0);
14252   SDValue RHS = SVN->getOperand(1);
14253   auto Mask = SVN->getMask();
14254   int NumElts = LHS.getValueType().getVectorNumElements();
14255   SDValue Res(SVN, 0);
14256   SDLoc dl(SVN);
14257 
14258   // None of these combines are useful on big endian systems since the ISA
14259   // already has a big endian bias.
14260   if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14261     return Res;
14262 
14263   // If this is not a shuffle of a shuffle and the first element comes from
14264   // the second vector, canonicalize to the commuted form. This will make it
14265   // more likely to match one of the single instruction patterns.
14266   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14267       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14268     std::swap(LHS, RHS);
14269     Res = DAG.getCommutedVectorShuffle(*SVN);
14270     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14271   }
14272 
14273   // Adjust the shuffle mask if either input vector comes from a
14274   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14275   // form (to prevent the need for a swap).
14276   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14277   SDValue SToVLHS = isScalarToVec(LHS);
14278   SDValue SToVRHS = isScalarToVec(RHS);
14279   if (SToVLHS || SToVRHS) {
14280     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14281                             : SToVRHS.getValueType().getVectorNumElements();
14282     int NumEltsOut = ShuffV.size();
14283 
14284     // Initially assume that neither input is permuted. These will be adjusted
14285     // accordingly if either input is.
14286     int LHSMaxIdx = -1;
14287     int RHSMinIdx = -1;
14288     int RHSMaxIdx = -1;
14289     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14290 
14291     // Get the permuted scalar to vector nodes for the source(s) that come from
14292     // ISD::SCALAR_TO_VECTOR.
14293     if (SToVLHS) {
14294       // Set up the values for the shuffle vector fixup.
14295       LHSMaxIdx = NumEltsOut / NumEltsIn;
14296       SToVLHS = getSToVPermuted(SToVLHS, DAG);
14297       if (SToVLHS.getValueType() != LHS.getValueType())
14298         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14299       LHS = SToVLHS;
14300     }
14301     if (SToVRHS) {
14302       RHSMinIdx = NumEltsOut;
14303       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14304       SToVRHS = getSToVPermuted(SToVRHS, DAG);
14305       if (SToVRHS.getValueType() != RHS.getValueType())
14306         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14307       RHS = SToVRHS;
14308     }
14309 
14310     // Fix up the shuffle mask to reflect where the desired element actually is.
14311     // The minimum and maximum indices that correspond to element zero for both
14312     // the LHS and RHS are computed and will control which shuffle mask entries
14313     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14314     // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by
14315     // HalfVec to refer to the corresponding element in the permuted vector.
14316     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14317                                     HalfVec);
14318     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14319 
14320     // We may have simplified away the shuffle. We won't be able to do anything
14321     // further with it here.
14322     if (!isa<ShuffleVectorSDNode>(Res))
14323       return Res;
14324     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14325   }
14326 
14327   // The common case after we commuted the shuffle is that the RHS is a splat
14328   // and we have elements coming in from the splat at indices that are not
14329   // conducive to using a merge.
14330   // Example:
14331   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14332   if (!isSplatBV(RHS))
14333     return Res;
14334 
14335   // We are looking for a mask such that all even elements are from
14336   // one vector and all odd elements from the other.
14337   if (!isAlternatingShuffMask(Mask, NumElts))
14338     return Res;
14339 
14340   // Adjust the mask so we are pulling in the same index from the splat
14341   // as the index from the interesting vector in consecutive elements.
14342   // Example (even elements from first vector):
14343   // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14344   if (Mask[0] < NumElts)
14345     for (int i = 1, e = Mask.size(); i < e; i += 2)
14346       ShuffV[i] = (ShuffV[i - 1] + NumElts);
14347   // Example (odd elements from first vector):
14348   // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14349   else
14350     for (int i = 0, e = Mask.size(); i < e; i += 2)
14351       ShuffV[i] = (ShuffV[i + 1] + NumElts);
14352 
14353   // If the RHS has undefs, we need to remove them since we may have created
14354   // a shuffle that adds those instead of the splat value.
14355   SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue();
14356   RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal);
14357 
14358   Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14359   return Res;
14360 }
14361 
14362 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14363                                                 LSBaseSDNode *LSBase,
14364                                                 DAGCombinerInfo &DCI) const {
14365   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14366         "Not a reverse memop pattern!");
14367 
14368   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14369     auto Mask = SVN->getMask();
14370     int i = 0;
14371     auto I = Mask.rbegin();
14372     auto E = Mask.rend();
14373 
14374     for (; I != E; ++I) {
14375       if (*I != i)
14376         return false;
14377       i++;
14378     }
14379     return true;
14380   };
14381 
14382   SelectionDAG &DAG = DCI.DAG;
14383   EVT VT = SVN->getValueType(0);
14384 
14385   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14386     return SDValue();
14387 
14388   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14389   // See comment in PPCVSXSwapRemoval.cpp.
14390   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14391   if (!Subtarget.hasP9Vector())
14392     return SDValue();
14393 
14394   if(!IsElementReverse(SVN))
14395     return SDValue();
14396 
14397   if (LSBase->getOpcode() == ISD::LOAD) {
14398     // If the load has more than one user except the shufflevector instruction,
14399     // it is not profitable to replace the shufflevector with a reverse load.
14400     if (!LSBase->hasOneUse())
14401       return SDValue();
14402 
14403     SDLoc dl(SVN);
14404     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14405     return DAG.getMemIntrinsicNode(
14406         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14407         LSBase->getMemoryVT(), LSBase->getMemOperand());
14408   }
14409 
14410   if (LSBase->getOpcode() == ISD::STORE) {
14411     // If there are other uses of the shuffle, the swap cannot be avoided.
14412     // Forcing the use of an X-Form (since swapped stores only have
14413     // X-Forms) without removing the swap is unprofitable.
14414     if (!SVN->hasOneUse())
14415       return SDValue();
14416 
14417     SDLoc dl(LSBase);
14418     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14419                           LSBase->getBasePtr()};
14420     return DAG.getMemIntrinsicNode(
14421         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14422         LSBase->getMemoryVT(), LSBase->getMemOperand());
14423   }
14424 
14425   llvm_unreachable("Expected a load or store node here");
14426 }
14427 
14428 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14429                                              DAGCombinerInfo &DCI) const {
14430   SelectionDAG &DAG = DCI.DAG;
14431   SDLoc dl(N);
14432   switch (N->getOpcode()) {
14433   default: break;
14434   case ISD::ADD:
14435     return combineADD(N, DCI);
14436   case ISD::SHL:
14437     return combineSHL(N, DCI);
14438   case ISD::SRA:
14439     return combineSRA(N, DCI);
14440   case ISD::SRL:
14441     return combineSRL(N, DCI);
14442   case ISD::MUL:
14443     return combineMUL(N, DCI);
14444   case ISD::FMA:
14445   case PPCISD::FNMSUB:
14446     return combineFMALike(N, DCI);
14447   case PPCISD::SHL:
14448     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14449         return N->getOperand(0);
14450     break;
14451   case PPCISD::SRL:
14452     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14453         return N->getOperand(0);
14454     break;
14455   case PPCISD::SRA:
14456     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14457       if (C->isNullValue() ||   //  0 >>s V -> 0.
14458           C->isAllOnesValue())    // -1 >>s V -> -1.
14459         return N->getOperand(0);
14460     }
14461     break;
14462   case ISD::SIGN_EXTEND:
14463   case ISD::ZERO_EXTEND:
14464   case ISD::ANY_EXTEND:
14465     return DAGCombineExtBoolTrunc(N, DCI);
14466   case ISD::TRUNCATE:
14467     return combineTRUNCATE(N, DCI);
14468   case ISD::SETCC:
14469     if (SDValue CSCC = combineSetCC(N, DCI))
14470       return CSCC;
14471     LLVM_FALLTHROUGH;
14472   case ISD::SELECT_CC:
14473     return DAGCombineTruncBoolExt(N, DCI);
14474   case ISD::SINT_TO_FP:
14475   case ISD::UINT_TO_FP:
14476     return combineFPToIntToFP(N, DCI);
14477   case ISD::VECTOR_SHUFFLE:
14478     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14479       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14480       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14481     }
14482     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14483   case ISD::STORE: {
14484 
14485     EVT Op1VT = N->getOperand(1).getValueType();
14486     unsigned Opcode = N->getOperand(1).getOpcode();
14487 
14488     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14489       SDValue Val= combineStoreFPToInt(N, DCI);
14490       if (Val)
14491         return Val;
14492     }
14493 
14494     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14495       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14496       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14497       if (Val)
14498         return Val;
14499     }
14500 
14501     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14502     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14503         N->getOperand(1).getNode()->hasOneUse() &&
14504         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14505          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14506 
14507       // STBRX can only handle simple types and it makes no sense to store less
14508       // two bytes in byte-reversed order.
14509       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14510       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14511         break;
14512 
14513       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14514       // Do an any-extend to 32-bits if this is a half-word input.
14515       if (BSwapOp.getValueType() == MVT::i16)
14516         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14517 
14518       // If the type of BSWAP operand is wider than stored memory width
14519       // it need to be shifted to the right side before STBRX.
14520       if (Op1VT.bitsGT(mVT)) {
14521         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14522         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14523                               DAG.getConstant(Shift, dl, MVT::i32));
14524         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14525         if (Op1VT == MVT::i64)
14526           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14527       }
14528 
14529       SDValue Ops[] = {
14530         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14531       };
14532       return
14533         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14534                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14535                                 cast<StoreSDNode>(N)->getMemOperand());
14536     }
14537 
14538     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14539     // So it can increase the chance of CSE constant construction.
14540     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14541         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14542       // Need to sign-extended to 64-bits to handle negative values.
14543       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14544       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14545                                     MemVT.getSizeInBits());
14546       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14547 
14548       // DAG.getTruncStore() can't be used here because it doesn't accept
14549       // the general (base + offset) addressing mode.
14550       // So we use UpdateNodeOperands and setTruncatingStore instead.
14551       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14552                              N->getOperand(3));
14553       cast<StoreSDNode>(N)->setTruncatingStore(true);
14554       return SDValue(N, 0);
14555     }
14556 
14557     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14558     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14559     if (Op1VT.isSimple()) {
14560       MVT StoreVT = Op1VT.getSimpleVT();
14561       if (Subtarget.needsSwapsForVSXMemOps() &&
14562           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14563            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14564         return expandVSXStoreForLE(N, DCI);
14565     }
14566     break;
14567   }
14568   case ISD::LOAD: {
14569     LoadSDNode *LD = cast<LoadSDNode>(N);
14570     EVT VT = LD->getValueType(0);
14571 
14572     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14573     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14574     if (VT.isSimple()) {
14575       MVT LoadVT = VT.getSimpleVT();
14576       if (Subtarget.needsSwapsForVSXMemOps() &&
14577           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14578            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14579         return expandVSXLoadForLE(N, DCI);
14580     }
14581 
14582     // We sometimes end up with a 64-bit integer load, from which we extract
14583     // two single-precision floating-point numbers. This happens with
14584     // std::complex<float>, and other similar structures, because of the way we
14585     // canonicalize structure copies. However, if we lack direct moves,
14586     // then the final bitcasts from the extracted integer values to the
14587     // floating-point numbers turn into store/load pairs. Even with direct moves,
14588     // just loading the two floating-point numbers is likely better.
14589     auto ReplaceTwoFloatLoad = [&]() {
14590       if (VT != MVT::i64)
14591         return false;
14592 
14593       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14594           LD->isVolatile())
14595         return false;
14596 
14597       //  We're looking for a sequence like this:
14598       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14599       //      t16: i64 = srl t13, Constant:i32<32>
14600       //    t17: i32 = truncate t16
14601       //  t18: f32 = bitcast t17
14602       //    t19: i32 = truncate t13
14603       //  t20: f32 = bitcast t19
14604 
14605       if (!LD->hasNUsesOfValue(2, 0))
14606         return false;
14607 
14608       auto UI = LD->use_begin();
14609       while (UI.getUse().getResNo() != 0) ++UI;
14610       SDNode *Trunc = *UI++;
14611       while (UI.getUse().getResNo() != 0) ++UI;
14612       SDNode *RightShift = *UI;
14613       if (Trunc->getOpcode() != ISD::TRUNCATE)
14614         std::swap(Trunc, RightShift);
14615 
14616       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14617           Trunc->getValueType(0) != MVT::i32 ||
14618           !Trunc->hasOneUse())
14619         return false;
14620       if (RightShift->getOpcode() != ISD::SRL ||
14621           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14622           RightShift->getConstantOperandVal(1) != 32 ||
14623           !RightShift->hasOneUse())
14624         return false;
14625 
14626       SDNode *Trunc2 = *RightShift->use_begin();
14627       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14628           Trunc2->getValueType(0) != MVT::i32 ||
14629           !Trunc2->hasOneUse())
14630         return false;
14631 
14632       SDNode *Bitcast = *Trunc->use_begin();
14633       SDNode *Bitcast2 = *Trunc2->use_begin();
14634 
14635       if (Bitcast->getOpcode() != ISD::BITCAST ||
14636           Bitcast->getValueType(0) != MVT::f32)
14637         return false;
14638       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14639           Bitcast2->getValueType(0) != MVT::f32)
14640         return false;
14641 
14642       if (Subtarget.isLittleEndian())
14643         std::swap(Bitcast, Bitcast2);
14644 
14645       // Bitcast has the second float (in memory-layout order) and Bitcast2
14646       // has the first one.
14647 
14648       SDValue BasePtr = LD->getBasePtr();
14649       if (LD->isIndexed()) {
14650         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14651                "Non-pre-inc AM on PPC?");
14652         BasePtr =
14653           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14654                       LD->getOffset());
14655       }
14656 
14657       auto MMOFlags =
14658           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14659       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14660                                       LD->getPointerInfo(), LD->getAlignment(),
14661                                       MMOFlags, LD->getAAInfo());
14662       SDValue AddPtr =
14663         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14664                     BasePtr, DAG.getIntPtrConstant(4, dl));
14665       SDValue FloatLoad2 = DAG.getLoad(
14666           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14667           LD->getPointerInfo().getWithOffset(4),
14668           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14669 
14670       if (LD->isIndexed()) {
14671         // Note that DAGCombine should re-form any pre-increment load(s) from
14672         // what is produced here if that makes sense.
14673         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14674       }
14675 
14676       DCI.CombineTo(Bitcast2, FloatLoad);
14677       DCI.CombineTo(Bitcast, FloatLoad2);
14678 
14679       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14680                                     SDValue(FloatLoad2.getNode(), 1));
14681       return true;
14682     };
14683 
14684     if (ReplaceTwoFloatLoad())
14685       return SDValue(N, 0);
14686 
14687     EVT MemVT = LD->getMemoryVT();
14688     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14689     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
14690     if (LD->isUnindexed() && VT.isVector() &&
14691         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14692           // P8 and later hardware should just use LOAD.
14693           !Subtarget.hasP8Vector() &&
14694           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
14695            VT == MVT::v4f32))) &&
14696         LD->getAlign() < ABIAlignment) {
14697       // This is a type-legal unaligned Altivec load.
14698       SDValue Chain = LD->getChain();
14699       SDValue Ptr = LD->getBasePtr();
14700       bool isLittleEndian = Subtarget.isLittleEndian();
14701 
14702       // This implements the loading of unaligned vectors as described in
14703       // the venerable Apple Velocity Engine overview. Specifically:
14704       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14705       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14706       //
14707       // The general idea is to expand a sequence of one or more unaligned
14708       // loads into an alignment-based permutation-control instruction (lvsl
14709       // or lvsr), a series of regular vector loads (which always truncate
14710       // their input address to an aligned address), and a series of
14711       // permutations.  The results of these permutations are the requested
14712       // loaded values.  The trick is that the last "extra" load is not taken
14713       // from the address you might suspect (sizeof(vector) bytes after the
14714       // last requested load), but rather sizeof(vector) - 1 bytes after the
14715       // last requested vector. The point of this is to avoid a page fault if
14716       // the base address happened to be aligned. This works because if the
14717       // base address is aligned, then adding less than a full vector length
14718       // will cause the last vector in the sequence to be (re)loaded.
14719       // Otherwise, the next vector will be fetched as you might suspect was
14720       // necessary.
14721 
14722       // We might be able to reuse the permutation generation from
14723       // a different base address offset from this one by an aligned amount.
14724       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14725       // optimization later.
14726       Intrinsic::ID Intr, IntrLD, IntrPerm;
14727       MVT PermCntlTy, PermTy, LDTy;
14728       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14729                             : Intrinsic::ppc_altivec_lvsl;
14730       IntrLD = Intrinsic::ppc_altivec_lvx;
14731       IntrPerm = Intrinsic::ppc_altivec_vperm;
14732       PermCntlTy = MVT::v16i8;
14733       PermTy = MVT::v4i32;
14734       LDTy = MVT::v4i32;
14735 
14736       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14737 
14738       // Create the new MMO for the new base load. It is like the original MMO,
14739       // but represents an area in memory almost twice the vector size centered
14740       // on the original address. If the address is unaligned, we might start
14741       // reading up to (sizeof(vector)-1) bytes below the address of the
14742       // original unaligned load.
14743       MachineFunction &MF = DAG.getMachineFunction();
14744       MachineMemOperand *BaseMMO =
14745         MF.getMachineMemOperand(LD->getMemOperand(),
14746                                 -(long)MemVT.getStoreSize()+1,
14747                                 2*MemVT.getStoreSize()-1);
14748 
14749       // Create the new base load.
14750       SDValue LDXIntID =
14751           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14752       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14753       SDValue BaseLoad =
14754         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14755                                 DAG.getVTList(PermTy, MVT::Other),
14756                                 BaseLoadOps, LDTy, BaseMMO);
14757 
14758       // Note that the value of IncOffset (which is provided to the next
14759       // load's pointer info offset value, and thus used to calculate the
14760       // alignment), and the value of IncValue (which is actually used to
14761       // increment the pointer value) are different! This is because we
14762       // require the next load to appear to be aligned, even though it
14763       // is actually offset from the base pointer by a lesser amount.
14764       int IncOffset = VT.getSizeInBits() / 8;
14765       int IncValue = IncOffset;
14766 
14767       // Walk (both up and down) the chain looking for another load at the real
14768       // (aligned) offset (the alignment of the other load does not matter in
14769       // this case). If found, then do not use the offset reduction trick, as
14770       // that will prevent the loads from being later combined (as they would
14771       // otherwise be duplicates).
14772       if (!findConsecutiveLoad(LD, DAG))
14773         --IncValue;
14774 
14775       SDValue Increment =
14776           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14777       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14778 
14779       MachineMemOperand *ExtraMMO =
14780         MF.getMachineMemOperand(LD->getMemOperand(),
14781                                 1, 2*MemVT.getStoreSize()-1);
14782       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14783       SDValue ExtraLoad =
14784         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14785                                 DAG.getVTList(PermTy, MVT::Other),
14786                                 ExtraLoadOps, LDTy, ExtraMMO);
14787 
14788       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14789         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14790 
14791       // Because vperm has a big-endian bias, we must reverse the order
14792       // of the input vectors and complement the permute control vector
14793       // when generating little endian code.  We have already handled the
14794       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14795       // and ExtraLoad here.
14796       SDValue Perm;
14797       if (isLittleEndian)
14798         Perm = BuildIntrinsicOp(IntrPerm,
14799                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14800       else
14801         Perm = BuildIntrinsicOp(IntrPerm,
14802                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14803 
14804       if (VT != PermTy)
14805         Perm = Subtarget.hasAltivec()
14806                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
14807                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
14808                                  DAG.getTargetConstant(1, dl, MVT::i64));
14809                                // second argument is 1 because this rounding
14810                                // is always exact.
14811 
14812       // The output of the permutation is our loaded result, the TokenFactor is
14813       // our new chain.
14814       DCI.CombineTo(N, Perm, TF);
14815       return SDValue(N, 0);
14816     }
14817     }
14818     break;
14819     case ISD::INTRINSIC_WO_CHAIN: {
14820       bool isLittleEndian = Subtarget.isLittleEndian();
14821       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14822       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14823                                            : Intrinsic::ppc_altivec_lvsl);
14824       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
14825         SDValue Add = N->getOperand(1);
14826 
14827         int Bits = 4 /* 16 byte alignment */;
14828 
14829         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14830                                   APInt::getAllOnesValue(Bits /* alignment */)
14831                                       .zext(Add.getScalarValueSizeInBits()))) {
14832           SDNode *BasePtr = Add->getOperand(0).getNode();
14833           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14834                                     UE = BasePtr->use_end();
14835                UI != UE; ++UI) {
14836             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14837                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
14838                     IID) {
14839               // We've found another LVSL/LVSR, and this address is an aligned
14840               // multiple of that one. The results will be the same, so use the
14841               // one we've just found instead.
14842 
14843               return SDValue(*UI, 0);
14844             }
14845           }
14846         }
14847 
14848         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14849           SDNode *BasePtr = Add->getOperand(0).getNode();
14850           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14851                UE = BasePtr->use_end(); UI != UE; ++UI) {
14852             if (UI->getOpcode() == ISD::ADD &&
14853                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14854                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14855                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14856                 (1ULL << Bits) == 0) {
14857               SDNode *OtherAdd = *UI;
14858               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14859                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14860                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14861                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14862                   return SDValue(*VI, 0);
14863                 }
14864               }
14865             }
14866           }
14867         }
14868       }
14869 
14870       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14871       // Expose the vabsduw/h/b opportunity for down stream
14872       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14873           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14874            IID == Intrinsic::ppc_altivec_vmaxsh ||
14875            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14876         SDValue V1 = N->getOperand(1);
14877         SDValue V2 = N->getOperand(2);
14878         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14879              V1.getSimpleValueType() == MVT::v8i16 ||
14880              V1.getSimpleValueType() == MVT::v16i8) &&
14881             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14882           // (0-a, a)
14883           if (V1.getOpcode() == ISD::SUB &&
14884               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14885               V1.getOperand(1) == V2) {
14886             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14887           }
14888           // (a, 0-a)
14889           if (V2.getOpcode() == ISD::SUB &&
14890               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14891               V2.getOperand(1) == V1) {
14892             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14893           }
14894           // (x-y, y-x)
14895           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14896               V1.getOperand(0) == V2.getOperand(1) &&
14897               V1.getOperand(1) == V2.getOperand(0)) {
14898             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14899           }
14900         }
14901       }
14902     }
14903 
14904     break;
14905   case ISD::INTRINSIC_W_CHAIN:
14906     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14907     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14908     if (Subtarget.needsSwapsForVSXMemOps()) {
14909       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14910       default:
14911         break;
14912       case Intrinsic::ppc_vsx_lxvw4x:
14913       case Intrinsic::ppc_vsx_lxvd2x:
14914         return expandVSXLoadForLE(N, DCI);
14915       }
14916     }
14917     break;
14918   case ISD::INTRINSIC_VOID:
14919     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14920     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14921     if (Subtarget.needsSwapsForVSXMemOps()) {
14922       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14923       default:
14924         break;
14925       case Intrinsic::ppc_vsx_stxvw4x:
14926       case Intrinsic::ppc_vsx_stxvd2x:
14927         return expandVSXStoreForLE(N, DCI);
14928       }
14929     }
14930     break;
14931   case ISD::BSWAP:
14932     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14933     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14934         N->getOperand(0).hasOneUse() &&
14935         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14936          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14937           N->getValueType(0) == MVT::i64))) {
14938       SDValue Load = N->getOperand(0);
14939       LoadSDNode *LD = cast<LoadSDNode>(Load);
14940       // Create the byte-swapping load.
14941       SDValue Ops[] = {
14942         LD->getChain(),    // Chain
14943         LD->getBasePtr(),  // Ptr
14944         DAG.getValueType(N->getValueType(0)) // VT
14945       };
14946       SDValue BSLoad =
14947         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14948                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14949                                               MVT::i64 : MVT::i32, MVT::Other),
14950                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14951 
14952       // If this is an i16 load, insert the truncate.
14953       SDValue ResVal = BSLoad;
14954       if (N->getValueType(0) == MVT::i16)
14955         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14956 
14957       // First, combine the bswap away.  This makes the value produced by the
14958       // load dead.
14959       DCI.CombineTo(N, ResVal);
14960 
14961       // Next, combine the load away, we give it a bogus result value but a real
14962       // chain result.  The result value is dead because the bswap is dead.
14963       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14964 
14965       // Return N so it doesn't get rechecked!
14966       return SDValue(N, 0);
14967     }
14968     break;
14969   case PPCISD::VCMP:
14970     // If a VCMP_rec node already exists with exactly the same operands as this
14971     // node, use its result instead of this node (VCMP_rec computes both a CR6
14972     // and a normal output).
14973     //
14974     if (!N->getOperand(0).hasOneUse() &&
14975         !N->getOperand(1).hasOneUse() &&
14976         !N->getOperand(2).hasOneUse()) {
14977 
14978       // Scan all of the users of the LHS, looking for VCMP_rec's that match.
14979       SDNode *VCMPrecNode = nullptr;
14980 
14981       SDNode *LHSN = N->getOperand(0).getNode();
14982       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14983            UI != E; ++UI)
14984         if (UI->getOpcode() == PPCISD::VCMP_rec &&
14985             UI->getOperand(1) == N->getOperand(1) &&
14986             UI->getOperand(2) == N->getOperand(2) &&
14987             UI->getOperand(0) == N->getOperand(0)) {
14988           VCMPrecNode = *UI;
14989           break;
14990         }
14991 
14992       // If there is no VCMP_rec node, or if the flag value has a single use,
14993       // don't transform this.
14994       if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
14995         break;
14996 
14997       // Look at the (necessarily single) use of the flag value.  If it has a
14998       // chain, this transformation is more complex.  Note that multiple things
14999       // could use the value result, which we should ignore.
15000       SDNode *FlagUser = nullptr;
15001       for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
15002            FlagUser == nullptr; ++UI) {
15003         assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
15004         SDNode *User = *UI;
15005         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
15006           if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
15007             FlagUser = User;
15008             break;
15009           }
15010         }
15011       }
15012 
15013       // If the user is a MFOCRF instruction, we know this is safe.
15014       // Otherwise we give up for right now.
15015       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
15016         return SDValue(VCMPrecNode, 0);
15017     }
15018     break;
15019   case ISD::BRCOND: {
15020     SDValue Cond = N->getOperand(1);
15021     SDValue Target = N->getOperand(2);
15022 
15023     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15024         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15025           Intrinsic::loop_decrement) {
15026 
15027       // We now need to make the intrinsic dead (it cannot be instruction
15028       // selected).
15029       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15030       assert(Cond.getNode()->hasOneUse() &&
15031              "Counter decrement has more than one use");
15032 
15033       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15034                          N->getOperand(0), Target);
15035     }
15036   }
15037   break;
15038   case ISD::BR_CC: {
15039     // If this is a branch on an altivec predicate comparison, lower this so
15040     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15041     // lowering is done pre-legalize, because the legalizer lowers the predicate
15042     // compare down to code that is difficult to reassemble.
15043     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15044     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15045 
15046     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15047     // value. If so, pass-through the AND to get to the intrinsic.
15048     if (LHS.getOpcode() == ISD::AND &&
15049         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15050         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15051           Intrinsic::loop_decrement &&
15052         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15053         !isNullConstant(LHS.getOperand(1)))
15054       LHS = LHS.getOperand(0);
15055 
15056     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15057         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15058           Intrinsic::loop_decrement &&
15059         isa<ConstantSDNode>(RHS)) {
15060       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15061              "Counter decrement comparison is not EQ or NE");
15062 
15063       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15064       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15065                     (CC == ISD::SETNE && !Val);
15066 
15067       // We now need to make the intrinsic dead (it cannot be instruction
15068       // selected).
15069       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15070       assert(LHS.getNode()->hasOneUse() &&
15071              "Counter decrement has more than one use");
15072 
15073       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15074                          N->getOperand(0), N->getOperand(4));
15075     }
15076 
15077     int CompareOpc;
15078     bool isDot;
15079 
15080     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15081         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15082         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15083       assert(isDot && "Can't compare against a vector result!");
15084 
15085       // If this is a comparison against something other than 0/1, then we know
15086       // that the condition is never/always true.
15087       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15088       if (Val != 0 && Val != 1) {
15089         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15090           return N->getOperand(0);
15091         // Always !=, turn it into an unconditional branch.
15092         return DAG.getNode(ISD::BR, dl, MVT::Other,
15093                            N->getOperand(0), N->getOperand(4));
15094       }
15095 
15096       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15097 
15098       // Create the PPCISD altivec 'dot' comparison node.
15099       SDValue Ops[] = {
15100         LHS.getOperand(2),  // LHS of compare
15101         LHS.getOperand(3),  // RHS of compare
15102         DAG.getConstant(CompareOpc, dl, MVT::i32)
15103       };
15104       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15105       SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
15106 
15107       // Unpack the result based on how the target uses it.
15108       PPC::Predicate CompOpc;
15109       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15110       default:  // Can't happen, don't crash on invalid number though.
15111       case 0:   // Branch on the value of the EQ bit of CR6.
15112         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15113         break;
15114       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15115         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15116         break;
15117       case 2:   // Branch on the value of the LT bit of CR6.
15118         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15119         break;
15120       case 3:   // Branch on the inverted value of the LT bit of CR6.
15121         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15122         break;
15123       }
15124 
15125       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15126                          DAG.getConstant(CompOpc, dl, MVT::i32),
15127                          DAG.getRegister(PPC::CR6, MVT::i32),
15128                          N->getOperand(4), CompNode.getValue(1));
15129     }
15130     break;
15131   }
15132   case ISD::BUILD_VECTOR:
15133     return DAGCombineBuildVector(N, DCI);
15134   case ISD::ABS:
15135     return combineABS(N, DCI);
15136   case ISD::VSELECT:
15137     return combineVSelect(N, DCI);
15138   }
15139 
15140   return SDValue();
15141 }
15142 
15143 SDValue
15144 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15145                                  SelectionDAG &DAG,
15146                                  SmallVectorImpl<SDNode *> &Created) const {
15147   // fold (sdiv X, pow2)
15148   EVT VT = N->getValueType(0);
15149   if (VT == MVT::i64 && !Subtarget.isPPC64())
15150     return SDValue();
15151   if ((VT != MVT::i32 && VT != MVT::i64) ||
15152       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
15153     return SDValue();
15154 
15155   SDLoc DL(N);
15156   SDValue N0 = N->getOperand(0);
15157 
15158   bool IsNegPow2 = (-Divisor).isPowerOf2();
15159   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15160   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15161 
15162   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15163   Created.push_back(Op.getNode());
15164 
15165   if (IsNegPow2) {
15166     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15167     Created.push_back(Op.getNode());
15168   }
15169 
15170   return Op;
15171 }
15172 
15173 //===----------------------------------------------------------------------===//
15174 // Inline Assembly Support
15175 //===----------------------------------------------------------------------===//
15176 
15177 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15178                                                       KnownBits &Known,
15179                                                       const APInt &DemandedElts,
15180                                                       const SelectionDAG &DAG,
15181                                                       unsigned Depth) const {
15182   Known.resetAll();
15183   switch (Op.getOpcode()) {
15184   default: break;
15185   case PPCISD::LBRX: {
15186     // lhbrx is known to have the top bits cleared out.
15187     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15188       Known.Zero = 0xFFFF0000;
15189     break;
15190   }
15191   case ISD::INTRINSIC_WO_CHAIN: {
15192     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15193     default: break;
15194     case Intrinsic::ppc_altivec_vcmpbfp_p:
15195     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15196     case Intrinsic::ppc_altivec_vcmpequb_p:
15197     case Intrinsic::ppc_altivec_vcmpequh_p:
15198     case Intrinsic::ppc_altivec_vcmpequw_p:
15199     case Intrinsic::ppc_altivec_vcmpequd_p:
15200     case Intrinsic::ppc_altivec_vcmpequq_p:
15201     case Intrinsic::ppc_altivec_vcmpgefp_p:
15202     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15203     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15204     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15205     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15206     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15207     case Intrinsic::ppc_altivec_vcmpgtsq_p:
15208     case Intrinsic::ppc_altivec_vcmpgtub_p:
15209     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15210     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15211     case Intrinsic::ppc_altivec_vcmpgtud_p:
15212     case Intrinsic::ppc_altivec_vcmpgtuq_p:
15213       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15214       break;
15215     }
15216   }
15217   }
15218 }
15219 
15220 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15221   switch (Subtarget.getCPUDirective()) {
15222   default: break;
15223   case PPC::DIR_970:
15224   case PPC::DIR_PWR4:
15225   case PPC::DIR_PWR5:
15226   case PPC::DIR_PWR5X:
15227   case PPC::DIR_PWR6:
15228   case PPC::DIR_PWR6X:
15229   case PPC::DIR_PWR7:
15230   case PPC::DIR_PWR8:
15231   case PPC::DIR_PWR9:
15232   case PPC::DIR_PWR10:
15233   case PPC::DIR_PWR_FUTURE: {
15234     if (!ML)
15235       break;
15236 
15237     if (!DisableInnermostLoopAlign32) {
15238       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15239       // so that we can decrease cache misses and branch-prediction misses.
15240       // Actual alignment of the loop will depend on the hotness check and other
15241       // logic in alignBlocks.
15242       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15243         return Align(32);
15244     }
15245 
15246     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15247 
15248     // For small loops (between 5 and 8 instructions), align to a 32-byte
15249     // boundary so that the entire loop fits in one instruction-cache line.
15250     uint64_t LoopSize = 0;
15251     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15252       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15253         LoopSize += TII->getInstSizeInBytes(*J);
15254         if (LoopSize > 32)
15255           break;
15256       }
15257 
15258     if (LoopSize > 16 && LoopSize <= 32)
15259       return Align(32);
15260 
15261     break;
15262   }
15263   }
15264 
15265   return TargetLowering::getPrefLoopAlignment(ML);
15266 }
15267 
15268 /// getConstraintType - Given a constraint, return the type of
15269 /// constraint it is for this target.
15270 PPCTargetLowering::ConstraintType
15271 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15272   if (Constraint.size() == 1) {
15273     switch (Constraint[0]) {
15274     default: break;
15275     case 'b':
15276     case 'r':
15277     case 'f':
15278     case 'd':
15279     case 'v':
15280     case 'y':
15281       return C_RegisterClass;
15282     case 'Z':
15283       // FIXME: While Z does indicate a memory constraint, it specifically
15284       // indicates an r+r address (used in conjunction with the 'y' modifier
15285       // in the replacement string). Currently, we're forcing the base
15286       // register to be r0 in the asm printer (which is interpreted as zero)
15287       // and forming the complete address in the second register. This is
15288       // suboptimal.
15289       return C_Memory;
15290     }
15291   } else if (Constraint == "wc") { // individual CR bits.
15292     return C_RegisterClass;
15293   } else if (Constraint == "wa" || Constraint == "wd" ||
15294              Constraint == "wf" || Constraint == "ws" ||
15295              Constraint == "wi" || Constraint == "ww") {
15296     return C_RegisterClass; // VSX registers.
15297   }
15298   return TargetLowering::getConstraintType(Constraint);
15299 }
15300 
15301 /// Examine constraint type and operand type and determine a weight value.
15302 /// This object must already have been set up with the operand type
15303 /// and the current alternative constraint selected.
15304 TargetLowering::ConstraintWeight
15305 PPCTargetLowering::getSingleConstraintMatchWeight(
15306     AsmOperandInfo &info, const char *constraint) const {
15307   ConstraintWeight weight = CW_Invalid;
15308   Value *CallOperandVal = info.CallOperandVal;
15309     // If we don't have a value, we can't do a match,
15310     // but allow it at the lowest weight.
15311   if (!CallOperandVal)
15312     return CW_Default;
15313   Type *type = CallOperandVal->getType();
15314 
15315   // Look at the constraint type.
15316   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15317     return CW_Register; // an individual CR bit.
15318   else if ((StringRef(constraint) == "wa" ||
15319             StringRef(constraint) == "wd" ||
15320             StringRef(constraint) == "wf") &&
15321            type->isVectorTy())
15322     return CW_Register;
15323   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15324     return CW_Register; // just hold 64-bit integers data.
15325   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15326     return CW_Register;
15327   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15328     return CW_Register;
15329 
15330   switch (*constraint) {
15331   default:
15332     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15333     break;
15334   case 'b':
15335     if (type->isIntegerTy())
15336       weight = CW_Register;
15337     break;
15338   case 'f':
15339     if (type->isFloatTy())
15340       weight = CW_Register;
15341     break;
15342   case 'd':
15343     if (type->isDoubleTy())
15344       weight = CW_Register;
15345     break;
15346   case 'v':
15347     if (type->isVectorTy())
15348       weight = CW_Register;
15349     break;
15350   case 'y':
15351     weight = CW_Register;
15352     break;
15353   case 'Z':
15354     weight = CW_Memory;
15355     break;
15356   }
15357   return weight;
15358 }
15359 
15360 std::pair<unsigned, const TargetRegisterClass *>
15361 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15362                                                 StringRef Constraint,
15363                                                 MVT VT) const {
15364   if (Constraint.size() == 1) {
15365     // GCC RS6000 Constraint Letters
15366     switch (Constraint[0]) {
15367     case 'b':   // R1-R31
15368       if (VT == MVT::i64 && Subtarget.isPPC64())
15369         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15370       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15371     case 'r':   // R0-R31
15372       if (VT == MVT::i64 && Subtarget.isPPC64())
15373         return std::make_pair(0U, &PPC::G8RCRegClass);
15374       return std::make_pair(0U, &PPC::GPRCRegClass);
15375     // 'd' and 'f' constraints are both defined to be "the floating point
15376     // registers", where one is for 32-bit and the other for 64-bit. We don't
15377     // really care overly much here so just give them all the same reg classes.
15378     case 'd':
15379     case 'f':
15380       if (Subtarget.hasSPE()) {
15381         if (VT == MVT::f32 || VT == MVT::i32)
15382           return std::make_pair(0U, &PPC::GPRCRegClass);
15383         if (VT == MVT::f64 || VT == MVT::i64)
15384           return std::make_pair(0U, &PPC::SPERCRegClass);
15385       } else {
15386         if (VT == MVT::f32 || VT == MVT::i32)
15387           return std::make_pair(0U, &PPC::F4RCRegClass);
15388         if (VT == MVT::f64 || VT == MVT::i64)
15389           return std::make_pair(0U, &PPC::F8RCRegClass);
15390       }
15391       break;
15392     case 'v':
15393       if (Subtarget.hasAltivec())
15394         return std::make_pair(0U, &PPC::VRRCRegClass);
15395       break;
15396     case 'y':   // crrc
15397       return std::make_pair(0U, &PPC::CRRCRegClass);
15398     }
15399   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15400     // An individual CR bit.
15401     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15402   } else if ((Constraint == "wa" || Constraint == "wd" ||
15403              Constraint == "wf" || Constraint == "wi") &&
15404              Subtarget.hasVSX()) {
15405     return std::make_pair(0U, &PPC::VSRCRegClass);
15406   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15407     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15408       return std::make_pair(0U, &PPC::VSSRCRegClass);
15409     else
15410       return std::make_pair(0U, &PPC::VSFRCRegClass);
15411   }
15412 
15413   // Handle special cases of physical registers that are not properly handled
15414   // by the base class.
15415   if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
15416     // If we name a VSX register, we can't defer to the base class because it
15417     // will not recognize the correct register (their names will be VSL{0-31}
15418     // and V{0-31} so they won't match). So we match them here.
15419     if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15420       int VSNum = atoi(Constraint.data() + 3);
15421       assert(VSNum >= 0 && VSNum <= 63 &&
15422              "Attempted to access a vsr out of range");
15423       if (VSNum < 32)
15424         return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15425       return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15426     }
15427 
15428     // For float registers, we can't defer to the base class as it will match
15429     // the SPILLTOVSRRC class.
15430     if (Constraint.size() > 3 && Constraint[1] == 'f') {
15431       int RegNum = atoi(Constraint.data() + 2);
15432       if (RegNum > 31 || RegNum < 0)
15433         report_fatal_error("Invalid floating point register number");
15434       if (VT == MVT::f32 || VT == MVT::i32)
15435         return Subtarget.hasSPE()
15436                    ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
15437                    : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
15438       if (VT == MVT::f64 || VT == MVT::i64)
15439         return Subtarget.hasSPE()
15440                    ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
15441                    : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
15442     }
15443   }
15444 
15445   std::pair<unsigned, const TargetRegisterClass *> R =
15446       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15447 
15448   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15449   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15450   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15451   // register.
15452   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15453   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15454   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15455       PPC::GPRCRegClass.contains(R.first))
15456     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15457                             PPC::sub_32, &PPC::G8RCRegClass),
15458                           &PPC::G8RCRegClass);
15459 
15460   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15461   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15462     R.first = PPC::CR0;
15463     R.second = &PPC::CRRCRegClass;
15464   }
15465   // FIXME: This warning should ideally be emitted in the front end.
15466   const auto &TM = getTargetMachine();
15467   if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) {
15468     if (((R.first >= PPC::V20 && R.first <= PPC::V31) ||
15469          (R.first >= PPC::VF20 && R.first <= PPC::VF31)) &&
15470         (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass))
15471       errs() << "warning: vector registers 20 to 32 are reserved in the "
15472                 "default AIX AltiVec ABI and cannot be used\n";
15473   }
15474 
15475   return R;
15476 }
15477 
15478 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15479 /// vector.  If it is invalid, don't add anything to Ops.
15480 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15481                                                      std::string &Constraint,
15482                                                      std::vector<SDValue>&Ops,
15483                                                      SelectionDAG &DAG) const {
15484   SDValue Result;
15485 
15486   // Only support length 1 constraints.
15487   if (Constraint.length() > 1) return;
15488 
15489   char Letter = Constraint[0];
15490   switch (Letter) {
15491   default: break;
15492   case 'I':
15493   case 'J':
15494   case 'K':
15495   case 'L':
15496   case 'M':
15497   case 'N':
15498   case 'O':
15499   case 'P': {
15500     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15501     if (!CST) return; // Must be an immediate to match.
15502     SDLoc dl(Op);
15503     int64_t Value = CST->getSExtValue();
15504     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15505                          // numbers are printed as such.
15506     switch (Letter) {
15507     default: llvm_unreachable("Unknown constraint letter!");
15508     case 'I':  // "I" is a signed 16-bit constant.
15509       if (isInt<16>(Value))
15510         Result = DAG.getTargetConstant(Value, dl, TCVT);
15511       break;
15512     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15513       if (isShiftedUInt<16, 16>(Value))
15514         Result = DAG.getTargetConstant(Value, dl, TCVT);
15515       break;
15516     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15517       if (isShiftedInt<16, 16>(Value))
15518         Result = DAG.getTargetConstant(Value, dl, TCVT);
15519       break;
15520     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15521       if (isUInt<16>(Value))
15522         Result = DAG.getTargetConstant(Value, dl, TCVT);
15523       break;
15524     case 'M':  // "M" is a constant that is greater than 31.
15525       if (Value > 31)
15526         Result = DAG.getTargetConstant(Value, dl, TCVT);
15527       break;
15528     case 'N':  // "N" is a positive constant that is an exact power of two.
15529       if (Value > 0 && isPowerOf2_64(Value))
15530         Result = DAG.getTargetConstant(Value, dl, TCVT);
15531       break;
15532     case 'O':  // "O" is the constant zero.
15533       if (Value == 0)
15534         Result = DAG.getTargetConstant(Value, dl, TCVT);
15535       break;
15536     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15537       if (isInt<16>(-Value))
15538         Result = DAG.getTargetConstant(Value, dl, TCVT);
15539       break;
15540     }
15541     break;
15542   }
15543   }
15544 
15545   if (Result.getNode()) {
15546     Ops.push_back(Result);
15547     return;
15548   }
15549 
15550   // Handle standard constraint letters.
15551   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15552 }
15553 
15554 // isLegalAddressingMode - Return true if the addressing mode represented
15555 // by AM is legal for this target, for a load/store of the specified type.
15556 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15557                                               const AddrMode &AM, Type *Ty,
15558                                               unsigned AS,
15559                                               Instruction *I) const {
15560   // Vector type r+i form is supported since power9 as DQ form. We don't check
15561   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
15562   // imm form is preferred and the offset can be adjusted to use imm form later
15563   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
15564   // max offset to check legal addressing mode, we should be a little aggressive
15565   // to contain other offsets for that LSRUse.
15566   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
15567     return false;
15568 
15569   // PPC allows a sign-extended 16-bit immediate field.
15570   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15571     return false;
15572 
15573   // No global is ever allowed as a base.
15574   if (AM.BaseGV)
15575     return false;
15576 
15577   // PPC only support r+r,
15578   switch (AM.Scale) {
15579   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15580     break;
15581   case 1:
15582     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15583       return false;
15584     // Otherwise we have r+r or r+i.
15585     break;
15586   case 2:
15587     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15588       return false;
15589     // Allow 2*r as r+r.
15590     break;
15591   default:
15592     // No other scales are supported.
15593     return false;
15594   }
15595 
15596   return true;
15597 }
15598 
15599 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15600                                            SelectionDAG &DAG) const {
15601   MachineFunction &MF = DAG.getMachineFunction();
15602   MachineFrameInfo &MFI = MF.getFrameInfo();
15603   MFI.setReturnAddressIsTaken(true);
15604 
15605   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15606     return SDValue();
15607 
15608   SDLoc dl(Op);
15609   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15610 
15611   // Make sure the function does not optimize away the store of the RA to
15612   // the stack.
15613   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15614   FuncInfo->setLRStoreRequired();
15615   bool isPPC64 = Subtarget.isPPC64();
15616   auto PtrVT = getPointerTy(MF.getDataLayout());
15617 
15618   if (Depth > 0) {
15619     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15620     SDValue Offset =
15621         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15622                         isPPC64 ? MVT::i64 : MVT::i32);
15623     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15624                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15625                        MachinePointerInfo());
15626   }
15627 
15628   // Just load the return address off the stack.
15629   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15630   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15631                      MachinePointerInfo());
15632 }
15633 
15634 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15635                                           SelectionDAG &DAG) const {
15636   SDLoc dl(Op);
15637   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15638 
15639   MachineFunction &MF = DAG.getMachineFunction();
15640   MachineFrameInfo &MFI = MF.getFrameInfo();
15641   MFI.setFrameAddressIsTaken(true);
15642 
15643   EVT PtrVT = getPointerTy(MF.getDataLayout());
15644   bool isPPC64 = PtrVT == MVT::i64;
15645 
15646   // Naked functions never have a frame pointer, and so we use r1. For all
15647   // other functions, this decision must be delayed until during PEI.
15648   unsigned FrameReg;
15649   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15650     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15651   else
15652     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15653 
15654   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15655                                          PtrVT);
15656   while (Depth--)
15657     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15658                             FrameAddr, MachinePointerInfo());
15659   return FrameAddr;
15660 }
15661 
15662 // FIXME? Maybe this could be a TableGen attribute on some registers and
15663 // this table could be generated automatically from RegInfo.
15664 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15665                                               const MachineFunction &MF) const {
15666   bool isPPC64 = Subtarget.isPPC64();
15667 
15668   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15669   if (!is64Bit && VT != LLT::scalar(32))
15670     report_fatal_error("Invalid register global variable type");
15671 
15672   Register Reg = StringSwitch<Register>(RegName)
15673                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15674                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15675                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15676                      .Default(Register());
15677 
15678   if (Reg)
15679     return Reg;
15680   report_fatal_error("Invalid register name global variable");
15681 }
15682 
15683 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15684   // 32-bit SVR4 ABI access everything as got-indirect.
15685   if (Subtarget.is32BitELFABI())
15686     return true;
15687 
15688   // AIX accesses everything indirectly through the TOC, which is similar to
15689   // the GOT.
15690   if (Subtarget.isAIXABI())
15691     return true;
15692 
15693   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15694   // If it is small or large code model, module locals are accessed
15695   // indirectly by loading their address from .toc/.got.
15696   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15697     return true;
15698 
15699   // JumpTable and BlockAddress are accessed as got-indirect.
15700   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15701     return true;
15702 
15703   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15704     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15705 
15706   return false;
15707 }
15708 
15709 bool
15710 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15711   // The PowerPC target isn't yet aware of offsets.
15712   return false;
15713 }
15714 
15715 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15716                                            const CallInst &I,
15717                                            MachineFunction &MF,
15718                                            unsigned Intrinsic) const {
15719   switch (Intrinsic) {
15720   case Intrinsic::ppc_altivec_lvx:
15721   case Intrinsic::ppc_altivec_lvxl:
15722   case Intrinsic::ppc_altivec_lvebx:
15723   case Intrinsic::ppc_altivec_lvehx:
15724   case Intrinsic::ppc_altivec_lvewx:
15725   case Intrinsic::ppc_vsx_lxvd2x:
15726   case Intrinsic::ppc_vsx_lxvw4x:
15727   case Intrinsic::ppc_vsx_lxvd2x_be:
15728   case Intrinsic::ppc_vsx_lxvw4x_be:
15729   case Intrinsic::ppc_vsx_lxvl:
15730   case Intrinsic::ppc_vsx_lxvll: {
15731     EVT VT;
15732     switch (Intrinsic) {
15733     case Intrinsic::ppc_altivec_lvebx:
15734       VT = MVT::i8;
15735       break;
15736     case Intrinsic::ppc_altivec_lvehx:
15737       VT = MVT::i16;
15738       break;
15739     case Intrinsic::ppc_altivec_lvewx:
15740       VT = MVT::i32;
15741       break;
15742     case Intrinsic::ppc_vsx_lxvd2x:
15743     case Intrinsic::ppc_vsx_lxvd2x_be:
15744       VT = MVT::v2f64;
15745       break;
15746     default:
15747       VT = MVT::v4i32;
15748       break;
15749     }
15750 
15751     Info.opc = ISD::INTRINSIC_W_CHAIN;
15752     Info.memVT = VT;
15753     Info.ptrVal = I.getArgOperand(0);
15754     Info.offset = -VT.getStoreSize()+1;
15755     Info.size = 2*VT.getStoreSize()-1;
15756     Info.align = Align(1);
15757     Info.flags = MachineMemOperand::MOLoad;
15758     return true;
15759   }
15760   case Intrinsic::ppc_altivec_stvx:
15761   case Intrinsic::ppc_altivec_stvxl:
15762   case Intrinsic::ppc_altivec_stvebx:
15763   case Intrinsic::ppc_altivec_stvehx:
15764   case Intrinsic::ppc_altivec_stvewx:
15765   case Intrinsic::ppc_vsx_stxvd2x:
15766   case Intrinsic::ppc_vsx_stxvw4x:
15767   case Intrinsic::ppc_vsx_stxvd2x_be:
15768   case Intrinsic::ppc_vsx_stxvw4x_be:
15769   case Intrinsic::ppc_vsx_stxvl:
15770   case Intrinsic::ppc_vsx_stxvll: {
15771     EVT VT;
15772     switch (Intrinsic) {
15773     case Intrinsic::ppc_altivec_stvebx:
15774       VT = MVT::i8;
15775       break;
15776     case Intrinsic::ppc_altivec_stvehx:
15777       VT = MVT::i16;
15778       break;
15779     case Intrinsic::ppc_altivec_stvewx:
15780       VT = MVT::i32;
15781       break;
15782     case Intrinsic::ppc_vsx_stxvd2x:
15783     case Intrinsic::ppc_vsx_stxvd2x_be:
15784       VT = MVT::v2f64;
15785       break;
15786     default:
15787       VT = MVT::v4i32;
15788       break;
15789     }
15790 
15791     Info.opc = ISD::INTRINSIC_VOID;
15792     Info.memVT = VT;
15793     Info.ptrVal = I.getArgOperand(1);
15794     Info.offset = -VT.getStoreSize()+1;
15795     Info.size = 2*VT.getStoreSize()-1;
15796     Info.align = Align(1);
15797     Info.flags = MachineMemOperand::MOStore;
15798     return true;
15799   }
15800   default:
15801     break;
15802   }
15803 
15804   return false;
15805 }
15806 
15807 /// It returns EVT::Other if the type should be determined using generic
15808 /// target-independent logic.
15809 EVT PPCTargetLowering::getOptimalMemOpType(
15810     const MemOp &Op, const AttributeList &FuncAttributes) const {
15811   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15812     // We should use Altivec/VSX loads and stores when available. For unaligned
15813     // addresses, unaligned VSX loads are only fast starting with the P8.
15814     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15815         (Op.isAligned(Align(16)) ||
15816          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15817       return MVT::v4i32;
15818   }
15819 
15820   if (Subtarget.isPPC64()) {
15821     return MVT::i64;
15822   }
15823 
15824   return MVT::i32;
15825 }
15826 
15827 /// Returns true if it is beneficial to convert a load of a constant
15828 /// to just the constant itself.
15829 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15830                                                           Type *Ty) const {
15831   assert(Ty->isIntegerTy());
15832 
15833   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15834   return !(BitSize == 0 || BitSize > 64);
15835 }
15836 
15837 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15838   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15839     return false;
15840   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15841   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15842   return NumBits1 == 64 && NumBits2 == 32;
15843 }
15844 
15845 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15846   if (!VT1.isInteger() || !VT2.isInteger())
15847     return false;
15848   unsigned NumBits1 = VT1.getSizeInBits();
15849   unsigned NumBits2 = VT2.getSizeInBits();
15850   return NumBits1 == 64 && NumBits2 == 32;
15851 }
15852 
15853 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15854   // Generally speaking, zexts are not free, but they are free when they can be
15855   // folded with other operations.
15856   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15857     EVT MemVT = LD->getMemoryVT();
15858     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15859          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15860         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15861          LD->getExtensionType() == ISD::ZEXTLOAD))
15862       return true;
15863   }
15864 
15865   // FIXME: Add other cases...
15866   //  - 32-bit shifts with a zext to i64
15867   //  - zext after ctlz, bswap, etc.
15868   //  - zext after and by a constant mask
15869 
15870   return TargetLowering::isZExtFree(Val, VT2);
15871 }
15872 
15873 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15874   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15875          "invalid fpext types");
15876   // Extending to float128 is not free.
15877   if (DestVT == MVT::f128)
15878     return false;
15879   return true;
15880 }
15881 
15882 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15883   return isInt<16>(Imm) || isUInt<16>(Imm);
15884 }
15885 
15886 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15887   return isInt<16>(Imm) || isUInt<16>(Imm);
15888 }
15889 
15890 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align,
15891                                                        MachineMemOperand::Flags,
15892                                                        bool *Fast) const {
15893   if (DisablePPCUnaligned)
15894     return false;
15895 
15896   // PowerPC supports unaligned memory access for simple non-vector types.
15897   // Although accessing unaligned addresses is not as efficient as accessing
15898   // aligned addresses, it is generally more efficient than manual expansion,
15899   // and generally only traps for software emulation when crossing page
15900   // boundaries.
15901 
15902   if (!VT.isSimple())
15903     return false;
15904 
15905   if (VT.isFloatingPoint() && !VT.isVector() &&
15906       !Subtarget.allowsUnalignedFPAccess())
15907     return false;
15908 
15909   if (VT.getSimpleVT().isVector()) {
15910     if (Subtarget.hasVSX()) {
15911       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15912           VT != MVT::v4f32 && VT != MVT::v4i32)
15913         return false;
15914     } else {
15915       return false;
15916     }
15917   }
15918 
15919   if (VT == MVT::ppcf128)
15920     return false;
15921 
15922   if (Fast)
15923     *Fast = true;
15924 
15925   return true;
15926 }
15927 
15928 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
15929                                                SDValue C) const {
15930   // Check integral scalar types.
15931   if (!VT.isScalarInteger())
15932     return false;
15933   if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
15934     if (!ConstNode->getAPIntValue().isSignedIntN(64))
15935       return false;
15936     // This transformation will generate >= 2 operations. But the following
15937     // cases will generate <= 2 instructions during ISEL. So exclude them.
15938     // 1. If the constant multiplier fits 16 bits, it can be handled by one
15939     // HW instruction, ie. MULLI
15940     // 2. If the multiplier after shifted fits 16 bits, an extra shift
15941     // instruction is needed than case 1, ie. MULLI and RLDICR
15942     int64_t Imm = ConstNode->getSExtValue();
15943     unsigned Shift = countTrailingZeros<uint64_t>(Imm);
15944     Imm >>= Shift;
15945     if (isInt<16>(Imm))
15946       return false;
15947     uint64_t UImm = static_cast<uint64_t>(Imm);
15948     if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
15949         isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
15950       return true;
15951   }
15952   return false;
15953 }
15954 
15955 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15956                                                    EVT VT) const {
15957   return isFMAFasterThanFMulAndFAdd(
15958       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15959 }
15960 
15961 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15962                                                    Type *Ty) const {
15963   switch (Ty->getScalarType()->getTypeID()) {
15964   case Type::FloatTyID:
15965   case Type::DoubleTyID:
15966     return true;
15967   case Type::FP128TyID:
15968     return Subtarget.hasP9Vector();
15969   default:
15970     return false;
15971   }
15972 }
15973 
15974 // FIXME: add more patterns which are not profitable to hoist.
15975 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
15976   if (!I->hasOneUse())
15977     return true;
15978 
15979   Instruction *User = I->user_back();
15980   assert(User && "A single use instruction with no uses.");
15981 
15982   switch (I->getOpcode()) {
15983   case Instruction::FMul: {
15984     // Don't break FMA, PowerPC prefers FMA.
15985     if (User->getOpcode() != Instruction::FSub &&
15986         User->getOpcode() != Instruction::FAdd)
15987       return true;
15988 
15989     const TargetOptions &Options = getTargetMachine().Options;
15990     const Function *F = I->getFunction();
15991     const DataLayout &DL = F->getParent()->getDataLayout();
15992     Type *Ty = User->getOperand(0)->getType();
15993 
15994     return !(
15995         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
15996         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
15997         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
15998   }
15999   case Instruction::Load: {
16000     // Don't break "store (load float*)" pattern, this pattern will be combined
16001     // to "store (load int32)" in later InstCombine pass. See function
16002     // combineLoadToOperationType. On PowerPC, loading a float point takes more
16003     // cycles than loading a 32 bit integer.
16004     LoadInst *LI = cast<LoadInst>(I);
16005     // For the loads that combineLoadToOperationType does nothing, like
16006     // ordered load, it should be profitable to hoist them.
16007     // For swifterror load, it can only be used for pointer to pointer type, so
16008     // later type check should get rid of this case.
16009     if (!LI->isUnordered())
16010       return true;
16011 
16012     if (User->getOpcode() != Instruction::Store)
16013       return true;
16014 
16015     if (I->getType()->getTypeID() != Type::FloatTyID)
16016       return true;
16017 
16018     return false;
16019   }
16020   default:
16021     return true;
16022   }
16023   return true;
16024 }
16025 
16026 const MCPhysReg *
16027 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
16028   // LR is a callee-save register, but we must treat it as clobbered by any call
16029   // site. Hence we include LR in the scratch registers, which are in turn added
16030   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
16031   // to CTR, which is used by any indirect call.
16032   static const MCPhysReg ScratchRegs[] = {
16033     PPC::X12, PPC::LR8, PPC::CTR8, 0
16034   };
16035 
16036   return ScratchRegs;
16037 }
16038 
16039 Register PPCTargetLowering::getExceptionPointerRegister(
16040     const Constant *PersonalityFn) const {
16041   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
16042 }
16043 
16044 Register PPCTargetLowering::getExceptionSelectorRegister(
16045     const Constant *PersonalityFn) const {
16046   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
16047 }
16048 
16049 bool
16050 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
16051                      EVT VT , unsigned DefinedValues) const {
16052   if (VT == MVT::v2i64)
16053     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
16054 
16055   if (Subtarget.hasVSX())
16056     return true;
16057 
16058   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
16059 }
16060 
16061 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16062   if (DisableILPPref || Subtarget.enableMachineScheduler())
16063     return TargetLowering::getSchedulingPreference(N);
16064 
16065   return Sched::ILP;
16066 }
16067 
16068 // Create a fast isel object.
16069 FastISel *
16070 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16071                                   const TargetLibraryInfo *LibInfo) const {
16072   return PPC::createFastISel(FuncInfo, LibInfo);
16073 }
16074 
16075 // 'Inverted' means the FMA opcode after negating one multiplicand.
16076 // For example, (fma -a b c) = (fnmsub a b c)
16077 static unsigned invertFMAOpcode(unsigned Opc) {
16078   switch (Opc) {
16079   default:
16080     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16081   case ISD::FMA:
16082     return PPCISD::FNMSUB;
16083   case PPCISD::FNMSUB:
16084     return ISD::FMA;
16085   }
16086 }
16087 
16088 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16089                                                 bool LegalOps, bool OptForSize,
16090                                                 NegatibleCost &Cost,
16091                                                 unsigned Depth) const {
16092   if (Depth > SelectionDAG::MaxRecursionDepth)
16093     return SDValue();
16094 
16095   unsigned Opc = Op.getOpcode();
16096   EVT VT = Op.getValueType();
16097   SDNodeFlags Flags = Op.getNode()->getFlags();
16098 
16099   switch (Opc) {
16100   case PPCISD::FNMSUB:
16101     if (!Op.hasOneUse() || !isTypeLegal(VT))
16102       break;
16103 
16104     const TargetOptions &Options = getTargetMachine().Options;
16105     SDValue N0 = Op.getOperand(0);
16106     SDValue N1 = Op.getOperand(1);
16107     SDValue N2 = Op.getOperand(2);
16108     SDLoc Loc(Op);
16109 
16110     NegatibleCost N2Cost = NegatibleCost::Expensive;
16111     SDValue NegN2 =
16112         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16113 
16114     if (!NegN2)
16115       return SDValue();
16116 
16117     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16118     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16119     // These transformations may change sign of zeroes. For example,
16120     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16121     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16122       // Try and choose the cheaper one to negate.
16123       NegatibleCost N0Cost = NegatibleCost::Expensive;
16124       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16125                                            N0Cost, Depth + 1);
16126 
16127       NegatibleCost N1Cost = NegatibleCost::Expensive;
16128       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16129                                            N1Cost, Depth + 1);
16130 
16131       if (NegN0 && N0Cost <= N1Cost) {
16132         Cost = std::min(N0Cost, N2Cost);
16133         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16134       } else if (NegN1) {
16135         Cost = std::min(N1Cost, N2Cost);
16136         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16137       }
16138     }
16139 
16140     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16141     if (isOperationLegal(ISD::FMA, VT)) {
16142       Cost = N2Cost;
16143       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16144     }
16145 
16146     break;
16147   }
16148 
16149   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16150                                               Cost, Depth);
16151 }
16152 
16153 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16154 bool PPCTargetLowering::useLoadStackGuardNode() const {
16155   if (!Subtarget.isTargetLinux())
16156     return TargetLowering::useLoadStackGuardNode();
16157   return true;
16158 }
16159 
16160 // Override to disable global variable loading on Linux.
16161 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16162   if (!Subtarget.isTargetLinux())
16163     return TargetLowering::insertSSPDeclarations(M);
16164 }
16165 
16166 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16167                                      bool ForCodeSize) const {
16168   if (!VT.isSimple() || !Subtarget.hasVSX())
16169     return false;
16170 
16171   switch(VT.getSimpleVT().SimpleTy) {
16172   default:
16173     // For FP types that are currently not supported by PPC backend, return
16174     // false. Examples: f16, f80.
16175     return false;
16176   case MVT::f32:
16177   case MVT::f64:
16178     if (Subtarget.hasPrefixInstrs()) {
16179       // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP.
16180       return true;
16181     }
16182     LLVM_FALLTHROUGH;
16183   case MVT::ppcf128:
16184     return Imm.isPosZero();
16185   }
16186 }
16187 
16188 // For vector shift operation op, fold
16189 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16190 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16191                                   SelectionDAG &DAG) {
16192   SDValue N0 = N->getOperand(0);
16193   SDValue N1 = N->getOperand(1);
16194   EVT VT = N0.getValueType();
16195   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16196   unsigned Opcode = N->getOpcode();
16197   unsigned TargetOpcode;
16198 
16199   switch (Opcode) {
16200   default:
16201     llvm_unreachable("Unexpected shift operation");
16202   case ISD::SHL:
16203     TargetOpcode = PPCISD::SHL;
16204     break;
16205   case ISD::SRL:
16206     TargetOpcode = PPCISD::SRL;
16207     break;
16208   case ISD::SRA:
16209     TargetOpcode = PPCISD::SRA;
16210     break;
16211   }
16212 
16213   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16214       N1->getOpcode() == ISD::AND)
16215     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16216       if (Mask->getZExtValue() == OpSizeInBits - 1)
16217         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16218 
16219   return SDValue();
16220 }
16221 
16222 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16223   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16224     return Value;
16225 
16226   SDValue N0 = N->getOperand(0);
16227   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16228   if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
16229       N0.getOpcode() != ISD::SIGN_EXTEND ||
16230       N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
16231       N->getValueType(0) != MVT::i64)
16232     return SDValue();
16233 
16234   // We can't save an operation here if the value is already extended, and
16235   // the existing shift is easier to combine.
16236   SDValue ExtsSrc = N0.getOperand(0);
16237   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16238       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16239     return SDValue();
16240 
16241   SDLoc DL(N0);
16242   SDValue ShiftBy = SDValue(CN1, 0);
16243   // We want the shift amount to be i32 on the extswli, but the shift could
16244   // have an i64.
16245   if (ShiftBy.getValueType() == MVT::i64)
16246     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16247 
16248   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16249                          ShiftBy);
16250 }
16251 
16252 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16253   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16254     return Value;
16255 
16256   return SDValue();
16257 }
16258 
16259 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16260   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16261     return Value;
16262 
16263   return SDValue();
16264 }
16265 
16266 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16267 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16268 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16269 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16270 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16271                                  const PPCSubtarget &Subtarget) {
16272   if (!Subtarget.isPPC64())
16273     return SDValue();
16274 
16275   SDValue LHS = N->getOperand(0);
16276   SDValue RHS = N->getOperand(1);
16277 
16278   auto isZextOfCompareWithConstant = [](SDValue Op) {
16279     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16280         Op.getValueType() != MVT::i64)
16281       return false;
16282 
16283     SDValue Cmp = Op.getOperand(0);
16284     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16285         Cmp.getOperand(0).getValueType() != MVT::i64)
16286       return false;
16287 
16288     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
16289       int64_t NegConstant = 0 - Constant->getSExtValue();
16290       // Due to the limitations of the addi instruction,
16291       // -C is required to be [-32768, 32767].
16292       return isInt<16>(NegConstant);
16293     }
16294 
16295     return false;
16296   };
16297 
16298   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
16299   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16300 
16301   // If there is a pattern, canonicalize a zext operand to the RHS.
16302   if (LHSHasPattern && !RHSHasPattern)
16303     std::swap(LHS, RHS);
16304   else if (!LHSHasPattern && !RHSHasPattern)
16305     return SDValue();
16306 
16307   SDLoc DL(N);
16308   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16309   SDValue Cmp = RHS.getOperand(0);
16310   SDValue Z = Cmp.getOperand(0);
16311   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
16312 
16313   assert(Constant && "Constant Should not be a null pointer.");
16314   int64_t NegConstant = 0 - Constant->getSExtValue();
16315 
16316   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16317   default: break;
16318   case ISD::SETNE: {
16319     //                                 when C == 0
16320     //                             --> addze X, (addic Z, -1).carry
16321     //                            /
16322     // add X, (zext(setne Z, C))--
16323     //                            \    when -32768 <= -C <= 32767 && C != 0
16324     //                             --> addze X, (addic (addi Z, -C), -1).carry
16325     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16326                               DAG.getConstant(NegConstant, DL, MVT::i64));
16327     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16328     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16329                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16330     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16331                        SDValue(Addc.getNode(), 1));
16332     }
16333   case ISD::SETEQ: {
16334     //                                 when C == 0
16335     //                             --> addze X, (subfic Z, 0).carry
16336     //                            /
16337     // add X, (zext(sete  Z, C))--
16338     //                            \    when -32768 <= -C <= 32767 && C != 0
16339     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16340     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16341                               DAG.getConstant(NegConstant, DL, MVT::i64));
16342     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16343     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16344                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16345     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16346                        SDValue(Subc.getNode(), 1));
16347     }
16348   }
16349 
16350   return SDValue();
16351 }
16352 
16353 // Transform
16354 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16355 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16356 // In this case both C1 and C2 must be known constants.
16357 // C1+C2 must fit into a 34 bit signed integer.
16358 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16359                                           const PPCSubtarget &Subtarget) {
16360   if (!Subtarget.isUsingPCRelativeCalls())
16361     return SDValue();
16362 
16363   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16364   // If we find that node try to cast the Global Address and the Constant.
16365   SDValue LHS = N->getOperand(0);
16366   SDValue RHS = N->getOperand(1);
16367 
16368   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16369     std::swap(LHS, RHS);
16370 
16371   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16372     return SDValue();
16373 
16374   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16375   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16376   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16377 
16378   // Check that both casts succeeded.
16379   if (!GSDN || !ConstNode)
16380     return SDValue();
16381 
16382   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16383   SDLoc DL(GSDN);
16384 
16385   // The signed int offset needs to fit in 34 bits.
16386   if (!isInt<34>(NewOffset))
16387     return SDValue();
16388 
16389   // The new global address is a copy of the old global address except
16390   // that it has the updated Offset.
16391   SDValue GA =
16392       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16393                                  NewOffset, GSDN->getTargetFlags());
16394   SDValue MatPCRel =
16395       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16396   return MatPCRel;
16397 }
16398 
16399 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16400   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16401     return Value;
16402 
16403   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16404     return Value;
16405 
16406   return SDValue();
16407 }
16408 
16409 // Detect TRUNCATE operations on bitcasts of float128 values.
16410 // What we are looking for here is the situtation where we extract a subset
16411 // of bits from a 128 bit float.
16412 // This can be of two forms:
16413 // 1) BITCAST of f128 feeding TRUNCATE
16414 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16415 // The reason this is required is because we do not have a legal i128 type
16416 // and so we want to prevent having to store the f128 and then reload part
16417 // of it.
16418 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16419                                            DAGCombinerInfo &DCI) const {
16420   // If we are using CRBits then try that first.
16421   if (Subtarget.useCRBits()) {
16422     // Check if CRBits did anything and return that if it did.
16423     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16424       return CRTruncValue;
16425   }
16426 
16427   SDLoc dl(N);
16428   SDValue Op0 = N->getOperand(0);
16429 
16430   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
16431   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
16432     EVT VT = N->getValueType(0);
16433     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16434       return SDValue();
16435     SDValue Sub = Op0.getOperand(0);
16436     if (Sub.getOpcode() == ISD::SUB) {
16437       SDValue SubOp0 = Sub.getOperand(0);
16438       SDValue SubOp1 = Sub.getOperand(1);
16439       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16440           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16441         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16442                                SubOp1.getOperand(0),
16443                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16444       }
16445     }
16446   }
16447 
16448   // Looking for a truncate of i128 to i64.
16449   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16450     return SDValue();
16451 
16452   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16453 
16454   // SRL feeding TRUNCATE.
16455   if (Op0.getOpcode() == ISD::SRL) {
16456     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16457     // The right shift has to be by 64 bits.
16458     if (!ConstNode || ConstNode->getZExtValue() != 64)
16459       return SDValue();
16460 
16461     // Switch the element number to extract.
16462     EltToExtract = EltToExtract ? 0 : 1;
16463     // Update Op0 past the SRL.
16464     Op0 = Op0.getOperand(0);
16465   }
16466 
16467   // BITCAST feeding a TRUNCATE possibly via SRL.
16468   if (Op0.getOpcode() == ISD::BITCAST &&
16469       Op0.getValueType() == MVT::i128 &&
16470       Op0.getOperand(0).getValueType() == MVT::f128) {
16471     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16472     return DCI.DAG.getNode(
16473         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16474         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16475   }
16476   return SDValue();
16477 }
16478 
16479 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16480   SelectionDAG &DAG = DCI.DAG;
16481 
16482   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16483   if (!ConstOpOrElement)
16484     return SDValue();
16485 
16486   // An imul is usually smaller than the alternative sequence for legal type.
16487   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16488       isOperationLegal(ISD::MUL, N->getValueType(0)))
16489     return SDValue();
16490 
16491   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16492     switch (this->Subtarget.getCPUDirective()) {
16493     default:
16494       // TODO: enhance the condition for subtarget before pwr8
16495       return false;
16496     case PPC::DIR_PWR8:
16497       //  type        mul     add    shl
16498       // scalar        4       1      1
16499       // vector        7       2      2
16500       return true;
16501     case PPC::DIR_PWR9:
16502     case PPC::DIR_PWR10:
16503     case PPC::DIR_PWR_FUTURE:
16504       //  type        mul     add    shl
16505       // scalar        5       2      2
16506       // vector        7       2      2
16507 
16508       // The cycle RATIO of related operations are showed as a table above.
16509       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16510       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16511       // are 4, it is always profitable; but for 3 instrs patterns
16512       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16513       // So we should only do it for vector type.
16514       return IsAddOne && IsNeg ? VT.isVector() : true;
16515     }
16516   };
16517 
16518   EVT VT = N->getValueType(0);
16519   SDLoc DL(N);
16520 
16521   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16522   bool IsNeg = MulAmt.isNegative();
16523   APInt MulAmtAbs = MulAmt.abs();
16524 
16525   if ((MulAmtAbs - 1).isPowerOf2()) {
16526     // (mul x, 2^N + 1) => (add (shl x, N), x)
16527     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16528 
16529     if (!IsProfitable(IsNeg, true, VT))
16530       return SDValue();
16531 
16532     SDValue Op0 = N->getOperand(0);
16533     SDValue Op1 =
16534         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16535                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16536     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16537 
16538     if (!IsNeg)
16539       return Res;
16540 
16541     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16542   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16543     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16544     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16545 
16546     if (!IsProfitable(IsNeg, false, VT))
16547       return SDValue();
16548 
16549     SDValue Op0 = N->getOperand(0);
16550     SDValue Op1 =
16551         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16552                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16553 
16554     if (!IsNeg)
16555       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16556     else
16557       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16558 
16559   } else {
16560     return SDValue();
16561   }
16562 }
16563 
16564 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16565 // in combiner since we need to check SD flags and other subtarget features.
16566 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16567                                           DAGCombinerInfo &DCI) const {
16568   SDValue N0 = N->getOperand(0);
16569   SDValue N1 = N->getOperand(1);
16570   SDValue N2 = N->getOperand(2);
16571   SDNodeFlags Flags = N->getFlags();
16572   EVT VT = N->getValueType(0);
16573   SelectionDAG &DAG = DCI.DAG;
16574   const TargetOptions &Options = getTargetMachine().Options;
16575   unsigned Opc = N->getOpcode();
16576   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16577   bool LegalOps = !DCI.isBeforeLegalizeOps();
16578   SDLoc Loc(N);
16579 
16580   if (!isOperationLegal(ISD::FMA, VT))
16581     return SDValue();
16582 
16583   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16584   // since (fnmsub a b c)=-0 while c-ab=+0.
16585   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16586     return SDValue();
16587 
16588   // (fma (fneg a) b c) => (fnmsub a b c)
16589   // (fnmsub (fneg a) b c) => (fma a b c)
16590   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16591     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16592 
16593   // (fma a (fneg b) c) => (fnmsub a b c)
16594   // (fnmsub a (fneg b) c) => (fma a b c)
16595   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16596     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16597 
16598   return SDValue();
16599 }
16600 
16601 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16602   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16603   if (!Subtarget.is64BitELFABI())
16604     return false;
16605 
16606   // If not a tail call then no need to proceed.
16607   if (!CI->isTailCall())
16608     return false;
16609 
16610   // If sibling calls have been disabled and tail-calls aren't guaranteed
16611   // there is no reason to duplicate.
16612   auto &TM = getTargetMachine();
16613   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16614     return false;
16615 
16616   // Can't tail call a function called indirectly, or if it has variadic args.
16617   const Function *Callee = CI->getCalledFunction();
16618   if (!Callee || Callee->isVarArg())
16619     return false;
16620 
16621   // Make sure the callee and caller calling conventions are eligible for tco.
16622   const Function *Caller = CI->getParent()->getParent();
16623   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16624                                            CI->getCallingConv()))
16625       return false;
16626 
16627   // If the function is local then we have a good chance at tail-calling it
16628   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16629 }
16630 
16631 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16632   if (!Subtarget.hasVSX())
16633     return false;
16634   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16635     return true;
16636   return VT == MVT::f32 || VT == MVT::f64 ||
16637     VT == MVT::v4f32 || VT == MVT::v2f64;
16638 }
16639 
16640 bool PPCTargetLowering::
16641 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16642   const Value *Mask = AndI.getOperand(1);
16643   // If the mask is suitable for andi. or andis. we should sink the and.
16644   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16645     // Can't handle constants wider than 64-bits.
16646     if (CI->getBitWidth() > 64)
16647       return false;
16648     int64_t ConstVal = CI->getZExtValue();
16649     return isUInt<16>(ConstVal) ||
16650       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16651   }
16652 
16653   // For non-constant masks, we can always use the record-form and.
16654   return true;
16655 }
16656 
16657 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16658 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16659 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16660 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16661 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16662 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16663   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16664   assert(Subtarget.hasP9Altivec() &&
16665          "Only combine this when P9 altivec supported!");
16666   EVT VT = N->getValueType(0);
16667   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16668     return SDValue();
16669 
16670   SelectionDAG &DAG = DCI.DAG;
16671   SDLoc dl(N);
16672   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16673     // Even for signed integers, if it's known to be positive (as signed
16674     // integer) due to zero-extended inputs.
16675     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16676     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16677     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16678          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16679         (SubOpcd1 == ISD::ZERO_EXTEND ||
16680          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16681       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16682                          N->getOperand(0)->getOperand(0),
16683                          N->getOperand(0)->getOperand(1),
16684                          DAG.getTargetConstant(0, dl, MVT::i32));
16685     }
16686 
16687     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16688     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16689         N->getOperand(0).hasOneUse()) {
16690       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16691                          N->getOperand(0)->getOperand(0),
16692                          N->getOperand(0)->getOperand(1),
16693                          DAG.getTargetConstant(1, dl, MVT::i32));
16694     }
16695   }
16696 
16697   return SDValue();
16698 }
16699 
16700 // For type v4i32/v8ii16/v16i8, transform
16701 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16702 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16703 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16704 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16705 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16706                                           DAGCombinerInfo &DCI) const {
16707   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16708   assert(Subtarget.hasP9Altivec() &&
16709          "Only combine this when P9 altivec supported!");
16710 
16711   SelectionDAG &DAG = DCI.DAG;
16712   SDLoc dl(N);
16713   SDValue Cond = N->getOperand(0);
16714   SDValue TrueOpnd = N->getOperand(1);
16715   SDValue FalseOpnd = N->getOperand(2);
16716   EVT VT = N->getOperand(1).getValueType();
16717 
16718   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16719       FalseOpnd.getOpcode() != ISD::SUB)
16720     return SDValue();
16721 
16722   // ABSD only available for type v4i32/v8i16/v16i8
16723   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16724     return SDValue();
16725 
16726   // At least to save one more dependent computation
16727   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16728     return SDValue();
16729 
16730   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16731 
16732   // Can only handle unsigned comparison here
16733   switch (CC) {
16734   default:
16735     return SDValue();
16736   case ISD::SETUGT:
16737   case ISD::SETUGE:
16738     break;
16739   case ISD::SETULT:
16740   case ISD::SETULE:
16741     std::swap(TrueOpnd, FalseOpnd);
16742     break;
16743   }
16744 
16745   SDValue CmpOpnd1 = Cond.getOperand(0);
16746   SDValue CmpOpnd2 = Cond.getOperand(1);
16747 
16748   // SETCC CmpOpnd1 CmpOpnd2 cond
16749   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16750   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16751   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16752       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16753       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16754       FalseOpnd.getOperand(1) == CmpOpnd1) {
16755     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16756                        CmpOpnd1, CmpOpnd2,
16757                        DAG.getTargetConstant(0, dl, MVT::i32));
16758   }
16759 
16760   return SDValue();
16761 }
16762