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 static cl::opt<bool> EnableQuadwordAtomics(
125     "ppc-quadword-atomics",
126     cl::desc("enable quadword lock-free atomic operations"), cl::init(false),
127     cl::Hidden);
128 
129 STATISTIC(NumTailCalls, "Number of tail calls");
130 STATISTIC(NumSiblingCalls, "Number of sibling calls");
131 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM");
132 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
133 
134 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
135 
136 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
137 
138 static const char AIXSSPCanaryWordName[] = "__ssp_canary_word";
139 
140 // FIXME: Remove this once the bug has been fixed!
141 extern cl::opt<bool> ANDIGlueBug;
142 
143 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
144                                      const PPCSubtarget &STI)
145     : TargetLowering(TM), Subtarget(STI) {
146   // Initialize map that relates the PPC addressing modes to the computed flags
147   // of a load/store instruction. The map is used to determine the optimal
148   // addressing mode when selecting load and stores.
149   initializeAddrModeMap();
150   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
151   // arguments are at least 4/8 bytes aligned.
152   bool isPPC64 = Subtarget.isPPC64();
153   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
154 
155   // Set up the register classes.
156   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
157   if (!useSoftFloat()) {
158     if (hasSPE()) {
159       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
160       // EFPU2 APU only supports f32
161       if (!Subtarget.hasEFPU2())
162         addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
163     } else {
164       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
165       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
166     }
167   }
168 
169   // Match BITREVERSE to customized fast code sequence in the td file.
170   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
171   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
172 
173   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
174   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
175 
176   // Custom lower inline assembly to check for special registers.
177   setOperationAction(ISD::INLINEASM, MVT::Other, Custom);
178   setOperationAction(ISD::INLINEASM_BR, MVT::Other, Custom);
179 
180   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
181   for (MVT VT : MVT::integer_valuetypes()) {
182     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
183     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
184   }
185 
186   if (Subtarget.isISA3_0()) {
187     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
188     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
189     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
190     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
191   } else {
192     // No extending loads from f16 or HW conversions back and forth.
193     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
194     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
195     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
196     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
197     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
198     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
199     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
200     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
201   }
202 
203   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
204 
205   // PowerPC has pre-inc load and store's.
206   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
207   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
208   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
209   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
210   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
211   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
212   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
213   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
214   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
215   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
216   if (!Subtarget.hasSPE()) {
217     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
218     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
219     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
220     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
221   }
222 
223   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
224   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
225   for (MVT VT : ScalarIntVTs) {
226     setOperationAction(ISD::ADDC, VT, Legal);
227     setOperationAction(ISD::ADDE, VT, Legal);
228     setOperationAction(ISD::SUBC, VT, Legal);
229     setOperationAction(ISD::SUBE, VT, Legal);
230   }
231 
232   if (Subtarget.useCRBits()) {
233     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
234 
235     if (isPPC64 || Subtarget.hasFPCVT()) {
236       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote);
237       AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1,
238                         isPPC64 ? MVT::i64 : MVT::i32);
239       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote);
240       AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1,
241                         isPPC64 ? MVT::i64 : MVT::i32);
242 
243       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
244       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
245                          isPPC64 ? MVT::i64 : MVT::i32);
246       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
247       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
248                         isPPC64 ? MVT::i64 : MVT::i32);
249 
250       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote);
251       AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1,
252                         isPPC64 ? MVT::i64 : MVT::i32);
253       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote);
254       AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1,
255                         isPPC64 ? MVT::i64 : MVT::i32);
256 
257       setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
258       AddPromotedToType(ISD::FP_TO_SINT, MVT::i1,
259                         isPPC64 ? MVT::i64 : MVT::i32);
260       setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
261       AddPromotedToType(ISD::FP_TO_UINT, MVT::i1,
262                         isPPC64 ? MVT::i64 : MVT::i32);
263     } else {
264       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom);
265       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom);
266       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
267       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
268     }
269 
270     // PowerPC does not support direct load/store of condition registers.
271     setOperationAction(ISD::LOAD, MVT::i1, Custom);
272     setOperationAction(ISD::STORE, MVT::i1, Custom);
273 
274     // FIXME: Remove this once the ANDI glue bug is fixed:
275     if (ANDIGlueBug)
276       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
277 
278     for (MVT VT : MVT::integer_valuetypes()) {
279       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
280       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
281       setTruncStoreAction(VT, MVT::i1, Expand);
282     }
283 
284     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
285   }
286 
287   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
288   // PPC (the libcall is not available).
289   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
290   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
291   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom);
292   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom);
293 
294   // We do not currently implement these libm ops for PowerPC.
295   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
296   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
297   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
298   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
299   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
300   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
301 
302   // PowerPC has no SREM/UREM instructions unless we are on P9
303   // On P9 we may use a hardware instruction to compute the remainder.
304   // When the result of both the remainder and the division is required it is
305   // more efficient to compute the remainder from the result of the division
306   // rather than use the remainder instruction. The instructions are legalized
307   // directly because the DivRemPairsPass performs the transformation at the IR
308   // level.
309   if (Subtarget.isISA3_0()) {
310     setOperationAction(ISD::SREM, MVT::i32, Legal);
311     setOperationAction(ISD::UREM, MVT::i32, Legal);
312     setOperationAction(ISD::SREM, MVT::i64, Legal);
313     setOperationAction(ISD::UREM, MVT::i64, Legal);
314   } else {
315     setOperationAction(ISD::SREM, MVT::i32, Expand);
316     setOperationAction(ISD::UREM, MVT::i32, Expand);
317     setOperationAction(ISD::SREM, MVT::i64, Expand);
318     setOperationAction(ISD::UREM, MVT::i64, Expand);
319   }
320 
321   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
322   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
323   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
324   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
325   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
326   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
327   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
328   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
329   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
330 
331   // Handle constrained floating-point operations of scalar.
332   // TODO: Handle SPE specific operation.
333   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
334   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
335   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
336   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
337   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
338 
339   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
340   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
341   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
342   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
343 
344   if (!Subtarget.hasSPE()) {
345     setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
346     setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
347   }
348 
349   if (Subtarget.hasVSX()) {
350     setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal);
351     setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal);
352   }
353 
354   if (Subtarget.hasFSQRT()) {
355     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
356     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
357   }
358 
359   if (Subtarget.hasFPRND()) {
360     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
361     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
362     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
363     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
364 
365     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
366     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
367     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
368     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
369   }
370 
371   // We don't support sin/cos/sqrt/fmod/pow
372   setOperationAction(ISD::FSIN , MVT::f64, Expand);
373   setOperationAction(ISD::FCOS , MVT::f64, Expand);
374   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
375   setOperationAction(ISD::FREM , MVT::f64, Expand);
376   setOperationAction(ISD::FPOW , MVT::f64, Expand);
377   setOperationAction(ISD::FSIN , MVT::f32, Expand);
378   setOperationAction(ISD::FCOS , MVT::f32, Expand);
379   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
380   setOperationAction(ISD::FREM , MVT::f32, Expand);
381   setOperationAction(ISD::FPOW , MVT::f32, Expand);
382   if (Subtarget.hasSPE()) {
383     setOperationAction(ISD::FMA  , MVT::f64, Expand);
384     setOperationAction(ISD::FMA  , MVT::f32, Expand);
385   } else {
386     setOperationAction(ISD::FMA  , MVT::f64, Legal);
387     setOperationAction(ISD::FMA  , MVT::f32, Legal);
388   }
389 
390   if (Subtarget.hasSPE())
391     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
392 
393   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
394 
395   // If we're enabling GP optimizations, use hardware square root
396   if (!Subtarget.hasFSQRT() &&
397       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
398         Subtarget.hasFRE()))
399     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
400 
401   if (!Subtarget.hasFSQRT() &&
402       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
403         Subtarget.hasFRES()))
404     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
405 
406   if (Subtarget.hasFCPSGN()) {
407     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
408     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
409   } else {
410     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
411     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
412   }
413 
414   if (Subtarget.hasFPRND()) {
415     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
416     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
417     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
418     setOperationAction(ISD::FROUND, MVT::f64, Legal);
419 
420     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
421     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
422     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
423     setOperationAction(ISD::FROUND, MVT::f32, Legal);
424   }
425 
426   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
427   // to speed up scalar BSWAP64.
428   // CTPOP or CTTZ were introduced in P8/P9 respectively
429   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
430   if (Subtarget.hasP9Vector() && Subtarget.isPPC64())
431     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
432   else
433     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
434   if (Subtarget.isISA3_0()) {
435     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
436     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
437   } else {
438     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
439     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
440   }
441 
442   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
443     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
444     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
445   } else {
446     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
447     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
448   }
449 
450   // PowerPC does not have ROTR
451   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
452   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
453 
454   if (!Subtarget.useCRBits()) {
455     // PowerPC does not have Select
456     setOperationAction(ISD::SELECT, MVT::i32, Expand);
457     setOperationAction(ISD::SELECT, MVT::i64, Expand);
458     setOperationAction(ISD::SELECT, MVT::f32, Expand);
459     setOperationAction(ISD::SELECT, MVT::f64, Expand);
460   }
461 
462   // PowerPC wants to turn select_cc of FP into fsel when possible.
463   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
464   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
465 
466   // PowerPC wants to optimize integer setcc a bit
467   if (!Subtarget.useCRBits())
468     setOperationAction(ISD::SETCC, MVT::i32, Custom);
469 
470   if (Subtarget.hasFPU()) {
471     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
472     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
473     setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
474 
475     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
476     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
477     setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
478   }
479 
480   // PowerPC does not have BRCOND which requires SetCC
481   if (!Subtarget.useCRBits())
482     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
483 
484   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
485 
486   if (Subtarget.hasSPE()) {
487     // SPE has built-in conversions
488     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
489     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
490     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
491     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
492     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
493     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
494 
495     // SPE supports signaling compare of f32/f64.
496     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
497     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
498   } else {
499     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
500     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
501     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
502 
503     // PowerPC does not have [U|S]INT_TO_FP
504     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand);
505     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand);
506     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
507     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
508   }
509 
510   if (Subtarget.hasDirectMove() && isPPC64) {
511     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
512     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
513     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
514     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
515     if (TM.Options.UnsafeFPMath) {
516       setOperationAction(ISD::LRINT, MVT::f64, Legal);
517       setOperationAction(ISD::LRINT, MVT::f32, Legal);
518       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
519       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
520       setOperationAction(ISD::LROUND, MVT::f64, Legal);
521       setOperationAction(ISD::LROUND, MVT::f32, Legal);
522       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
523       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
524     }
525   } else {
526     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
527     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
528     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
529     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
530   }
531 
532   // We cannot sextinreg(i1).  Expand to shifts.
533   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
534 
535   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
536   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
537   // support continuation, user-level threading, and etc.. As a result, no
538   // other SjLj exception interfaces are implemented and please don't build
539   // your own exception handling based on them.
540   // LLVM/Clang supports zero-cost DWARF exception handling.
541   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
542   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
543 
544   // We want to legalize GlobalAddress and ConstantPool nodes into the
545   // appropriate instructions to materialize the address.
546   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
547   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
548   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
549   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
550   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
551   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
552   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
553   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
554   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
555   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
556 
557   // TRAP is legal.
558   setOperationAction(ISD::TRAP, MVT::Other, Legal);
559 
560   // TRAMPOLINE is custom lowered.
561   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
562   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
563 
564   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
565   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
566 
567   if (Subtarget.is64BitELFABI()) {
568     // VAARG always uses double-word chunks, so promote anything smaller.
569     setOperationAction(ISD::VAARG, MVT::i1, Promote);
570     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
571     setOperationAction(ISD::VAARG, MVT::i8, Promote);
572     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
573     setOperationAction(ISD::VAARG, MVT::i16, Promote);
574     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
575     setOperationAction(ISD::VAARG, MVT::i32, Promote);
576     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
577     setOperationAction(ISD::VAARG, MVT::Other, Expand);
578   } else if (Subtarget.is32BitELFABI()) {
579     // VAARG is custom lowered with the 32-bit SVR4 ABI.
580     setOperationAction(ISD::VAARG, MVT::Other, Custom);
581     setOperationAction(ISD::VAARG, MVT::i64, Custom);
582   } else
583     setOperationAction(ISD::VAARG, MVT::Other, Expand);
584 
585   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
586   if (Subtarget.is32BitELFABI())
587     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
588   else
589     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
590 
591   // Use the default implementation.
592   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
593   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
594   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
595   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
596   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
597   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
598   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
599   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
600   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
601 
602   // We want to custom lower some of our intrinsics.
603   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
604   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f64, Custom);
605   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::ppcf128, Custom);
606 
607   // To handle counter-based loop conditions.
608   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
609 
610   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
611   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
612   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
613   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
614 
615   // Comparisons that require checking two conditions.
616   if (Subtarget.hasSPE()) {
617     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
618     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
619     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
620     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
621   }
622   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
623   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
624   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
625   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
626   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
627   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
628   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
629   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
630   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
631   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
632   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
633   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
634 
635   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
636   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
637 
638   if (Subtarget.has64BitSupport()) {
639     // They also have instructions for converting between i64 and fp.
640     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
641     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
642     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
643     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
644     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
645     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
646     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
647     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
648     // This is just the low 32 bits of a (signed) fp->i64 conversion.
649     // We cannot do this with Promote because i64 is not a legal type.
650     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
651     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
652 
653     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
654       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
655       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
656     }
657   } else {
658     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
659     if (Subtarget.hasSPE()) {
660       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
661       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
662     } else {
663       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
664       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
665     }
666   }
667 
668   // With the instructions enabled under FPCVT, we can do everything.
669   if (Subtarget.hasFPCVT()) {
670     if (Subtarget.has64BitSupport()) {
671       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
672       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
673       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
674       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
675       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
676       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
677       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
678       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
679     }
680 
681     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
682     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
683     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
684     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
685     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
686     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
687     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
688     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
689   }
690 
691   if (Subtarget.use64BitRegs()) {
692     // 64-bit PowerPC implementations can support i64 types directly
693     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
694     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
695     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
696     // 64-bit PowerPC wants to expand i128 shifts itself.
697     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
698     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
699     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
700   } else {
701     // 32-bit PowerPC wants to expand i64 shifts itself.
702     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
703     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
704     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
705   }
706 
707   // PowerPC has better expansions for funnel shifts than the generic
708   // TargetLowering::expandFunnelShift.
709   if (Subtarget.has64BitSupport()) {
710     setOperationAction(ISD::FSHL, MVT::i64, Custom);
711     setOperationAction(ISD::FSHR, MVT::i64, Custom);
712   }
713   setOperationAction(ISD::FSHL, MVT::i32, Custom);
714   setOperationAction(ISD::FSHR, MVT::i32, Custom);
715 
716   if (Subtarget.hasVSX()) {
717     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
718     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
719     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
720     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
721   }
722 
723   if (Subtarget.hasAltivec()) {
724     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
725       setOperationAction(ISD::SADDSAT, VT, Legal);
726       setOperationAction(ISD::SSUBSAT, VT, Legal);
727       setOperationAction(ISD::UADDSAT, VT, Legal);
728       setOperationAction(ISD::USUBSAT, VT, Legal);
729     }
730     // First set operation action for all vector types to expand. Then we
731     // will selectively turn on ones that can be effectively codegen'd.
732     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
733       // add/sub are legal for all supported vector VT's.
734       setOperationAction(ISD::ADD, VT, Legal);
735       setOperationAction(ISD::SUB, VT, Legal);
736 
737       // For v2i64, these are only valid with P8Vector. This is corrected after
738       // the loop.
739       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
740         setOperationAction(ISD::SMAX, VT, Legal);
741         setOperationAction(ISD::SMIN, VT, Legal);
742         setOperationAction(ISD::UMAX, VT, Legal);
743         setOperationAction(ISD::UMIN, VT, Legal);
744       }
745       else {
746         setOperationAction(ISD::SMAX, VT, Expand);
747         setOperationAction(ISD::SMIN, VT, Expand);
748         setOperationAction(ISD::UMAX, VT, Expand);
749         setOperationAction(ISD::UMIN, VT, Expand);
750       }
751 
752       if (Subtarget.hasVSX()) {
753         setOperationAction(ISD::FMAXNUM, VT, Legal);
754         setOperationAction(ISD::FMINNUM, VT, Legal);
755       }
756 
757       // Vector instructions introduced in P8
758       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
759         setOperationAction(ISD::CTPOP, VT, Legal);
760         setOperationAction(ISD::CTLZ, VT, Legal);
761       }
762       else {
763         setOperationAction(ISD::CTPOP, VT, Expand);
764         setOperationAction(ISD::CTLZ, VT, Expand);
765       }
766 
767       // Vector instructions introduced in P9
768       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
769         setOperationAction(ISD::CTTZ, VT, Legal);
770       else
771         setOperationAction(ISD::CTTZ, VT, Expand);
772 
773       // We promote all shuffles to v16i8.
774       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
775       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
776 
777       // We promote all non-typed operations to v4i32.
778       setOperationAction(ISD::AND   , VT, Promote);
779       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
780       setOperationAction(ISD::OR    , VT, Promote);
781       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
782       setOperationAction(ISD::XOR   , VT, Promote);
783       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
784       setOperationAction(ISD::LOAD  , VT, Promote);
785       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
786       setOperationAction(ISD::SELECT, VT, Promote);
787       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
788       setOperationAction(ISD::VSELECT, VT, Legal);
789       setOperationAction(ISD::SELECT_CC, VT, Promote);
790       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
791       setOperationAction(ISD::STORE, VT, Promote);
792       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
793 
794       // No other operations are legal.
795       setOperationAction(ISD::MUL , VT, Expand);
796       setOperationAction(ISD::SDIV, VT, Expand);
797       setOperationAction(ISD::SREM, VT, Expand);
798       setOperationAction(ISD::UDIV, VT, Expand);
799       setOperationAction(ISD::UREM, VT, Expand);
800       setOperationAction(ISD::FDIV, VT, Expand);
801       setOperationAction(ISD::FREM, VT, Expand);
802       setOperationAction(ISD::FNEG, VT, Expand);
803       setOperationAction(ISD::FSQRT, VT, Expand);
804       setOperationAction(ISD::FLOG, VT, Expand);
805       setOperationAction(ISD::FLOG10, VT, Expand);
806       setOperationAction(ISD::FLOG2, VT, Expand);
807       setOperationAction(ISD::FEXP, VT, Expand);
808       setOperationAction(ISD::FEXP2, VT, Expand);
809       setOperationAction(ISD::FSIN, VT, Expand);
810       setOperationAction(ISD::FCOS, VT, Expand);
811       setOperationAction(ISD::FABS, VT, Expand);
812       setOperationAction(ISD::FFLOOR, VT, Expand);
813       setOperationAction(ISD::FCEIL,  VT, Expand);
814       setOperationAction(ISD::FTRUNC, VT, Expand);
815       setOperationAction(ISD::FRINT,  VT, Expand);
816       setOperationAction(ISD::FNEARBYINT, VT, Expand);
817       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
818       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
819       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
820       setOperationAction(ISD::MULHU, VT, Expand);
821       setOperationAction(ISD::MULHS, VT, Expand);
822       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
823       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
824       setOperationAction(ISD::UDIVREM, VT, Expand);
825       setOperationAction(ISD::SDIVREM, VT, Expand);
826       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
827       setOperationAction(ISD::FPOW, VT, Expand);
828       setOperationAction(ISD::BSWAP, VT, Expand);
829       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
830       setOperationAction(ISD::ROTL, VT, Expand);
831       setOperationAction(ISD::ROTR, VT, Expand);
832 
833       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
834         setTruncStoreAction(VT, InnerVT, Expand);
835         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
836         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
837         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
838       }
839     }
840     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
841     if (!Subtarget.hasP8Vector()) {
842       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
843       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
844       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
845       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
846     }
847 
848     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
849     // with merges, splats, etc.
850     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
851 
852     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
853     // are cheap, so handle them before they get expanded to scalar.
854     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
855     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
856     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
857     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
858     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
859 
860     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
861     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
862     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
863     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
864     setOperationAction(ISD::SELECT, MVT::v4i32,
865                        Subtarget.useCRBits() ? Legal : Expand);
866     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
867     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
868     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
869     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
870     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
871     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
872     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
873     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
874     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
875     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
876     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
877     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
878     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
879 
880     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
881     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
882     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
883     if (Subtarget.hasAltivec())
884       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
885         setOperationAction(ISD::ROTL, VT, Legal);
886     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
887     if (Subtarget.hasP8Altivec())
888       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
889 
890     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
891     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
892     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
893     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
894 
895     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
896     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
897 
898     if (Subtarget.hasVSX()) {
899       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
900       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
901       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
902     }
903 
904     if (Subtarget.hasP8Altivec())
905       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
906     else
907       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
908 
909     if (Subtarget.isISA3_1()) {
910       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
911       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
912       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
913       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
914       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
915       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
916       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
917       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
918       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
919       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
920       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
921       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
922       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
923       setOperationAction(ISD::UREM, MVT::v1i128, Legal);
924       setOperationAction(ISD::SREM, MVT::v1i128, Legal);
925       setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
926       setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
927       setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
928     }
929 
930     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
931     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
932 
933     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
934     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
935 
936     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
937     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
938     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
939     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
940 
941     // Altivec does not contain unordered floating-point compare instructions
942     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
943     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
944     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
945     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
946 
947     if (Subtarget.hasVSX()) {
948       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
949       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
950       if (Subtarget.hasP8Vector()) {
951         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
952         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
953       }
954       if (Subtarget.hasDirectMove() && isPPC64) {
955         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
956         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
957         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
958         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
959         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
960         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
961         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
962         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
963       }
964       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
965 
966       // The nearbyint variants are not allowed to raise the inexact exception
967       // so we can only code-gen them with unsafe math.
968       if (TM.Options.UnsafeFPMath) {
969         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
970         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
971       }
972 
973       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
974       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
975       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
976       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
977       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
978       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
979       setOperationAction(ISD::FROUND, MVT::f64, Legal);
980       setOperationAction(ISD::FRINT, MVT::f64, Legal);
981 
982       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
983       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
984       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
985       setOperationAction(ISD::FROUND, MVT::f32, Legal);
986       setOperationAction(ISD::FRINT, MVT::f32, Legal);
987 
988       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
989       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
990 
991       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
992       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
993 
994       // Share the Altivec comparison restrictions.
995       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
996       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
997       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
998       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
999 
1000       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1001       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
1002 
1003       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
1004 
1005       if (Subtarget.hasP8Vector())
1006         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
1007 
1008       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
1009 
1010       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
1011       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
1012       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
1013 
1014       if (Subtarget.hasP8Altivec()) {
1015         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1016         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
1017         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1018 
1019         // 128 bit shifts can be accomplished via 3 instructions for SHL and
1020         // SRL, but not for SRA because of the instructions available:
1021         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1022         // doing
1023         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
1024         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
1025         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1026 
1027         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
1028       }
1029       else {
1030         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
1031         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1032         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1033 
1034         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1035 
1036         // VSX v2i64 only supports non-arithmetic operations.
1037         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1038         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1039       }
1040 
1041       if (Subtarget.isISA3_1())
1042         setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1043       else
1044         setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1045 
1046       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1047       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1048       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1049       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1050 
1051       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
1052 
1053       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1054       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1055       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1056       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1057       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1058       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1059       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1060       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1061 
1062       // Custom handling for partial vectors of integers converted to
1063       // floating point. We already have optimal handling for v2i32 through
1064       // the DAG combine, so those aren't necessary.
1065       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1066       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1067       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1068       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1069       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1070       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1071       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1072       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1073       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1074       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1075       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1076       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1077       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1078       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1079       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1080       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1081 
1082       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1083       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1084       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1085       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1086       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1087       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1088 
1089       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1090       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1091 
1092       // Handle constrained floating-point operations of vector.
1093       // The predictor is `hasVSX` because altivec instruction has
1094       // no exception but VSX vector instruction has.
1095       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1096       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1097       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1098       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1099       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1100       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1101       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1102       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1103       setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
1104       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1105       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1106       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1107       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1108 
1109       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1110       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1111       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1112       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1113       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1114       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1115       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1116       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1117       setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
1118       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1119       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1120       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1121       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1122 
1123       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1124       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1125 
1126       for (MVT FPT : MVT::fp_valuetypes())
1127         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1128 
1129       // Expand the SELECT to SELECT_CC
1130       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1131 
1132       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1133       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1134 
1135       // No implementation for these ops for PowerPC.
1136       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1137       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1138       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1139       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1140       setOperationAction(ISD::FREM, MVT::f128, Expand);
1141     }
1142 
1143     if (Subtarget.hasP8Altivec()) {
1144       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1145       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1146     }
1147 
1148     if (Subtarget.hasP9Vector()) {
1149       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1150       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1151 
1152       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1153       // SRL, but not for SRA because of the instructions available:
1154       // VS{RL} and VS{RL}O.
1155       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1156       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1157       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1158 
1159       setOperationAction(ISD::FADD, MVT::f128, Legal);
1160       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1161       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1162       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1163       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1164 
1165       setOperationAction(ISD::FMA, MVT::f128, Legal);
1166       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1167       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1168       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1169       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1170       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1171       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1172 
1173       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1174       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1175       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1176       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1177       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1178       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1179 
1180       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1181       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1182       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1183 
1184       // Handle constrained floating-point operations of fp128
1185       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1186       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1187       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1188       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1189       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1190       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1191       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1192       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1193       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1194       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1195       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1196       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1197       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1198       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1199       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1200       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1201       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1202       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1203       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1204       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1205     } else if (Subtarget.hasVSX()) {
1206       setOperationAction(ISD::LOAD, MVT::f128, Promote);
1207       setOperationAction(ISD::STORE, MVT::f128, Promote);
1208 
1209       AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
1210       AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
1211 
1212       // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1213       // fp_to_uint and int_to_fp.
1214       setOperationAction(ISD::FADD, MVT::f128, LibCall);
1215       setOperationAction(ISD::FSUB, MVT::f128, LibCall);
1216 
1217       setOperationAction(ISD::FMUL, MVT::f128, Expand);
1218       setOperationAction(ISD::FDIV, MVT::f128, Expand);
1219       setOperationAction(ISD::FNEG, MVT::f128, Expand);
1220       setOperationAction(ISD::FABS, MVT::f128, Expand);
1221       setOperationAction(ISD::FSQRT, MVT::f128, Expand);
1222       setOperationAction(ISD::FMA, MVT::f128, Expand);
1223       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
1224 
1225       // Expand the fp_extend if the target type is fp128.
1226       setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand);
1227       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand);
1228 
1229       // Expand the fp_round if the source type is fp128.
1230       for (MVT VT : {MVT::f32, MVT::f64}) {
1231         setOperationAction(ISD::FP_ROUND, VT, Custom);
1232         setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom);
1233       }
1234 
1235       setOperationAction(ISD::SETCC, MVT::f128, Custom);
1236       setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
1237       setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
1238       setOperationAction(ISD::BR_CC, MVT::f128, Expand);
1239 
1240       // Lower following f128 select_cc pattern:
1241       // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
1242       setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
1243 
1244       // We need to handle f128 SELECT_CC with integer result type.
1245       setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1246       setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand);
1247     }
1248 
1249     if (Subtarget.hasP9Altivec()) {
1250       if (Subtarget.isISA3_1()) {
1251         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
1252         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Legal);
1253         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Legal);
1254         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
1255         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Legal);
1256       } else {
1257         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1258         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1259       }
1260       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1261       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1262       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1263       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1264       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1265       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1266       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1267     }
1268   }
1269 
1270   if (Subtarget.pairedVectorMemops()) {
1271     addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1272     setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1273     setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1274   }
1275   if (Subtarget.hasMMA()) {
1276     addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1277     setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1278     setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1279     setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom);
1280   }
1281 
1282   if (Subtarget.has64BitSupport())
1283     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1284 
1285   if (Subtarget.isISA3_1())
1286     setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1287 
1288   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1289 
1290   if (!isPPC64) {
1291     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1292     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1293   }
1294 
1295   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics()) {
1296     setMaxAtomicSizeInBitsSupported(128);
1297     setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
1298     setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom);
1299     setOperationAction(ISD::INTRINSIC_VOID, MVT::i128, Custom);
1300   }
1301 
1302   setBooleanContents(ZeroOrOneBooleanContent);
1303 
1304   if (Subtarget.hasAltivec()) {
1305     // Altivec instructions set fields to all zeros or all ones.
1306     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1307   }
1308 
1309   if (!isPPC64) {
1310     // These libcalls are not available in 32-bit.
1311     setLibcallName(RTLIB::SHL_I128, nullptr);
1312     setLibcallName(RTLIB::SRL_I128, nullptr);
1313     setLibcallName(RTLIB::SRA_I128, nullptr);
1314     setLibcallName(RTLIB::MULO_I64, nullptr);
1315   }
1316 
1317   if (!isPPC64)
1318     setMaxAtomicSizeInBitsSupported(32);
1319 
1320   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1321 
1322   // We have target-specific dag combine patterns for the following nodes:
1323   setTargetDAGCombine(ISD::ADD);
1324   setTargetDAGCombine(ISD::SHL);
1325   setTargetDAGCombine(ISD::SRA);
1326   setTargetDAGCombine(ISD::SRL);
1327   setTargetDAGCombine(ISD::MUL);
1328   setTargetDAGCombine(ISD::FMA);
1329   setTargetDAGCombine(ISD::SINT_TO_FP);
1330   setTargetDAGCombine(ISD::BUILD_VECTOR);
1331   if (Subtarget.hasFPCVT())
1332     setTargetDAGCombine(ISD::UINT_TO_FP);
1333   setTargetDAGCombine(ISD::LOAD);
1334   setTargetDAGCombine(ISD::STORE);
1335   setTargetDAGCombine(ISD::BR_CC);
1336   if (Subtarget.useCRBits())
1337     setTargetDAGCombine(ISD::BRCOND);
1338   setTargetDAGCombine(ISD::BSWAP);
1339   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1340   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1341   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1342 
1343   setTargetDAGCombine(ISD::SIGN_EXTEND);
1344   setTargetDAGCombine(ISD::ZERO_EXTEND);
1345   setTargetDAGCombine(ISD::ANY_EXTEND);
1346 
1347   setTargetDAGCombine(ISD::TRUNCATE);
1348   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1349 
1350 
1351   if (Subtarget.useCRBits()) {
1352     setTargetDAGCombine(ISD::TRUNCATE);
1353     setTargetDAGCombine(ISD::SETCC);
1354     setTargetDAGCombine(ISD::SELECT_CC);
1355   }
1356 
1357   if (Subtarget.hasP9Altivec()) {
1358     setTargetDAGCombine(ISD::ABS);
1359     setTargetDAGCombine(ISD::VSELECT);
1360   }
1361 
1362   setLibcallName(RTLIB::LOG_F128, "logf128");
1363   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1364   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1365   setLibcallName(RTLIB::EXP_F128, "expf128");
1366   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1367   setLibcallName(RTLIB::SIN_F128, "sinf128");
1368   setLibcallName(RTLIB::COS_F128, "cosf128");
1369   setLibcallName(RTLIB::POW_F128, "powf128");
1370   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1371   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1372   setLibcallName(RTLIB::REM_F128, "fmodf128");
1373   setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1374   setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1375   setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1376   setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1377   setLibcallName(RTLIB::ROUND_F128, "roundf128");
1378   setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1379   setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1380   setLibcallName(RTLIB::RINT_F128, "rintf128");
1381   setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1382   setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1383   setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1384   setLibcallName(RTLIB::FMA_F128, "fmaf128");
1385 
1386   // With 32 condition bits, we don't need to sink (and duplicate) compares
1387   // aggressively in CodeGenPrep.
1388   if (Subtarget.useCRBits()) {
1389     setHasMultipleConditionRegisters();
1390     setJumpIsExpensive();
1391   }
1392 
1393   setMinFunctionAlignment(Align(4));
1394 
1395   switch (Subtarget.getCPUDirective()) {
1396   default: break;
1397   case PPC::DIR_970:
1398   case PPC::DIR_A2:
1399   case PPC::DIR_E500:
1400   case PPC::DIR_E500mc:
1401   case PPC::DIR_E5500:
1402   case PPC::DIR_PWR4:
1403   case PPC::DIR_PWR5:
1404   case PPC::DIR_PWR5X:
1405   case PPC::DIR_PWR6:
1406   case PPC::DIR_PWR6X:
1407   case PPC::DIR_PWR7:
1408   case PPC::DIR_PWR8:
1409   case PPC::DIR_PWR9:
1410   case PPC::DIR_PWR10:
1411   case PPC::DIR_PWR_FUTURE:
1412     setPrefLoopAlignment(Align(16));
1413     setPrefFunctionAlignment(Align(16));
1414     break;
1415   }
1416 
1417   if (Subtarget.enableMachineScheduler())
1418     setSchedulingPreference(Sched::Source);
1419   else
1420     setSchedulingPreference(Sched::Hybrid);
1421 
1422   computeRegisterProperties(STI.getRegisterInfo());
1423 
1424   // The Freescale cores do better with aggressive inlining of memcpy and
1425   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1426   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1427       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1428     MaxStoresPerMemset = 32;
1429     MaxStoresPerMemsetOptSize = 16;
1430     MaxStoresPerMemcpy = 32;
1431     MaxStoresPerMemcpyOptSize = 8;
1432     MaxStoresPerMemmove = 32;
1433     MaxStoresPerMemmoveOptSize = 8;
1434   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1435     // The A2 also benefits from (very) aggressive inlining of memcpy and
1436     // friends. The overhead of a the function call, even when warm, can be
1437     // over one hundred cycles.
1438     MaxStoresPerMemset = 128;
1439     MaxStoresPerMemcpy = 128;
1440     MaxStoresPerMemmove = 128;
1441     MaxLoadsPerMemcmp = 128;
1442   } else {
1443     MaxLoadsPerMemcmp = 8;
1444     MaxLoadsPerMemcmpOptSize = 4;
1445   }
1446 
1447   IsStrictFPEnabled = true;
1448 
1449   // Let the subtarget (CPU) decide if a predictable select is more expensive
1450   // than the corresponding branch. This information is used in CGP to decide
1451   // when to convert selects into branches.
1452   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1453 }
1454 
1455 // *********************************** NOTE ************************************
1456 // For selecting load and store instructions, the addressing modes are defined
1457 // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
1458 // patterns to match the load the store instructions.
1459 //
1460 // The TD definitions for the addressing modes correspond to their respective
1461 // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
1462 // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
1463 // address mode flags of a particular node. Afterwards, the computed address
1464 // flags are passed into getAddrModeForFlags() in order to retrieve the optimal
1465 // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
1466 // accordingly, based on the preferred addressing mode.
1467 //
1468 // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
1469 // MemOpFlags contains all the possible flags that can be used to compute the
1470 // optimal addressing mode for load and store instructions.
1471 // AddrMode contains all the possible load and store addressing modes available
1472 // on Power (such as DForm, DSForm, DQForm, XForm, etc.)
1473 //
1474 // When adding new load and store instructions, it is possible that new address
1475 // flags may need to be added into MemOpFlags, and a new addressing mode will
1476 // need to be added to AddrMode. An entry of the new addressing mode (consisting
1477 // of the minimal and main distinguishing address flags for the new load/store
1478 // instructions) will need to be added into initializeAddrModeMap() below.
1479 // Finally, when adding new addressing modes, the getAddrModeForFlags() will
1480 // need to be updated to account for selecting the optimal addressing mode.
1481 // *****************************************************************************
1482 /// Initialize the map that relates the different addressing modes of the load
1483 /// and store instructions to a set of flags. This ensures the load/store
1484 /// instruction is correctly matched during instruction selection.
1485 void PPCTargetLowering::initializeAddrModeMap() {
1486   AddrModesMap[PPC::AM_DForm] = {
1487       // LWZ, STW
1488       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt,
1489       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt,
1490       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1491       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1492       // LBZ, LHZ, STB, STH
1493       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1494       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1495       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1496       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1497       // LHA
1498       PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1499       PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1500       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1501       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1502       // LFS, LFD, STFS, STFD
1503       PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1504       PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1505       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1506       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1507   };
1508   AddrModesMap[PPC::AM_DSForm] = {
1509       // LWA
1510       PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt,
1511       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1512       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1513       // LD, STD
1514       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt,
1515       PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt,
1516       PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt,
1517       // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
1518       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1519       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1520       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1521   };
1522   AddrModesMap[PPC::AM_DQForm] = {
1523       // LXV, STXV
1524       PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1525       PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1526       PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1527   };
1528   AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 |
1529                                        PPC::MOF_SubtargetP10};
1530   // TODO: Add mapping for quadword load/store.
1531 }
1532 
1533 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1534 /// the desired ByVal argument alignment.
1535 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1536   if (MaxAlign == MaxMaxAlign)
1537     return;
1538   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1539     if (MaxMaxAlign >= 32 &&
1540         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1541       MaxAlign = Align(32);
1542     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1543              MaxAlign < 16)
1544       MaxAlign = Align(16);
1545   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1546     Align EltAlign;
1547     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1548     if (EltAlign > MaxAlign)
1549       MaxAlign = EltAlign;
1550   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1551     for (auto *EltTy : STy->elements()) {
1552       Align EltAlign;
1553       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1554       if (EltAlign > MaxAlign)
1555         MaxAlign = EltAlign;
1556       if (MaxAlign == MaxMaxAlign)
1557         break;
1558     }
1559   }
1560 }
1561 
1562 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1563 /// function arguments in the caller parameter area.
1564 uint64_t PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1565                                                   const DataLayout &DL) const {
1566   // 16byte and wider vectors are passed on 16byte boundary.
1567   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1568   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1569   if (Subtarget.hasAltivec())
1570     getMaxByValAlign(Ty, Alignment, Align(16));
1571   return Alignment.value();
1572 }
1573 
1574 bool PPCTargetLowering::useSoftFloat() const {
1575   return Subtarget.useSoftFloat();
1576 }
1577 
1578 bool PPCTargetLowering::hasSPE() const {
1579   return Subtarget.hasSPE();
1580 }
1581 
1582 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1583   return VT.isScalarInteger();
1584 }
1585 
1586 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1587   switch ((PPCISD::NodeType)Opcode) {
1588   case PPCISD::FIRST_NUMBER:    break;
1589   case PPCISD::FSEL:            return "PPCISD::FSEL";
1590   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1591   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1592   case PPCISD::FCFID:           return "PPCISD::FCFID";
1593   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1594   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1595   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1596   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1597   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1598   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1599   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1600   case PPCISD::FP_TO_UINT_IN_VSR:
1601                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1602   case PPCISD::FP_TO_SINT_IN_VSR:
1603                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1604   case PPCISD::FRE:             return "PPCISD::FRE";
1605   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1606   case PPCISD::FTSQRT:
1607     return "PPCISD::FTSQRT";
1608   case PPCISD::FSQRT:
1609     return "PPCISD::FSQRT";
1610   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1611   case PPCISD::VPERM:           return "PPCISD::VPERM";
1612   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1613   case PPCISD::XXSPLTI_SP_TO_DP:
1614     return "PPCISD::XXSPLTI_SP_TO_DP";
1615   case PPCISD::XXSPLTI32DX:
1616     return "PPCISD::XXSPLTI32DX";
1617   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1618   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1619   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1620   case PPCISD::CMPB:            return "PPCISD::CMPB";
1621   case PPCISD::Hi:              return "PPCISD::Hi";
1622   case PPCISD::Lo:              return "PPCISD::Lo";
1623   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1624   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1625   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1626   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1627   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1628   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1629   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1630   case PPCISD::SRL:             return "PPCISD::SRL";
1631   case PPCISD::SRA:             return "PPCISD::SRA";
1632   case PPCISD::SHL:             return "PPCISD::SHL";
1633   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1634   case PPCISD::CALL:            return "PPCISD::CALL";
1635   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1636   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1637   case PPCISD::CALL_RM:
1638     return "PPCISD::CALL_RM";
1639   case PPCISD::CALL_NOP_RM:
1640     return "PPCISD::CALL_NOP_RM";
1641   case PPCISD::CALL_NOTOC_RM:
1642     return "PPCISD::CALL_NOTOC_RM";
1643   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1644   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1645   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1646   case PPCISD::BCTRL_RM:
1647     return "PPCISD::BCTRL_RM";
1648   case PPCISD::BCTRL_LOAD_TOC_RM:
1649     return "PPCISD::BCTRL_LOAD_TOC_RM";
1650   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1651   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1652   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1653   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1654   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1655   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1656   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1657   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1658   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1659   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1660   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1661     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1662   case PPCISD::ANDI_rec_1_EQ_BIT:
1663     return "PPCISD::ANDI_rec_1_EQ_BIT";
1664   case PPCISD::ANDI_rec_1_GT_BIT:
1665     return "PPCISD::ANDI_rec_1_GT_BIT";
1666   case PPCISD::VCMP:            return "PPCISD::VCMP";
1667   case PPCISD::VCMP_rec:        return "PPCISD::VCMP_rec";
1668   case PPCISD::LBRX:            return "PPCISD::LBRX";
1669   case PPCISD::STBRX:           return "PPCISD::STBRX";
1670   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1671   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1672   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1673   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1674   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1675   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1676   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1677   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1678   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1679   case PPCISD::ST_VSR_SCAL_INT:
1680                                 return "PPCISD::ST_VSR_SCAL_INT";
1681   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1682   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1683   case PPCISD::BDZ:             return "PPCISD::BDZ";
1684   case PPCISD::MFFS:            return "PPCISD::MFFS";
1685   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1686   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1687   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1688   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1689   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1690   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1691   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1692   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1693   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1694   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1695   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1696   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1697   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1698   case PPCISD::TLSGD_AIX:       return "PPCISD::TLSGD_AIX";
1699   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1700   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1701   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1702   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1703   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1704   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1705   case PPCISD::PADDI_DTPREL:
1706     return "PPCISD::PADDI_DTPREL";
1707   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1708   case PPCISD::SC:              return "PPCISD::SC";
1709   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1710   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1711   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1712   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1713   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1714   case PPCISD::VABSD:           return "PPCISD::VABSD";
1715   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1716   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1717   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1718   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1719   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1720   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1721   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1722   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1723     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1724   case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1725     return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1726   case PPCISD::ACC_BUILD:       return "PPCISD::ACC_BUILD";
1727   case PPCISD::PAIR_BUILD:      return "PPCISD::PAIR_BUILD";
1728   case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1729   case PPCISD::XXMFACC:         return "PPCISD::XXMFACC";
1730   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1731   case PPCISD::ZEXT_LD_SPLAT:   return "PPCISD::ZEXT_LD_SPLAT";
1732   case PPCISD::SEXT_LD_SPLAT:   return "PPCISD::SEXT_LD_SPLAT";
1733   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1734   case PPCISD::STRICT_FADDRTZ:
1735     return "PPCISD::STRICT_FADDRTZ";
1736   case PPCISD::STRICT_FCTIDZ:
1737     return "PPCISD::STRICT_FCTIDZ";
1738   case PPCISD::STRICT_FCTIWZ:
1739     return "PPCISD::STRICT_FCTIWZ";
1740   case PPCISD::STRICT_FCTIDUZ:
1741     return "PPCISD::STRICT_FCTIDUZ";
1742   case PPCISD::STRICT_FCTIWUZ:
1743     return "PPCISD::STRICT_FCTIWUZ";
1744   case PPCISD::STRICT_FCFID:
1745     return "PPCISD::STRICT_FCFID";
1746   case PPCISD::STRICT_FCFIDU:
1747     return "PPCISD::STRICT_FCFIDU";
1748   case PPCISD::STRICT_FCFIDS:
1749     return "PPCISD::STRICT_FCFIDS";
1750   case PPCISD::STRICT_FCFIDUS:
1751     return "PPCISD::STRICT_FCFIDUS";
1752   case PPCISD::LXVRZX:          return "PPCISD::LXVRZX";
1753   }
1754   return nullptr;
1755 }
1756 
1757 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1758                                           EVT VT) const {
1759   if (!VT.isVector())
1760     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1761 
1762   return VT.changeVectorElementTypeToInteger();
1763 }
1764 
1765 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1766   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1767   return true;
1768 }
1769 
1770 //===----------------------------------------------------------------------===//
1771 // Node matching predicates, for use by the tblgen matching code.
1772 //===----------------------------------------------------------------------===//
1773 
1774 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1775 static bool isFloatingPointZero(SDValue Op) {
1776   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1777     return CFP->getValueAPF().isZero();
1778   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1779     // Maybe this has already been legalized into the constant pool?
1780     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1781       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1782         return CFP->getValueAPF().isZero();
1783   }
1784   return false;
1785 }
1786 
1787 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1788 /// true if Op is undef or if it matches the specified value.
1789 static bool isConstantOrUndef(int Op, int Val) {
1790   return Op < 0 || Op == Val;
1791 }
1792 
1793 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1794 /// VPKUHUM instruction.
1795 /// The ShuffleKind distinguishes between big-endian operations with
1796 /// two different inputs (0), either-endian operations with two identical
1797 /// inputs (1), and little-endian operations with two different inputs (2).
1798 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1799 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1800                                SelectionDAG &DAG) {
1801   bool IsLE = DAG.getDataLayout().isLittleEndian();
1802   if (ShuffleKind == 0) {
1803     if (IsLE)
1804       return false;
1805     for (unsigned i = 0; i != 16; ++i)
1806       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1807         return false;
1808   } else if (ShuffleKind == 2) {
1809     if (!IsLE)
1810       return false;
1811     for (unsigned i = 0; i != 16; ++i)
1812       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1813         return false;
1814   } else if (ShuffleKind == 1) {
1815     unsigned j = IsLE ? 0 : 1;
1816     for (unsigned i = 0; i != 8; ++i)
1817       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1818           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1819         return false;
1820   }
1821   return true;
1822 }
1823 
1824 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1825 /// VPKUWUM instruction.
1826 /// The ShuffleKind distinguishes between big-endian operations with
1827 /// two different inputs (0), either-endian operations with two identical
1828 /// inputs (1), and little-endian operations with two different inputs (2).
1829 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1830 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1831                                SelectionDAG &DAG) {
1832   bool IsLE = DAG.getDataLayout().isLittleEndian();
1833   if (ShuffleKind == 0) {
1834     if (IsLE)
1835       return false;
1836     for (unsigned i = 0; i != 16; i += 2)
1837       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1838           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1839         return false;
1840   } else if (ShuffleKind == 2) {
1841     if (!IsLE)
1842       return false;
1843     for (unsigned i = 0; i != 16; i += 2)
1844       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1845           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1846         return false;
1847   } else if (ShuffleKind == 1) {
1848     unsigned j = IsLE ? 0 : 2;
1849     for (unsigned i = 0; i != 8; i += 2)
1850       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1851           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1852           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1853           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1854         return false;
1855   }
1856   return true;
1857 }
1858 
1859 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1860 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1861 /// current subtarget.
1862 ///
1863 /// The ShuffleKind distinguishes between big-endian operations with
1864 /// two different inputs (0), either-endian operations with two identical
1865 /// inputs (1), and little-endian operations with two different inputs (2).
1866 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1867 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1868                                SelectionDAG &DAG) {
1869   const PPCSubtarget& Subtarget =
1870       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1871   if (!Subtarget.hasP8Vector())
1872     return false;
1873 
1874   bool IsLE = DAG.getDataLayout().isLittleEndian();
1875   if (ShuffleKind == 0) {
1876     if (IsLE)
1877       return false;
1878     for (unsigned i = 0; i != 16; i += 4)
1879       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1880           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1881           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1882           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1883         return false;
1884   } else if (ShuffleKind == 2) {
1885     if (!IsLE)
1886       return false;
1887     for (unsigned i = 0; i != 16; i += 4)
1888       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1889           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1890           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1891           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1892         return false;
1893   } else if (ShuffleKind == 1) {
1894     unsigned j = IsLE ? 0 : 4;
1895     for (unsigned i = 0; i != 8; i += 4)
1896       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1897           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1898           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1899           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1900           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1901           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1902           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1903           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1904         return false;
1905   }
1906   return true;
1907 }
1908 
1909 /// isVMerge - Common function, used to match vmrg* shuffles.
1910 ///
1911 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1912                      unsigned LHSStart, unsigned RHSStart) {
1913   if (N->getValueType(0) != MVT::v16i8)
1914     return false;
1915   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1916          "Unsupported merge size!");
1917 
1918   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1919     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1920       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1921                              LHSStart+j+i*UnitSize) ||
1922           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1923                              RHSStart+j+i*UnitSize))
1924         return false;
1925     }
1926   return true;
1927 }
1928 
1929 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1930 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1931 /// The ShuffleKind distinguishes between big-endian merges with two
1932 /// different inputs (0), either-endian merges with two identical inputs (1),
1933 /// and little-endian merges with two different inputs (2).  For the latter,
1934 /// the input operands are swapped (see PPCInstrAltivec.td).
1935 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1936                              unsigned ShuffleKind, SelectionDAG &DAG) {
1937   if (DAG.getDataLayout().isLittleEndian()) {
1938     if (ShuffleKind == 1) // unary
1939       return isVMerge(N, UnitSize, 0, 0);
1940     else if (ShuffleKind == 2) // swapped
1941       return isVMerge(N, UnitSize, 0, 16);
1942     else
1943       return false;
1944   } else {
1945     if (ShuffleKind == 1) // unary
1946       return isVMerge(N, UnitSize, 8, 8);
1947     else if (ShuffleKind == 0) // normal
1948       return isVMerge(N, UnitSize, 8, 24);
1949     else
1950       return false;
1951   }
1952 }
1953 
1954 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1955 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1956 /// The ShuffleKind distinguishes between big-endian merges with two
1957 /// different inputs (0), either-endian merges with two identical inputs (1),
1958 /// and little-endian merges with two different inputs (2).  For the latter,
1959 /// the input operands are swapped (see PPCInstrAltivec.td).
1960 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1961                              unsigned ShuffleKind, SelectionDAG &DAG) {
1962   if (DAG.getDataLayout().isLittleEndian()) {
1963     if (ShuffleKind == 1) // unary
1964       return isVMerge(N, UnitSize, 8, 8);
1965     else if (ShuffleKind == 2) // swapped
1966       return isVMerge(N, UnitSize, 8, 24);
1967     else
1968       return false;
1969   } else {
1970     if (ShuffleKind == 1) // unary
1971       return isVMerge(N, UnitSize, 0, 0);
1972     else if (ShuffleKind == 0) // normal
1973       return isVMerge(N, UnitSize, 0, 16);
1974     else
1975       return false;
1976   }
1977 }
1978 
1979 /**
1980  * Common function used to match vmrgew and vmrgow shuffles
1981  *
1982  * The indexOffset determines whether to look for even or odd words in
1983  * the shuffle mask. This is based on the of the endianness of the target
1984  * machine.
1985  *   - Little Endian:
1986  *     - Use offset of 0 to check for odd elements
1987  *     - Use offset of 4 to check for even elements
1988  *   - Big Endian:
1989  *     - Use offset of 0 to check for even elements
1990  *     - Use offset of 4 to check for odd elements
1991  * A detailed description of the vector element ordering for little endian and
1992  * big endian can be found at
1993  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1994  * Targeting your applications - what little endian and big endian IBM XL C/C++
1995  * compiler differences mean to you
1996  *
1997  * The mask to the shuffle vector instruction specifies the indices of the
1998  * elements from the two input vectors to place in the result. The elements are
1999  * numbered in array-access order, starting with the first vector. These vectors
2000  * are always of type v16i8, thus each vector will contain 16 elements of size
2001  * 8. More info on the shuffle vector can be found in the
2002  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
2003  * Language Reference.
2004  *
2005  * The RHSStartValue indicates whether the same input vectors are used (unary)
2006  * or two different input vectors are used, based on the following:
2007  *   - If the instruction uses the same vector for both inputs, the range of the
2008  *     indices will be 0 to 15. In this case, the RHSStart value passed should
2009  *     be 0.
2010  *   - If the instruction has two different vectors then the range of the
2011  *     indices will be 0 to 31. In this case, the RHSStart value passed should
2012  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
2013  *     to 31 specify elements in the second vector).
2014  *
2015  * \param[in] N The shuffle vector SD Node to analyze
2016  * \param[in] IndexOffset Specifies whether to look for even or odd elements
2017  * \param[in] RHSStartValue Specifies the starting index for the righthand input
2018  * vector to the shuffle_vector instruction
2019  * \return true iff this shuffle vector represents an even or odd word merge
2020  */
2021 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
2022                      unsigned RHSStartValue) {
2023   if (N->getValueType(0) != MVT::v16i8)
2024     return false;
2025 
2026   for (unsigned i = 0; i < 2; ++i)
2027     for (unsigned j = 0; j < 4; ++j)
2028       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
2029                              i*RHSStartValue+j+IndexOffset) ||
2030           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
2031                              i*RHSStartValue+j+IndexOffset+8))
2032         return false;
2033   return true;
2034 }
2035 
2036 /**
2037  * Determine if the specified shuffle mask is suitable for the vmrgew or
2038  * vmrgow instructions.
2039  *
2040  * \param[in] N The shuffle vector SD Node to analyze
2041  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
2042  * \param[in] ShuffleKind Identify the type of merge:
2043  *   - 0 = big-endian merge with two different inputs;
2044  *   - 1 = either-endian merge with two identical inputs;
2045  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
2046  *     little-endian merges).
2047  * \param[in] DAG The current SelectionDAG
2048  * \return true iff this shuffle mask
2049  */
2050 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
2051                               unsigned ShuffleKind, SelectionDAG &DAG) {
2052   if (DAG.getDataLayout().isLittleEndian()) {
2053     unsigned indexOffset = CheckEven ? 4 : 0;
2054     if (ShuffleKind == 1) // Unary
2055       return isVMerge(N, indexOffset, 0);
2056     else if (ShuffleKind == 2) // swapped
2057       return isVMerge(N, indexOffset, 16);
2058     else
2059       return false;
2060   }
2061   else {
2062     unsigned indexOffset = CheckEven ? 0 : 4;
2063     if (ShuffleKind == 1) // Unary
2064       return isVMerge(N, indexOffset, 0);
2065     else if (ShuffleKind == 0) // Normal
2066       return isVMerge(N, indexOffset, 16);
2067     else
2068       return false;
2069   }
2070   return false;
2071 }
2072 
2073 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
2074 /// amount, otherwise return -1.
2075 /// The ShuffleKind distinguishes between big-endian operations with two
2076 /// different inputs (0), either-endian operations with two identical inputs
2077 /// (1), and little-endian operations with two different inputs (2).  For the
2078 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
2079 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
2080                              SelectionDAG &DAG) {
2081   if (N->getValueType(0) != MVT::v16i8)
2082     return -1;
2083 
2084   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2085 
2086   // Find the first non-undef value in the shuffle mask.
2087   unsigned i;
2088   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
2089     /*search*/;
2090 
2091   if (i == 16) return -1;  // all undef.
2092 
2093   // Otherwise, check to see if the rest of the elements are consecutively
2094   // numbered from this value.
2095   unsigned ShiftAmt = SVOp->getMaskElt(i);
2096   if (ShiftAmt < i) return -1;
2097 
2098   ShiftAmt -= i;
2099   bool isLE = DAG.getDataLayout().isLittleEndian();
2100 
2101   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
2102     // Check the rest of the elements to see if they are consecutive.
2103     for (++i; i != 16; ++i)
2104       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2105         return -1;
2106   } else if (ShuffleKind == 1) {
2107     // Check the rest of the elements to see if they are consecutive.
2108     for (++i; i != 16; ++i)
2109       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
2110         return -1;
2111   } else
2112     return -1;
2113 
2114   if (isLE)
2115     ShiftAmt = 16 - ShiftAmt;
2116 
2117   return ShiftAmt;
2118 }
2119 
2120 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2121 /// specifies a splat of a single element that is suitable for input to
2122 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2123 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
2124   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
2125          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2126 
2127   // The consecutive indices need to specify an element, not part of two
2128   // different elements.  So abandon ship early if this isn't the case.
2129   if (N->getMaskElt(0) % EltSize != 0)
2130     return false;
2131 
2132   // This is a splat operation if each element of the permute is the same, and
2133   // if the value doesn't reference the second vector.
2134   unsigned ElementBase = N->getMaskElt(0);
2135 
2136   // FIXME: Handle UNDEF elements too!
2137   if (ElementBase >= 16)
2138     return false;
2139 
2140   // Check that the indices are consecutive, in the case of a multi-byte element
2141   // splatted with a v16i8 mask.
2142   for (unsigned i = 1; i != EltSize; ++i)
2143     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2144       return false;
2145 
2146   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2147     if (N->getMaskElt(i) < 0) continue;
2148     for (unsigned j = 0; j != EltSize; ++j)
2149       if (N->getMaskElt(i+j) != N->getMaskElt(j))
2150         return false;
2151   }
2152   return true;
2153 }
2154 
2155 /// Check that the mask is shuffling N byte elements. Within each N byte
2156 /// element of the mask, the indices could be either in increasing or
2157 /// decreasing order as long as they are consecutive.
2158 /// \param[in] N the shuffle vector SD Node to analyze
2159 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2160 /// Word/DoubleWord/QuadWord).
2161 /// \param[in] StepLen the delta indices number among the N byte element, if
2162 /// the mask is in increasing/decreasing order then it is 1/-1.
2163 /// \return true iff the mask is shuffling N byte elements.
2164 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2165                                    int StepLen) {
2166   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2167          "Unexpected element width.");
2168   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2169 
2170   unsigned NumOfElem = 16 / Width;
2171   unsigned MaskVal[16]; //  Width is never greater than 16
2172   for (unsigned i = 0; i < NumOfElem; ++i) {
2173     MaskVal[0] = N->getMaskElt(i * Width);
2174     if ((StepLen == 1) && (MaskVal[0] % Width)) {
2175       return false;
2176     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2177       return false;
2178     }
2179 
2180     for (unsigned int j = 1; j < Width; ++j) {
2181       MaskVal[j] = N->getMaskElt(i * Width + j);
2182       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2183         return false;
2184       }
2185     }
2186   }
2187 
2188   return true;
2189 }
2190 
2191 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2192                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2193   if (!isNByteElemShuffleMask(N, 4, 1))
2194     return false;
2195 
2196   // Now we look at mask elements 0,4,8,12
2197   unsigned M0 = N->getMaskElt(0) / 4;
2198   unsigned M1 = N->getMaskElt(4) / 4;
2199   unsigned M2 = N->getMaskElt(8) / 4;
2200   unsigned M3 = N->getMaskElt(12) / 4;
2201   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2202   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2203 
2204   // Below, let H and L be arbitrary elements of the shuffle mask
2205   // where H is in the range [4,7] and L is in the range [0,3].
2206   // H, 1, 2, 3 or L, 5, 6, 7
2207   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2208       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2209     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2210     InsertAtByte = IsLE ? 12 : 0;
2211     Swap = M0 < 4;
2212     return true;
2213   }
2214   // 0, H, 2, 3 or 4, L, 6, 7
2215   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2216       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2217     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2218     InsertAtByte = IsLE ? 8 : 4;
2219     Swap = M1 < 4;
2220     return true;
2221   }
2222   // 0, 1, H, 3 or 4, 5, L, 7
2223   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2224       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2225     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2226     InsertAtByte = IsLE ? 4 : 8;
2227     Swap = M2 < 4;
2228     return true;
2229   }
2230   // 0, 1, 2, H or 4, 5, 6, L
2231   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2232       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2233     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2234     InsertAtByte = IsLE ? 0 : 12;
2235     Swap = M3 < 4;
2236     return true;
2237   }
2238 
2239   // If both vector operands for the shuffle are the same vector, the mask will
2240   // contain only elements from the first one and the second one will be undef.
2241   if (N->getOperand(1).isUndef()) {
2242     ShiftElts = 0;
2243     Swap = true;
2244     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2245     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2246       InsertAtByte = IsLE ? 12 : 0;
2247       return true;
2248     }
2249     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2250       InsertAtByte = IsLE ? 8 : 4;
2251       return true;
2252     }
2253     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2254       InsertAtByte = IsLE ? 4 : 8;
2255       return true;
2256     }
2257     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2258       InsertAtByte = IsLE ? 0 : 12;
2259       return true;
2260     }
2261   }
2262 
2263   return false;
2264 }
2265 
2266 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2267                                bool &Swap, bool IsLE) {
2268   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2269   // Ensure each byte index of the word is consecutive.
2270   if (!isNByteElemShuffleMask(N, 4, 1))
2271     return false;
2272 
2273   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2274   unsigned M0 = N->getMaskElt(0) / 4;
2275   unsigned M1 = N->getMaskElt(4) / 4;
2276   unsigned M2 = N->getMaskElt(8) / 4;
2277   unsigned M3 = N->getMaskElt(12) / 4;
2278 
2279   // If both vector operands for the shuffle are the same vector, the mask will
2280   // contain only elements from the first one and the second one will be undef.
2281   if (N->getOperand(1).isUndef()) {
2282     assert(M0 < 4 && "Indexing into an undef vector?");
2283     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2284       return false;
2285 
2286     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2287     Swap = false;
2288     return true;
2289   }
2290 
2291   // Ensure each word index of the ShuffleVector Mask is consecutive.
2292   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2293     return false;
2294 
2295   if (IsLE) {
2296     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2297       // Input vectors don't need to be swapped if the leading element
2298       // of the result is one of the 3 left elements of the second vector
2299       // (or if there is no shift to be done at all).
2300       Swap = false;
2301       ShiftElts = (8 - M0) % 8;
2302     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2303       // Input vectors need to be swapped if the leading element
2304       // of the result is one of the 3 left elements of the first vector
2305       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2306       Swap = true;
2307       ShiftElts = (4 - M0) % 4;
2308     }
2309 
2310     return true;
2311   } else {                                          // BE
2312     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2313       // Input vectors don't need to be swapped if the leading element
2314       // of the result is one of the 4 elements of the first vector.
2315       Swap = false;
2316       ShiftElts = M0;
2317     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2318       // Input vectors need to be swapped if the leading element
2319       // of the result is one of the 4 elements of the right vector.
2320       Swap = true;
2321       ShiftElts = M0 - 4;
2322     }
2323 
2324     return true;
2325   }
2326 }
2327 
2328 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2329   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2330 
2331   if (!isNByteElemShuffleMask(N, Width, -1))
2332     return false;
2333 
2334   for (int i = 0; i < 16; i += Width)
2335     if (N->getMaskElt(i) != i + Width - 1)
2336       return false;
2337 
2338   return true;
2339 }
2340 
2341 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2342   return isXXBRShuffleMaskHelper(N, 2);
2343 }
2344 
2345 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2346   return isXXBRShuffleMaskHelper(N, 4);
2347 }
2348 
2349 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2350   return isXXBRShuffleMaskHelper(N, 8);
2351 }
2352 
2353 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2354   return isXXBRShuffleMaskHelper(N, 16);
2355 }
2356 
2357 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2358 /// if the inputs to the instruction should be swapped and set \p DM to the
2359 /// value for the immediate.
2360 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2361 /// AND element 0 of the result comes from the first input (LE) or second input
2362 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2363 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2364 /// mask.
2365 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2366                                bool &Swap, bool IsLE) {
2367   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2368 
2369   // Ensure each byte index of the double word is consecutive.
2370   if (!isNByteElemShuffleMask(N, 8, 1))
2371     return false;
2372 
2373   unsigned M0 = N->getMaskElt(0) / 8;
2374   unsigned M1 = N->getMaskElt(8) / 8;
2375   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2376 
2377   // If both vector operands for the shuffle are the same vector, the mask will
2378   // contain only elements from the first one and the second one will be undef.
2379   if (N->getOperand(1).isUndef()) {
2380     if ((M0 | M1) < 2) {
2381       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2382       Swap = false;
2383       return true;
2384     } else
2385       return false;
2386   }
2387 
2388   if (IsLE) {
2389     if (M0 > 1 && M1 < 2) {
2390       Swap = false;
2391     } else if (M0 < 2 && M1 > 1) {
2392       M0 = (M0 + 2) % 4;
2393       M1 = (M1 + 2) % 4;
2394       Swap = true;
2395     } else
2396       return false;
2397 
2398     // Note: if control flow comes here that means Swap is already set above
2399     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2400     return true;
2401   } else { // BE
2402     if (M0 < 2 && M1 > 1) {
2403       Swap = false;
2404     } else if (M0 > 1 && M1 < 2) {
2405       M0 = (M0 + 2) % 4;
2406       M1 = (M1 + 2) % 4;
2407       Swap = true;
2408     } else
2409       return false;
2410 
2411     // Note: if control flow comes here that means Swap is already set above
2412     DM = (M0 << 1) + (M1 & 1);
2413     return true;
2414   }
2415 }
2416 
2417 
2418 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2419 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2420 /// elements are counted from the left of the vector register).
2421 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2422                                          SelectionDAG &DAG) {
2423   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2424   assert(isSplatShuffleMask(SVOp, EltSize));
2425   if (DAG.getDataLayout().isLittleEndian())
2426     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2427   else
2428     return SVOp->getMaskElt(0) / EltSize;
2429 }
2430 
2431 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2432 /// by using a vspltis[bhw] instruction of the specified element size, return
2433 /// the constant being splatted.  The ByteSize field indicates the number of
2434 /// bytes of each element [124] -> [bhw].
2435 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2436   SDValue OpVal;
2437 
2438   // If ByteSize of the splat is bigger than the element size of the
2439   // build_vector, then we have a case where we are checking for a splat where
2440   // multiple elements of the buildvector are folded together into a single
2441   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2442   unsigned EltSize = 16/N->getNumOperands();
2443   if (EltSize < ByteSize) {
2444     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2445     SDValue UniquedVals[4];
2446     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2447 
2448     // See if all of the elements in the buildvector agree across.
2449     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2450       if (N->getOperand(i).isUndef()) continue;
2451       // If the element isn't a constant, bail fully out.
2452       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2453 
2454       if (!UniquedVals[i&(Multiple-1)].getNode())
2455         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2456       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2457         return SDValue();  // no match.
2458     }
2459 
2460     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2461     // either constant or undef values that are identical for each chunk.  See
2462     // if these chunks can form into a larger vspltis*.
2463 
2464     // Check to see if all of the leading entries are either 0 or -1.  If
2465     // neither, then this won't fit into the immediate field.
2466     bool LeadingZero = true;
2467     bool LeadingOnes = true;
2468     for (unsigned i = 0; i != Multiple-1; ++i) {
2469       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2470 
2471       LeadingZero &= isNullConstant(UniquedVals[i]);
2472       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2473     }
2474     // Finally, check the least significant entry.
2475     if (LeadingZero) {
2476       if (!UniquedVals[Multiple-1].getNode())
2477         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2478       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2479       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2480         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2481     }
2482     if (LeadingOnes) {
2483       if (!UniquedVals[Multiple-1].getNode())
2484         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2485       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2486       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2487         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2488     }
2489 
2490     return SDValue();
2491   }
2492 
2493   // Check to see if this buildvec has a single non-undef value in its elements.
2494   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2495     if (N->getOperand(i).isUndef()) continue;
2496     if (!OpVal.getNode())
2497       OpVal = N->getOperand(i);
2498     else if (OpVal != N->getOperand(i))
2499       return SDValue();
2500   }
2501 
2502   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2503 
2504   unsigned ValSizeInBytes = EltSize;
2505   uint64_t Value = 0;
2506   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2507     Value = CN->getZExtValue();
2508   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2509     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2510     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2511   }
2512 
2513   // If the splat value is larger than the element value, then we can never do
2514   // this splat.  The only case that we could fit the replicated bits into our
2515   // immediate field for would be zero, and we prefer to use vxor for it.
2516   if (ValSizeInBytes < ByteSize) return SDValue();
2517 
2518   // If the element value is larger than the splat value, check if it consists
2519   // of a repeated bit pattern of size ByteSize.
2520   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2521     return SDValue();
2522 
2523   // Properly sign extend the value.
2524   int MaskVal = SignExtend32(Value, ByteSize * 8);
2525 
2526   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2527   if (MaskVal == 0) return SDValue();
2528 
2529   // Finally, if this value fits in a 5 bit sext field, return it
2530   if (SignExtend32<5>(MaskVal) == MaskVal)
2531     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2532   return SDValue();
2533 }
2534 
2535 //===----------------------------------------------------------------------===//
2536 //  Addressing Mode Selection
2537 //===----------------------------------------------------------------------===//
2538 
2539 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2540 /// or 64-bit immediate, and if the value can be accurately represented as a
2541 /// sign extension from a 16-bit value.  If so, this returns true and the
2542 /// immediate.
2543 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2544   if (!isa<ConstantSDNode>(N))
2545     return false;
2546 
2547   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2548   if (N->getValueType(0) == MVT::i32)
2549     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2550   else
2551     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2552 }
2553 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2554   return isIntS16Immediate(Op.getNode(), Imm);
2555 }
2556 
2557 /// Used when computing address flags for selecting loads and stores.
2558 /// If we have an OR, check if the LHS and RHS are provably disjoint.
2559 /// An OR of two provably disjoint values is equivalent to an ADD.
2560 /// Most PPC load/store instructions compute the effective address as a sum,
2561 /// so doing this conversion is useful.
2562 static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
2563   if (N.getOpcode() != ISD::OR)
2564     return false;
2565   KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2566   if (!LHSKnown.Zero.getBoolValue())
2567     return false;
2568   KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2569   return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
2570 }
2571 
2572 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2573 /// be represented as an indexed [r+r] operation.
2574 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2575                                                SDValue &Index,
2576                                                SelectionDAG &DAG) const {
2577   for (SDNode *U : N->uses()) {
2578     if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) {
2579       if (Memop->getMemoryVT() == MVT::f64) {
2580           Base = N.getOperand(0);
2581           Index = N.getOperand(1);
2582           return true;
2583       }
2584     }
2585   }
2586   return false;
2587 }
2588 
2589 /// isIntS34Immediate - This method tests if value of node given can be
2590 /// accurately represented as a sign extension from a 34-bit value.  If so,
2591 /// this returns true and the immediate.
2592 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2593   if (!isa<ConstantSDNode>(N))
2594     return false;
2595 
2596   Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2597   return isInt<34>(Imm);
2598 }
2599 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2600   return isIntS34Immediate(Op.getNode(), Imm);
2601 }
2602 
2603 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2604 /// can be represented as an indexed [r+r] operation.  Returns false if it
2605 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2606 /// non-zero and N can be represented by a base register plus a signed 16-bit
2607 /// displacement, make a more precise judgement by checking (displacement % \p
2608 /// EncodingAlignment).
2609 bool PPCTargetLowering::SelectAddressRegReg(
2610     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2611     MaybeAlign EncodingAlignment) const {
2612   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2613   // a [pc+imm].
2614   if (SelectAddressPCRel(N, Base))
2615     return false;
2616 
2617   int16_t Imm = 0;
2618   if (N.getOpcode() == ISD::ADD) {
2619     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2620     // SPE load/store can only handle 8-bit offsets.
2621     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2622         return true;
2623     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2624         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2625       return false; // r+i
2626     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2627       return false;    // r+i
2628 
2629     Base = N.getOperand(0);
2630     Index = N.getOperand(1);
2631     return true;
2632   } else if (N.getOpcode() == ISD::OR) {
2633     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2634         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2635       return false; // r+i can fold it if we can.
2636 
2637     // If this is an or of disjoint bitfields, we can codegen this as an add
2638     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2639     // disjoint.
2640     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2641 
2642     if (LHSKnown.Zero.getBoolValue()) {
2643       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2644       // If all of the bits are known zero on the LHS or RHS, the add won't
2645       // carry.
2646       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2647         Base = N.getOperand(0);
2648         Index = N.getOperand(1);
2649         return true;
2650       }
2651     }
2652   }
2653 
2654   return false;
2655 }
2656 
2657 // If we happen to be doing an i64 load or store into a stack slot that has
2658 // less than a 4-byte alignment, then the frame-index elimination may need to
2659 // use an indexed load or store instruction (because the offset may not be a
2660 // multiple of 4). The extra register needed to hold the offset comes from the
2661 // register scavenger, and it is possible that the scavenger will need to use
2662 // an emergency spill slot. As a result, we need to make sure that a spill slot
2663 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2664 // stack slot.
2665 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2666   // FIXME: This does not handle the LWA case.
2667   if (VT != MVT::i64)
2668     return;
2669 
2670   // NOTE: We'll exclude negative FIs here, which come from argument
2671   // lowering, because there are no known test cases triggering this problem
2672   // using packed structures (or similar). We can remove this exclusion if
2673   // we find such a test case. The reason why this is so test-case driven is
2674   // because this entire 'fixup' is only to prevent crashes (from the
2675   // register scavenger) on not-really-valid inputs. For example, if we have:
2676   //   %a = alloca i1
2677   //   %b = bitcast i1* %a to i64*
2678   //   store i64* a, i64 b
2679   // then the store should really be marked as 'align 1', but is not. If it
2680   // were marked as 'align 1' then the indexed form would have been
2681   // instruction-selected initially, and the problem this 'fixup' is preventing
2682   // won't happen regardless.
2683   if (FrameIdx < 0)
2684     return;
2685 
2686   MachineFunction &MF = DAG.getMachineFunction();
2687   MachineFrameInfo &MFI = MF.getFrameInfo();
2688 
2689   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2690     return;
2691 
2692   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2693   FuncInfo->setHasNonRISpills();
2694 }
2695 
2696 /// Returns true if the address N can be represented by a base register plus
2697 /// a signed 16-bit displacement [r+imm], and if it is not better
2698 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2699 /// displacements that are multiples of that value.
2700 bool PPCTargetLowering::SelectAddressRegImm(
2701     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2702     MaybeAlign EncodingAlignment) const {
2703   // FIXME dl should come from parent load or store, not from address
2704   SDLoc dl(N);
2705 
2706   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2707   // a [pc+imm].
2708   if (SelectAddressPCRel(N, Base))
2709     return false;
2710 
2711   // If this can be more profitably realized as r+r, fail.
2712   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2713     return false;
2714 
2715   if (N.getOpcode() == ISD::ADD) {
2716     int16_t imm = 0;
2717     if (isIntS16Immediate(N.getOperand(1), imm) &&
2718         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2719       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2720       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2721         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2722         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2723       } else {
2724         Base = N.getOperand(0);
2725       }
2726       return true; // [r+i]
2727     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2728       // Match LOAD (ADD (X, Lo(G))).
2729       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2730              && "Cannot handle constant offsets yet!");
2731       Disp = N.getOperand(1).getOperand(0);  // The global address.
2732       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2733              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2734              Disp.getOpcode() == ISD::TargetConstantPool ||
2735              Disp.getOpcode() == ISD::TargetJumpTable);
2736       Base = N.getOperand(0);
2737       return true;  // [&g+r]
2738     }
2739   } else if (N.getOpcode() == ISD::OR) {
2740     int16_t imm = 0;
2741     if (isIntS16Immediate(N.getOperand(1), imm) &&
2742         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2743       // If this is an or of disjoint bitfields, we can codegen this as an add
2744       // (for better address arithmetic) if the LHS and RHS of the OR are
2745       // provably disjoint.
2746       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2747 
2748       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2749         // If all of the bits are known zero on the LHS or RHS, the add won't
2750         // carry.
2751         if (FrameIndexSDNode *FI =
2752               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2753           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2754           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2755         } else {
2756           Base = N.getOperand(0);
2757         }
2758         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2759         return true;
2760       }
2761     }
2762   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2763     // Loading from a constant address.
2764 
2765     // If this address fits entirely in a 16-bit sext immediate field, codegen
2766     // this as "d, 0"
2767     int16_t Imm;
2768     if (isIntS16Immediate(CN, Imm) &&
2769         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2770       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2771       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2772                              CN->getValueType(0));
2773       return true;
2774     }
2775 
2776     // Handle 32-bit sext immediates with LIS + addr mode.
2777     if ((CN->getValueType(0) == MVT::i32 ||
2778          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2779         (!EncodingAlignment ||
2780          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2781       int Addr = (int)CN->getZExtValue();
2782 
2783       // Otherwise, break this down into an LIS + disp.
2784       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2785 
2786       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2787                                    MVT::i32);
2788       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2789       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2790       return true;
2791     }
2792   }
2793 
2794   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2795   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2796     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2797     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2798   } else
2799     Base = N;
2800   return true;      // [r+0]
2801 }
2802 
2803 /// Similar to the 16-bit case but for instructions that take a 34-bit
2804 /// displacement field (prefixed loads/stores).
2805 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp,
2806                                               SDValue &Base,
2807                                               SelectionDAG &DAG) const {
2808   // Only on 64-bit targets.
2809   if (N.getValueType() != MVT::i64)
2810     return false;
2811 
2812   SDLoc dl(N);
2813   int64_t Imm = 0;
2814 
2815   if (N.getOpcode() == ISD::ADD) {
2816     if (!isIntS34Immediate(N.getOperand(1), Imm))
2817       return false;
2818     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2819     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2820       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2821     else
2822       Base = N.getOperand(0);
2823     return true;
2824   }
2825 
2826   if (N.getOpcode() == ISD::OR) {
2827     if (!isIntS34Immediate(N.getOperand(1), Imm))
2828       return false;
2829     // If this is an or of disjoint bitfields, we can codegen this as an add
2830     // (for better address arithmetic) if the LHS and RHS of the OR are
2831     // provably disjoint.
2832     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2833     if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2834       return false;
2835     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2836       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2837     else
2838       Base = N.getOperand(0);
2839     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2840     return true;
2841   }
2842 
2843   if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2844     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2845     Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2846     return true;
2847   }
2848 
2849   return false;
2850 }
2851 
2852 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2853 /// represented as an indexed [r+r] operation.
2854 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2855                                                 SDValue &Index,
2856                                                 SelectionDAG &DAG) const {
2857   // Check to see if we can easily represent this as an [r+r] address.  This
2858   // will fail if it thinks that the address is more profitably represented as
2859   // reg+imm, e.g. where imm = 0.
2860   if (SelectAddressRegReg(N, Base, Index, DAG))
2861     return true;
2862 
2863   // If the address is the result of an add, we will utilize the fact that the
2864   // address calculation includes an implicit add.  However, we can reduce
2865   // register pressure if we do not materialize a constant just for use as the
2866   // index register.  We only get rid of the add if it is not an add of a
2867   // value and a 16-bit signed constant and both have a single use.
2868   int16_t imm = 0;
2869   if (N.getOpcode() == ISD::ADD &&
2870       (!isIntS16Immediate(N.getOperand(1), imm) ||
2871        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2872     Base = N.getOperand(0);
2873     Index = N.getOperand(1);
2874     return true;
2875   }
2876 
2877   // Otherwise, do it the hard way, using R0 as the base register.
2878   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2879                          N.getValueType());
2880   Index = N;
2881   return true;
2882 }
2883 
2884 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2885   Ty *PCRelCand = dyn_cast<Ty>(N);
2886   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2887 }
2888 
2889 /// Returns true if this address is a PC Relative address.
2890 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2891 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2892 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2893   // This is a materialize PC Relative node. Always select this as PC Relative.
2894   Base = N;
2895   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2896     return true;
2897   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2898       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2899       isValidPCRelNode<JumpTableSDNode>(N) ||
2900       isValidPCRelNode<BlockAddressSDNode>(N))
2901     return true;
2902   return false;
2903 }
2904 
2905 /// Returns true if we should use a direct load into vector instruction
2906 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2907 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2908 
2909   // If there are any other uses other than scalar to vector, then we should
2910   // keep it as a scalar load -> direct move pattern to prevent multiple
2911   // loads.
2912   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2913   if (!LD)
2914     return false;
2915 
2916   EVT MemVT = LD->getMemoryVT();
2917   if (!MemVT.isSimple())
2918     return false;
2919   switch(MemVT.getSimpleVT().SimpleTy) {
2920   case MVT::i64:
2921     break;
2922   case MVT::i32:
2923     if (!ST.hasP8Vector())
2924       return false;
2925     break;
2926   case MVT::i16:
2927   case MVT::i8:
2928     if (!ST.hasP9Vector())
2929       return false;
2930     break;
2931   default:
2932     return false;
2933   }
2934 
2935   SDValue LoadedVal(N, 0);
2936   if (!LoadedVal.hasOneUse())
2937     return false;
2938 
2939   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2940        UI != UE; ++UI)
2941     if (UI.getUse().get().getResNo() == 0 &&
2942         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2943         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2944       return false;
2945 
2946   return true;
2947 }
2948 
2949 /// getPreIndexedAddressParts - returns true by value, base pointer and
2950 /// offset pointer and addressing mode by reference if the node's address
2951 /// can be legally represented as pre-indexed load / store address.
2952 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2953                                                   SDValue &Offset,
2954                                                   ISD::MemIndexedMode &AM,
2955                                                   SelectionDAG &DAG) const {
2956   if (DisablePPCPreinc) return false;
2957 
2958   bool isLoad = true;
2959   SDValue Ptr;
2960   EVT VT;
2961   unsigned Alignment;
2962   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2963     Ptr = LD->getBasePtr();
2964     VT = LD->getMemoryVT();
2965     Alignment = LD->getAlignment();
2966   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2967     Ptr = ST->getBasePtr();
2968     VT  = ST->getMemoryVT();
2969     Alignment = ST->getAlignment();
2970     isLoad = false;
2971   } else
2972     return false;
2973 
2974   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2975   // instructions because we can fold these into a more efficient instruction
2976   // instead, (such as LXSD).
2977   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2978     return false;
2979   }
2980 
2981   // PowerPC doesn't have preinc load/store instructions for vectors
2982   if (VT.isVector())
2983     return false;
2984 
2985   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2986     // Common code will reject creating a pre-inc form if the base pointer
2987     // is a frame index, or if N is a store and the base pointer is either
2988     // the same as or a predecessor of the value being stored.  Check for
2989     // those situations here, and try with swapped Base/Offset instead.
2990     bool Swap = false;
2991 
2992     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2993       Swap = true;
2994     else if (!isLoad) {
2995       SDValue Val = cast<StoreSDNode>(N)->getValue();
2996       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2997         Swap = true;
2998     }
2999 
3000     if (Swap)
3001       std::swap(Base, Offset);
3002 
3003     AM = ISD::PRE_INC;
3004     return true;
3005   }
3006 
3007   // LDU/STU can only handle immediates that are a multiple of 4.
3008   if (VT != MVT::i64) {
3009     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
3010       return false;
3011   } else {
3012     // LDU/STU need an address with at least 4-byte alignment.
3013     if (Alignment < 4)
3014       return false;
3015 
3016     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
3017       return false;
3018   }
3019 
3020   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3021     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
3022     // sext i32 to i64 when addr mode is r+i.
3023     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
3024         LD->getExtensionType() == ISD::SEXTLOAD &&
3025         isa<ConstantSDNode>(Offset))
3026       return false;
3027   }
3028 
3029   AM = ISD::PRE_INC;
3030   return true;
3031 }
3032 
3033 //===----------------------------------------------------------------------===//
3034 //  LowerOperation implementation
3035 //===----------------------------------------------------------------------===//
3036 
3037 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
3038 /// and LoOpFlags to the target MO flags.
3039 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
3040                                unsigned &HiOpFlags, unsigned &LoOpFlags,
3041                                const GlobalValue *GV = nullptr) {
3042   HiOpFlags = PPCII::MO_HA;
3043   LoOpFlags = PPCII::MO_LO;
3044 
3045   // Don't use the pic base if not in PIC relocation model.
3046   if (IsPIC) {
3047     HiOpFlags |= PPCII::MO_PIC_FLAG;
3048     LoOpFlags |= PPCII::MO_PIC_FLAG;
3049   }
3050 }
3051 
3052 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
3053                              SelectionDAG &DAG) {
3054   SDLoc DL(HiPart);
3055   EVT PtrVT = HiPart.getValueType();
3056   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
3057 
3058   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
3059   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
3060 
3061   // With PIC, the first instruction is actually "GR+hi(&G)".
3062   if (isPIC)
3063     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
3064                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
3065 
3066   // Generate non-pic code that has direct accesses to the constant pool.
3067   // The address of the global is just (hi(&g)+lo(&g)).
3068   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
3069 }
3070 
3071 static void setUsesTOCBasePtr(MachineFunction &MF) {
3072   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3073   FuncInfo->setUsesTOCBasePtr();
3074 }
3075 
3076 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
3077   setUsesTOCBasePtr(DAG.getMachineFunction());
3078 }
3079 
3080 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
3081                                        SDValue GA) const {
3082   const bool Is64Bit = Subtarget.isPPC64();
3083   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
3084   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
3085                         : Subtarget.isAIXABI()
3086                               ? DAG.getRegister(PPC::R2, VT)
3087                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
3088   SDValue Ops[] = { GA, Reg };
3089   return DAG.getMemIntrinsicNode(
3090       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
3091       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
3092       MachineMemOperand::MOLoad);
3093 }
3094 
3095 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
3096                                              SelectionDAG &DAG) const {
3097   EVT PtrVT = Op.getValueType();
3098   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3099   const Constant *C = CP->getConstVal();
3100 
3101   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3102   // The actual address of the GlobalValue is stored in the TOC.
3103   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3104     if (Subtarget.isUsingPCRelativeCalls()) {
3105       SDLoc DL(CP);
3106       EVT Ty = getPointerTy(DAG.getDataLayout());
3107       SDValue ConstPool = DAG.getTargetConstantPool(
3108           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
3109       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
3110     }
3111     setUsesTOCBasePtr(DAG);
3112     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
3113     return getTOCEntry(DAG, SDLoc(CP), GA);
3114   }
3115 
3116   unsigned MOHiFlag, MOLoFlag;
3117   bool IsPIC = isPositionIndependent();
3118   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3119 
3120   if (IsPIC && Subtarget.isSVR4ABI()) {
3121     SDValue GA =
3122         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
3123     return getTOCEntry(DAG, SDLoc(CP), GA);
3124   }
3125 
3126   SDValue CPIHi =
3127       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3128   SDValue CPILo =
3129       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3130   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3131 }
3132 
3133 // For 64-bit PowerPC, prefer the more compact relative encodings.
3134 // This trades 32 bits per jump table entry for one or two instructions
3135 // on the jump site.
3136 unsigned PPCTargetLowering::getJumpTableEncoding() const {
3137   if (isJumpTableRelative())
3138     return MachineJumpTableInfo::EK_LabelDifference32;
3139 
3140   return TargetLowering::getJumpTableEncoding();
3141 }
3142 
3143 bool PPCTargetLowering::isJumpTableRelative() const {
3144   if (UseAbsoluteJumpTables)
3145     return false;
3146   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3147     return true;
3148   return TargetLowering::isJumpTableRelative();
3149 }
3150 
3151 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
3152                                                     SelectionDAG &DAG) const {
3153   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3154     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3155 
3156   switch (getTargetMachine().getCodeModel()) {
3157   case CodeModel::Small:
3158   case CodeModel::Medium:
3159     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3160   default:
3161     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3162                        getPointerTy(DAG.getDataLayout()));
3163   }
3164 }
3165 
3166 const MCExpr *
3167 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
3168                                                 unsigned JTI,
3169                                                 MCContext &Ctx) const {
3170   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3171     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3172 
3173   switch (getTargetMachine().getCodeModel()) {
3174   case CodeModel::Small:
3175   case CodeModel::Medium:
3176     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3177   default:
3178     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3179   }
3180 }
3181 
3182 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3183   EVT PtrVT = Op.getValueType();
3184   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3185 
3186   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3187   if (Subtarget.isUsingPCRelativeCalls()) {
3188     SDLoc DL(JT);
3189     EVT Ty = getPointerTy(DAG.getDataLayout());
3190     SDValue GA =
3191         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3192     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3193     return MatAddr;
3194   }
3195 
3196   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3197   // The actual address of the GlobalValue is stored in the TOC.
3198   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3199     setUsesTOCBasePtr(DAG);
3200     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3201     return getTOCEntry(DAG, SDLoc(JT), GA);
3202   }
3203 
3204   unsigned MOHiFlag, MOLoFlag;
3205   bool IsPIC = isPositionIndependent();
3206   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3207 
3208   if (IsPIC && Subtarget.isSVR4ABI()) {
3209     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3210                                         PPCII::MO_PIC_FLAG);
3211     return getTOCEntry(DAG, SDLoc(GA), GA);
3212   }
3213 
3214   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3215   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3216   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3217 }
3218 
3219 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3220                                              SelectionDAG &DAG) const {
3221   EVT PtrVT = Op.getValueType();
3222   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3223   const BlockAddress *BA = BASDN->getBlockAddress();
3224 
3225   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3226   if (Subtarget.isUsingPCRelativeCalls()) {
3227     SDLoc DL(BASDN);
3228     EVT Ty = getPointerTy(DAG.getDataLayout());
3229     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3230                                            PPCII::MO_PCREL_FLAG);
3231     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3232     return MatAddr;
3233   }
3234 
3235   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3236   // The actual BlockAddress is stored in the TOC.
3237   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3238     setUsesTOCBasePtr(DAG);
3239     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3240     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3241   }
3242 
3243   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3244   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3245     return getTOCEntry(
3246         DAG, SDLoc(BASDN),
3247         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3248 
3249   unsigned MOHiFlag, MOLoFlag;
3250   bool IsPIC = isPositionIndependent();
3251   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3252   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3253   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3254   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3255 }
3256 
3257 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3258                                               SelectionDAG &DAG) const {
3259   if (Subtarget.isAIXABI())
3260     return LowerGlobalTLSAddressAIX(Op, DAG);
3261 
3262   return LowerGlobalTLSAddressLinux(Op, DAG);
3263 }
3264 
3265 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3266                                                     SelectionDAG &DAG) const {
3267   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3268 
3269   if (DAG.getTarget().useEmulatedTLS())
3270     report_fatal_error("Emulated TLS is not yet supported on AIX");
3271 
3272   SDLoc dl(GA);
3273   const GlobalValue *GV = GA->getGlobal();
3274   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3275 
3276   // The general-dynamic model is the only access model supported for now, so
3277   // all the GlobalTLSAddress nodes are lowered with this model.
3278   // We need to generate two TOC entries, one for the variable offset, one for
3279   // the region handle. The global address for the TOC entry of the region
3280   // handle is created with the MO_TLSGDM_FLAG flag and the global address
3281   // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG.
3282   SDValue VariableOffsetTGA =
3283       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3284   SDValue RegionHandleTGA =
3285       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG);
3286   SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3287   SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3288   return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3289                      RegionHandle);
3290 }
3291 
3292 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3293                                                       SelectionDAG &DAG) const {
3294   // FIXME: TLS addresses currently use medium model code sequences,
3295   // which is the most useful form.  Eventually support for small and
3296   // large models could be added if users need it, at the cost of
3297   // additional complexity.
3298   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3299   if (DAG.getTarget().useEmulatedTLS())
3300     return LowerToTLSEmulatedModel(GA, DAG);
3301 
3302   SDLoc dl(GA);
3303   const GlobalValue *GV = GA->getGlobal();
3304   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3305   bool is64bit = Subtarget.isPPC64();
3306   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3307   PICLevel::Level picLevel = M->getPICLevel();
3308 
3309   const TargetMachine &TM = getTargetMachine();
3310   TLSModel::Model Model = TM.getTLSModel(GV);
3311 
3312   if (Model == TLSModel::LocalExec) {
3313     if (Subtarget.isUsingPCRelativeCalls()) {
3314       SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3315       SDValue TGA = DAG.getTargetGlobalAddress(
3316           GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3317       SDValue MatAddr =
3318           DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3319       return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3320     }
3321 
3322     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3323                                                PPCII::MO_TPREL_HA);
3324     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3325                                                PPCII::MO_TPREL_LO);
3326     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3327                              : DAG.getRegister(PPC::R2, MVT::i32);
3328 
3329     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3330     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3331   }
3332 
3333   if (Model == TLSModel::InitialExec) {
3334     bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3335     SDValue TGA = DAG.getTargetGlobalAddress(
3336         GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3337     SDValue TGATLS = DAG.getTargetGlobalAddress(
3338         GV, dl, PtrVT, 0,
3339         IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3340     SDValue TPOffset;
3341     if (IsPCRel) {
3342       SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3343       TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3344                              MachinePointerInfo());
3345     } else {
3346       SDValue GOTPtr;
3347       if (is64bit) {
3348         setUsesTOCBasePtr(DAG);
3349         SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3350         GOTPtr =
3351             DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3352       } else {
3353         if (!TM.isPositionIndependent())
3354           GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3355         else if (picLevel == PICLevel::SmallPIC)
3356           GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3357         else
3358           GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3359       }
3360       TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3361     }
3362     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3363   }
3364 
3365   if (Model == TLSModel::GeneralDynamic) {
3366     if (Subtarget.isUsingPCRelativeCalls()) {
3367       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3368                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3369       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3370     }
3371 
3372     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3373     SDValue GOTPtr;
3374     if (is64bit) {
3375       setUsesTOCBasePtr(DAG);
3376       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3377       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3378                                    GOTReg, TGA);
3379     } else {
3380       if (picLevel == PICLevel::SmallPIC)
3381         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3382       else
3383         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3384     }
3385     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3386                        GOTPtr, TGA, TGA);
3387   }
3388 
3389   if (Model == TLSModel::LocalDynamic) {
3390     if (Subtarget.isUsingPCRelativeCalls()) {
3391       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3392                                                PPCII::MO_GOT_TLSLD_PCREL_FLAG);
3393       SDValue MatPCRel =
3394           DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3395       return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3396     }
3397 
3398     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3399     SDValue GOTPtr;
3400     if (is64bit) {
3401       setUsesTOCBasePtr(DAG);
3402       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3403       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3404                            GOTReg, TGA);
3405     } else {
3406       if (picLevel == PICLevel::SmallPIC)
3407         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3408       else
3409         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3410     }
3411     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3412                                   PtrVT, GOTPtr, TGA, TGA);
3413     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3414                                       PtrVT, TLSAddr, TGA);
3415     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3416   }
3417 
3418   llvm_unreachable("Unknown TLS model!");
3419 }
3420 
3421 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3422                                               SelectionDAG &DAG) const {
3423   EVT PtrVT = Op.getValueType();
3424   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3425   SDLoc DL(GSDN);
3426   const GlobalValue *GV = GSDN->getGlobal();
3427 
3428   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3429   // The actual address of the GlobalValue is stored in the TOC.
3430   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3431     if (Subtarget.isUsingPCRelativeCalls()) {
3432       EVT Ty = getPointerTy(DAG.getDataLayout());
3433       if (isAccessedAsGotIndirect(Op)) {
3434         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3435                                                 PPCII::MO_PCREL_FLAG |
3436                                                     PPCII::MO_GOT_FLAG);
3437         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3438         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3439                                    MachinePointerInfo());
3440         return Load;
3441       } else {
3442         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3443                                                 PPCII::MO_PCREL_FLAG);
3444         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3445       }
3446     }
3447     setUsesTOCBasePtr(DAG);
3448     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3449     return getTOCEntry(DAG, DL, GA);
3450   }
3451 
3452   unsigned MOHiFlag, MOLoFlag;
3453   bool IsPIC = isPositionIndependent();
3454   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3455 
3456   if (IsPIC && Subtarget.isSVR4ABI()) {
3457     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3458                                             GSDN->getOffset(),
3459                                             PPCII::MO_PIC_FLAG);
3460     return getTOCEntry(DAG, DL, GA);
3461   }
3462 
3463   SDValue GAHi =
3464     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3465   SDValue GALo =
3466     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3467 
3468   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3469 }
3470 
3471 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3472   bool IsStrict = Op->isStrictFPOpcode();
3473   ISD::CondCode CC =
3474       cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
3475   SDValue LHS = Op.getOperand(IsStrict ? 1 : 0);
3476   SDValue RHS = Op.getOperand(IsStrict ? 2 : 1);
3477   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
3478   EVT LHSVT = LHS.getValueType();
3479   SDLoc dl(Op);
3480 
3481   // Soften the setcc with libcall if it is fp128.
3482   if (LHSVT == MVT::f128) {
3483     assert(!Subtarget.hasP9Vector() &&
3484            "SETCC for f128 is already legal under Power9!");
3485     softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain,
3486                         Op->getOpcode() == ISD::STRICT_FSETCCS);
3487     if (RHS.getNode())
3488       LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS,
3489                         DAG.getCondCode(CC));
3490     if (IsStrict)
3491       return DAG.getMergeValues({LHS, Chain}, dl);
3492     return LHS;
3493   }
3494 
3495   assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!");
3496 
3497   if (Op.getValueType() == MVT::v2i64) {
3498     // When the operands themselves are v2i64 values, we need to do something
3499     // special because VSX has no underlying comparison operations for these.
3500     if (LHS.getValueType() == MVT::v2i64) {
3501       // Equality can be handled by casting to the legal type for Altivec
3502       // comparisons, everything else needs to be expanded.
3503       if (CC != ISD::SETEQ && CC != ISD::SETNE)
3504         return SDValue();
3505       SDValue SetCC32 = DAG.getSetCC(
3506           dl, MVT::v4i32, DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS),
3507           DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC);
3508       int ShuffV[] = {1, 0, 3, 2};
3509       SDValue Shuff =
3510           DAG.getVectorShuffle(MVT::v4i32, dl, SetCC32, SetCC32, ShuffV);
3511       return DAG.getBitcast(MVT::v2i64,
3512                             DAG.getNode(CC == ISD::SETEQ ? ISD::AND : ISD::OR,
3513                                         dl, MVT::v4i32, Shuff, SetCC32));
3514     }
3515 
3516     // We handle most of these in the usual way.
3517     return Op;
3518   }
3519 
3520   // If we're comparing for equality to zero, expose the fact that this is
3521   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3522   // fold the new nodes.
3523   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3524     return V;
3525 
3526   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
3527     // Leave comparisons against 0 and -1 alone for now, since they're usually
3528     // optimized.  FIXME: revisit this when we can custom lower all setcc
3529     // optimizations.
3530     if (C->isAllOnes() || C->isZero())
3531       return SDValue();
3532   }
3533 
3534   // If we have an integer seteq/setne, turn it into a compare against zero
3535   // by xor'ing the rhs with the lhs, which is faster than setting a
3536   // condition register, reading it back out, and masking the correct bit.  The
3537   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3538   // the result to other bit-twiddling opportunities.
3539   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3540     EVT VT = Op.getValueType();
3541     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS);
3542     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3543   }
3544   return SDValue();
3545 }
3546 
3547 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3548   SDNode *Node = Op.getNode();
3549   EVT VT = Node->getValueType(0);
3550   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3551   SDValue InChain = Node->getOperand(0);
3552   SDValue VAListPtr = Node->getOperand(1);
3553   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3554   SDLoc dl(Node);
3555 
3556   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3557 
3558   // gpr_index
3559   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3560                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3561   InChain = GprIndex.getValue(1);
3562 
3563   if (VT == MVT::i64) {
3564     // Check if GprIndex is even
3565     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3566                                  DAG.getConstant(1, dl, MVT::i32));
3567     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3568                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3569     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3570                                           DAG.getConstant(1, dl, MVT::i32));
3571     // Align GprIndex to be even if it isn't
3572     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3573                            GprIndex);
3574   }
3575 
3576   // fpr index is 1 byte after gpr
3577   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3578                                DAG.getConstant(1, dl, MVT::i32));
3579 
3580   // fpr
3581   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3582                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3583   InChain = FprIndex.getValue(1);
3584 
3585   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3586                                        DAG.getConstant(8, dl, MVT::i32));
3587 
3588   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3589                                         DAG.getConstant(4, dl, MVT::i32));
3590 
3591   // areas
3592   SDValue OverflowArea =
3593       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3594   InChain = OverflowArea.getValue(1);
3595 
3596   SDValue RegSaveArea =
3597       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3598   InChain = RegSaveArea.getValue(1);
3599 
3600   // select overflow_area if index > 8
3601   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3602                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3603 
3604   // adjustment constant gpr_index * 4/8
3605   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3606                                     VT.isInteger() ? GprIndex : FprIndex,
3607                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3608                                                     MVT::i32));
3609 
3610   // OurReg = RegSaveArea + RegConstant
3611   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3612                                RegConstant);
3613 
3614   // Floating types are 32 bytes into RegSaveArea
3615   if (VT.isFloatingPoint())
3616     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3617                          DAG.getConstant(32, dl, MVT::i32));
3618 
3619   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3620   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3621                                    VT.isInteger() ? GprIndex : FprIndex,
3622                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3623                                                    MVT::i32));
3624 
3625   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3626                               VT.isInteger() ? VAListPtr : FprPtr,
3627                               MachinePointerInfo(SV), MVT::i8);
3628 
3629   // determine if we should load from reg_save_area or overflow_area
3630   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3631 
3632   // increase overflow_area by 4/8 if gpr/fpr > 8
3633   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3634                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3635                                           dl, MVT::i32));
3636 
3637   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3638                              OverflowAreaPlusN);
3639 
3640   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3641                               MachinePointerInfo(), MVT::i32);
3642 
3643   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3644 }
3645 
3646 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3647   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3648 
3649   // We have to copy the entire va_list struct:
3650   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3651   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3652                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3653                        false, true, false, MachinePointerInfo(),
3654                        MachinePointerInfo());
3655 }
3656 
3657 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3658                                                   SelectionDAG &DAG) const {
3659   if (Subtarget.isAIXABI())
3660     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3661 
3662   return Op.getOperand(0);
3663 }
3664 
3665 SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
3666   MachineFunction &MF = DAG.getMachineFunction();
3667   PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>();
3668 
3669   assert((Op.getOpcode() == ISD::INLINEASM ||
3670           Op.getOpcode() == ISD::INLINEASM_BR) &&
3671          "Expecting Inline ASM node.");
3672 
3673   // If an LR store is already known to be required then there is not point in
3674   // checking this ASM as well.
3675   if (MFI.isLRStoreRequired())
3676     return Op;
3677 
3678   // Inline ASM nodes have an optional last operand that is an incoming Flag of
3679   // type MVT::Glue. We want to ignore this last operand if that is the case.
3680   unsigned NumOps = Op.getNumOperands();
3681   if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue)
3682     --NumOps;
3683 
3684   // Check all operands that may contain the LR.
3685   for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
3686     unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue();
3687     unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
3688     ++i; // Skip the ID value.
3689 
3690     switch (InlineAsm::getKind(Flags)) {
3691     default:
3692       llvm_unreachable("Bad flags!");
3693     case InlineAsm::Kind_RegUse:
3694     case InlineAsm::Kind_Imm:
3695     case InlineAsm::Kind_Mem:
3696       i += NumVals;
3697       break;
3698     case InlineAsm::Kind_Clobber:
3699     case InlineAsm::Kind_RegDef:
3700     case InlineAsm::Kind_RegDefEarlyClobber: {
3701       for (; NumVals; --NumVals, ++i) {
3702         Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg();
3703         if (Reg != PPC::LR && Reg != PPC::LR8)
3704           continue;
3705         MFI.setLRStoreRequired();
3706         return Op;
3707       }
3708       break;
3709     }
3710     }
3711   }
3712 
3713   return Op;
3714 }
3715 
3716 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3717                                                 SelectionDAG &DAG) const {
3718   if (Subtarget.isAIXABI())
3719     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3720 
3721   SDValue Chain = Op.getOperand(0);
3722   SDValue Trmp = Op.getOperand(1); // trampoline
3723   SDValue FPtr = Op.getOperand(2); // nested function
3724   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3725   SDLoc dl(Op);
3726 
3727   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3728   bool isPPC64 = (PtrVT == MVT::i64);
3729   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3730 
3731   TargetLowering::ArgListTy Args;
3732   TargetLowering::ArgListEntry Entry;
3733 
3734   Entry.Ty = IntPtrTy;
3735   Entry.Node = Trmp; Args.push_back(Entry);
3736 
3737   // TrampSize == (isPPC64 ? 48 : 40);
3738   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3739                                isPPC64 ? MVT::i64 : MVT::i32);
3740   Args.push_back(Entry);
3741 
3742   Entry.Node = FPtr; Args.push_back(Entry);
3743   Entry.Node = Nest; Args.push_back(Entry);
3744 
3745   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3746   TargetLowering::CallLoweringInfo CLI(DAG);
3747   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3748       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3749       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3750 
3751   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3752   return CallResult.second;
3753 }
3754 
3755 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3756   MachineFunction &MF = DAG.getMachineFunction();
3757   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3758   EVT PtrVT = getPointerTy(MF.getDataLayout());
3759 
3760   SDLoc dl(Op);
3761 
3762   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3763     // vastart just stores the address of the VarArgsFrameIndex slot into the
3764     // memory location argument.
3765     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3766     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3767     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3768                         MachinePointerInfo(SV));
3769   }
3770 
3771   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3772   // We suppose the given va_list is already allocated.
3773   //
3774   // typedef struct {
3775   //  char gpr;     /* index into the array of 8 GPRs
3776   //                 * stored in the register save area
3777   //                 * gpr=0 corresponds to r3,
3778   //                 * gpr=1 to r4, etc.
3779   //                 */
3780   //  char fpr;     /* index into the array of 8 FPRs
3781   //                 * stored in the register save area
3782   //                 * fpr=0 corresponds to f1,
3783   //                 * fpr=1 to f2, etc.
3784   //                 */
3785   //  char *overflow_arg_area;
3786   //                /* location on stack that holds
3787   //                 * the next overflow argument
3788   //                 */
3789   //  char *reg_save_area;
3790   //               /* where r3:r10 and f1:f8 (if saved)
3791   //                * are stored
3792   //                */
3793   // } va_list[1];
3794 
3795   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3796   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3797   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3798                                             PtrVT);
3799   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3800                                  PtrVT);
3801 
3802   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3803   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3804 
3805   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3806   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3807 
3808   uint64_t FPROffset = 1;
3809   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3810 
3811   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3812 
3813   // Store first byte : number of int regs
3814   SDValue firstStore =
3815       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3816                         MachinePointerInfo(SV), MVT::i8);
3817   uint64_t nextOffset = FPROffset;
3818   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3819                                   ConstFPROffset);
3820 
3821   // Store second byte : number of float regs
3822   SDValue secondStore =
3823       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3824                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3825   nextOffset += StackOffset;
3826   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3827 
3828   // Store second word : arguments given on stack
3829   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3830                                     MachinePointerInfo(SV, nextOffset));
3831   nextOffset += FrameOffset;
3832   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3833 
3834   // Store third word : arguments given in registers
3835   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3836                       MachinePointerInfo(SV, nextOffset));
3837 }
3838 
3839 /// FPR - The set of FP registers that should be allocated for arguments
3840 /// on Darwin and AIX.
3841 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3842                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3843                                 PPC::F11, PPC::F12, PPC::F13};
3844 
3845 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3846 /// the stack.
3847 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3848                                        unsigned PtrByteSize) {
3849   unsigned ArgSize = ArgVT.getStoreSize();
3850   if (Flags.isByVal())
3851     ArgSize = Flags.getByValSize();
3852 
3853   // Round up to multiples of the pointer size, except for array members,
3854   // which are always packed.
3855   if (!Flags.isInConsecutiveRegs())
3856     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3857 
3858   return ArgSize;
3859 }
3860 
3861 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3862 /// on the stack.
3863 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3864                                          ISD::ArgFlagsTy Flags,
3865                                          unsigned PtrByteSize) {
3866   Align Alignment(PtrByteSize);
3867 
3868   // Altivec parameters are padded to a 16 byte boundary.
3869   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3870       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3871       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3872       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3873     Alignment = Align(16);
3874 
3875   // ByVal parameters are aligned as requested.
3876   if (Flags.isByVal()) {
3877     auto BVAlign = Flags.getNonZeroByValAlign();
3878     if (BVAlign > PtrByteSize) {
3879       if (BVAlign.value() % PtrByteSize != 0)
3880         llvm_unreachable(
3881             "ByVal alignment is not a multiple of the pointer size");
3882 
3883       Alignment = BVAlign;
3884     }
3885   }
3886 
3887   // Array members are always packed to their original alignment.
3888   if (Flags.isInConsecutiveRegs()) {
3889     // If the array member was split into multiple registers, the first
3890     // needs to be aligned to the size of the full type.  (Except for
3891     // ppcf128, which is only aligned as its f64 components.)
3892     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3893       Alignment = Align(OrigVT.getStoreSize());
3894     else
3895       Alignment = Align(ArgVT.getStoreSize());
3896   }
3897 
3898   return Alignment;
3899 }
3900 
3901 /// CalculateStackSlotUsed - Return whether this argument will use its
3902 /// stack slot (instead of being passed in registers).  ArgOffset,
3903 /// AvailableFPRs, and AvailableVRs must hold the current argument
3904 /// position, and will be updated to account for this argument.
3905 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3906                                    unsigned PtrByteSize, unsigned LinkageSize,
3907                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3908                                    unsigned &AvailableFPRs,
3909                                    unsigned &AvailableVRs) {
3910   bool UseMemory = false;
3911 
3912   // Respect alignment of argument on the stack.
3913   Align Alignment =
3914       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3915   ArgOffset = alignTo(ArgOffset, Alignment);
3916   // If there's no space left in the argument save area, we must
3917   // use memory (this check also catches zero-sized arguments).
3918   if (ArgOffset >= LinkageSize + ParamAreaSize)
3919     UseMemory = true;
3920 
3921   // Allocate argument on the stack.
3922   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3923   if (Flags.isInConsecutiveRegsLast())
3924     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3925   // If we overran the argument save area, we must use memory
3926   // (this check catches arguments passed partially in memory)
3927   if (ArgOffset > LinkageSize + ParamAreaSize)
3928     UseMemory = true;
3929 
3930   // However, if the argument is actually passed in an FPR or a VR,
3931   // we don't use memory after all.
3932   if (!Flags.isByVal()) {
3933     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3934       if (AvailableFPRs > 0) {
3935         --AvailableFPRs;
3936         return false;
3937       }
3938     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3939         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3940         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3941         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3942       if (AvailableVRs > 0) {
3943         --AvailableVRs;
3944         return false;
3945       }
3946   }
3947 
3948   return UseMemory;
3949 }
3950 
3951 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3952 /// ensure minimum alignment required for target.
3953 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3954                                      unsigned NumBytes) {
3955   return alignTo(NumBytes, Lowering->getStackAlign());
3956 }
3957 
3958 SDValue PPCTargetLowering::LowerFormalArguments(
3959     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3960     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3961     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3962   if (Subtarget.isAIXABI())
3963     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3964                                     InVals);
3965   if (Subtarget.is64BitELFABI())
3966     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3967                                        InVals);
3968   assert(Subtarget.is32BitELFABI());
3969   return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3970                                      InVals);
3971 }
3972 
3973 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3974     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3975     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3976     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3977 
3978   // 32-bit SVR4 ABI Stack Frame Layout:
3979   //              +-----------------------------------+
3980   //        +-->  |            Back chain             |
3981   //        |     +-----------------------------------+
3982   //        |     | Floating-point register save area |
3983   //        |     +-----------------------------------+
3984   //        |     |    General register save area     |
3985   //        |     +-----------------------------------+
3986   //        |     |          CR save word             |
3987   //        |     +-----------------------------------+
3988   //        |     |         VRSAVE save word          |
3989   //        |     +-----------------------------------+
3990   //        |     |         Alignment padding         |
3991   //        |     +-----------------------------------+
3992   //        |     |     Vector register save area     |
3993   //        |     +-----------------------------------+
3994   //        |     |       Local variable space        |
3995   //        |     +-----------------------------------+
3996   //        |     |        Parameter list area        |
3997   //        |     +-----------------------------------+
3998   //        |     |           LR save word            |
3999   //        |     +-----------------------------------+
4000   // SP-->  +---  |            Back chain             |
4001   //              +-----------------------------------+
4002   //
4003   // Specifications:
4004   //   System V Application Binary Interface PowerPC Processor Supplement
4005   //   AltiVec Technology Programming Interface Manual
4006 
4007   MachineFunction &MF = DAG.getMachineFunction();
4008   MachineFrameInfo &MFI = MF.getFrameInfo();
4009   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4010 
4011   EVT PtrVT = getPointerTy(MF.getDataLayout());
4012   // Potential tail calls could cause overwriting of argument stack slots.
4013   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4014                        (CallConv == CallingConv::Fast));
4015   const Align PtrAlign(4);
4016 
4017   // Assign locations to all of the incoming arguments.
4018   SmallVector<CCValAssign, 16> ArgLocs;
4019   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4020                  *DAG.getContext());
4021 
4022   // Reserve space for the linkage area on the stack.
4023   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4024   CCInfo.AllocateStack(LinkageSize, PtrAlign);
4025   if (useSoftFloat())
4026     CCInfo.PreAnalyzeFormalArguments(Ins);
4027 
4028   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
4029   CCInfo.clearWasPPCF128();
4030 
4031   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4032     CCValAssign &VA = ArgLocs[i];
4033 
4034     // Arguments stored in registers.
4035     if (VA.isRegLoc()) {
4036       const TargetRegisterClass *RC;
4037       EVT ValVT = VA.getValVT();
4038 
4039       switch (ValVT.getSimpleVT().SimpleTy) {
4040         default:
4041           llvm_unreachable("ValVT not supported by formal arguments Lowering");
4042         case MVT::i1:
4043         case MVT::i32:
4044           RC = &PPC::GPRCRegClass;
4045           break;
4046         case MVT::f32:
4047           if (Subtarget.hasP8Vector())
4048             RC = &PPC::VSSRCRegClass;
4049           else if (Subtarget.hasSPE())
4050             RC = &PPC::GPRCRegClass;
4051           else
4052             RC = &PPC::F4RCRegClass;
4053           break;
4054         case MVT::f64:
4055           if (Subtarget.hasVSX())
4056             RC = &PPC::VSFRCRegClass;
4057           else if (Subtarget.hasSPE())
4058             // SPE passes doubles in GPR pairs.
4059             RC = &PPC::GPRCRegClass;
4060           else
4061             RC = &PPC::F8RCRegClass;
4062           break;
4063         case MVT::v16i8:
4064         case MVT::v8i16:
4065         case MVT::v4i32:
4066           RC = &PPC::VRRCRegClass;
4067           break;
4068         case MVT::v4f32:
4069           RC = &PPC::VRRCRegClass;
4070           break;
4071         case MVT::v2f64:
4072         case MVT::v2i64:
4073           RC = &PPC::VRRCRegClass;
4074           break;
4075       }
4076 
4077       SDValue ArgValue;
4078       // Transform the arguments stored in physical registers into
4079       // virtual ones.
4080       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
4081         assert(i + 1 < e && "No second half of double precision argument");
4082         Register RegLo = MF.addLiveIn(VA.getLocReg(), RC);
4083         Register RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
4084         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
4085         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
4086         if (!Subtarget.isLittleEndian())
4087           std::swap (ArgValueLo, ArgValueHi);
4088         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
4089                                ArgValueHi);
4090       } else {
4091         Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4092         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
4093                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
4094         if (ValVT == MVT::i1)
4095           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
4096       }
4097 
4098       InVals.push_back(ArgValue);
4099     } else {
4100       // Argument stored in memory.
4101       assert(VA.isMemLoc());
4102 
4103       // Get the extended size of the argument type in stack
4104       unsigned ArgSize = VA.getLocVT().getStoreSize();
4105       // Get the actual size of the argument type
4106       unsigned ObjSize = VA.getValVT().getStoreSize();
4107       unsigned ArgOffset = VA.getLocMemOffset();
4108       // Stack objects in PPC32 are right justified.
4109       ArgOffset += ArgSize - ObjSize;
4110       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
4111 
4112       // Create load nodes to retrieve arguments from the stack.
4113       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4114       InVals.push_back(
4115           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
4116     }
4117   }
4118 
4119   // Assign locations to all of the incoming aggregate by value arguments.
4120   // Aggregates passed by value are stored in the local variable space of the
4121   // caller's stack frame, right above the parameter list area.
4122   SmallVector<CCValAssign, 16> ByValArgLocs;
4123   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4124                       ByValArgLocs, *DAG.getContext());
4125 
4126   // Reserve stack space for the allocations in CCInfo.
4127   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
4128 
4129   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
4130 
4131   // Area that is at least reserved in the caller of this function.
4132   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
4133   MinReservedArea = std::max(MinReservedArea, LinkageSize);
4134 
4135   // Set the size that is at least reserved in caller of this function.  Tail
4136   // call optimized function's reserved stack space needs to be aligned so that
4137   // taking the difference between two stack areas will result in an aligned
4138   // stack.
4139   MinReservedArea =
4140       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4141   FuncInfo->setMinReservedArea(MinReservedArea);
4142 
4143   SmallVector<SDValue, 8> MemOps;
4144 
4145   // If the function takes variable number of arguments, make a frame index for
4146   // the start of the first vararg value... for expansion of llvm.va_start.
4147   if (isVarArg) {
4148     static const MCPhysReg GPArgRegs[] = {
4149       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4150       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4151     };
4152     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
4153 
4154     static const MCPhysReg FPArgRegs[] = {
4155       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
4156       PPC::F8
4157     };
4158     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
4159 
4160     if (useSoftFloat() || hasSPE())
4161        NumFPArgRegs = 0;
4162 
4163     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
4164     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
4165 
4166     // Make room for NumGPArgRegs and NumFPArgRegs.
4167     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
4168                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
4169 
4170     FuncInfo->setVarArgsStackOffset(
4171       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4172                             CCInfo.getNextStackOffset(), true));
4173 
4174     FuncInfo->setVarArgsFrameIndex(
4175         MFI.CreateStackObject(Depth, Align(8), false));
4176     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4177 
4178     // The fixed integer arguments of a variadic function are stored to the
4179     // VarArgsFrameIndex on the stack so that they may be loaded by
4180     // dereferencing the result of va_next.
4181     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
4182       // Get an existing live-in vreg, or add a new one.
4183       Register VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
4184       if (!VReg)
4185         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
4186 
4187       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4188       SDValue Store =
4189           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4190       MemOps.push_back(Store);
4191       // Increment the address by four for the next argument to store
4192       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4193       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4194     }
4195 
4196     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
4197     // is set.
4198     // The double arguments are stored to the VarArgsFrameIndex
4199     // on the stack.
4200     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
4201       // Get an existing live-in vreg, or add a new one.
4202       Register VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
4203       if (!VReg)
4204         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
4205 
4206       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
4207       SDValue Store =
4208           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4209       MemOps.push_back(Store);
4210       // Increment the address by eight for the next argument to store
4211       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
4212                                          PtrVT);
4213       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4214     }
4215   }
4216 
4217   if (!MemOps.empty())
4218     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4219 
4220   return Chain;
4221 }
4222 
4223 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4224 // value to MVT::i64 and then truncate to the correct register size.
4225 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
4226                                              EVT ObjectVT, SelectionDAG &DAG,
4227                                              SDValue ArgVal,
4228                                              const SDLoc &dl) const {
4229   if (Flags.isSExt())
4230     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
4231                          DAG.getValueType(ObjectVT));
4232   else if (Flags.isZExt())
4233     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
4234                          DAG.getValueType(ObjectVT));
4235 
4236   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
4237 }
4238 
4239 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
4240     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4241     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4242     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4243   // TODO: add description of PPC stack frame format, or at least some docs.
4244   //
4245   bool isELFv2ABI = Subtarget.isELFv2ABI();
4246   bool isLittleEndian = Subtarget.isLittleEndian();
4247   MachineFunction &MF = DAG.getMachineFunction();
4248   MachineFrameInfo &MFI = MF.getFrameInfo();
4249   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4250 
4251   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4252          "fastcc not supported on varargs functions");
4253 
4254   EVT PtrVT = getPointerTy(MF.getDataLayout());
4255   // Potential tail calls could cause overwriting of argument stack slots.
4256   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4257                        (CallConv == CallingConv::Fast));
4258   unsigned PtrByteSize = 8;
4259   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4260 
4261   static const MCPhysReg GPR[] = {
4262     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4263     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4264   };
4265   static const MCPhysReg VR[] = {
4266     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4267     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4268   };
4269 
4270   const unsigned Num_GPR_Regs = array_lengthof(GPR);
4271   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4272   const unsigned Num_VR_Regs  = array_lengthof(VR);
4273 
4274   // Do a first pass over the arguments to determine whether the ABI
4275   // guarantees that our caller has allocated the parameter save area
4276   // on its stack frame.  In the ELFv1 ABI, this is always the case;
4277   // in the ELFv2 ABI, it is true if this is a vararg function or if
4278   // any parameter is located in a stack slot.
4279 
4280   bool HasParameterArea = !isELFv2ABI || isVarArg;
4281   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4282   unsigned NumBytes = LinkageSize;
4283   unsigned AvailableFPRs = Num_FPR_Regs;
4284   unsigned AvailableVRs = Num_VR_Regs;
4285   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4286     if (Ins[i].Flags.isNest())
4287       continue;
4288 
4289     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
4290                                PtrByteSize, LinkageSize, ParamAreaSize,
4291                                NumBytes, AvailableFPRs, AvailableVRs))
4292       HasParameterArea = true;
4293   }
4294 
4295   // Add DAG nodes to load the arguments or copy them out of registers.  On
4296   // entry to a function on PPC, the arguments start after the linkage area,
4297   // although the first ones are often in registers.
4298 
4299   unsigned ArgOffset = LinkageSize;
4300   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4301   SmallVector<SDValue, 8> MemOps;
4302   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4303   unsigned CurArgIdx = 0;
4304   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4305     SDValue ArgVal;
4306     bool needsLoad = false;
4307     EVT ObjectVT = Ins[ArgNo].VT;
4308     EVT OrigVT = Ins[ArgNo].ArgVT;
4309     unsigned ObjSize = ObjectVT.getStoreSize();
4310     unsigned ArgSize = ObjSize;
4311     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4312     if (Ins[ArgNo].isOrigArg()) {
4313       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4314       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4315     }
4316     // We re-align the argument offset for each argument, except when using the
4317     // fast calling convention, when we need to make sure we do that only when
4318     // we'll actually use a stack slot.
4319     unsigned CurArgOffset;
4320     Align Alignment;
4321     auto ComputeArgOffset = [&]() {
4322       /* Respect alignment of argument on the stack.  */
4323       Alignment =
4324           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4325       ArgOffset = alignTo(ArgOffset, Alignment);
4326       CurArgOffset = ArgOffset;
4327     };
4328 
4329     if (CallConv != CallingConv::Fast) {
4330       ComputeArgOffset();
4331 
4332       /* Compute GPR index associated with argument offset.  */
4333       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4334       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4335     }
4336 
4337     // FIXME the codegen can be much improved in some cases.
4338     // We do not have to keep everything in memory.
4339     if (Flags.isByVal()) {
4340       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4341 
4342       if (CallConv == CallingConv::Fast)
4343         ComputeArgOffset();
4344 
4345       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4346       ObjSize = Flags.getByValSize();
4347       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4348       // Empty aggregate parameters do not take up registers.  Examples:
4349       //   struct { } a;
4350       //   union  { } b;
4351       //   int c[0];
4352       // etc.  However, we have to provide a place-holder in InVals, so
4353       // pretend we have an 8-byte item at the current address for that
4354       // purpose.
4355       if (!ObjSize) {
4356         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4357         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4358         InVals.push_back(FIN);
4359         continue;
4360       }
4361 
4362       // Create a stack object covering all stack doublewords occupied
4363       // by the argument.  If the argument is (fully or partially) on
4364       // the stack, or if the argument is fully in registers but the
4365       // caller has allocated the parameter save anyway, we can refer
4366       // directly to the caller's stack frame.  Otherwise, create a
4367       // local copy in our own frame.
4368       int FI;
4369       if (HasParameterArea ||
4370           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4371         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4372       else
4373         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4374       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4375 
4376       // Handle aggregates smaller than 8 bytes.
4377       if (ObjSize < PtrByteSize) {
4378         // The value of the object is its address, which differs from the
4379         // address of the enclosing doubleword on big-endian systems.
4380         SDValue Arg = FIN;
4381         if (!isLittleEndian) {
4382           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4383           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4384         }
4385         InVals.push_back(Arg);
4386 
4387         if (GPR_idx != Num_GPR_Regs) {
4388           Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4389           FuncInfo->addLiveInAttr(VReg, Flags);
4390           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4391           EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8);
4392           SDValue Store =
4393               DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4394                                 MachinePointerInfo(&*FuncArg), ObjType);
4395           MemOps.push_back(Store);
4396         }
4397         // Whether we copied from a register or not, advance the offset
4398         // into the parameter save area by a full doubleword.
4399         ArgOffset += PtrByteSize;
4400         continue;
4401       }
4402 
4403       // The value of the object is its address, which is the address of
4404       // its first stack doubleword.
4405       InVals.push_back(FIN);
4406 
4407       // Store whatever pieces of the object are in registers to memory.
4408       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4409         if (GPR_idx == Num_GPR_Regs)
4410           break;
4411 
4412         Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4413         FuncInfo->addLiveInAttr(VReg, Flags);
4414         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4415         SDValue Addr = FIN;
4416         if (j) {
4417           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4418           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4419         }
4420         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4421                                      MachinePointerInfo(&*FuncArg, j));
4422         MemOps.push_back(Store);
4423         ++GPR_idx;
4424       }
4425       ArgOffset += ArgSize;
4426       continue;
4427     }
4428 
4429     switch (ObjectVT.getSimpleVT().SimpleTy) {
4430     default: llvm_unreachable("Unhandled argument type!");
4431     case MVT::i1:
4432     case MVT::i32:
4433     case MVT::i64:
4434       if (Flags.isNest()) {
4435         // The 'nest' parameter, if any, is passed in R11.
4436         Register VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4437         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4438 
4439         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4440           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4441 
4442         break;
4443       }
4444 
4445       // These can be scalar arguments or elements of an integer array type
4446       // passed directly.  Clang may use those instead of "byval" aggregate
4447       // types to avoid forcing arguments to memory unnecessarily.
4448       if (GPR_idx != Num_GPR_Regs) {
4449         Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4450         FuncInfo->addLiveInAttr(VReg, Flags);
4451         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4452 
4453         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4454           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4455           // value to MVT::i64 and then truncate to the correct register size.
4456           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4457       } else {
4458         if (CallConv == CallingConv::Fast)
4459           ComputeArgOffset();
4460 
4461         needsLoad = true;
4462         ArgSize = PtrByteSize;
4463       }
4464       if (CallConv != CallingConv::Fast || needsLoad)
4465         ArgOffset += 8;
4466       break;
4467 
4468     case MVT::f32:
4469     case MVT::f64:
4470       // These can be scalar arguments or elements of a float array type
4471       // passed directly.  The latter are used to implement ELFv2 homogenous
4472       // float aggregates.
4473       if (FPR_idx != Num_FPR_Regs) {
4474         unsigned VReg;
4475 
4476         if (ObjectVT == MVT::f32)
4477           VReg = MF.addLiveIn(FPR[FPR_idx],
4478                               Subtarget.hasP8Vector()
4479                                   ? &PPC::VSSRCRegClass
4480                                   : &PPC::F4RCRegClass);
4481         else
4482           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4483                                                 ? &PPC::VSFRCRegClass
4484                                                 : &PPC::F8RCRegClass);
4485 
4486         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4487         ++FPR_idx;
4488       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4489         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4490         // once we support fp <-> gpr moves.
4491 
4492         // This can only ever happen in the presence of f32 array types,
4493         // since otherwise we never run out of FPRs before running out
4494         // of GPRs.
4495         Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4496         FuncInfo->addLiveInAttr(VReg, Flags);
4497         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4498 
4499         if (ObjectVT == MVT::f32) {
4500           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4501             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4502                                  DAG.getConstant(32, dl, MVT::i32));
4503           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4504         }
4505 
4506         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4507       } else {
4508         if (CallConv == CallingConv::Fast)
4509           ComputeArgOffset();
4510 
4511         needsLoad = true;
4512       }
4513 
4514       // When passing an array of floats, the array occupies consecutive
4515       // space in the argument area; only round up to the next doubleword
4516       // at the end of the array.  Otherwise, each float takes 8 bytes.
4517       if (CallConv != CallingConv::Fast || needsLoad) {
4518         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4519         ArgOffset += ArgSize;
4520         if (Flags.isInConsecutiveRegsLast())
4521           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4522       }
4523       break;
4524     case MVT::v4f32:
4525     case MVT::v4i32:
4526     case MVT::v8i16:
4527     case MVT::v16i8:
4528     case MVT::v2f64:
4529     case MVT::v2i64:
4530     case MVT::v1i128:
4531     case MVT::f128:
4532       // These can be scalar arguments or elements of a vector array type
4533       // passed directly.  The latter are used to implement ELFv2 homogenous
4534       // vector aggregates.
4535       if (VR_idx != Num_VR_Regs) {
4536         Register VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4537         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4538         ++VR_idx;
4539       } else {
4540         if (CallConv == CallingConv::Fast)
4541           ComputeArgOffset();
4542         needsLoad = true;
4543       }
4544       if (CallConv != CallingConv::Fast || needsLoad)
4545         ArgOffset += 16;
4546       break;
4547     }
4548 
4549     // We need to load the argument to a virtual register if we determined
4550     // above that we ran out of physical registers of the appropriate type.
4551     if (needsLoad) {
4552       if (ObjSize < ArgSize && !isLittleEndian)
4553         CurArgOffset += ArgSize - ObjSize;
4554       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4555       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4556       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4557     }
4558 
4559     InVals.push_back(ArgVal);
4560   }
4561 
4562   // Area that is at least reserved in the caller of this function.
4563   unsigned MinReservedArea;
4564   if (HasParameterArea)
4565     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4566   else
4567     MinReservedArea = LinkageSize;
4568 
4569   // Set the size that is at least reserved in caller of this function.  Tail
4570   // call optimized functions' reserved stack space needs to be aligned so that
4571   // taking the difference between two stack areas will result in an aligned
4572   // stack.
4573   MinReservedArea =
4574       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4575   FuncInfo->setMinReservedArea(MinReservedArea);
4576 
4577   // If the function takes variable number of arguments, make a frame index for
4578   // the start of the first vararg value... for expansion of llvm.va_start.
4579   // On ELFv2ABI spec, it writes:
4580   // C programs that are intended to be *portable* across different compilers
4581   // and architectures must use the header file <stdarg.h> to deal with variable
4582   // argument lists.
4583   if (isVarArg && MFI.hasVAStart()) {
4584     int Depth = ArgOffset;
4585 
4586     FuncInfo->setVarArgsFrameIndex(
4587       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4588     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4589 
4590     // If this function is vararg, store any remaining integer argument regs
4591     // to their spots on the stack so that they may be loaded by dereferencing
4592     // the result of va_next.
4593     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4594          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4595       Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4596       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4597       SDValue Store =
4598           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4599       MemOps.push_back(Store);
4600       // Increment the address by four for the next argument to store
4601       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4602       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4603     }
4604   }
4605 
4606   if (!MemOps.empty())
4607     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4608 
4609   return Chain;
4610 }
4611 
4612 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4613 /// adjusted to accommodate the arguments for the tailcall.
4614 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4615                                    unsigned ParamSize) {
4616 
4617   if (!isTailCall) return 0;
4618 
4619   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4620   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4621   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4622   // Remember only if the new adjustment is bigger.
4623   if (SPDiff < FI->getTailCallSPDelta())
4624     FI->setTailCallSPDelta(SPDiff);
4625 
4626   return SPDiff;
4627 }
4628 
4629 static bool isFunctionGlobalAddress(SDValue Callee);
4630 
4631 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4632                               const TargetMachine &TM) {
4633   // It does not make sense to call callsShareTOCBase() with a caller that
4634   // is PC Relative since PC Relative callers do not have a TOC.
4635 #ifndef NDEBUG
4636   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4637   assert(!STICaller->isUsingPCRelativeCalls() &&
4638          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4639 #endif
4640 
4641   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4642   // don't have enough information to determine if the caller and callee share
4643   // the same  TOC base, so we have to pessimistically assume they don't for
4644   // correctness.
4645   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4646   if (!G)
4647     return false;
4648 
4649   const GlobalValue *GV = G->getGlobal();
4650 
4651   // If the callee is preemptable, then the static linker will use a plt-stub
4652   // which saves the toc to the stack, and needs a nop after the call
4653   // instruction to convert to a toc-restore.
4654   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4655     return false;
4656 
4657   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4658   // We may need a TOC restore in the situation where the caller requires a
4659   // valid TOC but the callee is PC Relative and does not.
4660   const Function *F = dyn_cast<Function>(GV);
4661   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4662 
4663   // If we have an Alias we can try to get the function from there.
4664   if (Alias) {
4665     const GlobalObject *GlobalObj = Alias->getAliaseeObject();
4666     F = dyn_cast<Function>(GlobalObj);
4667   }
4668 
4669   // If we still have no valid function pointer we do not have enough
4670   // information to determine if the callee uses PC Relative calls so we must
4671   // assume that it does.
4672   if (!F)
4673     return false;
4674 
4675   // If the callee uses PC Relative we cannot guarantee that the callee won't
4676   // clobber the TOC of the caller and so we must assume that the two
4677   // functions do not share a TOC base.
4678   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4679   if (STICallee->isUsingPCRelativeCalls())
4680     return false;
4681 
4682   // If the GV is not a strong definition then we need to assume it can be
4683   // replaced by another function at link time. The function that replaces
4684   // it may not share the same TOC as the caller since the callee may be
4685   // replaced by a PC Relative version of the same function.
4686   if (!GV->isStrongDefinitionForLinker())
4687     return false;
4688 
4689   // The medium and large code models are expected to provide a sufficiently
4690   // large TOC to provide all data addressing needs of a module with a
4691   // single TOC.
4692   if (CodeModel::Medium == TM.getCodeModel() ||
4693       CodeModel::Large == TM.getCodeModel())
4694     return true;
4695 
4696   // Any explicitly-specified sections and section prefixes must also match.
4697   // Also, if we're using -ffunction-sections, then each function is always in
4698   // a different section (the same is true for COMDAT functions).
4699   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4700       GV->getSection() != Caller->getSection())
4701     return false;
4702   if (const auto *F = dyn_cast<Function>(GV)) {
4703     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4704       return false;
4705   }
4706 
4707   return true;
4708 }
4709 
4710 static bool
4711 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4712                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4713   assert(Subtarget.is64BitELFABI());
4714 
4715   const unsigned PtrByteSize = 8;
4716   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4717 
4718   static const MCPhysReg GPR[] = {
4719     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4720     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4721   };
4722   static const MCPhysReg VR[] = {
4723     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4724     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4725   };
4726 
4727   const unsigned NumGPRs = array_lengthof(GPR);
4728   const unsigned NumFPRs = 13;
4729   const unsigned NumVRs = array_lengthof(VR);
4730   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4731 
4732   unsigned NumBytes = LinkageSize;
4733   unsigned AvailableFPRs = NumFPRs;
4734   unsigned AvailableVRs = NumVRs;
4735 
4736   for (const ISD::OutputArg& Param : Outs) {
4737     if (Param.Flags.isNest()) continue;
4738 
4739     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4740                                LinkageSize, ParamAreaSize, NumBytes,
4741                                AvailableFPRs, AvailableVRs))
4742       return true;
4743   }
4744   return false;
4745 }
4746 
4747 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4748   if (CB.arg_size() != CallerFn->arg_size())
4749     return false;
4750 
4751   auto CalleeArgIter = CB.arg_begin();
4752   auto CalleeArgEnd = CB.arg_end();
4753   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4754 
4755   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4756     const Value* CalleeArg = *CalleeArgIter;
4757     const Value* CallerArg = &(*CallerArgIter);
4758     if (CalleeArg == CallerArg)
4759       continue;
4760 
4761     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4762     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4763     //      }
4764     // 1st argument of callee is undef and has the same type as caller.
4765     if (CalleeArg->getType() == CallerArg->getType() &&
4766         isa<UndefValue>(CalleeArg))
4767       continue;
4768 
4769     return false;
4770   }
4771 
4772   return true;
4773 }
4774 
4775 // Returns true if TCO is possible between the callers and callees
4776 // calling conventions.
4777 static bool
4778 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4779                                     CallingConv::ID CalleeCC) {
4780   // Tail calls are possible with fastcc and ccc.
4781   auto isTailCallableCC  = [] (CallingConv::ID CC){
4782       return  CC == CallingConv::C || CC == CallingConv::Fast;
4783   };
4784   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4785     return false;
4786 
4787   // We can safely tail call both fastcc and ccc callees from a c calling
4788   // convention caller. If the caller is fastcc, we may have less stack space
4789   // than a non-fastcc caller with the same signature so disable tail-calls in
4790   // that case.
4791   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4792 }
4793 
4794 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4795     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4796     const SmallVectorImpl<ISD::OutputArg> &Outs,
4797     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4798   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4799 
4800   if (DisableSCO && !TailCallOpt) return false;
4801 
4802   // Variadic argument functions are not supported.
4803   if (isVarArg) return false;
4804 
4805   auto &Caller = DAG.getMachineFunction().getFunction();
4806   // Check that the calling conventions are compatible for tco.
4807   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4808     return false;
4809 
4810   // Caller contains any byval parameter is not supported.
4811   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4812     return false;
4813 
4814   // Callee contains any byval parameter is not supported, too.
4815   // Note: This is a quick work around, because in some cases, e.g.
4816   // caller's stack size > callee's stack size, we are still able to apply
4817   // sibling call optimization. For example, gcc is able to do SCO for caller1
4818   // in the following example, but not for caller2.
4819   //   struct test {
4820   //     long int a;
4821   //     char ary[56];
4822   //   } gTest;
4823   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4824   //     b->a = v.a;
4825   //     return 0;
4826   //   }
4827   //   void caller1(struct test a, struct test c, struct test *b) {
4828   //     callee(gTest, b); }
4829   //   void caller2(struct test *b) { callee(gTest, b); }
4830   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4831     return false;
4832 
4833   // If callee and caller use different calling conventions, we cannot pass
4834   // parameters on stack since offsets for the parameter area may be different.
4835   if (Caller.getCallingConv() != CalleeCC &&
4836       needStackSlotPassParameters(Subtarget, Outs))
4837     return false;
4838 
4839   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4840   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4841   // callee potentially have different TOC bases then we cannot tail call since
4842   // we need to restore the TOC pointer after the call.
4843   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4844   // We cannot guarantee this for indirect calls or calls to external functions.
4845   // When PC-Relative addressing is used, the concept of the TOC is no longer
4846   // applicable so this check is not required.
4847   // Check first for indirect calls.
4848   if (!Subtarget.isUsingPCRelativeCalls() &&
4849       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4850     return false;
4851 
4852   // Check if we share the TOC base.
4853   if (!Subtarget.isUsingPCRelativeCalls() &&
4854       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4855     return false;
4856 
4857   // TCO allows altering callee ABI, so we don't have to check further.
4858   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4859     return true;
4860 
4861   if (DisableSCO) return false;
4862 
4863   // If callee use the same argument list that caller is using, then we can
4864   // apply SCO on this case. If it is not, then we need to check if callee needs
4865   // stack for passing arguments.
4866   // PC Relative tail calls may not have a CallBase.
4867   // If there is no CallBase we cannot verify if we have the same argument
4868   // list so assume that we don't have the same argument list.
4869   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4870       needStackSlotPassParameters(Subtarget, Outs))
4871     return false;
4872   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4873     return false;
4874 
4875   return true;
4876 }
4877 
4878 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4879 /// for tail call optimization. Targets which want to do tail call
4880 /// optimization should implement this function.
4881 bool
4882 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4883                                                      CallingConv::ID CalleeCC,
4884                                                      bool isVarArg,
4885                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4886                                                      SelectionDAG& DAG) const {
4887   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4888     return false;
4889 
4890   // Variable argument functions are not supported.
4891   if (isVarArg)
4892     return false;
4893 
4894   MachineFunction &MF = DAG.getMachineFunction();
4895   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4896   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4897     // Functions containing by val parameters are not supported.
4898     for (unsigned i = 0; i != Ins.size(); i++) {
4899        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4900        if (Flags.isByVal()) return false;
4901     }
4902 
4903     // Non-PIC/GOT tail calls are supported.
4904     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4905       return true;
4906 
4907     // At the moment we can only do local tail calls (in same module, hidden
4908     // or protected) if we are generating PIC.
4909     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4910       return G->getGlobal()->hasHiddenVisibility()
4911           || G->getGlobal()->hasProtectedVisibility();
4912   }
4913 
4914   return false;
4915 }
4916 
4917 /// isCallCompatibleAddress - Return the immediate to use if the specified
4918 /// 32-bit value is representable in the immediate field of a BxA instruction.
4919 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4920   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4921   if (!C) return nullptr;
4922 
4923   int Addr = C->getZExtValue();
4924   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4925       SignExtend32<26>(Addr) != Addr)
4926     return nullptr;  // Top 6 bits have to be sext of immediate.
4927 
4928   return DAG
4929       .getConstant(
4930           (int)C->getZExtValue() >> 2, SDLoc(Op),
4931           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4932       .getNode();
4933 }
4934 
4935 namespace {
4936 
4937 struct TailCallArgumentInfo {
4938   SDValue Arg;
4939   SDValue FrameIdxOp;
4940   int FrameIdx = 0;
4941 
4942   TailCallArgumentInfo() = default;
4943 };
4944 
4945 } // end anonymous namespace
4946 
4947 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4948 static void StoreTailCallArgumentsToStackSlot(
4949     SelectionDAG &DAG, SDValue Chain,
4950     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4951     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4952   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4953     SDValue Arg = TailCallArgs[i].Arg;
4954     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4955     int FI = TailCallArgs[i].FrameIdx;
4956     // Store relative to framepointer.
4957     MemOpChains.push_back(DAG.getStore(
4958         Chain, dl, Arg, FIN,
4959         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4960   }
4961 }
4962 
4963 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4964 /// the appropriate stack slot for the tail call optimized function call.
4965 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4966                                              SDValue OldRetAddr, SDValue OldFP,
4967                                              int SPDiff, const SDLoc &dl) {
4968   if (SPDiff) {
4969     // Calculate the new stack slot for the return address.
4970     MachineFunction &MF = DAG.getMachineFunction();
4971     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4972     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4973     bool isPPC64 = Subtarget.isPPC64();
4974     int SlotSize = isPPC64 ? 8 : 4;
4975     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4976     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4977                                                          NewRetAddrLoc, true);
4978     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4979     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4980     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4981                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4982   }
4983   return Chain;
4984 }
4985 
4986 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4987 /// the position of the argument.
4988 static void
4989 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4990                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4991                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4992   int Offset = ArgOffset + SPDiff;
4993   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4994   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4995   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4996   SDValue FIN = DAG.getFrameIndex(FI, VT);
4997   TailCallArgumentInfo Info;
4998   Info.Arg = Arg;
4999   Info.FrameIdxOp = FIN;
5000   Info.FrameIdx = FI;
5001   TailCallArguments.push_back(Info);
5002 }
5003 
5004 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5005 /// stack slot. Returns the chain as result and the loaded frame pointers in
5006 /// LROpOut/FPOpout. Used when tail calling.
5007 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5008     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5009     SDValue &FPOpOut, const SDLoc &dl) const {
5010   if (SPDiff) {
5011     // Load the LR and FP stack slot for later adjusting.
5012     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5013     LROpOut = getReturnAddrFrameIndex(DAG);
5014     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5015     Chain = SDValue(LROpOut.getNode(), 1);
5016   }
5017   return Chain;
5018 }
5019 
5020 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5021 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5022 /// specified by the specific parameter attribute. The copy will be passed as
5023 /// a byval function parameter.
5024 /// Sometimes what we are copying is the end of a larger object, the part that
5025 /// does not fit in registers.
5026 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5027                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5028                                          SelectionDAG &DAG, const SDLoc &dl) {
5029   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5030   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5031                        Flags.getNonZeroByValAlign(), false, false, false,
5032                        MachinePointerInfo(), MachinePointerInfo());
5033 }
5034 
5035 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5036 /// tail calls.
5037 static void LowerMemOpCallTo(
5038     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5039     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5040     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5041     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5042   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5043   if (!isTailCall) {
5044     if (isVector) {
5045       SDValue StackPtr;
5046       if (isPPC64)
5047         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5048       else
5049         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5050       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5051                            DAG.getConstant(ArgOffset, dl, PtrVT));
5052     }
5053     MemOpChains.push_back(
5054         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5055     // Calculate and remember argument location.
5056   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5057                                   TailCallArguments);
5058 }
5059 
5060 static void
5061 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5062                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5063                 SDValue FPOp,
5064                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5065   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5066   // might overwrite each other in case of tail call optimization.
5067   SmallVector<SDValue, 8> MemOpChains2;
5068   // Do not flag preceding copytoreg stuff together with the following stuff.
5069   InFlag = SDValue();
5070   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5071                                     MemOpChains2, dl);
5072   if (!MemOpChains2.empty())
5073     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5074 
5075   // Store the return address to the appropriate stack slot.
5076   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5077 
5078   // Emit callseq_end just before tailcall node.
5079   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5080                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5081   InFlag = Chain.getValue(1);
5082 }
5083 
5084 // Is this global address that of a function that can be called by name? (as
5085 // opposed to something that must hold a descriptor for an indirect call).
5086 static bool isFunctionGlobalAddress(SDValue Callee) {
5087   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5088     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5089         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5090       return false;
5091 
5092     return G->getGlobal()->getValueType()->isFunctionTy();
5093   }
5094 
5095   return false;
5096 }
5097 
5098 SDValue PPCTargetLowering::LowerCallResult(
5099     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5100     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5101     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5102   SmallVector<CCValAssign, 16> RVLocs;
5103   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5104                     *DAG.getContext());
5105 
5106   CCRetInfo.AnalyzeCallResult(
5107       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5108                ? RetCC_PPC_Cold
5109                : RetCC_PPC);
5110 
5111   // Copy all of the result registers out of their specified physreg.
5112   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5113     CCValAssign &VA = RVLocs[i];
5114     assert(VA.isRegLoc() && "Can only return in registers!");
5115 
5116     SDValue Val;
5117 
5118     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5119       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5120                                       InFlag);
5121       Chain = Lo.getValue(1);
5122       InFlag = Lo.getValue(2);
5123       VA = RVLocs[++i]; // skip ahead to next loc
5124       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5125                                       InFlag);
5126       Chain = Hi.getValue(1);
5127       InFlag = Hi.getValue(2);
5128       if (!Subtarget.isLittleEndian())
5129         std::swap (Lo, Hi);
5130       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5131     } else {
5132       Val = DAG.getCopyFromReg(Chain, dl,
5133                                VA.getLocReg(), VA.getLocVT(), InFlag);
5134       Chain = Val.getValue(1);
5135       InFlag = Val.getValue(2);
5136     }
5137 
5138     switch (VA.getLocInfo()) {
5139     default: llvm_unreachable("Unknown loc info!");
5140     case CCValAssign::Full: break;
5141     case CCValAssign::AExt:
5142       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5143       break;
5144     case CCValAssign::ZExt:
5145       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5146                         DAG.getValueType(VA.getValVT()));
5147       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5148       break;
5149     case CCValAssign::SExt:
5150       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5151                         DAG.getValueType(VA.getValVT()));
5152       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5153       break;
5154     }
5155 
5156     InVals.push_back(Val);
5157   }
5158 
5159   return Chain;
5160 }
5161 
5162 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5163                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5164   // PatchPoint calls are not indirect.
5165   if (isPatchPoint)
5166     return false;
5167 
5168   if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee))
5169     return false;
5170 
5171   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5172   // becuase the immediate function pointer points to a descriptor instead of
5173   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5174   // pointer immediate points to the global entry point, while the BLA would
5175   // need to jump to the local entry point (see rL211174).
5176   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5177       isBLACompatibleAddress(Callee, DAG))
5178     return false;
5179 
5180   return true;
5181 }
5182 
5183 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5184 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5185   return Subtarget.isAIXABI() ||
5186          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5187 }
5188 
5189 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5190                               const Function &Caller, const SDValue &Callee,
5191                               const PPCSubtarget &Subtarget,
5192                               const TargetMachine &TM,
5193                               bool IsStrictFPCall = false) {
5194   if (CFlags.IsTailCall)
5195     return PPCISD::TC_RETURN;
5196 
5197   unsigned RetOpc = 0;
5198   // This is a call through a function pointer.
5199   if (CFlags.IsIndirect) {
5200     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5201     // indirect calls. The save of the caller's TOC pointer to the stack will be
5202     // inserted into the DAG as part of call lowering. The restore of the TOC
5203     // pointer is modeled by using a pseudo instruction for the call opcode that
5204     // represents the 2 instruction sequence of an indirect branch and link,
5205     // immediately followed by a load of the TOC pointer from the the stack save
5206     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5207     // as it is not saved or used.
5208     RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5209                                                  : PPCISD::BCTRL;
5210   } else if (Subtarget.isUsingPCRelativeCalls()) {
5211     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5212     RetOpc = PPCISD::CALL_NOTOC;
5213   } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5214     // The ABIs that maintain a TOC pointer accross calls need to have a nop
5215     // immediately following the call instruction if the caller and callee may
5216     // have different TOC bases. At link time if the linker determines the calls
5217     // may not share a TOC base, the call is redirected to a trampoline inserted
5218     // by the linker. The trampoline will (among other things) save the callers
5219     // TOC pointer at an ABI designated offset in the linkage area and the
5220     // linker will rewrite the nop to be a load of the TOC pointer from the
5221     // linkage area into gpr2.
5222     RetOpc = callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5223                                                     : PPCISD::CALL_NOP;
5224   else
5225     RetOpc = PPCISD::CALL;
5226   if (IsStrictFPCall) {
5227     switch (RetOpc) {
5228     default:
5229       llvm_unreachable("Unknown call opcode");
5230     case PPCISD::BCTRL_LOAD_TOC:
5231       RetOpc = PPCISD::BCTRL_LOAD_TOC_RM;
5232       break;
5233     case PPCISD::BCTRL:
5234       RetOpc = PPCISD::BCTRL_RM;
5235       break;
5236     case PPCISD::CALL_NOTOC:
5237       RetOpc = PPCISD::CALL_NOTOC_RM;
5238       break;
5239     case PPCISD::CALL:
5240       RetOpc = PPCISD::CALL_RM;
5241       break;
5242     case PPCISD::CALL_NOP:
5243       RetOpc = PPCISD::CALL_NOP_RM;
5244       break;
5245     }
5246   }
5247   return RetOpc;
5248 }
5249 
5250 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5251                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5252   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5253     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5254       return SDValue(Dest, 0);
5255 
5256   // Returns true if the callee is local, and false otherwise.
5257   auto isLocalCallee = [&]() {
5258     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5259     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5260     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5261 
5262     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5263            !isa_and_nonnull<GlobalIFunc>(GV);
5264   };
5265 
5266   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5267   // a static relocation model causes some versions of GNU LD (2.17.50, at
5268   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5269   // built with secure-PLT.
5270   bool UsePlt =
5271       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5272       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5273 
5274   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5275     const TargetMachine &TM = Subtarget.getTargetMachine();
5276     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5277     MCSymbolXCOFF *S =
5278         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5279 
5280     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5281     return DAG.getMCSymbol(S, PtrVT);
5282   };
5283 
5284   if (isFunctionGlobalAddress(Callee)) {
5285     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5286 
5287     if (Subtarget.isAIXABI()) {
5288       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5289       return getAIXFuncEntryPointSymbolSDNode(GV);
5290     }
5291     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5292                                       UsePlt ? PPCII::MO_PLT : 0);
5293   }
5294 
5295   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5296     const char *SymName = S->getSymbol();
5297     if (Subtarget.isAIXABI()) {
5298       // If there exists a user-declared function whose name is the same as the
5299       // ExternalSymbol's, then we pick up the user-declared version.
5300       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5301       if (const Function *F =
5302               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5303         return getAIXFuncEntryPointSymbolSDNode(F);
5304 
5305       // On AIX, direct function calls reference the symbol for the function's
5306       // entry point, which is named by prepending a "." before the function's
5307       // C-linkage name. A Qualname is returned here because an external
5308       // function entry point is a csect with XTY_ER property.
5309       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5310         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5311         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5312             (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5313             XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER));
5314         return Sec->getQualNameSymbol();
5315       };
5316 
5317       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5318     }
5319     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5320                                        UsePlt ? PPCII::MO_PLT : 0);
5321   }
5322 
5323   // No transformation needed.
5324   assert(Callee.getNode() && "What no callee?");
5325   return Callee;
5326 }
5327 
5328 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5329   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5330          "Expected a CALLSEQ_STARTSDNode.");
5331 
5332   // The last operand is the chain, except when the node has glue. If the node
5333   // has glue, then the last operand is the glue, and the chain is the second
5334   // last operand.
5335   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5336   if (LastValue.getValueType() != MVT::Glue)
5337     return LastValue;
5338 
5339   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5340 }
5341 
5342 // Creates the node that moves a functions address into the count register
5343 // to prepare for an indirect call instruction.
5344 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5345                                 SDValue &Glue, SDValue &Chain,
5346                                 const SDLoc &dl) {
5347   SDValue MTCTROps[] = {Chain, Callee, Glue};
5348   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5349   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5350                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5351   // The glue is the second value produced.
5352   Glue = Chain.getValue(1);
5353 }
5354 
5355 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5356                                           SDValue &Glue, SDValue &Chain,
5357                                           SDValue CallSeqStart,
5358                                           const CallBase *CB, const SDLoc &dl,
5359                                           bool hasNest,
5360                                           const PPCSubtarget &Subtarget) {
5361   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5362   // entry point, but to the function descriptor (the function entry point
5363   // address is part of the function descriptor though).
5364   // The function descriptor is a three doubleword structure with the
5365   // following fields: function entry point, TOC base address and
5366   // environment pointer.
5367   // Thus for a call through a function pointer, the following actions need
5368   // to be performed:
5369   //   1. Save the TOC of the caller in the TOC save area of its stack
5370   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5371   //   2. Load the address of the function entry point from the function
5372   //      descriptor.
5373   //   3. Load the TOC of the callee from the function descriptor into r2.
5374   //   4. Load the environment pointer from the function descriptor into
5375   //      r11.
5376   //   5. Branch to the function entry point address.
5377   //   6. On return of the callee, the TOC of the caller needs to be
5378   //      restored (this is done in FinishCall()).
5379   //
5380   // The loads are scheduled at the beginning of the call sequence, and the
5381   // register copies are flagged together to ensure that no other
5382   // operations can be scheduled in between. E.g. without flagging the
5383   // copies together, a TOC access in the caller could be scheduled between
5384   // the assignment of the callee TOC and the branch to the callee, which leads
5385   // to incorrect code.
5386 
5387   // Start by loading the function address from the descriptor.
5388   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5389   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5390                       ? (MachineMemOperand::MODereferenceable |
5391                          MachineMemOperand::MOInvariant)
5392                       : MachineMemOperand::MONone;
5393 
5394   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5395 
5396   // Registers used in building the DAG.
5397   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5398   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5399 
5400   // Offsets of descriptor members.
5401   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5402   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5403 
5404   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5405   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5406 
5407   // One load for the functions entry point address.
5408   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5409                                     Alignment, MMOFlags);
5410 
5411   // One for loading the TOC anchor for the module that contains the called
5412   // function.
5413   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5414   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5415   SDValue TOCPtr =
5416       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5417                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5418 
5419   // One for loading the environment pointer.
5420   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5421   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5422   SDValue LoadEnvPtr =
5423       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5424                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5425 
5426 
5427   // Then copy the newly loaded TOC anchor to the TOC pointer.
5428   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5429   Chain = TOCVal.getValue(0);
5430   Glue = TOCVal.getValue(1);
5431 
5432   // If the function call has an explicit 'nest' parameter, it takes the
5433   // place of the environment pointer.
5434   assert((!hasNest || !Subtarget.isAIXABI()) &&
5435          "Nest parameter is not supported on AIX.");
5436   if (!hasNest) {
5437     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5438     Chain = EnvVal.getValue(0);
5439     Glue = EnvVal.getValue(1);
5440   }
5441 
5442   // The rest of the indirect call sequence is the same as the non-descriptor
5443   // DAG.
5444   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5445 }
5446 
5447 static void
5448 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5449                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5450                   SelectionDAG &DAG,
5451                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5452                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5453                   const PPCSubtarget &Subtarget) {
5454   const bool IsPPC64 = Subtarget.isPPC64();
5455   // MVT for a general purpose register.
5456   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5457 
5458   // First operand is always the chain.
5459   Ops.push_back(Chain);
5460 
5461   // If it's a direct call pass the callee as the second operand.
5462   if (!CFlags.IsIndirect)
5463     Ops.push_back(Callee);
5464   else {
5465     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5466 
5467     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5468     // on the stack (this would have been done in `LowerCall_64SVR4` or
5469     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5470     // represents both the indirect branch and a load that restores the TOC
5471     // pointer from the linkage area. The operand for the TOC restore is an add
5472     // of the TOC save offset to the stack pointer. This must be the second
5473     // operand: after the chain input but before any other variadic arguments.
5474     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5475     // saved or used.
5476     if (isTOCSaveRestoreRequired(Subtarget)) {
5477       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5478 
5479       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5480       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5481       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5482       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5483       Ops.push_back(AddTOC);
5484     }
5485 
5486     // Add the register used for the environment pointer.
5487     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5488       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5489                                     RegVT));
5490 
5491 
5492     // Add CTR register as callee so a bctr can be emitted later.
5493     if (CFlags.IsTailCall)
5494       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5495   }
5496 
5497   // If this is a tail call add stack pointer delta.
5498   if (CFlags.IsTailCall)
5499     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5500 
5501   // Add argument registers to the end of the list so that they are known live
5502   // into the call.
5503   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5504     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5505                                   RegsToPass[i].second.getValueType()));
5506 
5507   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5508   // no way to mark dependencies as implicit here.
5509   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5510   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5511        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5512     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5513 
5514   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5515   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5516     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5517 
5518   // Add a register mask operand representing the call-preserved registers.
5519   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5520   const uint32_t *Mask =
5521       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5522   assert(Mask && "Missing call preserved mask for calling convention");
5523   Ops.push_back(DAG.getRegisterMask(Mask));
5524 
5525   // If the glue is valid, it is the last operand.
5526   if (Glue.getNode())
5527     Ops.push_back(Glue);
5528 }
5529 
5530 SDValue PPCTargetLowering::FinishCall(
5531     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5532     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5533     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5534     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5535     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5536 
5537   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5538       Subtarget.isAIXABI())
5539     setUsesTOCBasePtr(DAG);
5540 
5541   unsigned CallOpc =
5542       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5543                     Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false);
5544 
5545   if (!CFlags.IsIndirect)
5546     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5547   else if (Subtarget.usesFunctionDescriptors())
5548     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5549                                   dl, CFlags.HasNest, Subtarget);
5550   else
5551     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5552 
5553   // Build the operand list for the call instruction.
5554   SmallVector<SDValue, 8> Ops;
5555   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5556                     SPDiff, Subtarget);
5557 
5558   // Emit tail call.
5559   if (CFlags.IsTailCall) {
5560     // Indirect tail call when using PC Relative calls do not have the same
5561     // constraints.
5562     assert(((Callee.getOpcode() == ISD::Register &&
5563              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5564             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5565             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5566             isa<ConstantSDNode>(Callee) ||
5567             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5568            "Expecting a global address, external symbol, absolute value, "
5569            "register or an indirect tail call when PC Relative calls are "
5570            "used.");
5571     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5572     assert(CallOpc == PPCISD::TC_RETURN &&
5573            "Unexpected call opcode for a tail call.");
5574     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5575     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5576   }
5577 
5578   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5579   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5580   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5581   Glue = Chain.getValue(1);
5582 
5583   // When performing tail call optimization the callee pops its arguments off
5584   // the stack. Account for this here so these bytes can be pushed back on in
5585   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5586   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5587                          getTargetMachine().Options.GuaranteedTailCallOpt)
5588                             ? NumBytes
5589                             : 0;
5590 
5591   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5592                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5593                              Glue, dl);
5594   Glue = Chain.getValue(1);
5595 
5596   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5597                          DAG, InVals);
5598 }
5599 
5600 SDValue
5601 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5602                              SmallVectorImpl<SDValue> &InVals) const {
5603   SelectionDAG &DAG                     = CLI.DAG;
5604   SDLoc &dl                             = CLI.DL;
5605   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5606   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5607   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5608   SDValue Chain                         = CLI.Chain;
5609   SDValue Callee                        = CLI.Callee;
5610   bool &isTailCall                      = CLI.IsTailCall;
5611   CallingConv::ID CallConv              = CLI.CallConv;
5612   bool isVarArg                         = CLI.IsVarArg;
5613   bool isPatchPoint                     = CLI.IsPatchPoint;
5614   const CallBase *CB                    = CLI.CB;
5615 
5616   if (isTailCall) {
5617     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5618       isTailCall = false;
5619     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5620       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5621           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5622     else
5623       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5624                                                      Ins, DAG);
5625     if (isTailCall) {
5626       ++NumTailCalls;
5627       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5628         ++NumSiblingCalls;
5629 
5630       // PC Relative calls no longer guarantee that the callee is a Global
5631       // Address Node. The callee could be an indirect tail call in which
5632       // case the SDValue for the callee could be a load (to load the address
5633       // of a function pointer) or it may be a register copy (to move the
5634       // address of the callee from a function parameter into a virtual
5635       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5636       assert((Subtarget.isUsingPCRelativeCalls() ||
5637               isa<GlobalAddressSDNode>(Callee)) &&
5638              "Callee should be an llvm::Function object.");
5639 
5640       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5641                         << "\nTCO callee: ");
5642       LLVM_DEBUG(Callee.dump());
5643     }
5644   }
5645 
5646   if (!isTailCall && CB && CB->isMustTailCall())
5647     report_fatal_error("failed to perform tail call elimination on a call "
5648                        "site marked musttail");
5649 
5650   // When long calls (i.e. indirect calls) are always used, calls are always
5651   // made via function pointer. If we have a function name, first translate it
5652   // into a pointer.
5653   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5654       !isTailCall)
5655     Callee = LowerGlobalAddress(Callee, DAG);
5656 
5657   CallFlags CFlags(
5658       CallConv, isTailCall, isVarArg, isPatchPoint,
5659       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5660       // hasNest
5661       Subtarget.is64BitELFABI() &&
5662           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5663       CLI.NoMerge);
5664 
5665   if (Subtarget.isAIXABI())
5666     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5667                          InVals, CB);
5668 
5669   assert(Subtarget.isSVR4ABI());
5670   if (Subtarget.isPPC64())
5671     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5672                             InVals, CB);
5673   return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5674                           InVals, CB);
5675 }
5676 
5677 SDValue PPCTargetLowering::LowerCall_32SVR4(
5678     SDValue Chain, SDValue Callee, CallFlags CFlags,
5679     const SmallVectorImpl<ISD::OutputArg> &Outs,
5680     const SmallVectorImpl<SDValue> &OutVals,
5681     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5682     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5683     const CallBase *CB) const {
5684   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5685   // of the 32-bit SVR4 ABI stack frame layout.
5686 
5687   const CallingConv::ID CallConv = CFlags.CallConv;
5688   const bool IsVarArg = CFlags.IsVarArg;
5689   const bool IsTailCall = CFlags.IsTailCall;
5690 
5691   assert((CallConv == CallingConv::C ||
5692           CallConv == CallingConv::Cold ||
5693           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5694 
5695   const Align PtrAlign(4);
5696 
5697   MachineFunction &MF = DAG.getMachineFunction();
5698 
5699   // Mark this function as potentially containing a function that contains a
5700   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5701   // and restoring the callers stack pointer in this functions epilog. This is
5702   // done because by tail calling the called function might overwrite the value
5703   // in this function's (MF) stack pointer stack slot 0(SP).
5704   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5705       CallConv == CallingConv::Fast)
5706     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5707 
5708   // Count how many bytes are to be pushed on the stack, including the linkage
5709   // area, parameter list area and the part of the local variable space which
5710   // contains copies of aggregates which are passed by value.
5711 
5712   // Assign locations to all of the outgoing arguments.
5713   SmallVector<CCValAssign, 16> ArgLocs;
5714   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5715 
5716   // Reserve space for the linkage area on the stack.
5717   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5718                        PtrAlign);
5719   if (useSoftFloat())
5720     CCInfo.PreAnalyzeCallOperands(Outs);
5721 
5722   if (IsVarArg) {
5723     // Handle fixed and variable vector arguments differently.
5724     // Fixed vector arguments go into registers as long as registers are
5725     // available. Variable vector arguments always go into memory.
5726     unsigned NumArgs = Outs.size();
5727 
5728     for (unsigned i = 0; i != NumArgs; ++i) {
5729       MVT ArgVT = Outs[i].VT;
5730       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5731       bool Result;
5732 
5733       if (Outs[i].IsFixed) {
5734         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5735                                CCInfo);
5736       } else {
5737         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5738                                       ArgFlags, CCInfo);
5739       }
5740 
5741       if (Result) {
5742 #ifndef NDEBUG
5743         errs() << "Call operand #" << i << " has unhandled type "
5744              << EVT(ArgVT).getEVTString() << "\n";
5745 #endif
5746         llvm_unreachable(nullptr);
5747       }
5748     }
5749   } else {
5750     // All arguments are treated the same.
5751     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5752   }
5753   CCInfo.clearWasPPCF128();
5754 
5755   // Assign locations to all of the outgoing aggregate by value arguments.
5756   SmallVector<CCValAssign, 16> ByValArgLocs;
5757   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5758 
5759   // Reserve stack space for the allocations in CCInfo.
5760   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5761 
5762   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5763 
5764   // Size of the linkage area, parameter list area and the part of the local
5765   // space variable where copies of aggregates which are passed by value are
5766   // stored.
5767   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5768 
5769   // Calculate by how many bytes the stack has to be adjusted in case of tail
5770   // call optimization.
5771   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5772 
5773   // Adjust the stack pointer for the new arguments...
5774   // These operations are automatically eliminated by the prolog/epilog pass
5775   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5776   SDValue CallSeqStart = Chain;
5777 
5778   // Load the return address and frame pointer so it can be moved somewhere else
5779   // later.
5780   SDValue LROp, FPOp;
5781   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5782 
5783   // Set up a copy of the stack pointer for use loading and storing any
5784   // arguments that may not fit in the registers available for argument
5785   // passing.
5786   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5787 
5788   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5789   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5790   SmallVector<SDValue, 8> MemOpChains;
5791 
5792   bool seenFloatArg = false;
5793   // Walk the register/memloc assignments, inserting copies/loads.
5794   // i - Tracks the index into the list of registers allocated for the call
5795   // RealArgIdx - Tracks the index into the list of actual function arguments
5796   // j - Tracks the index into the list of byval arguments
5797   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5798        i != e;
5799        ++i, ++RealArgIdx) {
5800     CCValAssign &VA = ArgLocs[i];
5801     SDValue Arg = OutVals[RealArgIdx];
5802     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5803 
5804     if (Flags.isByVal()) {
5805       // Argument is an aggregate which is passed by value, thus we need to
5806       // create a copy of it in the local variable space of the current stack
5807       // frame (which is the stack frame of the caller) and pass the address of
5808       // this copy to the callee.
5809       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5810       CCValAssign &ByValVA = ByValArgLocs[j++];
5811       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5812 
5813       // Memory reserved in the local variable space of the callers stack frame.
5814       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5815 
5816       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5817       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5818                            StackPtr, PtrOff);
5819 
5820       // Create a copy of the argument in the local area of the current
5821       // stack frame.
5822       SDValue MemcpyCall =
5823         CreateCopyOfByValArgument(Arg, PtrOff,
5824                                   CallSeqStart.getNode()->getOperand(0),
5825                                   Flags, DAG, dl);
5826 
5827       // This must go outside the CALLSEQ_START..END.
5828       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5829                                                      SDLoc(MemcpyCall));
5830       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5831                              NewCallSeqStart.getNode());
5832       Chain = CallSeqStart = NewCallSeqStart;
5833 
5834       // Pass the address of the aggregate copy on the stack either in a
5835       // physical register or in the parameter list area of the current stack
5836       // frame to the callee.
5837       Arg = PtrOff;
5838     }
5839 
5840     // When useCRBits() is true, there can be i1 arguments.
5841     // It is because getRegisterType(MVT::i1) => MVT::i1,
5842     // and for other integer types getRegisterType() => MVT::i32.
5843     // Extend i1 and ensure callee will get i32.
5844     if (Arg.getValueType() == MVT::i1)
5845       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5846                         dl, MVT::i32, Arg);
5847 
5848     if (VA.isRegLoc()) {
5849       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5850       // Put argument in a physical register.
5851       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5852         bool IsLE = Subtarget.isLittleEndian();
5853         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5854                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5855         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5856         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5857                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5858         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5859                              SVal.getValue(0)));
5860       } else
5861         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5862     } else {
5863       // Put argument in the parameter list area of the current stack frame.
5864       assert(VA.isMemLoc());
5865       unsigned LocMemOffset = VA.getLocMemOffset();
5866 
5867       if (!IsTailCall) {
5868         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5869         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5870                              StackPtr, PtrOff);
5871 
5872         MemOpChains.push_back(
5873             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5874       } else {
5875         // Calculate and remember argument location.
5876         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5877                                  TailCallArguments);
5878       }
5879     }
5880   }
5881 
5882   if (!MemOpChains.empty())
5883     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5884 
5885   // Build a sequence of copy-to-reg nodes chained together with token chain
5886   // and flag operands which copy the outgoing args into the appropriate regs.
5887   SDValue InFlag;
5888   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5889     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5890                              RegsToPass[i].second, InFlag);
5891     InFlag = Chain.getValue(1);
5892   }
5893 
5894   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5895   // registers.
5896   if (IsVarArg) {
5897     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5898     SDValue Ops[] = { Chain, InFlag };
5899 
5900     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5901                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5902 
5903     InFlag = Chain.getValue(1);
5904   }
5905 
5906   if (IsTailCall)
5907     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5908                     TailCallArguments);
5909 
5910   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5911                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5912 }
5913 
5914 // Copy an argument into memory, being careful to do this outside the
5915 // call sequence for the call to which the argument belongs.
5916 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5917     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5918     SelectionDAG &DAG, const SDLoc &dl) const {
5919   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5920                         CallSeqStart.getNode()->getOperand(0),
5921                         Flags, DAG, dl);
5922   // The MEMCPY must go outside the CALLSEQ_START..END.
5923   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5924   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5925                                                  SDLoc(MemcpyCall));
5926   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5927                          NewCallSeqStart.getNode());
5928   return NewCallSeqStart;
5929 }
5930 
5931 SDValue PPCTargetLowering::LowerCall_64SVR4(
5932     SDValue Chain, SDValue Callee, CallFlags CFlags,
5933     const SmallVectorImpl<ISD::OutputArg> &Outs,
5934     const SmallVectorImpl<SDValue> &OutVals,
5935     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5936     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5937     const CallBase *CB) const {
5938   bool isELFv2ABI = Subtarget.isELFv2ABI();
5939   bool isLittleEndian = Subtarget.isLittleEndian();
5940   unsigned NumOps = Outs.size();
5941   bool IsSibCall = false;
5942   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5943 
5944   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5945   unsigned PtrByteSize = 8;
5946 
5947   MachineFunction &MF = DAG.getMachineFunction();
5948 
5949   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5950     IsSibCall = true;
5951 
5952   // Mark this function as potentially containing a function that contains a
5953   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5954   // and restoring the callers stack pointer in this functions epilog. This is
5955   // done because by tail calling the called function might overwrite the value
5956   // in this function's (MF) stack pointer stack slot 0(SP).
5957   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5958     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5959 
5960   assert(!(IsFastCall && CFlags.IsVarArg) &&
5961          "fastcc not supported on varargs functions");
5962 
5963   // Count how many bytes are to be pushed on the stack, including the linkage
5964   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5965   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5966   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5967   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5968   unsigned NumBytes = LinkageSize;
5969   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5970 
5971   static const MCPhysReg GPR[] = {
5972     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5973     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5974   };
5975   static const MCPhysReg VR[] = {
5976     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5977     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5978   };
5979 
5980   const unsigned NumGPRs = array_lengthof(GPR);
5981   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5982   const unsigned NumVRs  = array_lengthof(VR);
5983 
5984   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5985   // can be passed to the callee in registers.
5986   // For the fast calling convention, there is another check below.
5987   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5988   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5989   if (!HasParameterArea) {
5990     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5991     unsigned AvailableFPRs = NumFPRs;
5992     unsigned AvailableVRs = NumVRs;
5993     unsigned NumBytesTmp = NumBytes;
5994     for (unsigned i = 0; i != NumOps; ++i) {
5995       if (Outs[i].Flags.isNest()) continue;
5996       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5997                                  PtrByteSize, LinkageSize, ParamAreaSize,
5998                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
5999         HasParameterArea = true;
6000     }
6001   }
6002 
6003   // When using the fast calling convention, we don't provide backing for
6004   // arguments that will be in registers.
6005   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6006 
6007   // Avoid allocating parameter area for fastcc functions if all the arguments
6008   // can be passed in the registers.
6009   if (IsFastCall)
6010     HasParameterArea = false;
6011 
6012   // Add up all the space actually used.
6013   for (unsigned i = 0; i != NumOps; ++i) {
6014     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6015     EVT ArgVT = Outs[i].VT;
6016     EVT OrigVT = Outs[i].ArgVT;
6017 
6018     if (Flags.isNest())
6019       continue;
6020 
6021     if (IsFastCall) {
6022       if (Flags.isByVal()) {
6023         NumGPRsUsed += (Flags.getByValSize()+7)/8;
6024         if (NumGPRsUsed > NumGPRs)
6025           HasParameterArea = true;
6026       } else {
6027         switch (ArgVT.getSimpleVT().SimpleTy) {
6028         default: llvm_unreachable("Unexpected ValueType for argument!");
6029         case MVT::i1:
6030         case MVT::i32:
6031         case MVT::i64:
6032           if (++NumGPRsUsed <= NumGPRs)
6033             continue;
6034           break;
6035         case MVT::v4i32:
6036         case MVT::v8i16:
6037         case MVT::v16i8:
6038         case MVT::v2f64:
6039         case MVT::v2i64:
6040         case MVT::v1i128:
6041         case MVT::f128:
6042           if (++NumVRsUsed <= NumVRs)
6043             continue;
6044           break;
6045         case MVT::v4f32:
6046           if (++NumVRsUsed <= NumVRs)
6047             continue;
6048           break;
6049         case MVT::f32:
6050         case MVT::f64:
6051           if (++NumFPRsUsed <= NumFPRs)
6052             continue;
6053           break;
6054         }
6055         HasParameterArea = true;
6056       }
6057     }
6058 
6059     /* Respect alignment of argument on the stack.  */
6060     auto Alignement =
6061         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6062     NumBytes = alignTo(NumBytes, Alignement);
6063 
6064     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6065     if (Flags.isInConsecutiveRegsLast())
6066       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6067   }
6068 
6069   unsigned NumBytesActuallyUsed = NumBytes;
6070 
6071   // In the old ELFv1 ABI,
6072   // the prolog code of the callee may store up to 8 GPR argument registers to
6073   // the stack, allowing va_start to index over them in memory if its varargs.
6074   // Because we cannot tell if this is needed on the caller side, we have to
6075   // conservatively assume that it is needed.  As such, make sure we have at
6076   // least enough stack space for the caller to store the 8 GPRs.
6077   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6078   // really requires memory operands, e.g. a vararg function.
6079   if (HasParameterArea)
6080     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6081   else
6082     NumBytes = LinkageSize;
6083 
6084   // Tail call needs the stack to be aligned.
6085   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6086     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6087 
6088   int SPDiff = 0;
6089 
6090   // Calculate by how many bytes the stack has to be adjusted in case of tail
6091   // call optimization.
6092   if (!IsSibCall)
6093     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6094 
6095   // To protect arguments on the stack from being clobbered in a tail call,
6096   // force all the loads to happen before doing any other lowering.
6097   if (CFlags.IsTailCall)
6098     Chain = DAG.getStackArgumentTokenFactor(Chain);
6099 
6100   // Adjust the stack pointer for the new arguments...
6101   // These operations are automatically eliminated by the prolog/epilog pass
6102   if (!IsSibCall)
6103     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6104   SDValue CallSeqStart = Chain;
6105 
6106   // Load the return address and frame pointer so it can be move somewhere else
6107   // later.
6108   SDValue LROp, FPOp;
6109   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6110 
6111   // Set up a copy of the stack pointer for use loading and storing any
6112   // arguments that may not fit in the registers available for argument
6113   // passing.
6114   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6115 
6116   // Figure out which arguments are going to go in registers, and which in
6117   // memory.  Also, if this is a vararg function, floating point operations
6118   // must be stored to our stack, and loaded into integer regs as well, if
6119   // any integer regs are available for argument passing.
6120   unsigned ArgOffset = LinkageSize;
6121 
6122   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6123   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6124 
6125   SmallVector<SDValue, 8> MemOpChains;
6126   for (unsigned i = 0; i != NumOps; ++i) {
6127     SDValue Arg = OutVals[i];
6128     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6129     EVT ArgVT = Outs[i].VT;
6130     EVT OrigVT = Outs[i].ArgVT;
6131 
6132     // PtrOff will be used to store the current argument to the stack if a
6133     // register cannot be found for it.
6134     SDValue PtrOff;
6135 
6136     // We re-align the argument offset for each argument, except when using the
6137     // fast calling convention, when we need to make sure we do that only when
6138     // we'll actually use a stack slot.
6139     auto ComputePtrOff = [&]() {
6140       /* Respect alignment of argument on the stack.  */
6141       auto Alignment =
6142           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6143       ArgOffset = alignTo(ArgOffset, Alignment);
6144 
6145       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6146 
6147       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6148     };
6149 
6150     if (!IsFastCall) {
6151       ComputePtrOff();
6152 
6153       /* Compute GPR index associated with argument offset.  */
6154       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6155       GPR_idx = std::min(GPR_idx, NumGPRs);
6156     }
6157 
6158     // Promote integers to 64-bit values.
6159     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6160       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6161       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6162       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6163     }
6164 
6165     // FIXME memcpy is used way more than necessary.  Correctness first.
6166     // Note: "by value" is code for passing a structure by value, not
6167     // basic types.
6168     if (Flags.isByVal()) {
6169       // Note: Size includes alignment padding, so
6170       //   struct x { short a; char b; }
6171       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6172       // These are the proper values we need for right-justifying the
6173       // aggregate in a parameter register.
6174       unsigned Size = Flags.getByValSize();
6175 
6176       // An empty aggregate parameter takes up no storage and no
6177       // registers.
6178       if (Size == 0)
6179         continue;
6180 
6181       if (IsFastCall)
6182         ComputePtrOff();
6183 
6184       // All aggregates smaller than 8 bytes must be passed right-justified.
6185       if (Size==1 || Size==2 || Size==4) {
6186         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6187         if (GPR_idx != NumGPRs) {
6188           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6189                                         MachinePointerInfo(), VT);
6190           MemOpChains.push_back(Load.getValue(1));
6191           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6192 
6193           ArgOffset += PtrByteSize;
6194           continue;
6195         }
6196       }
6197 
6198       if (GPR_idx == NumGPRs && Size < 8) {
6199         SDValue AddPtr = PtrOff;
6200         if (!isLittleEndian) {
6201           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6202                                           PtrOff.getValueType());
6203           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6204         }
6205         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6206                                                           CallSeqStart,
6207                                                           Flags, DAG, dl);
6208         ArgOffset += PtrByteSize;
6209         continue;
6210       }
6211       // Copy the object to parameter save area if it can not be entirely passed
6212       // by registers.
6213       // FIXME: we only need to copy the parts which need to be passed in
6214       // parameter save area. For the parts passed by registers, we don't need
6215       // to copy them to the stack although we need to allocate space for them
6216       // in parameter save area.
6217       if ((NumGPRs - GPR_idx) * PtrByteSize < Size)
6218         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6219                                                           CallSeqStart,
6220                                                           Flags, DAG, dl);
6221 
6222       // When a register is available, pass a small aggregate right-justified.
6223       if (Size < 8 && GPR_idx != NumGPRs) {
6224         // The easiest way to get this right-justified in a register
6225         // is to copy the structure into the rightmost portion of a
6226         // local variable slot, then load the whole slot into the
6227         // register.
6228         // FIXME: The memcpy seems to produce pretty awful code for
6229         // small aggregates, particularly for packed ones.
6230         // FIXME: It would be preferable to use the slot in the
6231         // parameter save area instead of a new local variable.
6232         SDValue AddPtr = PtrOff;
6233         if (!isLittleEndian) {
6234           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6235           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6236         }
6237         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6238                                                           CallSeqStart,
6239                                                           Flags, DAG, dl);
6240 
6241         // Load the slot into the register.
6242         SDValue Load =
6243             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6244         MemOpChains.push_back(Load.getValue(1));
6245         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6246 
6247         // Done with this argument.
6248         ArgOffset += PtrByteSize;
6249         continue;
6250       }
6251 
6252       // For aggregates larger than PtrByteSize, copy the pieces of the
6253       // object that fit into registers from the parameter save area.
6254       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6255         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6256         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6257         if (GPR_idx != NumGPRs) {
6258           SDValue Load =
6259               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6260           MemOpChains.push_back(Load.getValue(1));
6261           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6262           ArgOffset += PtrByteSize;
6263         } else {
6264           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6265           break;
6266         }
6267       }
6268       continue;
6269     }
6270 
6271     switch (Arg.getSimpleValueType().SimpleTy) {
6272     default: llvm_unreachable("Unexpected ValueType for argument!");
6273     case MVT::i1:
6274     case MVT::i32:
6275     case MVT::i64:
6276       if (Flags.isNest()) {
6277         // The 'nest' parameter, if any, is passed in R11.
6278         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6279         break;
6280       }
6281 
6282       // These can be scalar arguments or elements of an integer array type
6283       // passed directly.  Clang may use those instead of "byval" aggregate
6284       // types to avoid forcing arguments to memory unnecessarily.
6285       if (GPR_idx != NumGPRs) {
6286         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6287       } else {
6288         if (IsFastCall)
6289           ComputePtrOff();
6290 
6291         assert(HasParameterArea &&
6292                "Parameter area must exist to pass an argument in memory.");
6293         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6294                          true, CFlags.IsTailCall, false, MemOpChains,
6295                          TailCallArguments, dl);
6296         if (IsFastCall)
6297           ArgOffset += PtrByteSize;
6298       }
6299       if (!IsFastCall)
6300         ArgOffset += PtrByteSize;
6301       break;
6302     case MVT::f32:
6303     case MVT::f64: {
6304       // These can be scalar arguments or elements of a float array type
6305       // passed directly.  The latter are used to implement ELFv2 homogenous
6306       // float aggregates.
6307 
6308       // Named arguments go into FPRs first, and once they overflow, the
6309       // remaining arguments go into GPRs and then the parameter save area.
6310       // Unnamed arguments for vararg functions always go to GPRs and
6311       // then the parameter save area.  For now, put all arguments to vararg
6312       // routines always in both locations (FPR *and* GPR or stack slot).
6313       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6314       bool NeededLoad = false;
6315 
6316       // First load the argument into the next available FPR.
6317       if (FPR_idx != NumFPRs)
6318         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6319 
6320       // Next, load the argument into GPR or stack slot if needed.
6321       if (!NeedGPROrStack)
6322         ;
6323       else if (GPR_idx != NumGPRs && !IsFastCall) {
6324         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6325         // once we support fp <-> gpr moves.
6326 
6327         // In the non-vararg case, this can only ever happen in the
6328         // presence of f32 array types, since otherwise we never run
6329         // out of FPRs before running out of GPRs.
6330         SDValue ArgVal;
6331 
6332         // Double values are always passed in a single GPR.
6333         if (Arg.getValueType() != MVT::f32) {
6334           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6335 
6336         // Non-array float values are extended and passed in a GPR.
6337         } else if (!Flags.isInConsecutiveRegs()) {
6338           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6339           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6340 
6341         // If we have an array of floats, we collect every odd element
6342         // together with its predecessor into one GPR.
6343         } else if (ArgOffset % PtrByteSize != 0) {
6344           SDValue Lo, Hi;
6345           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6346           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6347           if (!isLittleEndian)
6348             std::swap(Lo, Hi);
6349           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6350 
6351         // The final element, if even, goes into the first half of a GPR.
6352         } else if (Flags.isInConsecutiveRegsLast()) {
6353           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6354           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6355           if (!isLittleEndian)
6356             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6357                                  DAG.getConstant(32, dl, MVT::i32));
6358 
6359         // Non-final even elements are skipped; they will be handled
6360         // together the with subsequent argument on the next go-around.
6361         } else
6362           ArgVal = SDValue();
6363 
6364         if (ArgVal.getNode())
6365           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6366       } else {
6367         if (IsFastCall)
6368           ComputePtrOff();
6369 
6370         // Single-precision floating-point values are mapped to the
6371         // second (rightmost) word of the stack doubleword.
6372         if (Arg.getValueType() == MVT::f32 &&
6373             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6374           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6375           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6376         }
6377 
6378         assert(HasParameterArea &&
6379                "Parameter area must exist to pass an argument in memory.");
6380         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6381                          true, CFlags.IsTailCall, false, MemOpChains,
6382                          TailCallArguments, dl);
6383 
6384         NeededLoad = true;
6385       }
6386       // When passing an array of floats, the array occupies consecutive
6387       // space in the argument area; only round up to the next doubleword
6388       // at the end of the array.  Otherwise, each float takes 8 bytes.
6389       if (!IsFastCall || NeededLoad) {
6390         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6391                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6392         if (Flags.isInConsecutiveRegsLast())
6393           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6394       }
6395       break;
6396     }
6397     case MVT::v4f32:
6398     case MVT::v4i32:
6399     case MVT::v8i16:
6400     case MVT::v16i8:
6401     case MVT::v2f64:
6402     case MVT::v2i64:
6403     case MVT::v1i128:
6404     case MVT::f128:
6405       // These can be scalar arguments or elements of a vector array type
6406       // passed directly.  The latter are used to implement ELFv2 homogenous
6407       // vector aggregates.
6408 
6409       // For a varargs call, named arguments go into VRs or on the stack as
6410       // usual; unnamed arguments always go to the stack or the corresponding
6411       // GPRs when within range.  For now, we always put the value in both
6412       // locations (or even all three).
6413       if (CFlags.IsVarArg) {
6414         assert(HasParameterArea &&
6415                "Parameter area must exist if we have a varargs call.");
6416         // We could elide this store in the case where the object fits
6417         // entirely in R registers.  Maybe later.
6418         SDValue Store =
6419             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6420         MemOpChains.push_back(Store);
6421         if (VR_idx != NumVRs) {
6422           SDValue Load =
6423               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6424           MemOpChains.push_back(Load.getValue(1));
6425           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6426         }
6427         ArgOffset += 16;
6428         for (unsigned i=0; i<16; i+=PtrByteSize) {
6429           if (GPR_idx == NumGPRs)
6430             break;
6431           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6432                                    DAG.getConstant(i, dl, PtrVT));
6433           SDValue Load =
6434               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6435           MemOpChains.push_back(Load.getValue(1));
6436           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6437         }
6438         break;
6439       }
6440 
6441       // Non-varargs Altivec params go into VRs or on the stack.
6442       if (VR_idx != NumVRs) {
6443         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6444       } else {
6445         if (IsFastCall)
6446           ComputePtrOff();
6447 
6448         assert(HasParameterArea &&
6449                "Parameter area must exist to pass an argument in memory.");
6450         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6451                          true, CFlags.IsTailCall, true, MemOpChains,
6452                          TailCallArguments, dl);
6453         if (IsFastCall)
6454           ArgOffset += 16;
6455       }
6456 
6457       if (!IsFastCall)
6458         ArgOffset += 16;
6459       break;
6460     }
6461   }
6462 
6463   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6464          "mismatch in size of parameter area");
6465   (void)NumBytesActuallyUsed;
6466 
6467   if (!MemOpChains.empty())
6468     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6469 
6470   // Check if this is an indirect call (MTCTR/BCTRL).
6471   // See prepareDescriptorIndirectCall and buildCallOperands for more
6472   // information about calls through function pointers in the 64-bit SVR4 ABI.
6473   if (CFlags.IsIndirect) {
6474     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6475     // caller in the TOC save area.
6476     if (isTOCSaveRestoreRequired(Subtarget)) {
6477       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6478       // Load r2 into a virtual register and store it to the TOC save area.
6479       setUsesTOCBasePtr(DAG);
6480       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6481       // TOC save area offset.
6482       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6483       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6484       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6485       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6486                            MachinePointerInfo::getStack(
6487                                DAG.getMachineFunction(), TOCSaveOffset));
6488     }
6489     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6490     // This does not mean the MTCTR instruction must use R12; it's easier
6491     // to model this as an extra parameter, so do that.
6492     if (isELFv2ABI && !CFlags.IsPatchPoint)
6493       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6494   }
6495 
6496   // Build a sequence of copy-to-reg nodes chained together with token chain
6497   // and flag operands which copy the outgoing args into the appropriate regs.
6498   SDValue InFlag;
6499   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6500     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6501                              RegsToPass[i].second, InFlag);
6502     InFlag = Chain.getValue(1);
6503   }
6504 
6505   if (CFlags.IsTailCall && !IsSibCall)
6506     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6507                     TailCallArguments);
6508 
6509   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6510                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6511 }
6512 
6513 // Returns true when the shadow of a general purpose argument register
6514 // in the parameter save area is aligned to at least 'RequiredAlign'.
6515 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
6516   assert(RequiredAlign.value() <= 16 &&
6517          "Required alignment greater than stack alignment.");
6518   switch (Reg) {
6519   default:
6520     report_fatal_error("called on invalid register.");
6521   case PPC::R5:
6522   case PPC::R9:
6523   case PPC::X3:
6524   case PPC::X5:
6525   case PPC::X7:
6526   case PPC::X9:
6527     // These registers are 16 byte aligned which is the most strict aligment
6528     // we can support.
6529     return true;
6530   case PPC::R3:
6531   case PPC::R7:
6532   case PPC::X4:
6533   case PPC::X6:
6534   case PPC::X8:
6535   case PPC::X10:
6536     // The shadow of these registers in the PSA is 8 byte aligned.
6537     return RequiredAlign <= 8;
6538   case PPC::R4:
6539   case PPC::R6:
6540   case PPC::R8:
6541   case PPC::R10:
6542     return RequiredAlign <= 4;
6543   }
6544 }
6545 
6546 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6547                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6548                    CCState &S) {
6549   AIXCCState &State = static_cast<AIXCCState &>(S);
6550   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6551       State.getMachineFunction().getSubtarget());
6552   const bool IsPPC64 = Subtarget.isPPC64();
6553   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6554   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6555 
6556   if (ValVT == MVT::f128)
6557     report_fatal_error("f128 is unimplemented on AIX.");
6558 
6559   if (ArgFlags.isNest())
6560     report_fatal_error("Nest arguments are unimplemented.");
6561 
6562   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6563                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6564                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6565   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6566                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6567                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6568 
6569   static const MCPhysReg VR[] = {// Vector registers.
6570                                  PPC::V2,  PPC::V3,  PPC::V4,  PPC::V5,
6571                                  PPC::V6,  PPC::V7,  PPC::V8,  PPC::V9,
6572                                  PPC::V10, PPC::V11, PPC::V12, PPC::V13};
6573 
6574   if (ArgFlags.isByVal()) {
6575     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6576       report_fatal_error("Pass-by-value arguments with alignment greater than "
6577                          "register width are not supported.");
6578 
6579     const unsigned ByValSize = ArgFlags.getByValSize();
6580 
6581     // An empty aggregate parameter takes up no storage and no registers,
6582     // but needs a MemLoc for a stack slot for the formal arguments side.
6583     if (ByValSize == 0) {
6584       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6585                                        State.getNextStackOffset(), RegVT,
6586                                        LocInfo));
6587       return false;
6588     }
6589 
6590     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6591     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6592     for (const unsigned E = Offset + StackSize; Offset < E;
6593          Offset += PtrAlign.value()) {
6594       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6595         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6596       else {
6597         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6598                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6599                                          LocInfo));
6600         break;
6601       }
6602     }
6603     return false;
6604   }
6605 
6606   // Arguments always reserve parameter save area.
6607   switch (ValVT.SimpleTy) {
6608   default:
6609     report_fatal_error("Unhandled value type for argument.");
6610   case MVT::i64:
6611     // i64 arguments should have been split to i32 for PPC32.
6612     assert(IsPPC64 && "PPC32 should have split i64 values.");
6613     LLVM_FALLTHROUGH;
6614   case MVT::i1:
6615   case MVT::i32: {
6616     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6617     // AIX integer arguments are always passed in register width.
6618     if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6619       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6620                                   : CCValAssign::LocInfo::ZExt;
6621     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6622       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6623     else
6624       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6625 
6626     return false;
6627   }
6628   case MVT::f32:
6629   case MVT::f64: {
6630     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6631     const unsigned StoreSize = LocVT.getStoreSize();
6632     // Floats are always 4-byte aligned in the PSA on AIX.
6633     // This includes f64 in 64-bit mode for ABI compatibility.
6634     const unsigned Offset =
6635         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6636     unsigned FReg = State.AllocateReg(FPR);
6637     if (FReg)
6638       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6639 
6640     // Reserve and initialize GPRs or initialize the PSA as required.
6641     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6642       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6643         assert(FReg && "An FPR should be available when a GPR is reserved.");
6644         if (State.isVarArg()) {
6645           // Successfully reserved GPRs are only initialized for vararg calls.
6646           // Custom handling is required for:
6647           //   f64 in PPC32 needs to be split into 2 GPRs.
6648           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6649           State.addLoc(
6650               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6651         }
6652       } else {
6653         // If there are insufficient GPRs, the PSA needs to be initialized.
6654         // Initialization occurs even if an FPR was initialized for
6655         // compatibility with the AIX XL compiler. The full memory for the
6656         // argument will be initialized even if a prior word is saved in GPR.
6657         // A custom memLoc is used when the argument also passes in FPR so
6658         // that the callee handling can skip over it easily.
6659         State.addLoc(
6660             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6661                                              LocInfo)
6662                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6663         break;
6664       }
6665     }
6666 
6667     return false;
6668   }
6669   case MVT::v4f32:
6670   case MVT::v4i32:
6671   case MVT::v8i16:
6672   case MVT::v16i8:
6673   case MVT::v2i64:
6674   case MVT::v2f64:
6675   case MVT::v1i128: {
6676     const unsigned VecSize = 16;
6677     const Align VecAlign(VecSize);
6678 
6679     if (!State.isVarArg()) {
6680       // If there are vector registers remaining we don't consume any stack
6681       // space.
6682       if (unsigned VReg = State.AllocateReg(VR)) {
6683         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6684         return false;
6685       }
6686       // Vectors passed on the stack do not shadow GPRs or FPRs even though they
6687       // might be allocated in the portion of the PSA that is shadowed by the
6688       // GPRs.
6689       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6690       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6691       return false;
6692     }
6693 
6694     const unsigned PtrSize = IsPPC64 ? 8 : 4;
6695     ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
6696 
6697     unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
6698     // Burn any underaligned registers and their shadowed stack space until
6699     // we reach the required alignment.
6700     while (NextRegIndex != GPRs.size() &&
6701            !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
6702       // Shadow allocate register and its stack shadow.
6703       unsigned Reg = State.AllocateReg(GPRs);
6704       State.AllocateStack(PtrSize, PtrAlign);
6705       assert(Reg && "Allocating register unexpectedly failed.");
6706       (void)Reg;
6707       NextRegIndex = State.getFirstUnallocated(GPRs);
6708     }
6709 
6710     // Vectors that are passed as fixed arguments are handled differently.
6711     // They are passed in VRs if any are available (unlike arguments passed
6712     // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
6713     // functions)
6714     if (State.isFixed(ValNo)) {
6715       if (unsigned VReg = State.AllocateReg(VR)) {
6716         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6717         // Shadow allocate GPRs and stack space even though we pass in a VR.
6718         for (unsigned I = 0; I != VecSize; I += PtrSize)
6719           State.AllocateReg(GPRs);
6720         State.AllocateStack(VecSize, VecAlign);
6721         return false;
6722       }
6723       // No vector registers remain so pass on the stack.
6724       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6725       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6726       return false;
6727     }
6728 
6729     // If all GPRS are consumed then we pass the argument fully on the stack.
6730     if (NextRegIndex == GPRs.size()) {
6731       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6732       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6733       return false;
6734     }
6735 
6736     // Corner case for 32-bit codegen. We have 2 registers to pass the first
6737     // half of the argument, and then need to pass the remaining half on the
6738     // stack.
6739     if (GPRs[NextRegIndex] == PPC::R9) {
6740       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6741       State.addLoc(
6742           CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6743 
6744       const unsigned FirstReg = State.AllocateReg(PPC::R9);
6745       const unsigned SecondReg = State.AllocateReg(PPC::R10);
6746       assert(FirstReg && SecondReg &&
6747              "Allocating R9 or R10 unexpectedly failed.");
6748       State.addLoc(
6749           CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
6750       State.addLoc(
6751           CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
6752       return false;
6753     }
6754 
6755     // We have enough GPRs to fully pass the vector argument, and we have
6756     // already consumed any underaligned registers. Start with the custom
6757     // MemLoc and then the custom RegLocs.
6758     const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6759     State.addLoc(
6760         CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6761     for (unsigned I = 0; I != VecSize; I += PtrSize) {
6762       const unsigned Reg = State.AllocateReg(GPRs);
6763       assert(Reg && "Failed to allocated register for vararg vector argument");
6764       State.addLoc(
6765           CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6766     }
6767     return false;
6768   }
6769   }
6770   return true;
6771 }
6772 
6773 // So far, this function is only used by LowerFormalArguments_AIX()
6774 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6775                                                     bool IsPPC64,
6776                                                     bool HasP8Vector,
6777                                                     bool HasVSX) {
6778   assert((IsPPC64 || SVT != MVT::i64) &&
6779          "i64 should have been split for 32-bit codegen.");
6780 
6781   switch (SVT) {
6782   default:
6783     report_fatal_error("Unexpected value type for formal argument");
6784   case MVT::i1:
6785   case MVT::i32:
6786   case MVT::i64:
6787     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6788   case MVT::f32:
6789     return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass;
6790   case MVT::f64:
6791     return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass;
6792   case MVT::v4f32:
6793   case MVT::v4i32:
6794   case MVT::v8i16:
6795   case MVT::v16i8:
6796   case MVT::v2i64:
6797   case MVT::v2f64:
6798   case MVT::v1i128:
6799     return &PPC::VRRCRegClass;
6800   }
6801 }
6802 
6803 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6804                                         SelectionDAG &DAG, SDValue ArgValue,
6805                                         MVT LocVT, const SDLoc &dl) {
6806   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6807   assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
6808 
6809   if (Flags.isSExt())
6810     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6811                            DAG.getValueType(ValVT));
6812   else if (Flags.isZExt())
6813     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6814                            DAG.getValueType(ValVT));
6815 
6816   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6817 }
6818 
6819 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6820   const unsigned LASize = FL->getLinkageSize();
6821 
6822   if (PPC::GPRCRegClass.contains(Reg)) {
6823     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6824            "Reg must be a valid argument register!");
6825     return LASize + 4 * (Reg - PPC::R3);
6826   }
6827 
6828   if (PPC::G8RCRegClass.contains(Reg)) {
6829     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6830            "Reg must be a valid argument register!");
6831     return LASize + 8 * (Reg - PPC::X3);
6832   }
6833 
6834   llvm_unreachable("Only general purpose registers expected.");
6835 }
6836 
6837 //   AIX ABI Stack Frame Layout:
6838 //
6839 //   Low Memory +--------------------------------------------+
6840 //   SP   +---> | Back chain                                 | ---+
6841 //        |     +--------------------------------------------+    |
6842 //        |     | Saved Condition Register                   |    |
6843 //        |     +--------------------------------------------+    |
6844 //        |     | Saved Linkage Register                     |    |
6845 //        |     +--------------------------------------------+    | Linkage Area
6846 //        |     | Reserved for compilers                     |    |
6847 //        |     +--------------------------------------------+    |
6848 //        |     | Reserved for binders                       |    |
6849 //        |     +--------------------------------------------+    |
6850 //        |     | Saved TOC pointer                          | ---+
6851 //        |     +--------------------------------------------+
6852 //        |     | Parameter save area                        |
6853 //        |     +--------------------------------------------+
6854 //        |     | Alloca space                               |
6855 //        |     +--------------------------------------------+
6856 //        |     | Local variable space                       |
6857 //        |     +--------------------------------------------+
6858 //        |     | Float/int conversion temporary             |
6859 //        |     +--------------------------------------------+
6860 //        |     | Save area for AltiVec registers            |
6861 //        |     +--------------------------------------------+
6862 //        |     | AltiVec alignment padding                  |
6863 //        |     +--------------------------------------------+
6864 //        |     | Save area for VRSAVE register              |
6865 //        |     +--------------------------------------------+
6866 //        |     | Save area for General Purpose registers    |
6867 //        |     +--------------------------------------------+
6868 //        |     | Save area for Floating Point registers     |
6869 //        |     +--------------------------------------------+
6870 //        +---- | Back chain                                 |
6871 // High Memory  +--------------------------------------------+
6872 //
6873 //  Specifications:
6874 //  AIX 7.2 Assembler Language Reference
6875 //  Subroutine linkage convention
6876 
6877 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6878     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6879     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6880     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6881 
6882   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6883           CallConv == CallingConv::Fast) &&
6884          "Unexpected calling convention!");
6885 
6886   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6887     report_fatal_error("Tail call support is unimplemented on AIX.");
6888 
6889   if (useSoftFloat())
6890     report_fatal_error("Soft float support is unimplemented on AIX.");
6891 
6892   const PPCSubtarget &Subtarget =
6893       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6894 
6895   const bool IsPPC64 = Subtarget.isPPC64();
6896   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6897 
6898   // Assign locations to all of the incoming arguments.
6899   SmallVector<CCValAssign, 16> ArgLocs;
6900   MachineFunction &MF = DAG.getMachineFunction();
6901   MachineFrameInfo &MFI = MF.getFrameInfo();
6902   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6903   AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6904 
6905   const EVT PtrVT = getPointerTy(MF.getDataLayout());
6906   // Reserve space for the linkage area on the stack.
6907   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6908   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
6909   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6910 
6911   SmallVector<SDValue, 8> MemOps;
6912 
6913   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
6914     CCValAssign &VA = ArgLocs[I++];
6915     MVT LocVT = VA.getLocVT();
6916     MVT ValVT = VA.getValVT();
6917     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
6918     // For compatibility with the AIX XL compiler, the float args in the
6919     // parameter save area are initialized even if the argument is available
6920     // in register.  The caller is required to initialize both the register
6921     // and memory, however, the callee can choose to expect it in either.
6922     // The memloc is dismissed here because the argument is retrieved from
6923     // the register.
6924     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
6925       continue;
6926 
6927     auto HandleMemLoc = [&]() {
6928       const unsigned LocSize = LocVT.getStoreSize();
6929       const unsigned ValSize = ValVT.getStoreSize();
6930       assert((ValSize <= LocSize) &&
6931              "Object size is larger than size of MemLoc");
6932       int CurArgOffset = VA.getLocMemOffset();
6933       // Objects are right-justified because AIX is big-endian.
6934       if (LocSize > ValSize)
6935         CurArgOffset += LocSize - ValSize;
6936       // Potential tail calls could cause overwriting of argument stack slots.
6937       const bool IsImmutable =
6938           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
6939             (CallConv == CallingConv::Fast));
6940       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
6941       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6942       SDValue ArgValue =
6943           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
6944       InVals.push_back(ArgValue);
6945     };
6946 
6947     // Vector arguments to VaArg functions are passed both on the stack, and
6948     // in any available GPRs. Load the value from the stack and add the GPRs
6949     // as live ins.
6950     if (VA.isMemLoc() && VA.needsCustom()) {
6951       assert(ValVT.isVector() && "Unexpected Custom MemLoc type.");
6952       assert(isVarArg && "Only use custom memloc for vararg.");
6953       // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
6954       // matching custom RegLocs.
6955       const unsigned OriginalValNo = VA.getValNo();
6956       (void)OriginalValNo;
6957 
6958       auto HandleCustomVecRegLoc = [&]() {
6959         assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
6960                "Missing custom RegLoc.");
6961         VA = ArgLocs[I++];
6962         assert(VA.getValVT().isVector() &&
6963                "Unexpected Val type for custom RegLoc.");
6964         assert(VA.getValNo() == OriginalValNo &&
6965                "ValNo mismatch between custom MemLoc and RegLoc.");
6966         MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy;
6967         MF.addLiveIn(VA.getLocReg(),
6968                      getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
6969                                        Subtarget.hasVSX()));
6970       };
6971 
6972       HandleMemLoc();
6973       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
6974       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
6975       // R10.
6976       HandleCustomVecRegLoc();
6977       HandleCustomVecRegLoc();
6978 
6979       // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
6980       // we passed the vector in R5, R6, R7 and R8.
6981       if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
6982         assert(!IsPPC64 &&
6983                "Only 2 custom RegLocs expected for 64-bit codegen.");
6984         HandleCustomVecRegLoc();
6985         HandleCustomVecRegLoc();
6986       }
6987 
6988       continue;
6989     }
6990 
6991     if (VA.isRegLoc()) {
6992       if (VA.getValVT().isScalarInteger())
6993         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
6994       else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) {
6995         switch (VA.getValVT().SimpleTy) {
6996         default:
6997           report_fatal_error("Unhandled value type for argument.");
6998         case MVT::f32:
6999           FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint);
7000           break;
7001         case MVT::f64:
7002           FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint);
7003           break;
7004         }
7005       } else if (VA.getValVT().isVector()) {
7006         switch (VA.getValVT().SimpleTy) {
7007         default:
7008           report_fatal_error("Unhandled value type for argument.");
7009         case MVT::v16i8:
7010           FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar);
7011           break;
7012         case MVT::v8i16:
7013           FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort);
7014           break;
7015         case MVT::v4i32:
7016         case MVT::v2i64:
7017         case MVT::v1i128:
7018           FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt);
7019           break;
7020         case MVT::v4f32:
7021         case MVT::v2f64:
7022           FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat);
7023           break;
7024         }
7025       }
7026     }
7027 
7028     if (Flags.isByVal() && VA.isMemLoc()) {
7029       const unsigned Size =
7030           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7031                   PtrByteSize);
7032       const int FI = MF.getFrameInfo().CreateFixedObject(
7033           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7034           /* IsAliased */ true);
7035       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7036       InVals.push_back(FIN);
7037 
7038       continue;
7039     }
7040 
7041     if (Flags.isByVal()) {
7042       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7043 
7044       const MCPhysReg ArgReg = VA.getLocReg();
7045       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7046 
7047       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7048         report_fatal_error("Over aligned byvals not supported yet.");
7049 
7050       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7051       const int FI = MF.getFrameInfo().CreateFixedObject(
7052           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7053           /* IsAliased */ true);
7054       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7055       InVals.push_back(FIN);
7056 
7057       // Add live ins for all the RegLocs for the same ByVal.
7058       const TargetRegisterClass *RegClass =
7059           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7060 
7061       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7062                                                unsigned Offset) {
7063         const Register VReg = MF.addLiveIn(PhysReg, RegClass);
7064         // Since the callers side has left justified the aggregate in the
7065         // register, we can simply store the entire register into the stack
7066         // slot.
7067         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7068         // The store to the fixedstack object is needed becuase accessing a
7069         // field of the ByVal will use a gep and load. Ideally we will optimize
7070         // to extracting the value from the register directly, and elide the
7071         // stores when the arguments address is not taken, but that will need to
7072         // be future work.
7073         SDValue Store = DAG.getStore(
7074             CopyFrom.getValue(1), dl, CopyFrom,
7075             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7076             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7077 
7078         MemOps.push_back(Store);
7079       };
7080 
7081       unsigned Offset = 0;
7082       HandleRegLoc(VA.getLocReg(), Offset);
7083       Offset += PtrByteSize;
7084       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7085            Offset += PtrByteSize) {
7086         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7087                "RegLocs should be for ByVal argument.");
7088 
7089         const CCValAssign RL = ArgLocs[I++];
7090         HandleRegLoc(RL.getLocReg(), Offset);
7091         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7092       }
7093 
7094       if (Offset != StackSize) {
7095         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7096                "Expected MemLoc for remaining bytes.");
7097         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7098         // Consume the MemLoc.The InVal has already been emitted, so nothing
7099         // more needs to be done.
7100         ++I;
7101       }
7102 
7103       continue;
7104     }
7105 
7106     if (VA.isRegLoc() && !VA.needsCustom()) {
7107       MVT::SimpleValueType SVT = ValVT.SimpleTy;
7108       Register VReg =
7109           MF.addLiveIn(VA.getLocReg(),
7110                        getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7111                                          Subtarget.hasVSX()));
7112       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7113       if (ValVT.isScalarInteger() &&
7114           (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7115         ArgValue =
7116             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7117       }
7118       InVals.push_back(ArgValue);
7119       continue;
7120     }
7121     if (VA.isMemLoc()) {
7122       HandleMemLoc();
7123       continue;
7124     }
7125   }
7126 
7127   // On AIX a minimum of 8 words is saved to the parameter save area.
7128   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7129   // Area that is at least reserved in the caller of this function.
7130   unsigned CallerReservedArea =
7131       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7132 
7133   // Set the size that is at least reserved in caller of this function. Tail
7134   // call optimized function's reserved stack space needs to be aligned so
7135   // that taking the difference between two stack areas will result in an
7136   // aligned stack.
7137   CallerReservedArea =
7138       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7139   FuncInfo->setMinReservedArea(CallerReservedArea);
7140 
7141   if (isVarArg) {
7142     FuncInfo->setVarArgsFrameIndex(
7143         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7144     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7145 
7146     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7147                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7148 
7149     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7150                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7151     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7152 
7153     // The fixed integer arguments of a variadic function are stored to the
7154     // VarArgsFrameIndex on the stack so that they may be loaded by
7155     // dereferencing the result of va_next.
7156     for (unsigned GPRIndex =
7157              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7158          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7159 
7160       const Register VReg =
7161           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7162                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7163 
7164       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7165       SDValue Store =
7166           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7167       MemOps.push_back(Store);
7168       // Increment the address for the next argument to store.
7169       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7170       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7171     }
7172   }
7173 
7174   if (!MemOps.empty())
7175     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7176 
7177   return Chain;
7178 }
7179 
7180 SDValue PPCTargetLowering::LowerCall_AIX(
7181     SDValue Chain, SDValue Callee, CallFlags CFlags,
7182     const SmallVectorImpl<ISD::OutputArg> &Outs,
7183     const SmallVectorImpl<SDValue> &OutVals,
7184     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7185     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7186     const CallBase *CB) const {
7187   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7188   // AIX ABI stack frame layout.
7189 
7190   assert((CFlags.CallConv == CallingConv::C ||
7191           CFlags.CallConv == CallingConv::Cold ||
7192           CFlags.CallConv == CallingConv::Fast) &&
7193          "Unexpected calling convention!");
7194 
7195   if (CFlags.IsPatchPoint)
7196     report_fatal_error("This call type is unimplemented on AIX.");
7197 
7198   const PPCSubtarget& Subtarget =
7199       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7200 
7201   MachineFunction &MF = DAG.getMachineFunction();
7202   SmallVector<CCValAssign, 16> ArgLocs;
7203   AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7204                     *DAG.getContext());
7205 
7206   // Reserve space for the linkage save area (LSA) on the stack.
7207   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7208   //   [SP][CR][LR][2 x reserved][TOC].
7209   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7210   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7211   const bool IsPPC64 = Subtarget.isPPC64();
7212   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7213   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7214   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7215   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7216 
7217   // The prolog code of the callee may store up to 8 GPR argument registers to
7218   // the stack, allowing va_start to index over them in memory if the callee
7219   // is variadic.
7220   // Because we cannot tell if this is needed on the caller side, we have to
7221   // conservatively assume that it is needed.  As such, make sure we have at
7222   // least enough stack space for the caller to store the 8 GPRs.
7223   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7224   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7225                                      CCInfo.getNextStackOffset());
7226 
7227   // Adjust the stack pointer for the new arguments...
7228   // These operations are automatically eliminated by the prolog/epilog pass.
7229   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7230   SDValue CallSeqStart = Chain;
7231 
7232   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7233   SmallVector<SDValue, 8> MemOpChains;
7234 
7235   // Set up a copy of the stack pointer for loading and storing any
7236   // arguments that may not fit in the registers available for argument
7237   // passing.
7238   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7239                                    : DAG.getRegister(PPC::R1, MVT::i32);
7240 
7241   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7242     const unsigned ValNo = ArgLocs[I].getValNo();
7243     SDValue Arg = OutVals[ValNo];
7244     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7245 
7246     if (Flags.isByVal()) {
7247       const unsigned ByValSize = Flags.getByValSize();
7248 
7249       // Nothing to do for zero-sized ByVals on the caller side.
7250       if (!ByValSize) {
7251         ++I;
7252         continue;
7253       }
7254 
7255       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7256         return DAG.getExtLoad(
7257             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7258             (LoadOffset != 0)
7259                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7260                 : Arg,
7261             MachinePointerInfo(), VT);
7262       };
7263 
7264       unsigned LoadOffset = 0;
7265 
7266       // Initialize registers, which are fully occupied by the by-val argument.
7267       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7268         SDValue Load = GetLoad(PtrVT, LoadOffset);
7269         MemOpChains.push_back(Load.getValue(1));
7270         LoadOffset += PtrByteSize;
7271         const CCValAssign &ByValVA = ArgLocs[I++];
7272         assert(ByValVA.getValNo() == ValNo &&
7273                "Unexpected location for pass-by-value argument.");
7274         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7275       }
7276 
7277       if (LoadOffset == ByValSize)
7278         continue;
7279 
7280       // There must be one more loc to handle the remainder.
7281       assert(ArgLocs[I].getValNo() == ValNo &&
7282              "Expected additional location for by-value argument.");
7283 
7284       if (ArgLocs[I].isMemLoc()) {
7285         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7286         const CCValAssign &ByValVA = ArgLocs[I++];
7287         ISD::ArgFlagsTy MemcpyFlags = Flags;
7288         // Only memcpy the bytes that don't pass in register.
7289         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7290         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7291             (LoadOffset != 0)
7292                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7293                 : Arg,
7294             DAG.getObjectPtrOffset(dl, StackPtr,
7295                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7296             CallSeqStart, MemcpyFlags, DAG, dl);
7297         continue;
7298       }
7299 
7300       // Initialize the final register residue.
7301       // Any residue that occupies the final by-val arg register must be
7302       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7303       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7304       // 2 and 1 byte loads.
7305       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7306       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7307              "Unexpected register residue for by-value argument.");
7308       SDValue ResidueVal;
7309       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7310         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7311         const MVT VT =
7312             N == 1 ? MVT::i8
7313                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7314         SDValue Load = GetLoad(VT, LoadOffset);
7315         MemOpChains.push_back(Load.getValue(1));
7316         LoadOffset += N;
7317         Bytes += N;
7318 
7319         // By-val arguments are passed left-justfied in register.
7320         // Every load here needs to be shifted, otherwise a full register load
7321         // should have been used.
7322         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7323                "Unexpected load emitted during handling of pass-by-value "
7324                "argument.");
7325         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7326         EVT ShiftAmountTy =
7327             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7328         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7329         SDValue ShiftedLoad =
7330             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7331         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7332                                               ShiftedLoad)
7333                                 : ShiftedLoad;
7334       }
7335 
7336       const CCValAssign &ByValVA = ArgLocs[I++];
7337       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7338       continue;
7339     }
7340 
7341     CCValAssign &VA = ArgLocs[I++];
7342     const MVT LocVT = VA.getLocVT();
7343     const MVT ValVT = VA.getValVT();
7344 
7345     switch (VA.getLocInfo()) {
7346     default:
7347       report_fatal_error("Unexpected argument extension type.");
7348     case CCValAssign::Full:
7349       break;
7350     case CCValAssign::ZExt:
7351       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7352       break;
7353     case CCValAssign::SExt:
7354       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7355       break;
7356     }
7357 
7358     if (VA.isRegLoc() && !VA.needsCustom()) {
7359       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7360       continue;
7361     }
7362 
7363     // Vector arguments passed to VarArg functions need custom handling when
7364     // they are passed (at least partially) in GPRs.
7365     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
7366       assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.");
7367       // Store value to its stack slot.
7368       SDValue PtrOff =
7369           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7370       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7371       SDValue Store =
7372           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
7373       MemOpChains.push_back(Store);
7374       const unsigned OriginalValNo = VA.getValNo();
7375       // Then load the GPRs from the stack
7376       unsigned LoadOffset = 0;
7377       auto HandleCustomVecRegLoc = [&]() {
7378         assert(I != E && "Unexpected end of CCvalAssigns.");
7379         assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7380                "Expected custom RegLoc.");
7381         CCValAssign RegVA = ArgLocs[I++];
7382         assert(RegVA.getValNo() == OriginalValNo &&
7383                "Custom MemLoc ValNo and custom RegLoc ValNo must match.");
7384         SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
7385                                   DAG.getConstant(LoadOffset, dl, PtrVT));
7386         SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
7387         MemOpChains.push_back(Load.getValue(1));
7388         RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
7389         LoadOffset += PtrByteSize;
7390       };
7391 
7392       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7393       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7394       // R10.
7395       HandleCustomVecRegLoc();
7396       HandleCustomVecRegLoc();
7397 
7398       if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7399           ArgLocs[I].getValNo() == OriginalValNo) {
7400         assert(!IsPPC64 &&
7401                "Only 2 custom RegLocs expected for 64-bit codegen.");
7402         HandleCustomVecRegLoc();
7403         HandleCustomVecRegLoc();
7404       }
7405 
7406       continue;
7407     }
7408 
7409     if (VA.isMemLoc()) {
7410       SDValue PtrOff =
7411           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7412       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7413       MemOpChains.push_back(
7414           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7415 
7416       continue;
7417     }
7418 
7419     if (!ValVT.isFloatingPoint())
7420       report_fatal_error(
7421           "Unexpected register handling for calling convention.");
7422 
7423     // Custom handling is used for GPR initializations for vararg float
7424     // arguments.
7425     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7426            LocVT.isInteger() &&
7427            "Custom register handling only expected for VarArg.");
7428 
7429     SDValue ArgAsInt =
7430         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7431 
7432     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7433       // f32 in 32-bit GPR
7434       // f64 in 64-bit GPR
7435       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7436     else if (Arg.getValueType().getFixedSizeInBits() <
7437              LocVT.getFixedSizeInBits())
7438       // f32 in 64-bit GPR.
7439       RegsToPass.push_back(std::make_pair(
7440           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7441     else {
7442       // f64 in two 32-bit GPRs
7443       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7444       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7445              "Unexpected custom register for argument!");
7446       CCValAssign &GPR1 = VA;
7447       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7448                                      DAG.getConstant(32, dl, MVT::i8));
7449       RegsToPass.push_back(std::make_pair(
7450           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7451 
7452       if (I != E) {
7453         // If only 1 GPR was available, there will only be one custom GPR and
7454         // the argument will also pass in memory.
7455         CCValAssign &PeekArg = ArgLocs[I];
7456         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7457           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7458           CCValAssign &GPR2 = ArgLocs[I++];
7459           RegsToPass.push_back(std::make_pair(
7460               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7461         }
7462       }
7463     }
7464   }
7465 
7466   if (!MemOpChains.empty())
7467     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7468 
7469   // For indirect calls, we need to save the TOC base to the stack for
7470   // restoration after the call.
7471   if (CFlags.IsIndirect) {
7472     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7473     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7474     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7475     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7476     const unsigned TOCSaveOffset =
7477         Subtarget.getFrameLowering()->getTOCSaveOffset();
7478 
7479     setUsesTOCBasePtr(DAG);
7480     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7481     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7482     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7483     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7484     Chain = DAG.getStore(
7485         Val.getValue(1), dl, Val, AddPtr,
7486         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7487   }
7488 
7489   // Build a sequence of copy-to-reg nodes chained together with token chain
7490   // and flag operands which copy the outgoing args into the appropriate regs.
7491   SDValue InFlag;
7492   for (auto Reg : RegsToPass) {
7493     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7494     InFlag = Chain.getValue(1);
7495   }
7496 
7497   const int SPDiff = 0;
7498   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7499                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7500 }
7501 
7502 bool
7503 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7504                                   MachineFunction &MF, bool isVarArg,
7505                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7506                                   LLVMContext &Context) const {
7507   SmallVector<CCValAssign, 16> RVLocs;
7508   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7509   return CCInfo.CheckReturn(
7510       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7511                 ? RetCC_PPC_Cold
7512                 : RetCC_PPC);
7513 }
7514 
7515 SDValue
7516 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7517                                bool isVarArg,
7518                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7519                                const SmallVectorImpl<SDValue> &OutVals,
7520                                const SDLoc &dl, SelectionDAG &DAG) const {
7521   SmallVector<CCValAssign, 16> RVLocs;
7522   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7523                  *DAG.getContext());
7524   CCInfo.AnalyzeReturn(Outs,
7525                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7526                            ? RetCC_PPC_Cold
7527                            : RetCC_PPC);
7528 
7529   SDValue Flag;
7530   SmallVector<SDValue, 4> RetOps(1, Chain);
7531 
7532   // Copy the result values into the output registers.
7533   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7534     CCValAssign &VA = RVLocs[i];
7535     assert(VA.isRegLoc() && "Can only return in registers!");
7536 
7537     SDValue Arg = OutVals[RealResIdx];
7538 
7539     switch (VA.getLocInfo()) {
7540     default: llvm_unreachable("Unknown loc info!");
7541     case CCValAssign::Full: break;
7542     case CCValAssign::AExt:
7543       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7544       break;
7545     case CCValAssign::ZExt:
7546       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7547       break;
7548     case CCValAssign::SExt:
7549       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7550       break;
7551     }
7552     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7553       bool isLittleEndian = Subtarget.isLittleEndian();
7554       // Legalize ret f64 -> ret 2 x i32.
7555       SDValue SVal =
7556           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7557                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7558       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7559       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7560       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7561                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7562       Flag = Chain.getValue(1);
7563       VA = RVLocs[++i]; // skip ahead to next loc
7564       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7565     } else
7566       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7567     Flag = Chain.getValue(1);
7568     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7569   }
7570 
7571   RetOps[0] = Chain;  // Update chain.
7572 
7573   // Add the flag if we have it.
7574   if (Flag.getNode())
7575     RetOps.push_back(Flag);
7576 
7577   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7578 }
7579 
7580 SDValue
7581 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7582                                                 SelectionDAG &DAG) const {
7583   SDLoc dl(Op);
7584 
7585   // Get the correct type for integers.
7586   EVT IntVT = Op.getValueType();
7587 
7588   // Get the inputs.
7589   SDValue Chain = Op.getOperand(0);
7590   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7591   // Build a DYNAREAOFFSET node.
7592   SDValue Ops[2] = {Chain, FPSIdx};
7593   SDVTList VTs = DAG.getVTList(IntVT);
7594   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7595 }
7596 
7597 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7598                                              SelectionDAG &DAG) const {
7599   // When we pop the dynamic allocation we need to restore the SP link.
7600   SDLoc dl(Op);
7601 
7602   // Get the correct type for pointers.
7603   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7604 
7605   // Construct the stack pointer operand.
7606   bool isPPC64 = Subtarget.isPPC64();
7607   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7608   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7609 
7610   // Get the operands for the STACKRESTORE.
7611   SDValue Chain = Op.getOperand(0);
7612   SDValue SaveSP = Op.getOperand(1);
7613 
7614   // Load the old link SP.
7615   SDValue LoadLinkSP =
7616       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7617 
7618   // Restore the stack pointer.
7619   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7620 
7621   // Store the old link SP.
7622   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7623 }
7624 
7625 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7626   MachineFunction &MF = DAG.getMachineFunction();
7627   bool isPPC64 = Subtarget.isPPC64();
7628   EVT PtrVT = getPointerTy(MF.getDataLayout());
7629 
7630   // Get current frame pointer save index.  The users of this index will be
7631   // primarily DYNALLOC instructions.
7632   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7633   int RASI = FI->getReturnAddrSaveIndex();
7634 
7635   // If the frame pointer save index hasn't been defined yet.
7636   if (!RASI) {
7637     // Find out what the fix offset of the frame pointer save area.
7638     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7639     // Allocate the frame index for frame pointer save area.
7640     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7641     // Save the result.
7642     FI->setReturnAddrSaveIndex(RASI);
7643   }
7644   return DAG.getFrameIndex(RASI, PtrVT);
7645 }
7646 
7647 SDValue
7648 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7649   MachineFunction &MF = DAG.getMachineFunction();
7650   bool isPPC64 = Subtarget.isPPC64();
7651   EVT PtrVT = getPointerTy(MF.getDataLayout());
7652 
7653   // Get current frame pointer save index.  The users of this index will be
7654   // primarily DYNALLOC instructions.
7655   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7656   int FPSI = FI->getFramePointerSaveIndex();
7657 
7658   // If the frame pointer save index hasn't been defined yet.
7659   if (!FPSI) {
7660     // Find out what the fix offset of the frame pointer save area.
7661     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7662     // Allocate the frame index for frame pointer save area.
7663     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7664     // Save the result.
7665     FI->setFramePointerSaveIndex(FPSI);
7666   }
7667   return DAG.getFrameIndex(FPSI, PtrVT);
7668 }
7669 
7670 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7671                                                    SelectionDAG &DAG) const {
7672   MachineFunction &MF = DAG.getMachineFunction();
7673   // Get the inputs.
7674   SDValue Chain = Op.getOperand(0);
7675   SDValue Size  = Op.getOperand(1);
7676   SDLoc dl(Op);
7677 
7678   // Get the correct type for pointers.
7679   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7680   // Negate the size.
7681   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7682                                 DAG.getConstant(0, dl, PtrVT), Size);
7683   // Construct a node for the frame pointer save index.
7684   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7685   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7686   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7687   if (hasInlineStackProbe(MF))
7688     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7689   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7690 }
7691 
7692 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7693                                                      SelectionDAG &DAG) const {
7694   MachineFunction &MF = DAG.getMachineFunction();
7695 
7696   bool isPPC64 = Subtarget.isPPC64();
7697   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7698 
7699   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7700   return DAG.getFrameIndex(FI, PtrVT);
7701 }
7702 
7703 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7704                                                SelectionDAG &DAG) const {
7705   SDLoc DL(Op);
7706   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7707                      DAG.getVTList(MVT::i32, MVT::Other),
7708                      Op.getOperand(0), Op.getOperand(1));
7709 }
7710 
7711 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7712                                                 SelectionDAG &DAG) const {
7713   SDLoc DL(Op);
7714   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7715                      Op.getOperand(0), Op.getOperand(1));
7716 }
7717 
7718 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7719   if (Op.getValueType().isVector())
7720     return LowerVectorLoad(Op, DAG);
7721 
7722   assert(Op.getValueType() == MVT::i1 &&
7723          "Custom lowering only for i1 loads");
7724 
7725   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7726 
7727   SDLoc dl(Op);
7728   LoadSDNode *LD = cast<LoadSDNode>(Op);
7729 
7730   SDValue Chain = LD->getChain();
7731   SDValue BasePtr = LD->getBasePtr();
7732   MachineMemOperand *MMO = LD->getMemOperand();
7733 
7734   SDValue NewLD =
7735       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7736                      BasePtr, MVT::i8, MMO);
7737   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7738 
7739   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7740   return DAG.getMergeValues(Ops, dl);
7741 }
7742 
7743 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7744   if (Op.getOperand(1).getValueType().isVector())
7745     return LowerVectorStore(Op, DAG);
7746 
7747   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7748          "Custom lowering only for i1 stores");
7749 
7750   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7751 
7752   SDLoc dl(Op);
7753   StoreSDNode *ST = cast<StoreSDNode>(Op);
7754 
7755   SDValue Chain = ST->getChain();
7756   SDValue BasePtr = ST->getBasePtr();
7757   SDValue Value = ST->getValue();
7758   MachineMemOperand *MMO = ST->getMemOperand();
7759 
7760   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7761                       Value);
7762   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7763 }
7764 
7765 // FIXME: Remove this once the ANDI glue bug is fixed:
7766 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7767   assert(Op.getValueType() == MVT::i1 &&
7768          "Custom lowering only for i1 results");
7769 
7770   SDLoc DL(Op);
7771   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7772 }
7773 
7774 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7775                                                SelectionDAG &DAG) const {
7776 
7777   // Implements a vector truncate that fits in a vector register as a shuffle.
7778   // We want to legalize vector truncates down to where the source fits in
7779   // a vector register (and target is therefore smaller than vector register
7780   // size).  At that point legalization will try to custom lower the sub-legal
7781   // result and get here - where we can contain the truncate as a single target
7782   // operation.
7783 
7784   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7785   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7786   //
7787   // We will implement it for big-endian ordering as this (where x denotes
7788   // undefined):
7789   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7790   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7791   //
7792   // The same operation in little-endian ordering will be:
7793   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7794   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7795 
7796   EVT TrgVT = Op.getValueType();
7797   assert(TrgVT.isVector() && "Vector type expected.");
7798   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7799   EVT EltVT = TrgVT.getVectorElementType();
7800   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
7801       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
7802       !isPowerOf2_32(EltVT.getSizeInBits()))
7803     return SDValue();
7804 
7805   SDValue N1 = Op.getOperand(0);
7806   EVT SrcVT = N1.getValueType();
7807   unsigned SrcSize = SrcVT.getSizeInBits();
7808   if (SrcSize > 256 ||
7809       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
7810       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
7811     return SDValue();
7812   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
7813     return SDValue();
7814 
7815   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7816   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7817 
7818   SDLoc DL(Op);
7819   SDValue Op1, Op2;
7820   if (SrcSize == 256) {
7821     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
7822     EVT SplitVT =
7823         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
7824     unsigned SplitNumElts = SplitVT.getVectorNumElements();
7825     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7826                       DAG.getConstant(0, DL, VecIdxTy));
7827     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7828                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
7829   }
7830   else {
7831     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7832     Op2 = DAG.getUNDEF(WideVT);
7833   }
7834 
7835   // First list the elements we want to keep.
7836   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7837   SmallVector<int, 16> ShuffV;
7838   if (Subtarget.isLittleEndian())
7839     for (unsigned i = 0; i < TrgNumElts; ++i)
7840       ShuffV.push_back(i * SizeMult);
7841   else
7842     for (unsigned i = 1; i <= TrgNumElts; ++i)
7843       ShuffV.push_back(i * SizeMult - 1);
7844 
7845   // Populate the remaining elements with undefs.
7846   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7847     // ShuffV.push_back(i + WideNumElts);
7848     ShuffV.push_back(WideNumElts + 1);
7849 
7850   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
7851   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
7852   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
7853 }
7854 
7855 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7856 /// possible.
7857 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7858   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7859   EVT ResVT = Op.getValueType();
7860   EVT CmpVT = Op.getOperand(0).getValueType();
7861   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7862   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7863   SDLoc dl(Op);
7864 
7865   // Without power9-vector, we don't have native instruction for f128 comparison.
7866   // Following transformation to libcall is needed for setcc:
7867   // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE
7868   if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) {
7869     SDValue Z = DAG.getSetCC(
7870         dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT),
7871         LHS, RHS, CC);
7872     SDValue Zero = DAG.getConstant(0, dl, Z.getValueType());
7873     return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE);
7874   }
7875 
7876   // Not FP, or using SPE? Not a fsel.
7877   if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() ||
7878       Subtarget.hasSPE())
7879     return Op;
7880 
7881   SDNodeFlags Flags = Op.getNode()->getFlags();
7882 
7883   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7884   // presence of infinities.
7885   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7886     switch (CC) {
7887     default:
7888       break;
7889     case ISD::SETOGT:
7890     case ISD::SETGT:
7891       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7892     case ISD::SETOLT:
7893     case ISD::SETLT:
7894       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7895     }
7896   }
7897 
7898   // We might be able to do better than this under some circumstances, but in
7899   // general, fsel-based lowering of select is a finite-math-only optimization.
7900   // For more information, see section F.3 of the 2.06 ISA specification.
7901   // With ISA 3.0
7902   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7903       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7904     return Op;
7905 
7906   // If the RHS of the comparison is a 0.0, we don't need to do the
7907   // subtraction at all.
7908   SDValue Sel1;
7909   if (isFloatingPointZero(RHS))
7910     switch (CC) {
7911     default: break;       // SETUO etc aren't handled by fsel.
7912     case ISD::SETNE:
7913       std::swap(TV, FV);
7914       LLVM_FALLTHROUGH;
7915     case ISD::SETEQ:
7916       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7917         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7918       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7919       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7920         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7921       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7922                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7923     case ISD::SETULT:
7924     case ISD::SETLT:
7925       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7926       LLVM_FALLTHROUGH;
7927     case ISD::SETOGE:
7928     case ISD::SETGE:
7929       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7930         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7931       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7932     case ISD::SETUGT:
7933     case ISD::SETGT:
7934       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7935       LLVM_FALLTHROUGH;
7936     case ISD::SETOLE:
7937     case ISD::SETLE:
7938       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7939         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7940       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7941                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7942     }
7943 
7944   SDValue Cmp;
7945   switch (CC) {
7946   default: break;       // SETUO etc aren't handled by fsel.
7947   case ISD::SETNE:
7948     std::swap(TV, FV);
7949     LLVM_FALLTHROUGH;
7950   case ISD::SETEQ:
7951     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7952     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7953       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7954     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7955     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7956       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7957     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7958                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7959   case ISD::SETULT:
7960   case ISD::SETLT:
7961     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7962     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7963       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7964     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7965   case ISD::SETOGE:
7966   case ISD::SETGE:
7967     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7968     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7969       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7970     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7971   case ISD::SETUGT:
7972   case ISD::SETGT:
7973     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7974     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7975       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7976     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7977   case ISD::SETOLE:
7978   case ISD::SETLE:
7979     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7980     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7981       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7982     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7983   }
7984   return Op;
7985 }
7986 
7987 static unsigned getPPCStrictOpcode(unsigned Opc) {
7988   switch (Opc) {
7989   default:
7990     llvm_unreachable("No strict version of this opcode!");
7991   case PPCISD::FCTIDZ:
7992     return PPCISD::STRICT_FCTIDZ;
7993   case PPCISD::FCTIWZ:
7994     return PPCISD::STRICT_FCTIWZ;
7995   case PPCISD::FCTIDUZ:
7996     return PPCISD::STRICT_FCTIDUZ;
7997   case PPCISD::FCTIWUZ:
7998     return PPCISD::STRICT_FCTIWUZ;
7999   case PPCISD::FCFID:
8000     return PPCISD::STRICT_FCFID;
8001   case PPCISD::FCFIDU:
8002     return PPCISD::STRICT_FCFIDU;
8003   case PPCISD::FCFIDS:
8004     return PPCISD::STRICT_FCFIDS;
8005   case PPCISD::FCFIDUS:
8006     return PPCISD::STRICT_FCFIDUS;
8007   }
8008 }
8009 
8010 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
8011                               const PPCSubtarget &Subtarget) {
8012   SDLoc dl(Op);
8013   bool IsStrict = Op->isStrictFPOpcode();
8014   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8015                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8016 
8017   // TODO: Any other flags to propagate?
8018   SDNodeFlags Flags;
8019   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8020 
8021   // For strict nodes, source is the second operand.
8022   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8023   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8024   assert(Src.getValueType().isFloatingPoint());
8025   if (Src.getValueType() == MVT::f32) {
8026     if (IsStrict) {
8027       Src =
8028           DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
8029                       DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
8030       Chain = Src.getValue(1);
8031     } else
8032       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8033   }
8034   SDValue Conv;
8035   unsigned Opc = ISD::DELETED_NODE;
8036   switch (Op.getSimpleValueType().SimpleTy) {
8037   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8038   case MVT::i32:
8039     Opc = IsSigned ? PPCISD::FCTIWZ
8040                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8041     break;
8042   case MVT::i64:
8043     assert((IsSigned || Subtarget.hasFPCVT()) &&
8044            "i64 FP_TO_UINT is supported only with FPCVT");
8045     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8046   }
8047   if (IsStrict) {
8048     Opc = getPPCStrictOpcode(Opc);
8049     Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
8050                        {Chain, Src}, Flags);
8051   } else {
8052     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8053   }
8054   return Conv;
8055 }
8056 
8057 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8058                                                SelectionDAG &DAG,
8059                                                const SDLoc &dl) const {
8060   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8061   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8062                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8063   bool IsStrict = Op->isStrictFPOpcode();
8064 
8065   // Convert the FP value to an int value through memory.
8066   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8067                   (IsSigned || Subtarget.hasFPCVT());
8068   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8069   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8070   MachinePointerInfo MPI =
8071       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8072 
8073   // Emit a store to the stack slot.
8074   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8075   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8076   if (i32Stack) {
8077     MachineFunction &MF = DAG.getMachineFunction();
8078     Alignment = Align(4);
8079     MachineMemOperand *MMO =
8080         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8081     SDValue Ops[] = { Chain, Tmp, FIPtr };
8082     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8083               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8084   } else
8085     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8086 
8087   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8088   // add in a bias on big endian.
8089   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8090     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8091                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8092     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8093   }
8094 
8095   RLI.Chain = Chain;
8096   RLI.Ptr = FIPtr;
8097   RLI.MPI = MPI;
8098   RLI.Alignment = Alignment;
8099 }
8100 
8101 /// Custom lowers floating point to integer conversions to use
8102 /// the direct move instructions available in ISA 2.07 to avoid the
8103 /// need for load/store combinations.
8104 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8105                                                     SelectionDAG &DAG,
8106                                                     const SDLoc &dl) const {
8107   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8108   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8109   if (Op->isStrictFPOpcode())
8110     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8111   else
8112     return Mov;
8113 }
8114 
8115 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8116                                           const SDLoc &dl) const {
8117   bool IsStrict = Op->isStrictFPOpcode();
8118   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8119                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8120   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8121   EVT SrcVT = Src.getValueType();
8122   EVT DstVT = Op.getValueType();
8123 
8124   // FP to INT conversions are legal for f128.
8125   if (SrcVT == MVT::f128)
8126     return Subtarget.hasP9Vector() ? Op : SDValue();
8127 
8128   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8129   // PPC (the libcall is not available).
8130   if (SrcVT == MVT::ppcf128) {
8131     if (DstVT == MVT::i32) {
8132       // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8133       // set other fast-math flags to FP operations in both strict and
8134       // non-strict cases. (FP_TO_SINT, FSUB)
8135       SDNodeFlags Flags;
8136       Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8137 
8138       if (IsSigned) {
8139         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8140                                  DAG.getIntPtrConstant(0, dl));
8141         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8142                                  DAG.getIntPtrConstant(1, dl));
8143 
8144         // Add the two halves of the long double in round-to-zero mode, and use
8145         // a smaller FP_TO_SINT.
8146         if (IsStrict) {
8147           SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8148                                     DAG.getVTList(MVT::f64, MVT::Other),
8149                                     {Op.getOperand(0), Lo, Hi}, Flags);
8150           return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8151                              DAG.getVTList(MVT::i32, MVT::Other),
8152                              {Res.getValue(1), Res}, Flags);
8153         } else {
8154           SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8155           return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8156         }
8157       } else {
8158         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8159         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8160         SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8161         SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8162         if (IsStrict) {
8163           // Sel = Src < 0x80000000
8164           // FltOfs = select Sel, 0.0, 0x80000000
8165           // IntOfs = select Sel, 0, 0x80000000
8166           // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8167           SDValue Chain = Op.getOperand(0);
8168           EVT SetCCVT =
8169               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8170           EVT DstSetCCVT =
8171               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8172           SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8173                                      Chain, true);
8174           Chain = Sel.getValue(1);
8175 
8176           SDValue FltOfs = DAG.getSelect(
8177               dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8178           Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8179 
8180           SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8181                                     DAG.getVTList(SrcVT, MVT::Other),
8182                                     {Chain, Src, FltOfs}, Flags);
8183           Chain = Val.getValue(1);
8184           SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8185                                      DAG.getVTList(DstVT, MVT::Other),
8186                                      {Chain, Val}, Flags);
8187           Chain = SInt.getValue(1);
8188           SDValue IntOfs = DAG.getSelect(
8189               dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8190           SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8191           return DAG.getMergeValues({Result, Chain}, dl);
8192         } else {
8193           // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8194           // FIXME: generated code sucks.
8195           SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8196           True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8197           True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8198           SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8199           return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8200         }
8201       }
8202     }
8203 
8204     return SDValue();
8205   }
8206 
8207   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8208     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8209 
8210   ReuseLoadInfo RLI;
8211   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8212 
8213   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8214                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8215 }
8216 
8217 // We're trying to insert a regular store, S, and then a load, L. If the
8218 // incoming value, O, is a load, we might just be able to have our load use the
8219 // address used by O. However, we don't know if anything else will store to
8220 // that address before we can load from it. To prevent this situation, we need
8221 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8222 // the same chain operand as O, we create a token factor from the chain results
8223 // of O and L, and we replace all uses of O's chain result with that token
8224 // factor (see spliceIntoChain below for this last part).
8225 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8226                                             ReuseLoadInfo &RLI,
8227                                             SelectionDAG &DAG,
8228                                             ISD::LoadExtType ET) const {
8229   // Conservatively skip reusing for constrained FP nodes.
8230   if (Op->isStrictFPOpcode())
8231     return false;
8232 
8233   SDLoc dl(Op);
8234   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8235                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8236   if (ET == ISD::NON_EXTLOAD &&
8237       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8238       isOperationLegalOrCustom(Op.getOpcode(),
8239                                Op.getOperand(0).getValueType())) {
8240 
8241     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8242     return true;
8243   }
8244 
8245   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8246   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8247       LD->isNonTemporal())
8248     return false;
8249   if (LD->getMemoryVT() != MemVT)
8250     return false;
8251 
8252   // If the result of the load is an illegal type, then we can't build a
8253   // valid chain for reuse since the legalised loads and token factor node that
8254   // ties the legalised loads together uses a different output chain then the
8255   // illegal load.
8256   if (!isTypeLegal(LD->getValueType(0)))
8257     return false;
8258 
8259   RLI.Ptr = LD->getBasePtr();
8260   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8261     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8262            "Non-pre-inc AM on PPC?");
8263     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8264                           LD->getOffset());
8265   }
8266 
8267   RLI.Chain = LD->getChain();
8268   RLI.MPI = LD->getPointerInfo();
8269   RLI.IsDereferenceable = LD->isDereferenceable();
8270   RLI.IsInvariant = LD->isInvariant();
8271   RLI.Alignment = LD->getAlign();
8272   RLI.AAInfo = LD->getAAInfo();
8273   RLI.Ranges = LD->getRanges();
8274 
8275   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8276   return true;
8277 }
8278 
8279 // Given the head of the old chain, ResChain, insert a token factor containing
8280 // it and NewResChain, and make users of ResChain now be users of that token
8281 // factor.
8282 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8283 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8284                                         SDValue NewResChain,
8285                                         SelectionDAG &DAG) const {
8286   if (!ResChain)
8287     return;
8288 
8289   SDLoc dl(NewResChain);
8290 
8291   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8292                            NewResChain, DAG.getUNDEF(MVT::Other));
8293   assert(TF.getNode() != NewResChain.getNode() &&
8294          "A new TF really is required here");
8295 
8296   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8297   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8298 }
8299 
8300 /// Analyze profitability of direct move
8301 /// prefer float load to int load plus direct move
8302 /// when there is no integer use of int load
8303 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8304   SDNode *Origin = Op.getOperand(0).getNode();
8305   if (Origin->getOpcode() != ISD::LOAD)
8306     return true;
8307 
8308   // If there is no LXSIBZX/LXSIHZX, like Power8,
8309   // prefer direct move if the memory size is 1 or 2 bytes.
8310   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8311   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8312     return true;
8313 
8314   for (SDNode::use_iterator UI = Origin->use_begin(),
8315                             UE = Origin->use_end();
8316        UI != UE; ++UI) {
8317 
8318     // Only look at the users of the loaded value.
8319     if (UI.getUse().get().getResNo() != 0)
8320       continue;
8321 
8322     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8323         UI->getOpcode() != ISD::UINT_TO_FP &&
8324         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8325         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8326       return true;
8327   }
8328 
8329   return false;
8330 }
8331 
8332 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8333                               const PPCSubtarget &Subtarget,
8334                               SDValue Chain = SDValue()) {
8335   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8336                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8337   SDLoc dl(Op);
8338 
8339   // TODO: Any other flags to propagate?
8340   SDNodeFlags Flags;
8341   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8342 
8343   // If we have FCFIDS, then use it when converting to single-precision.
8344   // Otherwise, convert to double-precision and then round.
8345   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8346   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8347                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8348   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8349   if (Op->isStrictFPOpcode()) {
8350     if (!Chain)
8351       Chain = Op.getOperand(0);
8352     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8353                        DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8354   } else
8355     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8356 }
8357 
8358 /// Custom lowers integer to floating point conversions to use
8359 /// the direct move instructions available in ISA 2.07 to avoid the
8360 /// need for load/store combinations.
8361 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8362                                                     SelectionDAG &DAG,
8363                                                     const SDLoc &dl) const {
8364   assert((Op.getValueType() == MVT::f32 ||
8365           Op.getValueType() == MVT::f64) &&
8366          "Invalid floating point type as target of conversion");
8367   assert(Subtarget.hasFPCVT() &&
8368          "Int to FP conversions with direct moves require FPCVT");
8369   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8370   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8371   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8372                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8373   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8374   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8375   return convertIntToFP(Op, Mov, DAG, Subtarget);
8376 }
8377 
8378 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8379 
8380   EVT VecVT = Vec.getValueType();
8381   assert(VecVT.isVector() && "Expected a vector type.");
8382   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8383 
8384   EVT EltVT = VecVT.getVectorElementType();
8385   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8386   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8387 
8388   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8389   SmallVector<SDValue, 16> Ops(NumConcat);
8390   Ops[0] = Vec;
8391   SDValue UndefVec = DAG.getUNDEF(VecVT);
8392   for (unsigned i = 1; i < NumConcat; ++i)
8393     Ops[i] = UndefVec;
8394 
8395   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8396 }
8397 
8398 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8399                                                 const SDLoc &dl) const {
8400   bool IsStrict = Op->isStrictFPOpcode();
8401   unsigned Opc = Op.getOpcode();
8402   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8403   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8404           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8405          "Unexpected conversion type");
8406   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8407          "Supports conversions to v2f64/v4f32 only.");
8408 
8409   // TODO: Any other flags to propagate?
8410   SDNodeFlags Flags;
8411   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8412 
8413   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8414   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8415 
8416   SDValue Wide = widenVec(DAG, Src, dl);
8417   EVT WideVT = Wide.getValueType();
8418   unsigned WideNumElts = WideVT.getVectorNumElements();
8419   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8420 
8421   SmallVector<int, 16> ShuffV;
8422   for (unsigned i = 0; i < WideNumElts; ++i)
8423     ShuffV.push_back(i + WideNumElts);
8424 
8425   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8426   int SaveElts = FourEltRes ? 4 : 2;
8427   if (Subtarget.isLittleEndian())
8428     for (int i = 0; i < SaveElts; i++)
8429       ShuffV[i * Stride] = i;
8430   else
8431     for (int i = 1; i <= SaveElts; i++)
8432       ShuffV[i * Stride - 1] = i - 1;
8433 
8434   SDValue ShuffleSrc2 =
8435       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8436   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8437 
8438   SDValue Extend;
8439   if (SignedConv) {
8440     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8441     EVT ExtVT = Src.getValueType();
8442     if (Subtarget.hasP9Altivec())
8443       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8444                                IntermediateVT.getVectorNumElements());
8445 
8446     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8447                          DAG.getValueType(ExtVT));
8448   } else
8449     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8450 
8451   if (IsStrict)
8452     return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8453                        {Op.getOperand(0), Extend}, Flags);
8454 
8455   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8456 }
8457 
8458 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8459                                           SelectionDAG &DAG) const {
8460   SDLoc dl(Op);
8461   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8462                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8463   bool IsStrict = Op->isStrictFPOpcode();
8464   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8465   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8466 
8467   // TODO: Any other flags to propagate?
8468   SDNodeFlags Flags;
8469   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8470 
8471   EVT InVT = Src.getValueType();
8472   EVT OutVT = Op.getValueType();
8473   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8474       isOperationCustom(Op.getOpcode(), InVT))
8475     return LowerINT_TO_FPVector(Op, DAG, dl);
8476 
8477   // Conversions to f128 are legal.
8478   if (Op.getValueType() == MVT::f128)
8479     return Subtarget.hasP9Vector() ? Op : SDValue();
8480 
8481   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8482   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8483     return SDValue();
8484 
8485   if (Src.getValueType() == MVT::i1) {
8486     SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8487                               DAG.getConstantFP(1.0, dl, Op.getValueType()),
8488                               DAG.getConstantFP(0.0, dl, Op.getValueType()));
8489     if (IsStrict)
8490       return DAG.getMergeValues({Sel, Chain}, dl);
8491     else
8492       return Sel;
8493   }
8494 
8495   // If we have direct moves, we can do all the conversion, skip the store/load
8496   // however, without FPCVT we can't do most conversions.
8497   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8498       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8499     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8500 
8501   assert((IsSigned || Subtarget.hasFPCVT()) &&
8502          "UINT_TO_FP is supported only with FPCVT");
8503 
8504   if (Src.getValueType() == MVT::i64) {
8505     SDValue SINT = Src;
8506     // When converting to single-precision, we actually need to convert
8507     // to double-precision first and then round to single-precision.
8508     // To avoid double-rounding effects during that operation, we have
8509     // to prepare the input operand.  Bits that might be truncated when
8510     // converting to double-precision are replaced by a bit that won't
8511     // be lost at this stage, but is below the single-precision rounding
8512     // position.
8513     //
8514     // However, if -enable-unsafe-fp-math is in effect, accept double
8515     // rounding to avoid the extra overhead.
8516     if (Op.getValueType() == MVT::f32 &&
8517         !Subtarget.hasFPCVT() &&
8518         !DAG.getTarget().Options.UnsafeFPMath) {
8519 
8520       // Twiddle input to make sure the low 11 bits are zero.  (If this
8521       // is the case, we are guaranteed the value will fit into the 53 bit
8522       // mantissa of an IEEE double-precision value without rounding.)
8523       // If any of those low 11 bits were not zero originally, make sure
8524       // bit 12 (value 2048) is set instead, so that the final rounding
8525       // to single-precision gets the correct result.
8526       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8527                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8528       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8529                           Round, DAG.getConstant(2047, dl, MVT::i64));
8530       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8531       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8532                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8533 
8534       // However, we cannot use that value unconditionally: if the magnitude
8535       // of the input value is small, the bit-twiddling we did above might
8536       // end up visibly changing the output.  Fortunately, in that case, we
8537       // don't need to twiddle bits since the original input will convert
8538       // exactly to double-precision floating-point already.  Therefore,
8539       // construct a conditional to use the original value if the top 11
8540       // bits are all sign-bit copies, and use the rounded value computed
8541       // above otherwise.
8542       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8543                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8544       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8545                          Cond, DAG.getConstant(1, dl, MVT::i64));
8546       Cond = DAG.getSetCC(
8547           dl,
8548           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8549           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8550 
8551       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8552     }
8553 
8554     ReuseLoadInfo RLI;
8555     SDValue Bits;
8556 
8557     MachineFunction &MF = DAG.getMachineFunction();
8558     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8559       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8560                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8561       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8562     } else if (Subtarget.hasLFIWAX() &&
8563                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8564       MachineMemOperand *MMO =
8565         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8566                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8567       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8568       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8569                                      DAG.getVTList(MVT::f64, MVT::Other),
8570                                      Ops, MVT::i32, MMO);
8571       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8572     } else if (Subtarget.hasFPCVT() &&
8573                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8574       MachineMemOperand *MMO =
8575         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8576                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8577       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8578       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8579                                      DAG.getVTList(MVT::f64, MVT::Other),
8580                                      Ops, MVT::i32, MMO);
8581       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8582     } else if (((Subtarget.hasLFIWAX() &&
8583                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8584                 (Subtarget.hasFPCVT() &&
8585                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8586                SINT.getOperand(0).getValueType() == MVT::i32) {
8587       MachineFrameInfo &MFI = MF.getFrameInfo();
8588       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8589 
8590       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8591       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8592 
8593       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8594                                    MachinePointerInfo::getFixedStack(
8595                                        DAG.getMachineFunction(), FrameIdx));
8596       Chain = Store;
8597 
8598       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8599              "Expected an i32 store");
8600 
8601       RLI.Ptr = FIdx;
8602       RLI.Chain = Chain;
8603       RLI.MPI =
8604           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8605       RLI.Alignment = Align(4);
8606 
8607       MachineMemOperand *MMO =
8608         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8609                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8610       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8611       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8612                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8613                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8614                                      Ops, MVT::i32, MMO);
8615       Chain = Bits.getValue(1);
8616     } else
8617       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8618 
8619     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8620     if (IsStrict)
8621       Chain = FP.getValue(1);
8622 
8623     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8624       if (IsStrict)
8625         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8626                          DAG.getVTList(MVT::f32, MVT::Other),
8627                          {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8628       else
8629         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8630                          DAG.getIntPtrConstant(0, dl));
8631     }
8632     return FP;
8633   }
8634 
8635   assert(Src.getValueType() == MVT::i32 &&
8636          "Unhandled INT_TO_FP type in custom expander!");
8637   // Since we only generate this in 64-bit mode, we can take advantage of
8638   // 64-bit registers.  In particular, sign extend the input value into the
8639   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8640   // then lfd it and fcfid it.
8641   MachineFunction &MF = DAG.getMachineFunction();
8642   MachineFrameInfo &MFI = MF.getFrameInfo();
8643   EVT PtrVT = getPointerTy(MF.getDataLayout());
8644 
8645   SDValue Ld;
8646   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8647     ReuseLoadInfo RLI;
8648     bool ReusingLoad;
8649     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8650       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8651       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8652 
8653       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8654                                    MachinePointerInfo::getFixedStack(
8655                                        DAG.getMachineFunction(), FrameIdx));
8656       Chain = Store;
8657 
8658       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8659              "Expected an i32 store");
8660 
8661       RLI.Ptr = FIdx;
8662       RLI.Chain = Chain;
8663       RLI.MPI =
8664           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8665       RLI.Alignment = Align(4);
8666     }
8667 
8668     MachineMemOperand *MMO =
8669       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8670                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8671     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8672     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8673                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8674                                  MVT::i32, MMO);
8675     Chain = Ld.getValue(1);
8676     if (ReusingLoad)
8677       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8678   } else {
8679     assert(Subtarget.isPPC64() &&
8680            "i32->FP without LFIWAX supported only on PPC64");
8681 
8682     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8683     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8684 
8685     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8686 
8687     // STD the extended value into the stack slot.
8688     SDValue Store = DAG.getStore(
8689         Chain, dl, Ext64, FIdx,
8690         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8691     Chain = Store;
8692 
8693     // Load the value as a double.
8694     Ld = DAG.getLoad(
8695         MVT::f64, dl, Chain, FIdx,
8696         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8697     Chain = Ld.getValue(1);
8698   }
8699 
8700   // FCFID it and return it.
8701   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8702   if (IsStrict)
8703     Chain = FP.getValue(1);
8704   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8705     if (IsStrict)
8706       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8707                        DAG.getVTList(MVT::f32, MVT::Other),
8708                        {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8709     else
8710       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8711                        DAG.getIntPtrConstant(0, dl));
8712   }
8713   return FP;
8714 }
8715 
8716 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8717                                             SelectionDAG &DAG) const {
8718   SDLoc dl(Op);
8719   /*
8720    The rounding mode is in bits 30:31 of FPSR, and has the following
8721    settings:
8722      00 Round to nearest
8723      01 Round to 0
8724      10 Round to +inf
8725      11 Round to -inf
8726 
8727   FLT_ROUNDS, on the other hand, expects the following:
8728     -1 Undefined
8729      0 Round to 0
8730      1 Round to nearest
8731      2 Round to +inf
8732      3 Round to -inf
8733 
8734   To perform the conversion, we do:
8735     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8736   */
8737 
8738   MachineFunction &MF = DAG.getMachineFunction();
8739   EVT VT = Op.getValueType();
8740   EVT PtrVT = getPointerTy(MF.getDataLayout());
8741 
8742   // Save FP Control Word to register
8743   SDValue Chain = Op.getOperand(0);
8744   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8745   Chain = MFFS.getValue(1);
8746 
8747   SDValue CWD;
8748   if (isTypeLegal(MVT::i64)) {
8749     CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
8750                       DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
8751   } else {
8752     // Save FP register to stack slot
8753     int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8754     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8755     Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8756 
8757     // Load FP Control Word from low 32 bits of stack slot.
8758     assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) &&
8759            "Stack slot adjustment is valid only on big endian subtargets!");
8760     SDValue Four = DAG.getConstant(4, dl, PtrVT);
8761     SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8762     CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8763     Chain = CWD.getValue(1);
8764   }
8765 
8766   // Transform as necessary
8767   SDValue CWD1 =
8768     DAG.getNode(ISD::AND, dl, MVT::i32,
8769                 CWD, DAG.getConstant(3, dl, MVT::i32));
8770   SDValue CWD2 =
8771     DAG.getNode(ISD::SRL, dl, MVT::i32,
8772                 DAG.getNode(ISD::AND, dl, MVT::i32,
8773                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8774                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8775                             DAG.getConstant(3, dl, MVT::i32)),
8776                 DAG.getConstant(1, dl, MVT::i32));
8777 
8778   SDValue RetVal =
8779     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8780 
8781   RetVal =
8782       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8783                   dl, VT, RetVal);
8784 
8785   return DAG.getMergeValues({RetVal, Chain}, dl);
8786 }
8787 
8788 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8789   EVT VT = Op.getValueType();
8790   unsigned BitWidth = VT.getSizeInBits();
8791   SDLoc dl(Op);
8792   assert(Op.getNumOperands() == 3 &&
8793          VT == Op.getOperand(1).getValueType() &&
8794          "Unexpected SHL!");
8795 
8796   // Expand into a bunch of logical ops.  Note that these ops
8797   // depend on the PPC behavior for oversized shift amounts.
8798   SDValue Lo = Op.getOperand(0);
8799   SDValue Hi = Op.getOperand(1);
8800   SDValue Amt = Op.getOperand(2);
8801   EVT AmtVT = Amt.getValueType();
8802 
8803   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8804                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8805   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8806   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8807   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8808   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8809                              DAG.getConstant(-BitWidth, dl, AmtVT));
8810   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8811   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8812   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8813   SDValue OutOps[] = { OutLo, OutHi };
8814   return DAG.getMergeValues(OutOps, dl);
8815 }
8816 
8817 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8818   EVT VT = Op.getValueType();
8819   SDLoc dl(Op);
8820   unsigned BitWidth = VT.getSizeInBits();
8821   assert(Op.getNumOperands() == 3 &&
8822          VT == Op.getOperand(1).getValueType() &&
8823          "Unexpected SRL!");
8824 
8825   // Expand into a bunch of logical ops.  Note that these ops
8826   // depend on the PPC behavior for oversized shift amounts.
8827   SDValue Lo = Op.getOperand(0);
8828   SDValue Hi = Op.getOperand(1);
8829   SDValue Amt = Op.getOperand(2);
8830   EVT AmtVT = Amt.getValueType();
8831 
8832   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8833                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8834   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8835   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8836   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8837   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8838                              DAG.getConstant(-BitWidth, dl, AmtVT));
8839   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8840   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8841   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8842   SDValue OutOps[] = { OutLo, OutHi };
8843   return DAG.getMergeValues(OutOps, dl);
8844 }
8845 
8846 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8847   SDLoc dl(Op);
8848   EVT VT = Op.getValueType();
8849   unsigned BitWidth = VT.getSizeInBits();
8850   assert(Op.getNumOperands() == 3 &&
8851          VT == Op.getOperand(1).getValueType() &&
8852          "Unexpected SRA!");
8853 
8854   // Expand into a bunch of logical ops, followed by a select_cc.
8855   SDValue Lo = Op.getOperand(0);
8856   SDValue Hi = Op.getOperand(1);
8857   SDValue Amt = Op.getOperand(2);
8858   EVT AmtVT = Amt.getValueType();
8859 
8860   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8861                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8862   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8863   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8864   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8865   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8866                              DAG.getConstant(-BitWidth, dl, AmtVT));
8867   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8868   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8869   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8870                                   Tmp4, Tmp6, ISD::SETLE);
8871   SDValue OutOps[] = { OutLo, OutHi };
8872   return DAG.getMergeValues(OutOps, dl);
8873 }
8874 
8875 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8876                                             SelectionDAG &DAG) const {
8877   SDLoc dl(Op);
8878   EVT VT = Op.getValueType();
8879   unsigned BitWidth = VT.getSizeInBits();
8880 
8881   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8882   SDValue X = Op.getOperand(0);
8883   SDValue Y = Op.getOperand(1);
8884   SDValue Z = Op.getOperand(2);
8885   EVT AmtVT = Z.getValueType();
8886 
8887   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8888   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8889   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8890   // on PowerPC shift by BW being well defined.
8891   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8892                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8893   SDValue SubZ =
8894       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8895   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8896   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8897   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8898 }
8899 
8900 //===----------------------------------------------------------------------===//
8901 // Vector related lowering.
8902 //
8903 
8904 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8905 /// element size of SplatSize. Cast the result to VT.
8906 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8907                                       SelectionDAG &DAG, const SDLoc &dl) {
8908   static const MVT VTys[] = { // canonical VT to use for each size.
8909     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8910   };
8911 
8912   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8913 
8914   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8915   if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
8916     SplatSize = 1;
8917     Val = 0xFF;
8918   }
8919 
8920   EVT CanonicalVT = VTys[SplatSize-1];
8921 
8922   // Build a canonical splat for this value.
8923   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8924 }
8925 
8926 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8927 /// specified intrinsic ID.
8928 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8929                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8930   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8931   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8932                      DAG.getConstant(IID, dl, MVT::i32), Op);
8933 }
8934 
8935 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8936 /// specified intrinsic ID.
8937 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8938                                 SelectionDAG &DAG, const SDLoc &dl,
8939                                 EVT DestVT = MVT::Other) {
8940   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8941   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8942                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8943 }
8944 
8945 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8946 /// specified intrinsic ID.
8947 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8948                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8949                                 EVT DestVT = MVT::Other) {
8950   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8951   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8952                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8953 }
8954 
8955 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8956 /// amount.  The result has the specified value type.
8957 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8958                            SelectionDAG &DAG, const SDLoc &dl) {
8959   // Force LHS/RHS to be the right type.
8960   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8961   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8962 
8963   int Ops[16];
8964   for (unsigned i = 0; i != 16; ++i)
8965     Ops[i] = i + Amt;
8966   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8967   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8968 }
8969 
8970 /// Do we have an efficient pattern in a .td file for this node?
8971 ///
8972 /// \param V - pointer to the BuildVectorSDNode being matched
8973 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8974 ///
8975 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8976 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8977 /// the opposite is true (expansion is beneficial) are:
8978 /// - The node builds a vector out of integers that are not 32 or 64-bits
8979 /// - The node builds a vector out of constants
8980 /// - The node is a "load-and-splat"
8981 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8982 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8983                                             bool HasDirectMove,
8984                                             bool HasP8Vector) {
8985   EVT VecVT = V->getValueType(0);
8986   bool RightType = VecVT == MVT::v2f64 ||
8987     (HasP8Vector && VecVT == MVT::v4f32) ||
8988     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8989   if (!RightType)
8990     return false;
8991 
8992   bool IsSplat = true;
8993   bool IsLoad = false;
8994   SDValue Op0 = V->getOperand(0);
8995 
8996   // This function is called in a block that confirms the node is not a constant
8997   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8998   // different constants.
8999   if (V->isConstant())
9000     return false;
9001   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9002     if (V->getOperand(i).isUndef())
9003       return false;
9004     // We want to expand nodes that represent load-and-splat even if the
9005     // loaded value is a floating point truncation or conversion to int.
9006     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9007         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9008          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9009         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9010          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9011         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9012          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9013       IsLoad = true;
9014     // If the operands are different or the input is not a load and has more
9015     // uses than just this BV node, then it isn't a splat.
9016     if (V->getOperand(i) != Op0 ||
9017         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9018       IsSplat = false;
9019   }
9020   return !(IsSplat && IsLoad);
9021 }
9022 
9023 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9024 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9025 
9026   SDLoc dl(Op);
9027   SDValue Op0 = Op->getOperand(0);
9028 
9029   if ((Op.getValueType() != MVT::f128) ||
9030       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9031       (Op0.getOperand(0).getValueType() != MVT::i64) ||
9032       (Op0.getOperand(1).getValueType() != MVT::i64))
9033     return SDValue();
9034 
9035   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9036                      Op0.getOperand(1));
9037 }
9038 
9039 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9040   const SDValue *InputLoad = &Op;
9041   if (InputLoad->getOpcode() == ISD::BITCAST)
9042     InputLoad = &InputLoad->getOperand(0);
9043   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9044       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9045     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9046     InputLoad = &InputLoad->getOperand(0);
9047   }
9048   if (InputLoad->getOpcode() != ISD::LOAD)
9049     return nullptr;
9050   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9051   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9052 }
9053 
9054 // Convert the argument APFloat to a single precision APFloat if there is no
9055 // loss in information during the conversion to single precision APFloat and the
9056 // resulting number is not a denormal number. Return true if successful.
9057 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9058   APFloat APFloatToConvert = ArgAPFloat;
9059   bool LosesInfo = true;
9060   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9061                            &LosesInfo);
9062   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9063   if (Success)
9064     ArgAPFloat = APFloatToConvert;
9065   return Success;
9066 }
9067 
9068 // Bitcast the argument APInt to a double and convert it to a single precision
9069 // APFloat, bitcast the APFloat to an APInt and assign it to the original
9070 // argument if there is no loss in information during the conversion from
9071 // double to single precision APFloat and the resulting number is not a denormal
9072 // number. Return true if successful.
9073 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9074   double DpValue = ArgAPInt.bitsToDouble();
9075   APFloat APFloatDp(DpValue);
9076   bool Success = convertToNonDenormSingle(APFloatDp);
9077   if (Success)
9078     ArgAPInt = APFloatDp.bitcastToAPInt();
9079   return Success;
9080 }
9081 
9082 // Nondestructive check for convertTonNonDenormSingle.
9083 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) {
9084   // Only convert if it loses info, since XXSPLTIDP should
9085   // handle the other case.
9086   APFloat APFloatToConvert = ArgAPFloat;
9087   bool LosesInfo = true;
9088   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9089                            &LosesInfo);
9090 
9091   return (!LosesInfo && !APFloatToConvert.isDenormal());
9092 }
9093 
9094 static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op,
9095                              unsigned &Opcode) {
9096   LoadSDNode *InputNode = dyn_cast<LoadSDNode>(Op.getOperand(0));
9097   if (!InputNode || !Subtarget.hasVSX() || !ISD::isUNINDEXEDLoad(InputNode))
9098     return false;
9099 
9100   EVT Ty = Op->getValueType(0);
9101   // For v2f64, v4f32 and v4i32 types, we require the load to be non-extending
9102   // as we cannot handle extending loads for these types.
9103   if ((Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32) &&
9104       ISD::isNON_EXTLoad(InputNode))
9105     return true;
9106 
9107   EVT MemVT = InputNode->getMemoryVT();
9108   // For v8i16 and v16i8 types, extending loads can be handled as long as the
9109   // memory VT is the same vector element VT type.
9110   // The loads feeding into the v8i16 and v16i8 types will be extending because
9111   // scalar i8/i16 are not legal types.
9112   if ((Ty == MVT::v8i16 || Ty == MVT::v16i8) && ISD::isEXTLoad(InputNode) &&
9113       (MemVT == Ty.getVectorElementType()))
9114     return true;
9115 
9116   if (Ty == MVT::v2i64) {
9117     // Check the extend type, when the input type is i32, and the output vector
9118     // type is v2i64.
9119     if (MemVT == MVT::i32) {
9120       if (ISD::isZEXTLoad(InputNode))
9121         Opcode = PPCISD::ZEXT_LD_SPLAT;
9122       if (ISD::isSEXTLoad(InputNode))
9123         Opcode = PPCISD::SEXT_LD_SPLAT;
9124     }
9125     return true;
9126   }
9127   return false;
9128 }
9129 
9130 // If this is a case we can't handle, return null and let the default
9131 // expansion code take care of it.  If we CAN select this case, and if it
9132 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9133 // this case more efficiently than a constant pool load, lower it to the
9134 // sequence of ops that should be used.
9135 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9136                                              SelectionDAG &DAG) const {
9137   SDLoc dl(Op);
9138   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9139   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9140 
9141   // Check if this is a splat of a constant value.
9142   APInt APSplatBits, APSplatUndef;
9143   unsigned SplatBitSize;
9144   bool HasAnyUndefs;
9145   bool BVNIsConstantSplat =
9146       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9147                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9148 
9149   // If it is a splat of a double, check if we can shrink it to a 32 bit
9150   // non-denormal float which when converted back to double gives us the same
9151   // double. This is to exploit the XXSPLTIDP instruction.
9152   // If we lose precision, we use XXSPLTI32DX.
9153   if (BVNIsConstantSplat && (SplatBitSize == 64) &&
9154       Subtarget.hasPrefixInstrs()) {
9155     // Check the type first to short-circuit so we don't modify APSplatBits if
9156     // this block isn't executed.
9157     if ((Op->getValueType(0) == MVT::v2f64) &&
9158         convertToNonDenormSingle(APSplatBits)) {
9159       SDValue SplatNode = DAG.getNode(
9160           PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9161           DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9162       return DAG.getBitcast(Op.getValueType(), SplatNode);
9163     } else {
9164       // We may lose precision, so we have to use XXSPLTI32DX.
9165 
9166       uint32_t Hi =
9167           (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32);
9168       uint32_t Lo =
9169           (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF);
9170       SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
9171 
9172       if (!Hi || !Lo)
9173         // If either load is 0, then we should generate XXLXOR to set to 0.
9174         SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
9175 
9176       if (Hi)
9177         SplatNode = DAG.getNode(
9178             PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9179             DAG.getTargetConstant(0, dl, MVT::i32),
9180             DAG.getTargetConstant(Hi, dl, MVT::i32));
9181 
9182       if (Lo)
9183         SplatNode =
9184             DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9185                         DAG.getTargetConstant(1, dl, MVT::i32),
9186                         DAG.getTargetConstant(Lo, dl, MVT::i32));
9187 
9188       return DAG.getBitcast(Op.getValueType(), SplatNode);
9189     }
9190   }
9191 
9192   if (!BVNIsConstantSplat || SplatBitSize > 32) {
9193     unsigned NewOpcode = PPCISD::LD_SPLAT;
9194 
9195     // Handle load-and-splat patterns as we have instructions that will do this
9196     // in one go.
9197     if (DAG.isSplatValue(Op, true) &&
9198         isValidSplatLoad(Subtarget, Op, NewOpcode)) {
9199       const SDValue *InputLoad = &Op.getOperand(0);
9200       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9201 
9202       // If the input load is an extending load, it will be an i32 -> i64
9203       // extending load and isValidSplatLoad() will update NewOpcode.
9204       unsigned MemorySize = LD->getMemoryVT().getScalarSizeInBits();
9205       unsigned ElementSize =
9206           MemorySize * ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2);
9207 
9208       assert(((ElementSize == 2 * MemorySize)
9209                   ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT ||
9210                      NewOpcode == PPCISD::SEXT_LD_SPLAT)
9211                   : (NewOpcode == PPCISD::LD_SPLAT)) &&
9212              "Unmatched element size and opcode!\n");
9213 
9214       // Checking for a single use of this load, we have to check for vector
9215       // width (128 bits) / ElementSize uses (since each operand of the
9216       // BUILD_VECTOR is a separate use of the value.
9217       unsigned NumUsesOfInputLD = 128 / ElementSize;
9218       for (SDValue BVInOp : Op->ops())
9219         if (BVInOp.isUndef())
9220           NumUsesOfInputLD--;
9221 
9222       // Exclude somes case where LD_SPLAT is worse than scalar_to_vector:
9223       // Below cases should also happen for "lfiwzx/lfiwax + LE target + index
9224       // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index
9225       // 15", but funciton IsValidSplatLoad() now will only return true when
9226       // the data at index 0 is not nullptr. So we will not get into trouble for
9227       // these cases.
9228       //
9229       // case 1 - lfiwzx/lfiwax
9230       // 1.1: load result is i32 and is sign/zero extend to i64;
9231       // 1.2: build a v2i64 vector type with above loaded value;
9232       // 1.3: the vector has only one value at index 0, others are all undef;
9233       // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute.
9234       if (NumUsesOfInputLD == 1 &&
9235           (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT &&
9236            !Subtarget.isLittleEndian() && Subtarget.hasVSX() &&
9237            Subtarget.hasLFIWAX()))
9238         return SDValue();
9239 
9240       // case 2 - lxvr[hb]x
9241       // 2.1: load result is at most i16;
9242       // 2.2: build a vector with above loaded value;
9243       // 2.3: the vector has only one value at index 0, others are all undef;
9244       // 2.4: on LE target, so that lxvr[hb]x does not need any permute.
9245       if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() &&
9246           Subtarget.isISA3_1() && ElementSize <= 16)
9247         return SDValue();
9248 
9249       assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
9250       if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
9251           Subtarget.hasVSX()) {
9252         SDValue Ops[] = {
9253           LD->getChain(),    // Chain
9254           LD->getBasePtr(),  // Ptr
9255           DAG.getValueType(Op.getValueType()) // VT
9256         };
9257         SDValue LdSplt = DAG.getMemIntrinsicNode(
9258             NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops,
9259             LD->getMemoryVT(), LD->getMemOperand());
9260         // Replace all uses of the output chain of the original load with the
9261         // output chain of the new load.
9262         DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
9263                                       LdSplt.getValue(1));
9264         return LdSplt;
9265       }
9266     }
9267 
9268     // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
9269     // 32-bits can be lowered to VSX instructions under certain conditions.
9270     // Without VSX, there is no pattern more efficient than expanding the node.
9271     if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
9272         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9273                                         Subtarget.hasP8Vector()))
9274       return Op;
9275     return SDValue();
9276   }
9277 
9278   uint64_t SplatBits = APSplatBits.getZExtValue();
9279   uint64_t SplatUndef = APSplatUndef.getZExtValue();
9280   unsigned SplatSize = SplatBitSize / 8;
9281 
9282   // First, handle single instruction cases.
9283 
9284   // All zeros?
9285   if (SplatBits == 0) {
9286     // Canonicalize all zero vectors to be v4i32.
9287     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9288       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9289       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9290     }
9291     return Op;
9292   }
9293 
9294   // We have XXSPLTIW for constant splats four bytes wide.
9295   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9296   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9297   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9298   // turned into a 4-byte splat of 0xABABABAB.
9299   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9300     return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
9301                                   Op.getValueType(), DAG, dl);
9302 
9303   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9304     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9305                                   dl);
9306 
9307   // We have XXSPLTIB for constant splats one byte wide.
9308   if (Subtarget.hasP9Vector() && SplatSize == 1)
9309     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9310                                   dl);
9311 
9312   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9313   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9314                     (32-SplatBitSize));
9315   if (SextVal >= -16 && SextVal <= 15)
9316     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9317                                   dl);
9318 
9319   // Two instruction sequences.
9320 
9321   // If this value is in the range [-32,30] and is even, use:
9322   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9323   // If this value is in the range [17,31] and is odd, use:
9324   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9325   // If this value is in the range [-31,-17] and is odd, use:
9326   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9327   // Note the last two are three-instruction sequences.
9328   if (SextVal >= -32 && SextVal <= 31) {
9329     // To avoid having these optimizations undone by constant folding,
9330     // we convert to a pseudo that will be expanded later into one of
9331     // the above forms.
9332     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9333     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9334               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9335     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9336     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9337     if (VT == Op.getValueType())
9338       return RetVal;
9339     else
9340       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9341   }
9342 
9343   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9344   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9345   // for fneg/fabs.
9346   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9347     // Make -1 and vspltisw -1:
9348     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9349 
9350     // Make the VSLW intrinsic, computing 0x8000_0000.
9351     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9352                                    OnesV, DAG, dl);
9353 
9354     // xor by OnesV to invert it.
9355     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9356     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9357   }
9358 
9359   // Check to see if this is a wide variety of vsplti*, binop self cases.
9360   static const signed char SplatCsts[] = {
9361     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9362     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9363   };
9364 
9365   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9366     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9367     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9368     int i = SplatCsts[idx];
9369 
9370     // Figure out what shift amount will be used by altivec if shifted by i in
9371     // this splat size.
9372     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9373 
9374     // vsplti + shl self.
9375     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9376       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9377       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9378         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9379         Intrinsic::ppc_altivec_vslw
9380       };
9381       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9382       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9383     }
9384 
9385     // vsplti + srl self.
9386     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9387       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9388       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9389         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9390         Intrinsic::ppc_altivec_vsrw
9391       };
9392       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9393       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9394     }
9395 
9396     // vsplti + rol self.
9397     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9398                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9399       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9400       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9401         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9402         Intrinsic::ppc_altivec_vrlw
9403       };
9404       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9405       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9406     }
9407 
9408     // t = vsplti c, result = vsldoi t, t, 1
9409     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9410       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9411       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9412       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9413     }
9414     // t = vsplti c, result = vsldoi t, t, 2
9415     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9416       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9417       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9418       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9419     }
9420     // t = vsplti c, result = vsldoi t, t, 3
9421     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9422       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9423       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9424       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9425     }
9426   }
9427 
9428   return SDValue();
9429 }
9430 
9431 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9432 /// the specified operations to build the shuffle.
9433 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9434                                       SDValue RHS, SelectionDAG &DAG,
9435                                       const SDLoc &dl) {
9436   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9437   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9438   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9439 
9440   enum {
9441     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9442     OP_VMRGHW,
9443     OP_VMRGLW,
9444     OP_VSPLTISW0,
9445     OP_VSPLTISW1,
9446     OP_VSPLTISW2,
9447     OP_VSPLTISW3,
9448     OP_VSLDOI4,
9449     OP_VSLDOI8,
9450     OP_VSLDOI12
9451   };
9452 
9453   if (OpNum == OP_COPY) {
9454     if (LHSID == (1*9+2)*9+3) return LHS;
9455     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9456     return RHS;
9457   }
9458 
9459   SDValue OpLHS, OpRHS;
9460   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9461   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9462 
9463   int ShufIdxs[16];
9464   switch (OpNum) {
9465   default: llvm_unreachable("Unknown i32 permute!");
9466   case OP_VMRGHW:
9467     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9468     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9469     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9470     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9471     break;
9472   case OP_VMRGLW:
9473     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9474     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9475     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9476     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9477     break;
9478   case OP_VSPLTISW0:
9479     for (unsigned i = 0; i != 16; ++i)
9480       ShufIdxs[i] = (i&3)+0;
9481     break;
9482   case OP_VSPLTISW1:
9483     for (unsigned i = 0; i != 16; ++i)
9484       ShufIdxs[i] = (i&3)+4;
9485     break;
9486   case OP_VSPLTISW2:
9487     for (unsigned i = 0; i != 16; ++i)
9488       ShufIdxs[i] = (i&3)+8;
9489     break;
9490   case OP_VSPLTISW3:
9491     for (unsigned i = 0; i != 16; ++i)
9492       ShufIdxs[i] = (i&3)+12;
9493     break;
9494   case OP_VSLDOI4:
9495     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9496   case OP_VSLDOI8:
9497     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9498   case OP_VSLDOI12:
9499     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9500   }
9501   EVT VT = OpLHS.getValueType();
9502   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9503   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9504   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9505   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9506 }
9507 
9508 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9509 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9510 /// SDValue.
9511 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9512                                            SelectionDAG &DAG) const {
9513   const unsigned BytesInVector = 16;
9514   bool IsLE = Subtarget.isLittleEndian();
9515   SDLoc dl(N);
9516   SDValue V1 = N->getOperand(0);
9517   SDValue V2 = N->getOperand(1);
9518   unsigned ShiftElts = 0, InsertAtByte = 0;
9519   bool Swap = false;
9520 
9521   // Shifts required to get the byte we want at element 7.
9522   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9523                                    0, 15, 14, 13, 12, 11, 10, 9};
9524   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9525                                 1, 2,  3,  4,  5,  6,  7,  8};
9526 
9527   ArrayRef<int> Mask = N->getMask();
9528   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9529 
9530   // For each mask element, find out if we're just inserting something
9531   // from V2 into V1 or vice versa.
9532   // Possible permutations inserting an element from V2 into V1:
9533   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9534   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9535   //   ...
9536   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9537   // Inserting from V1 into V2 will be similar, except mask range will be
9538   // [16,31].
9539 
9540   bool FoundCandidate = false;
9541   // If both vector operands for the shuffle are the same vector, the mask
9542   // will contain only elements from the first one and the second one will be
9543   // undef.
9544   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9545   // Go through the mask of half-words to find an element that's being moved
9546   // from one vector to the other.
9547   for (unsigned i = 0; i < BytesInVector; ++i) {
9548     unsigned CurrentElement = Mask[i];
9549     // If 2nd operand is undefined, we should only look for element 7 in the
9550     // Mask.
9551     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9552       continue;
9553 
9554     bool OtherElementsInOrder = true;
9555     // Examine the other elements in the Mask to see if they're in original
9556     // order.
9557     for (unsigned j = 0; j < BytesInVector; ++j) {
9558       if (j == i)
9559         continue;
9560       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9561       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9562       // in which we always assume we're always picking from the 1st operand.
9563       int MaskOffset =
9564           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9565       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9566         OtherElementsInOrder = false;
9567         break;
9568       }
9569     }
9570     // If other elements are in original order, we record the number of shifts
9571     // we need to get the element we want into element 7. Also record which byte
9572     // in the vector we should insert into.
9573     if (OtherElementsInOrder) {
9574       // If 2nd operand is undefined, we assume no shifts and no swapping.
9575       if (V2.isUndef()) {
9576         ShiftElts = 0;
9577         Swap = false;
9578       } else {
9579         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9580         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9581                          : BigEndianShifts[CurrentElement & 0xF];
9582         Swap = CurrentElement < BytesInVector;
9583       }
9584       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9585       FoundCandidate = true;
9586       break;
9587     }
9588   }
9589 
9590   if (!FoundCandidate)
9591     return SDValue();
9592 
9593   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9594   // optionally with VECSHL if shift is required.
9595   if (Swap)
9596     std::swap(V1, V2);
9597   if (V2.isUndef())
9598     V2 = V1;
9599   if (ShiftElts) {
9600     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9601                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9602     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9603                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9604   }
9605   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9606                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9607 }
9608 
9609 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9610 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9611 /// SDValue.
9612 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9613                                            SelectionDAG &DAG) const {
9614   const unsigned NumHalfWords = 8;
9615   const unsigned BytesInVector = NumHalfWords * 2;
9616   // Check that the shuffle is on half-words.
9617   if (!isNByteElemShuffleMask(N, 2, 1))
9618     return SDValue();
9619 
9620   bool IsLE = Subtarget.isLittleEndian();
9621   SDLoc dl(N);
9622   SDValue V1 = N->getOperand(0);
9623   SDValue V2 = N->getOperand(1);
9624   unsigned ShiftElts = 0, InsertAtByte = 0;
9625   bool Swap = false;
9626 
9627   // Shifts required to get the half-word we want at element 3.
9628   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9629   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9630 
9631   uint32_t Mask = 0;
9632   uint32_t OriginalOrderLow = 0x1234567;
9633   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9634   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9635   // 32-bit space, only need 4-bit nibbles per element.
9636   for (unsigned i = 0; i < NumHalfWords; ++i) {
9637     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9638     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9639   }
9640 
9641   // For each mask element, find out if we're just inserting something
9642   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9643   // from V2 into V1:
9644   //   X, 1, 2, 3, 4, 5, 6, 7
9645   //   0, X, 2, 3, 4, 5, 6, 7
9646   //   0, 1, X, 3, 4, 5, 6, 7
9647   //   0, 1, 2, X, 4, 5, 6, 7
9648   //   0, 1, 2, 3, X, 5, 6, 7
9649   //   0, 1, 2, 3, 4, X, 6, 7
9650   //   0, 1, 2, 3, 4, 5, X, 7
9651   //   0, 1, 2, 3, 4, 5, 6, X
9652   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9653 
9654   bool FoundCandidate = false;
9655   // Go through the mask of half-words to find an element that's being moved
9656   // from one vector to the other.
9657   for (unsigned i = 0; i < NumHalfWords; ++i) {
9658     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9659     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9660     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9661     uint32_t TargetOrder = 0x0;
9662 
9663     // If both vector operands for the shuffle are the same vector, the mask
9664     // will contain only elements from the first one and the second one will be
9665     // undef.
9666     if (V2.isUndef()) {
9667       ShiftElts = 0;
9668       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9669       TargetOrder = OriginalOrderLow;
9670       Swap = false;
9671       // Skip if not the correct element or mask of other elements don't equal
9672       // to our expected order.
9673       if (MaskOneElt == VINSERTHSrcElem &&
9674           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9675         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9676         FoundCandidate = true;
9677         break;
9678       }
9679     } else { // If both operands are defined.
9680       // Target order is [8,15] if the current mask is between [0,7].
9681       TargetOrder =
9682           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9683       // Skip if mask of other elements don't equal our expected order.
9684       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9685         // We only need the last 3 bits for the number of shifts.
9686         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9687                          : BigEndianShifts[MaskOneElt & 0x7];
9688         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9689         Swap = MaskOneElt < NumHalfWords;
9690         FoundCandidate = true;
9691         break;
9692       }
9693     }
9694   }
9695 
9696   if (!FoundCandidate)
9697     return SDValue();
9698 
9699   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9700   // optionally with VECSHL if shift is required.
9701   if (Swap)
9702     std::swap(V1, V2);
9703   if (V2.isUndef())
9704     V2 = V1;
9705   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9706   if (ShiftElts) {
9707     // Double ShiftElts because we're left shifting on v16i8 type.
9708     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9709                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9710     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9711     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9712                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9713     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9714   }
9715   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9716   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9717                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9718   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9719 }
9720 
9721 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9722 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9723 /// return the default SDValue.
9724 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9725                                               SelectionDAG &DAG) const {
9726   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9727   // to v16i8. Peek through the bitcasts to get the actual operands.
9728   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9729   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9730 
9731   auto ShuffleMask = SVN->getMask();
9732   SDValue VecShuffle(SVN, 0);
9733   SDLoc DL(SVN);
9734 
9735   // Check that we have a four byte shuffle.
9736   if (!isNByteElemShuffleMask(SVN, 4, 1))
9737     return SDValue();
9738 
9739   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9740   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9741     std::swap(LHS, RHS);
9742     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9743     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9744   }
9745 
9746   // Ensure that the RHS is a vector of constants.
9747   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9748   if (!BVN)
9749     return SDValue();
9750 
9751   // Check if RHS is a splat of 4-bytes (or smaller).
9752   APInt APSplatValue, APSplatUndef;
9753   unsigned SplatBitSize;
9754   bool HasAnyUndefs;
9755   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9756                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9757       SplatBitSize > 32)
9758     return SDValue();
9759 
9760   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9761   // The instruction splats a constant C into two words of the source vector
9762   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9763   // Thus we check that the shuffle mask is the equivalent  of
9764   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9765   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9766   // within each word are consecutive, so we only need to check the first byte.
9767   SDValue Index;
9768   bool IsLE = Subtarget.isLittleEndian();
9769   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9770       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9771        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9772     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9773   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9774            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9775             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9776     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9777   else
9778     return SDValue();
9779 
9780   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9781   // for XXSPLTI32DX.
9782   unsigned SplatVal = APSplatValue.getZExtValue();
9783   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9784     SplatVal |= (SplatVal << SplatBitSize);
9785 
9786   SDValue SplatNode = DAG.getNode(
9787       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9788       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9789   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9790 }
9791 
9792 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9793 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9794 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9795 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9796 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9797   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9798   assert(Op.getValueType() == MVT::v1i128 &&
9799          "Only set v1i128 as custom, other type shouldn't reach here!");
9800   SDLoc dl(Op);
9801   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9802   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9803   unsigned SHLAmt = N1.getConstantOperandVal(0);
9804   if (SHLAmt % 8 == 0) {
9805     SmallVector<int, 16> Mask(16, 0);
9806     std::iota(Mask.begin(), Mask.end(), 0);
9807     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9808     if (SDValue Shuffle =
9809             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9810                                  DAG.getUNDEF(MVT::v16i8), Mask))
9811       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9812   }
9813   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9814   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9815                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9816   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9817                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9818   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9819   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9820 }
9821 
9822 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9823 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9824 /// return the code it can be lowered into.  Worst case, it can always be
9825 /// lowered into a vperm.
9826 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9827                                                SelectionDAG &DAG) const {
9828   SDLoc dl(Op);
9829   SDValue V1 = Op.getOperand(0);
9830   SDValue V2 = Op.getOperand(1);
9831   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9832 
9833   // Any nodes that were combined in the target-independent combiner prior
9834   // to vector legalization will not be sent to the target combine. Try to
9835   // combine it here.
9836   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9837     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9838       return NewShuffle;
9839     Op = NewShuffle;
9840     SVOp = cast<ShuffleVectorSDNode>(Op);
9841     V1 = Op.getOperand(0);
9842     V2 = Op.getOperand(1);
9843   }
9844   EVT VT = Op.getValueType();
9845   bool isLittleEndian = Subtarget.isLittleEndian();
9846 
9847   unsigned ShiftElts, InsertAtByte;
9848   bool Swap = false;
9849 
9850   // If this is a load-and-splat, we can do that with a single instruction
9851   // in some cases. However if the load has multiple uses, we don't want to
9852   // combine it because that will just produce multiple loads.
9853   bool IsPermutedLoad = false;
9854   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9855   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9856       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9857       InputLoad->hasOneUse()) {
9858     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9859     int SplatIdx =
9860       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9861 
9862     // The splat index for permuted loads will be in the left half of the vector
9863     // which is strictly wider than the loaded value by 8 bytes. So we need to
9864     // adjust the splat index to point to the correct address in memory.
9865     if (IsPermutedLoad) {
9866       assert((isLittleEndian || IsFourByte) &&
9867              "Unexpected size for permuted load on big endian target");
9868       SplatIdx += IsFourByte ? 2 : 1;
9869       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9870              "Splat of a value outside of the loaded memory");
9871     }
9872 
9873     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9874     // For 4-byte load-and-splat, we need Power9.
9875     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9876       uint64_t Offset = 0;
9877       if (IsFourByte)
9878         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9879       else
9880         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9881 
9882       // If the width of the load is the same as the width of the splat,
9883       // loading with an offset would load the wrong memory.
9884       if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64))
9885         Offset = 0;
9886 
9887       SDValue BasePtr = LD->getBasePtr();
9888       if (Offset != 0)
9889         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9890                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9891       SDValue Ops[] = {
9892         LD->getChain(),    // Chain
9893         BasePtr,           // BasePtr
9894         DAG.getValueType(Op.getValueType()) // VT
9895       };
9896       SDVTList VTL =
9897         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9898       SDValue LdSplt =
9899         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9900                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9901       DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
9902       if (LdSplt.getValueType() != SVOp->getValueType(0))
9903         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9904       return LdSplt;
9905     }
9906   }
9907   if (Subtarget.hasP9Vector() &&
9908       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9909                            isLittleEndian)) {
9910     if (Swap)
9911       std::swap(V1, V2);
9912     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9913     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9914     if (ShiftElts) {
9915       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9916                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9917       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9918                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9919       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9920     }
9921     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9922                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9923     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9924   }
9925 
9926   if (Subtarget.hasPrefixInstrs()) {
9927     SDValue SplatInsertNode;
9928     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9929       return SplatInsertNode;
9930   }
9931 
9932   if (Subtarget.hasP9Altivec()) {
9933     SDValue NewISDNode;
9934     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9935       return NewISDNode;
9936 
9937     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9938       return NewISDNode;
9939   }
9940 
9941   if (Subtarget.hasVSX() &&
9942       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9943     if (Swap)
9944       std::swap(V1, V2);
9945     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9946     SDValue Conv2 =
9947         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9948 
9949     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9950                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9951     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9952   }
9953 
9954   if (Subtarget.hasVSX() &&
9955     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9956     if (Swap)
9957       std::swap(V1, V2);
9958     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9959     SDValue Conv2 =
9960         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9961 
9962     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9963                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9964     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9965   }
9966 
9967   if (Subtarget.hasP9Vector()) {
9968      if (PPC::isXXBRHShuffleMask(SVOp)) {
9969       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9970       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9971       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9972     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9973       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9974       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9975       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9976     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9977       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9978       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9979       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9980     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9981       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9982       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9983       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9984     }
9985   }
9986 
9987   if (Subtarget.hasVSX()) {
9988     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9989       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9990 
9991       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9992       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9993                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9994       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9995     }
9996 
9997     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9998     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9999       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
10000       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
10001       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
10002     }
10003   }
10004 
10005   // Cases that are handled by instructions that take permute immediates
10006   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
10007   // selected by the instruction selector.
10008   if (V2.isUndef()) {
10009     if (PPC::isSplatShuffleMask(SVOp, 1) ||
10010         PPC::isSplatShuffleMask(SVOp, 2) ||
10011         PPC::isSplatShuffleMask(SVOp, 4) ||
10012         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
10013         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
10014         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
10015         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
10016         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
10017         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
10018         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
10019         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
10020         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
10021         (Subtarget.hasP8Altivec() && (
10022          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
10023          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
10024          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
10025       return Op;
10026     }
10027   }
10028 
10029   // Altivec has a variety of "shuffle immediates" that take two vector inputs
10030   // and produce a fixed permutation.  If any of these match, do not lower to
10031   // VPERM.
10032   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
10033   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10034       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10035       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
10036       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10037       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10038       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10039       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10040       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10041       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10042       (Subtarget.hasP8Altivec() && (
10043        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10044        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
10045        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
10046     return Op;
10047 
10048   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
10049   // perfect shuffle table to emit an optimal matching sequence.
10050   ArrayRef<int> PermMask = SVOp->getMask();
10051 
10052   unsigned PFIndexes[4];
10053   bool isFourElementShuffle = true;
10054   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
10055     unsigned EltNo = 8;   // Start out undef.
10056     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
10057       if (PermMask[i*4+j] < 0)
10058         continue;   // Undef, ignore it.
10059 
10060       unsigned ByteSource = PermMask[i*4+j];
10061       if ((ByteSource & 3) != j) {
10062         isFourElementShuffle = false;
10063         break;
10064       }
10065 
10066       if (EltNo == 8) {
10067         EltNo = ByteSource/4;
10068       } else if (EltNo != ByteSource/4) {
10069         isFourElementShuffle = false;
10070         break;
10071       }
10072     }
10073     PFIndexes[i] = EltNo;
10074   }
10075 
10076   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
10077   // perfect shuffle vector to determine if it is cost effective to do this as
10078   // discrete instructions, or whether we should use a vperm.
10079   // For now, we skip this for little endian until such time as we have a
10080   // little-endian perfect shuffle table.
10081   if (isFourElementShuffle && !isLittleEndian) {
10082     // Compute the index in the perfect shuffle table.
10083     unsigned PFTableIndex =
10084       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
10085 
10086     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10087     unsigned Cost  = (PFEntry >> 30);
10088 
10089     // Determining when to avoid vperm is tricky.  Many things affect the cost
10090     // of vperm, particularly how many times the perm mask needs to be computed.
10091     // For example, if the perm mask can be hoisted out of a loop or is already
10092     // used (perhaps because there are multiple permutes with the same shuffle
10093     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
10094     // the loop requires an extra register.
10095     //
10096     // As a compromise, we only emit discrete instructions if the shuffle can be
10097     // generated in 3 or fewer operations.  When we have loop information
10098     // available, if this block is within a loop, we should avoid using vperm
10099     // for 3-operation perms and use a constant pool load instead.
10100     if (Cost < 3)
10101       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10102   }
10103 
10104   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10105   // vector that will get spilled to the constant pool.
10106   if (V2.isUndef()) V2 = V1;
10107 
10108   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10109   // that it is in input element units, not in bytes.  Convert now.
10110 
10111   // For little endian, the order of the input vectors is reversed, and
10112   // the permutation mask is complemented with respect to 31.  This is
10113   // necessary to produce proper semantics with the big-endian-biased vperm
10114   // instruction.
10115   EVT EltVT = V1.getValueType().getVectorElementType();
10116   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
10117 
10118   SmallVector<SDValue, 16> ResultMask;
10119   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10120     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10121 
10122     for (unsigned j = 0; j != BytesPerElement; ++j)
10123       if (isLittleEndian)
10124         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
10125                                              dl, MVT::i32));
10126       else
10127         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
10128                                              MVT::i32));
10129   }
10130 
10131   ShufflesHandledWithVPERM++;
10132   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10133   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
10134   LLVM_DEBUG(SVOp->dump());
10135   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
10136   LLVM_DEBUG(VPermMask.dump());
10137 
10138   if (isLittleEndian)
10139     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10140                        V2, V1, VPermMask);
10141   else
10142     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10143                        V1, V2, VPermMask);
10144 }
10145 
10146 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10147 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10148 /// information about the intrinsic.
10149 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10150                                  bool &isDot, const PPCSubtarget &Subtarget) {
10151   unsigned IntrinsicID =
10152       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10153   CompareOpc = -1;
10154   isDot = false;
10155   switch (IntrinsicID) {
10156   default:
10157     return false;
10158   // Comparison predicates.
10159   case Intrinsic::ppc_altivec_vcmpbfp_p:
10160     CompareOpc = 966;
10161     isDot = true;
10162     break;
10163   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10164     CompareOpc = 198;
10165     isDot = true;
10166     break;
10167   case Intrinsic::ppc_altivec_vcmpequb_p:
10168     CompareOpc = 6;
10169     isDot = true;
10170     break;
10171   case Intrinsic::ppc_altivec_vcmpequh_p:
10172     CompareOpc = 70;
10173     isDot = true;
10174     break;
10175   case Intrinsic::ppc_altivec_vcmpequw_p:
10176     CompareOpc = 134;
10177     isDot = true;
10178     break;
10179   case Intrinsic::ppc_altivec_vcmpequd_p:
10180     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10181       CompareOpc = 199;
10182       isDot = true;
10183     } else
10184       return false;
10185     break;
10186   case Intrinsic::ppc_altivec_vcmpneb_p:
10187   case Intrinsic::ppc_altivec_vcmpneh_p:
10188   case Intrinsic::ppc_altivec_vcmpnew_p:
10189   case Intrinsic::ppc_altivec_vcmpnezb_p:
10190   case Intrinsic::ppc_altivec_vcmpnezh_p:
10191   case Intrinsic::ppc_altivec_vcmpnezw_p:
10192     if (Subtarget.hasP9Altivec()) {
10193       switch (IntrinsicID) {
10194       default:
10195         llvm_unreachable("Unknown comparison intrinsic.");
10196       case Intrinsic::ppc_altivec_vcmpneb_p:
10197         CompareOpc = 7;
10198         break;
10199       case Intrinsic::ppc_altivec_vcmpneh_p:
10200         CompareOpc = 71;
10201         break;
10202       case Intrinsic::ppc_altivec_vcmpnew_p:
10203         CompareOpc = 135;
10204         break;
10205       case Intrinsic::ppc_altivec_vcmpnezb_p:
10206         CompareOpc = 263;
10207         break;
10208       case Intrinsic::ppc_altivec_vcmpnezh_p:
10209         CompareOpc = 327;
10210         break;
10211       case Intrinsic::ppc_altivec_vcmpnezw_p:
10212         CompareOpc = 391;
10213         break;
10214       }
10215       isDot = true;
10216     } else
10217       return false;
10218     break;
10219   case Intrinsic::ppc_altivec_vcmpgefp_p:
10220     CompareOpc = 454;
10221     isDot = true;
10222     break;
10223   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10224     CompareOpc = 710;
10225     isDot = true;
10226     break;
10227   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10228     CompareOpc = 774;
10229     isDot = true;
10230     break;
10231   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10232     CompareOpc = 838;
10233     isDot = true;
10234     break;
10235   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10236     CompareOpc = 902;
10237     isDot = true;
10238     break;
10239   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10240     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10241       CompareOpc = 967;
10242       isDot = true;
10243     } else
10244       return false;
10245     break;
10246   case Intrinsic::ppc_altivec_vcmpgtub_p:
10247     CompareOpc = 518;
10248     isDot = true;
10249     break;
10250   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10251     CompareOpc = 582;
10252     isDot = true;
10253     break;
10254   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10255     CompareOpc = 646;
10256     isDot = true;
10257     break;
10258   case Intrinsic::ppc_altivec_vcmpgtud_p:
10259     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10260       CompareOpc = 711;
10261       isDot = true;
10262     } else
10263       return false;
10264     break;
10265 
10266   case Intrinsic::ppc_altivec_vcmpequq:
10267   case Intrinsic::ppc_altivec_vcmpgtsq:
10268   case Intrinsic::ppc_altivec_vcmpgtuq:
10269     if (!Subtarget.isISA3_1())
10270       return false;
10271     switch (IntrinsicID) {
10272     default:
10273       llvm_unreachable("Unknown comparison intrinsic.");
10274     case Intrinsic::ppc_altivec_vcmpequq:
10275       CompareOpc = 455;
10276       break;
10277     case Intrinsic::ppc_altivec_vcmpgtsq:
10278       CompareOpc = 903;
10279       break;
10280     case Intrinsic::ppc_altivec_vcmpgtuq:
10281       CompareOpc = 647;
10282       break;
10283     }
10284     break;
10285 
10286   // VSX predicate comparisons use the same infrastructure
10287   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10288   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10289   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10290   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10291   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10292   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10293     if (Subtarget.hasVSX()) {
10294       switch (IntrinsicID) {
10295       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10296         CompareOpc = 99;
10297         break;
10298       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10299         CompareOpc = 115;
10300         break;
10301       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10302         CompareOpc = 107;
10303         break;
10304       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10305         CompareOpc = 67;
10306         break;
10307       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10308         CompareOpc = 83;
10309         break;
10310       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10311         CompareOpc = 75;
10312         break;
10313       }
10314       isDot = true;
10315     } else
10316       return false;
10317     break;
10318 
10319   // Normal Comparisons.
10320   case Intrinsic::ppc_altivec_vcmpbfp:
10321     CompareOpc = 966;
10322     break;
10323   case Intrinsic::ppc_altivec_vcmpeqfp:
10324     CompareOpc = 198;
10325     break;
10326   case Intrinsic::ppc_altivec_vcmpequb:
10327     CompareOpc = 6;
10328     break;
10329   case Intrinsic::ppc_altivec_vcmpequh:
10330     CompareOpc = 70;
10331     break;
10332   case Intrinsic::ppc_altivec_vcmpequw:
10333     CompareOpc = 134;
10334     break;
10335   case Intrinsic::ppc_altivec_vcmpequd:
10336     if (Subtarget.hasP8Altivec())
10337       CompareOpc = 199;
10338     else
10339       return false;
10340     break;
10341   case Intrinsic::ppc_altivec_vcmpneb:
10342   case Intrinsic::ppc_altivec_vcmpneh:
10343   case Intrinsic::ppc_altivec_vcmpnew:
10344   case Intrinsic::ppc_altivec_vcmpnezb:
10345   case Intrinsic::ppc_altivec_vcmpnezh:
10346   case Intrinsic::ppc_altivec_vcmpnezw:
10347     if (Subtarget.hasP9Altivec())
10348       switch (IntrinsicID) {
10349       default:
10350         llvm_unreachable("Unknown comparison intrinsic.");
10351       case Intrinsic::ppc_altivec_vcmpneb:
10352         CompareOpc = 7;
10353         break;
10354       case Intrinsic::ppc_altivec_vcmpneh:
10355         CompareOpc = 71;
10356         break;
10357       case Intrinsic::ppc_altivec_vcmpnew:
10358         CompareOpc = 135;
10359         break;
10360       case Intrinsic::ppc_altivec_vcmpnezb:
10361         CompareOpc = 263;
10362         break;
10363       case Intrinsic::ppc_altivec_vcmpnezh:
10364         CompareOpc = 327;
10365         break;
10366       case Intrinsic::ppc_altivec_vcmpnezw:
10367         CompareOpc = 391;
10368         break;
10369       }
10370     else
10371       return false;
10372     break;
10373   case Intrinsic::ppc_altivec_vcmpgefp:
10374     CompareOpc = 454;
10375     break;
10376   case Intrinsic::ppc_altivec_vcmpgtfp:
10377     CompareOpc = 710;
10378     break;
10379   case Intrinsic::ppc_altivec_vcmpgtsb:
10380     CompareOpc = 774;
10381     break;
10382   case Intrinsic::ppc_altivec_vcmpgtsh:
10383     CompareOpc = 838;
10384     break;
10385   case Intrinsic::ppc_altivec_vcmpgtsw:
10386     CompareOpc = 902;
10387     break;
10388   case Intrinsic::ppc_altivec_vcmpgtsd:
10389     if (Subtarget.hasP8Altivec())
10390       CompareOpc = 967;
10391     else
10392       return false;
10393     break;
10394   case Intrinsic::ppc_altivec_vcmpgtub:
10395     CompareOpc = 518;
10396     break;
10397   case Intrinsic::ppc_altivec_vcmpgtuh:
10398     CompareOpc = 582;
10399     break;
10400   case Intrinsic::ppc_altivec_vcmpgtuw:
10401     CompareOpc = 646;
10402     break;
10403   case Intrinsic::ppc_altivec_vcmpgtud:
10404     if (Subtarget.hasP8Altivec())
10405       CompareOpc = 711;
10406     else
10407       return false;
10408     break;
10409   case Intrinsic::ppc_altivec_vcmpequq_p:
10410   case Intrinsic::ppc_altivec_vcmpgtsq_p:
10411   case Intrinsic::ppc_altivec_vcmpgtuq_p:
10412     if (!Subtarget.isISA3_1())
10413       return false;
10414     switch (IntrinsicID) {
10415     default:
10416       llvm_unreachable("Unknown comparison intrinsic.");
10417     case Intrinsic::ppc_altivec_vcmpequq_p:
10418       CompareOpc = 455;
10419       break;
10420     case Intrinsic::ppc_altivec_vcmpgtsq_p:
10421       CompareOpc = 903;
10422       break;
10423     case Intrinsic::ppc_altivec_vcmpgtuq_p:
10424       CompareOpc = 647;
10425       break;
10426     }
10427     isDot = true;
10428     break;
10429   }
10430   return true;
10431 }
10432 
10433 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10434 /// lower, do it, otherwise return null.
10435 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10436                                                    SelectionDAG &DAG) const {
10437   unsigned IntrinsicID =
10438     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10439 
10440   SDLoc dl(Op);
10441 
10442   switch (IntrinsicID) {
10443   case Intrinsic::thread_pointer:
10444     // Reads the thread pointer register, used for __builtin_thread_pointer.
10445     if (Subtarget.isPPC64())
10446       return DAG.getRegister(PPC::X13, MVT::i64);
10447     return DAG.getRegister(PPC::R2, MVT::i32);
10448 
10449   case Intrinsic::ppc_mma_disassemble_acc:
10450   case Intrinsic::ppc_vsx_disassemble_pair: {
10451     int NumVecs = 2;
10452     SDValue WideVec = Op.getOperand(1);
10453     if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
10454       NumVecs = 4;
10455       WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
10456     }
10457     SmallVector<SDValue, 4> RetOps;
10458     for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
10459       SDValue Extract = DAG.getNode(
10460           PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
10461           DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
10462                                                      : VecNo,
10463                           dl, getPointerTy(DAG.getDataLayout())));
10464       RetOps.push_back(Extract);
10465     }
10466     return DAG.getMergeValues(RetOps, dl);
10467   }
10468 
10469   case Intrinsic::ppc_unpack_longdouble: {
10470     auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10471     assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&
10472            "Argument of long double unpack must be 0 or 1!");
10473     return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1),
10474                        DAG.getConstant(!!(Idx->getSExtValue()), dl,
10475                                        Idx->getValueType(0)));
10476   }
10477 
10478   case Intrinsic::ppc_compare_exp_lt:
10479   case Intrinsic::ppc_compare_exp_gt:
10480   case Intrinsic::ppc_compare_exp_eq:
10481   case Intrinsic::ppc_compare_exp_uo: {
10482     unsigned Pred;
10483     switch (IntrinsicID) {
10484     case Intrinsic::ppc_compare_exp_lt:
10485       Pred = PPC::PRED_LT;
10486       break;
10487     case Intrinsic::ppc_compare_exp_gt:
10488       Pred = PPC::PRED_GT;
10489       break;
10490     case Intrinsic::ppc_compare_exp_eq:
10491       Pred = PPC::PRED_EQ;
10492       break;
10493     case Intrinsic::ppc_compare_exp_uo:
10494       Pred = PPC::PRED_UN;
10495       break;
10496     }
10497     return SDValue(
10498         DAG.getMachineNode(
10499             PPC::SELECT_CC_I4, dl, MVT::i32,
10500             {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32,
10501                                         Op.getOperand(1), Op.getOperand(2)),
10502                      0),
10503              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10504              DAG.getTargetConstant(Pred, dl, MVT::i32)}),
10505         0);
10506   }
10507   case Intrinsic::ppc_test_data_class_d:
10508   case Intrinsic::ppc_test_data_class_f: {
10509     unsigned CmprOpc = PPC::XSTSTDCDP;
10510     if (IntrinsicID == Intrinsic::ppc_test_data_class_f)
10511       CmprOpc = PPC::XSTSTDCSP;
10512     return SDValue(
10513         DAG.getMachineNode(
10514             PPC::SELECT_CC_I4, dl, MVT::i32,
10515             {SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32, Op.getOperand(2),
10516                                         Op.getOperand(1)),
10517                      0),
10518              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10519              DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}),
10520         0);
10521   }
10522   case Intrinsic::ppc_convert_f128_to_ppcf128:
10523   case Intrinsic::ppc_convert_ppcf128_to_f128: {
10524     RTLIB::Libcall LC = IntrinsicID == Intrinsic::ppc_convert_ppcf128_to_f128
10525                             ? RTLIB::CONVERT_PPCF128_F128
10526                             : RTLIB::CONVERT_F128_PPCF128;
10527     MakeLibCallOptions CallOptions;
10528     std::pair<SDValue, SDValue> Result =
10529         makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(1), CallOptions,
10530                     dl, SDValue());
10531     return Result.first;
10532   }
10533   }
10534 
10535   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10536   // opcode number of the comparison.
10537   int CompareOpc;
10538   bool isDot;
10539   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10540     return SDValue();    // Don't custom lower most intrinsics.
10541 
10542   // If this is a non-dot comparison, make the VCMP node and we are done.
10543   if (!isDot) {
10544     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10545                               Op.getOperand(1), Op.getOperand(2),
10546                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10547     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10548   }
10549 
10550   // Create the PPCISD altivec 'dot' comparison node.
10551   SDValue Ops[] = {
10552     Op.getOperand(2),  // LHS
10553     Op.getOperand(3),  // RHS
10554     DAG.getConstant(CompareOpc, dl, MVT::i32)
10555   };
10556   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10557   SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
10558 
10559   // Now that we have the comparison, emit a copy from the CR to a GPR.
10560   // This is flagged to the above dot comparison.
10561   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10562                                 DAG.getRegister(PPC::CR6, MVT::i32),
10563                                 CompNode.getValue(1));
10564 
10565   // Unpack the result based on how the target uses it.
10566   unsigned BitNo;   // Bit # of CR6.
10567   bool InvertBit;   // Invert result?
10568   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10569   default:  // Can't happen, don't crash on invalid number though.
10570   case 0:   // Return the value of the EQ bit of CR6.
10571     BitNo = 0; InvertBit = false;
10572     break;
10573   case 1:   // Return the inverted value of the EQ bit of CR6.
10574     BitNo = 0; InvertBit = true;
10575     break;
10576   case 2:   // Return the value of the LT bit of CR6.
10577     BitNo = 2; InvertBit = false;
10578     break;
10579   case 3:   // Return the inverted value of the LT bit of CR6.
10580     BitNo = 2; InvertBit = true;
10581     break;
10582   }
10583 
10584   // Shift the bit into the low position.
10585   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10586                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10587   // Isolate the bit.
10588   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10589                       DAG.getConstant(1, dl, MVT::i32));
10590 
10591   // If we are supposed to, toggle the bit.
10592   if (InvertBit)
10593     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10594                         DAG.getConstant(1, dl, MVT::i32));
10595   return Flags;
10596 }
10597 
10598 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10599                                                SelectionDAG &DAG) const {
10600   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10601   // the beginning of the argument list.
10602   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10603   SDLoc DL(Op);
10604   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10605   case Intrinsic::ppc_cfence: {
10606     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10607     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10608     SDValue Val = Op.getOperand(ArgStart + 1);
10609     EVT Ty = Val.getValueType();
10610     if (Ty == MVT::i128) {
10611       // FIXME: Testing one of two paired registers is sufficient to guarantee
10612       // ordering?
10613       Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val);
10614     }
10615     return SDValue(
10616         DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10617                            DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Val),
10618                            Op.getOperand(0)),
10619         0);
10620   }
10621   default:
10622     break;
10623   }
10624   return SDValue();
10625 }
10626 
10627 // Lower scalar BSWAP64 to xxbrd.
10628 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10629   SDLoc dl(Op);
10630   if (!Subtarget.isPPC64())
10631     return Op;
10632   // MTVSRDD
10633   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10634                    Op.getOperand(0));
10635   // XXBRD
10636   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10637   // MFVSRD
10638   int VectorIndex = 0;
10639   if (Subtarget.isLittleEndian())
10640     VectorIndex = 1;
10641   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10642                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10643   return Op;
10644 }
10645 
10646 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10647 // compared to a value that is atomically loaded (atomic loads zero-extend).
10648 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10649                                                 SelectionDAG &DAG) const {
10650   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10651          "Expecting an atomic compare-and-swap here.");
10652   SDLoc dl(Op);
10653   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10654   EVT MemVT = AtomicNode->getMemoryVT();
10655   if (MemVT.getSizeInBits() >= 32)
10656     return Op;
10657 
10658   SDValue CmpOp = Op.getOperand(2);
10659   // If this is already correctly zero-extended, leave it alone.
10660   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10661   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10662     return Op;
10663 
10664   // Clear the high bits of the compare operand.
10665   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10666   SDValue NewCmpOp =
10667     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10668                 DAG.getConstant(MaskVal, dl, MVT::i32));
10669 
10670   // Replace the existing compare operand with the properly zero-extended one.
10671   SmallVector<SDValue, 4> Ops;
10672   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10673     Ops.push_back(AtomicNode->getOperand(i));
10674   Ops[2] = NewCmpOp;
10675   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10676   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10677   auto NodeTy =
10678     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10679   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10680 }
10681 
10682 SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op,
10683                                                   SelectionDAG &DAG) const {
10684   AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode());
10685   EVT MemVT = N->getMemoryVT();
10686   assert(MemVT.getSimpleVT() == MVT::i128 &&
10687          "Expect quadword atomic operations");
10688   SDLoc dl(N);
10689   unsigned Opc = N->getOpcode();
10690   switch (Opc) {
10691   case ISD::ATOMIC_LOAD: {
10692     // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be
10693     // lowered to ppc instructions by pattern matching instruction selector.
10694     SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
10695     SmallVector<SDValue, 4> Ops{
10696         N->getOperand(0),
10697         DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)};
10698     for (int I = 1, E = N->getNumOperands(); I < E; ++I)
10699       Ops.push_back(N->getOperand(I));
10700     SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys,
10701                                                 Ops, MemVT, N->getMemOperand());
10702     SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal);
10703     SDValue ValHi =
10704         DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1));
10705     ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi,
10706                         DAG.getConstant(64, dl, MVT::i32));
10707     SDValue Val =
10708         DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi});
10709     return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other},
10710                        {Val, LoadedVal.getValue(2)});
10711   }
10712   case ISD::ATOMIC_STORE: {
10713     // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be
10714     // lowered to ppc instructions by pattern matching instruction selector.
10715     SDVTList Tys = DAG.getVTList(MVT::Other);
10716     SmallVector<SDValue, 4> Ops{
10717         N->getOperand(0),
10718         DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)};
10719     SDValue Val = N->getOperand(2);
10720     SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val);
10721     SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val,
10722                                 DAG.getConstant(64, dl, MVT::i32));
10723     ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi);
10724     Ops.push_back(ValLo);
10725     Ops.push_back(ValHi);
10726     Ops.push_back(N->getOperand(1));
10727     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT,
10728                                    N->getMemOperand());
10729   }
10730   default:
10731     llvm_unreachable("Unexpected atomic opcode");
10732   }
10733 }
10734 
10735 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10736                                                  SelectionDAG &DAG) const {
10737   SDLoc dl(Op);
10738   // Create a stack slot that is 16-byte aligned.
10739   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10740   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10741   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10742   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10743 
10744   // Store the input value into Value#0 of the stack slot.
10745   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10746                                MachinePointerInfo());
10747   // Load it out.
10748   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10749 }
10750 
10751 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10752                                                   SelectionDAG &DAG) const {
10753   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10754          "Should only be called for ISD::INSERT_VECTOR_ELT");
10755 
10756   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10757 
10758   EVT VT = Op.getValueType();
10759   SDLoc dl(Op);
10760   SDValue V1 = Op.getOperand(0);
10761   SDValue V2 = Op.getOperand(1);
10762 
10763   if (VT == MVT::v2f64 && C)
10764     return Op;
10765 
10766   if (Subtarget.isISA3_1()) {
10767     if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64())
10768       return SDValue();
10769     // On P10, we have legal lowering for constant and variable indices for
10770     // all vectors.
10771     if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
10772         VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
10773       return Op;
10774   }
10775 
10776   // Before P10, we have legal lowering for constant indices but not for
10777   // variable ones.
10778   if (!C)
10779     return SDValue();
10780 
10781   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10782   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10783     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10784     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10785     unsigned InsertAtElement = C->getZExtValue();
10786     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10787     if (Subtarget.isLittleEndian()) {
10788       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10789     }
10790     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10791                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10792   }
10793   return Op;
10794 }
10795 
10796 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10797                                            SelectionDAG &DAG) const {
10798   SDLoc dl(Op);
10799   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10800   SDValue LoadChain = LN->getChain();
10801   SDValue BasePtr = LN->getBasePtr();
10802   EVT VT = Op.getValueType();
10803 
10804   if (VT != MVT::v256i1 && VT != MVT::v512i1)
10805     return Op;
10806 
10807   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10808   // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
10809   // 2 or 4 vsx registers.
10810   assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
10811          "Type unsupported without MMA");
10812   assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10813          "Type unsupported without paired vector support");
10814   Align Alignment = LN->getAlign();
10815   SmallVector<SDValue, 4> Loads;
10816   SmallVector<SDValue, 4> LoadChains;
10817   unsigned NumVecs = VT.getSizeInBits() / 128;
10818   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10819     SDValue Load =
10820         DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
10821                     LN->getPointerInfo().getWithOffset(Idx * 16),
10822                     commonAlignment(Alignment, Idx * 16),
10823                     LN->getMemOperand()->getFlags(), LN->getAAInfo());
10824     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10825                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10826     Loads.push_back(Load);
10827     LoadChains.push_back(Load.getValue(1));
10828   }
10829   if (Subtarget.isLittleEndian()) {
10830     std::reverse(Loads.begin(), Loads.end());
10831     std::reverse(LoadChains.begin(), LoadChains.end());
10832   }
10833   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10834   SDValue Value =
10835       DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
10836                   dl, VT, Loads);
10837   SDValue RetOps[] = {Value, TF};
10838   return DAG.getMergeValues(RetOps, dl);
10839 }
10840 
10841 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10842                                             SelectionDAG &DAG) const {
10843   SDLoc dl(Op);
10844   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10845   SDValue StoreChain = SN->getChain();
10846   SDValue BasePtr = SN->getBasePtr();
10847   SDValue Value = SN->getValue();
10848   EVT StoreVT = Value.getValueType();
10849 
10850   if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
10851     return Op;
10852 
10853   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10854   // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
10855   // underlying registers individually.
10856   assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
10857          "Type unsupported without MMA");
10858   assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10859          "Type unsupported without paired vector support");
10860   Align Alignment = SN->getAlign();
10861   SmallVector<SDValue, 4> Stores;
10862   unsigned NumVecs = 2;
10863   if (StoreVT == MVT::v512i1) {
10864     Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
10865     NumVecs = 4;
10866   }
10867   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10868     unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
10869     SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
10870                               DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
10871     SDValue Store =
10872         DAG.getStore(StoreChain, dl, Elt, BasePtr,
10873                      SN->getPointerInfo().getWithOffset(Idx * 16),
10874                      commonAlignment(Alignment, Idx * 16),
10875                      SN->getMemOperand()->getFlags(), SN->getAAInfo());
10876     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10877                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10878     Stores.push_back(Store);
10879   }
10880   SDValue TF = DAG.getTokenFactor(dl, Stores);
10881   return TF;
10882 }
10883 
10884 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10885   SDLoc dl(Op);
10886   if (Op.getValueType() == MVT::v4i32) {
10887     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10888 
10889     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10890     // +16 as shift amt.
10891     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10892     SDValue RHSSwap =   // = vrlw RHS, 16
10893       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10894 
10895     // Shrinkify inputs to v8i16.
10896     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10897     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10898     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10899 
10900     // Low parts multiplied together, generating 32-bit results (we ignore the
10901     // top parts).
10902     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10903                                         LHS, RHS, DAG, dl, MVT::v4i32);
10904 
10905     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10906                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10907     // Shift the high parts up 16 bits.
10908     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10909                               Neg16, DAG, dl);
10910     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10911   } else if (Op.getValueType() == MVT::v16i8) {
10912     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10913     bool isLittleEndian = Subtarget.isLittleEndian();
10914 
10915     // Multiply the even 8-bit parts, producing 16-bit sums.
10916     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10917                                            LHS, RHS, DAG, dl, MVT::v8i16);
10918     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10919 
10920     // Multiply the odd 8-bit parts, producing 16-bit sums.
10921     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10922                                           LHS, RHS, DAG, dl, MVT::v8i16);
10923     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10924 
10925     // Merge the results together.  Because vmuleub and vmuloub are
10926     // instructions with a big-endian bias, we must reverse the
10927     // element numbering and reverse the meaning of "odd" and "even"
10928     // when generating little endian code.
10929     int Ops[16];
10930     for (unsigned i = 0; i != 8; ++i) {
10931       if (isLittleEndian) {
10932         Ops[i*2  ] = 2*i;
10933         Ops[i*2+1] = 2*i+16;
10934       } else {
10935         Ops[i*2  ] = 2*i+1;
10936         Ops[i*2+1] = 2*i+1+16;
10937       }
10938     }
10939     if (isLittleEndian)
10940       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10941     else
10942       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10943   } else {
10944     llvm_unreachable("Unknown mul to lower!");
10945   }
10946 }
10947 
10948 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10949   bool IsStrict = Op->isStrictFPOpcode();
10950   if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
10951       !Subtarget.hasP9Vector())
10952     return SDValue();
10953 
10954   return Op;
10955 }
10956 
10957 // Custom lowering for fpext vf32 to v2f64
10958 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10959 
10960   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10961          "Should only be called for ISD::FP_EXTEND");
10962 
10963   // FIXME: handle extends from half precision float vectors on P9.
10964   // We only want to custom lower an extend from v2f32 to v2f64.
10965   if (Op.getValueType() != MVT::v2f64 ||
10966       Op.getOperand(0).getValueType() != MVT::v2f32)
10967     return SDValue();
10968 
10969   SDLoc dl(Op);
10970   SDValue Op0 = Op.getOperand(0);
10971 
10972   switch (Op0.getOpcode()) {
10973   default:
10974     return SDValue();
10975   case ISD::EXTRACT_SUBVECTOR: {
10976     assert(Op0.getNumOperands() == 2 &&
10977            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10978            "Node should have 2 operands with second one being a constant!");
10979 
10980     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10981       return SDValue();
10982 
10983     // Custom lower is only done for high or low doubleword.
10984     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10985     if (Idx % 2 != 0)
10986       return SDValue();
10987 
10988     // Since input is v4f32, at this point Idx is either 0 or 2.
10989     // Shift to get the doubleword position we want.
10990     int DWord = Idx >> 1;
10991 
10992     // High and low word positions are different on little endian.
10993     if (Subtarget.isLittleEndian())
10994       DWord ^= 0x1;
10995 
10996     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10997                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10998   }
10999   case ISD::FADD:
11000   case ISD::FMUL:
11001   case ISD::FSUB: {
11002     SDValue NewLoad[2];
11003     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
11004       // Ensure both input are loads.
11005       SDValue LdOp = Op0.getOperand(i);
11006       if (LdOp.getOpcode() != ISD::LOAD)
11007         return SDValue();
11008       // Generate new load node.
11009       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
11010       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11011       NewLoad[i] = DAG.getMemIntrinsicNode(
11012           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11013           LD->getMemoryVT(), LD->getMemOperand());
11014     }
11015     SDValue NewOp =
11016         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
11017                     NewLoad[1], Op0.getNode()->getFlags());
11018     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
11019                        DAG.getConstant(0, dl, MVT::i32));
11020   }
11021   case ISD::LOAD: {
11022     LoadSDNode *LD = cast<LoadSDNode>(Op0);
11023     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11024     SDValue NewLd = DAG.getMemIntrinsicNode(
11025         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11026         LD->getMemoryVT(), LD->getMemOperand());
11027     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
11028                        DAG.getConstant(0, dl, MVT::i32));
11029   }
11030   }
11031   llvm_unreachable("ERROR:Should return for all cases within swtich.");
11032 }
11033 
11034 /// LowerOperation - Provide custom lowering hooks for some operations.
11035 ///
11036 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11037   switch (Op.getOpcode()) {
11038   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
11039   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11040   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11041   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11042   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11043   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11044   case ISD::STRICT_FSETCC:
11045   case ISD::STRICT_FSETCCS:
11046   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11047   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11048   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11049 
11050   case ISD::INLINEASM:
11051   case ISD::INLINEASM_BR:       return LowerINLINEASM(Op, DAG);
11052   // Variable argument lowering.
11053   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11054   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11055   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11056 
11057   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
11058   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11059   case ISD::GET_DYNAMIC_AREA_OFFSET:
11060     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
11061 
11062   // Exception handling lowering.
11063   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
11064   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11065   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11066 
11067   case ISD::LOAD:               return LowerLOAD(Op, DAG);
11068   case ISD::STORE:              return LowerSTORE(Op, DAG);
11069   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
11070   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
11071   case ISD::STRICT_FP_TO_UINT:
11072   case ISD::STRICT_FP_TO_SINT:
11073   case ISD::FP_TO_UINT:
11074   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
11075   case ISD::STRICT_UINT_TO_FP:
11076   case ISD::STRICT_SINT_TO_FP:
11077   case ISD::UINT_TO_FP:
11078   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
11079   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11080 
11081   // Lower 64-bit shifts.
11082   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
11083   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
11084   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
11085 
11086   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
11087   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
11088 
11089   // Vector-related lowering.
11090   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11091   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11092   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11093   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11094   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11095   case ISD::MUL:                return LowerMUL(Op, DAG);
11096   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
11097   case ISD::STRICT_FP_ROUND:
11098   case ISD::FP_ROUND:
11099     return LowerFP_ROUND(Op, DAG);
11100   case ISD::ROTL:               return LowerROTL(Op, DAG);
11101 
11102   // For counter-based loop handling.
11103   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
11104 
11105   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11106 
11107   // Frame & Return address.
11108   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11109   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11110 
11111   case ISD::INTRINSIC_VOID:
11112     return LowerINTRINSIC_VOID(Op, DAG);
11113   case ISD::BSWAP:
11114     return LowerBSWAP(Op, DAG);
11115   case ISD::ATOMIC_CMP_SWAP:
11116     return LowerATOMIC_CMP_SWAP(Op, DAG);
11117   case ISD::ATOMIC_STORE:
11118     return LowerATOMIC_LOAD_STORE(Op, DAG);
11119   }
11120 }
11121 
11122 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
11123                                            SmallVectorImpl<SDValue>&Results,
11124                                            SelectionDAG &DAG) const {
11125   SDLoc dl(N);
11126   switch (N->getOpcode()) {
11127   default:
11128     llvm_unreachable("Do not know how to custom type legalize this operation!");
11129   case ISD::ATOMIC_LOAD: {
11130     SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG);
11131     Results.push_back(Res);
11132     Results.push_back(Res.getValue(1));
11133     break;
11134   }
11135   case ISD::READCYCLECOUNTER: {
11136     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11137     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
11138 
11139     Results.push_back(
11140         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
11141     Results.push_back(RTB.getValue(2));
11142     break;
11143   }
11144   case ISD::INTRINSIC_W_CHAIN: {
11145     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
11146         Intrinsic::loop_decrement)
11147       break;
11148 
11149     assert(N->getValueType(0) == MVT::i1 &&
11150            "Unexpected result type for CTR decrement intrinsic");
11151     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11152                                  N->getValueType(0));
11153     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
11154     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
11155                                  N->getOperand(1));
11156 
11157     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
11158     Results.push_back(NewInt.getValue(1));
11159     break;
11160   }
11161   case ISD::INTRINSIC_WO_CHAIN: {
11162     switch (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()) {
11163     case Intrinsic::ppc_pack_longdouble:
11164       Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
11165                                     N->getOperand(2), N->getOperand(1)));
11166       break;
11167     case Intrinsic::ppc_convert_f128_to_ppcf128:
11168       Results.push_back(LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG));
11169       break;
11170     }
11171     break;
11172   }
11173   case ISD::VAARG: {
11174     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
11175       return;
11176 
11177     EVT VT = N->getValueType(0);
11178 
11179     if (VT == MVT::i64) {
11180       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
11181 
11182       Results.push_back(NewNode);
11183       Results.push_back(NewNode.getValue(1));
11184     }
11185     return;
11186   }
11187   case ISD::STRICT_FP_TO_SINT:
11188   case ISD::STRICT_FP_TO_UINT:
11189   case ISD::FP_TO_SINT:
11190   case ISD::FP_TO_UINT: {
11191     // LowerFP_TO_INT() can only handle f32 and f64.
11192     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
11193         MVT::ppcf128)
11194       return;
11195     SDValue LoweredValue = LowerFP_TO_INT(SDValue(N, 0), DAG, dl);
11196     Results.push_back(LoweredValue);
11197     if (N->isStrictFPOpcode())
11198       Results.push_back(LoweredValue.getValue(1));
11199     return;
11200   }
11201   case ISD::TRUNCATE: {
11202     if (!N->getValueType(0).isVector())
11203       return;
11204     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
11205     if (Lowered)
11206       Results.push_back(Lowered);
11207     return;
11208   }
11209   case ISD::FSHL:
11210   case ISD::FSHR:
11211     // Don't handle funnel shifts here.
11212     return;
11213   case ISD::BITCAST:
11214     // Don't handle bitcast here.
11215     return;
11216   case ISD::FP_EXTEND:
11217     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
11218     if (Lowered)
11219       Results.push_back(Lowered);
11220     return;
11221   }
11222 }
11223 
11224 //===----------------------------------------------------------------------===//
11225 //  Other Lowering Code
11226 //===----------------------------------------------------------------------===//
11227 
11228 static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) {
11229   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11230   Function *Func = Intrinsic::getDeclaration(M, Id);
11231   return Builder.CreateCall(Func, {});
11232 }
11233 
11234 // The mappings for emitLeading/TrailingFence is taken from
11235 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11236 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11237                                                  Instruction *Inst,
11238                                                  AtomicOrdering Ord) const {
11239   if (Ord == AtomicOrdering::SequentiallyConsistent)
11240     return callIntrinsic(Builder, Intrinsic::ppc_sync);
11241   if (isReleaseOrStronger(Ord))
11242     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11243   return nullptr;
11244 }
11245 
11246 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11247                                                   Instruction *Inst,
11248                                                   AtomicOrdering Ord) const {
11249   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11250     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11251     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11252     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11253     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11254       return Builder.CreateCall(
11255           Intrinsic::getDeclaration(
11256               Builder.GetInsertBlock()->getParent()->getParent(),
11257               Intrinsic::ppc_cfence, {Inst->getType()}),
11258           {Inst});
11259     // FIXME: Can use isync for rmw operation.
11260     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11261   }
11262   return nullptr;
11263 }
11264 
11265 MachineBasicBlock *
11266 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11267                                     unsigned AtomicSize,
11268                                     unsigned BinOpcode,
11269                                     unsigned CmpOpcode,
11270                                     unsigned CmpPred) const {
11271   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11272   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11273 
11274   auto LoadMnemonic = PPC::LDARX;
11275   auto StoreMnemonic = PPC::STDCX;
11276   switch (AtomicSize) {
11277   default:
11278     llvm_unreachable("Unexpected size of atomic entity");
11279   case 1:
11280     LoadMnemonic = PPC::LBARX;
11281     StoreMnemonic = PPC::STBCX;
11282     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11283     break;
11284   case 2:
11285     LoadMnemonic = PPC::LHARX;
11286     StoreMnemonic = PPC::STHCX;
11287     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11288     break;
11289   case 4:
11290     LoadMnemonic = PPC::LWARX;
11291     StoreMnemonic = PPC::STWCX;
11292     break;
11293   case 8:
11294     LoadMnemonic = PPC::LDARX;
11295     StoreMnemonic = PPC::STDCX;
11296     break;
11297   }
11298 
11299   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11300   MachineFunction *F = BB->getParent();
11301   MachineFunction::iterator It = ++BB->getIterator();
11302 
11303   Register dest = MI.getOperand(0).getReg();
11304   Register ptrA = MI.getOperand(1).getReg();
11305   Register ptrB = MI.getOperand(2).getReg();
11306   Register incr = MI.getOperand(3).getReg();
11307   DebugLoc dl = MI.getDebugLoc();
11308 
11309   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11310   MachineBasicBlock *loop2MBB =
11311     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11312   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11313   F->insert(It, loopMBB);
11314   if (CmpOpcode)
11315     F->insert(It, loop2MBB);
11316   F->insert(It, exitMBB);
11317   exitMBB->splice(exitMBB->begin(), BB,
11318                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11319   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11320 
11321   MachineRegisterInfo &RegInfo = F->getRegInfo();
11322   Register TmpReg = (!BinOpcode) ? incr :
11323     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11324                                            : &PPC::GPRCRegClass);
11325 
11326   //  thisMBB:
11327   //   ...
11328   //   fallthrough --> loopMBB
11329   BB->addSuccessor(loopMBB);
11330 
11331   //  loopMBB:
11332   //   l[wd]arx dest, ptr
11333   //   add r0, dest, incr
11334   //   st[wd]cx. r0, ptr
11335   //   bne- loopMBB
11336   //   fallthrough --> exitMBB
11337 
11338   // For max/min...
11339   //  loopMBB:
11340   //   l[wd]arx dest, ptr
11341   //   cmpl?[wd] incr, dest
11342   //   bgt exitMBB
11343   //  loop2MBB:
11344   //   st[wd]cx. dest, ptr
11345   //   bne- loopMBB
11346   //   fallthrough --> exitMBB
11347 
11348   BB = loopMBB;
11349   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11350     .addReg(ptrA).addReg(ptrB);
11351   if (BinOpcode)
11352     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11353   if (CmpOpcode) {
11354     // Signed comparisons of byte or halfword values must be sign-extended.
11355     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11356       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11357       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11358               ExtReg).addReg(dest);
11359       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11360         .addReg(incr).addReg(ExtReg);
11361     } else
11362       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11363         .addReg(incr).addReg(dest);
11364 
11365     BuildMI(BB, dl, TII->get(PPC::BCC))
11366       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11367     BB->addSuccessor(loop2MBB);
11368     BB->addSuccessor(exitMBB);
11369     BB = loop2MBB;
11370   }
11371   BuildMI(BB, dl, TII->get(StoreMnemonic))
11372     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11373   BuildMI(BB, dl, TII->get(PPC::BCC))
11374     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11375   BB->addSuccessor(loopMBB);
11376   BB->addSuccessor(exitMBB);
11377 
11378   //  exitMBB:
11379   //   ...
11380   BB = exitMBB;
11381   return BB;
11382 }
11383 
11384 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) {
11385   switch(MI.getOpcode()) {
11386   default:
11387     return false;
11388   case PPC::COPY:
11389     return TII->isSignExtended(MI);
11390   case PPC::LHA:
11391   case PPC::LHA8:
11392   case PPC::LHAU:
11393   case PPC::LHAU8:
11394   case PPC::LHAUX:
11395   case PPC::LHAUX8:
11396   case PPC::LHAX:
11397   case PPC::LHAX8:
11398   case PPC::LWA:
11399   case PPC::LWAUX:
11400   case PPC::LWAX:
11401   case PPC::LWAX_32:
11402   case PPC::LWA_32:
11403   case PPC::PLHA:
11404   case PPC::PLHA8:
11405   case PPC::PLHA8pc:
11406   case PPC::PLHApc:
11407   case PPC::PLWA:
11408   case PPC::PLWA8:
11409   case PPC::PLWA8pc:
11410   case PPC::PLWApc:
11411   case PPC::EXTSB:
11412   case PPC::EXTSB8:
11413   case PPC::EXTSB8_32_64:
11414   case PPC::EXTSB8_rec:
11415   case PPC::EXTSB_rec:
11416   case PPC::EXTSH:
11417   case PPC::EXTSH8:
11418   case PPC::EXTSH8_32_64:
11419   case PPC::EXTSH8_rec:
11420   case PPC::EXTSH_rec:
11421   case PPC::EXTSW:
11422   case PPC::EXTSWSLI:
11423   case PPC::EXTSWSLI_32_64:
11424   case PPC::EXTSWSLI_32_64_rec:
11425   case PPC::EXTSWSLI_rec:
11426   case PPC::EXTSW_32:
11427   case PPC::EXTSW_32_64:
11428   case PPC::EXTSW_32_64_rec:
11429   case PPC::EXTSW_rec:
11430   case PPC::SRAW:
11431   case PPC::SRAWI:
11432   case PPC::SRAWI_rec:
11433   case PPC::SRAW_rec:
11434     return true;
11435   }
11436   return false;
11437 }
11438 
11439 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11440     MachineInstr &MI, MachineBasicBlock *BB,
11441     bool is8bit, // operation
11442     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11443   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11444   const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11445 
11446   // If this is a signed comparison and the value being compared is not known
11447   // to be sign extended, sign extend it here.
11448   DebugLoc dl = MI.getDebugLoc();
11449   MachineFunction *F = BB->getParent();
11450   MachineRegisterInfo &RegInfo = F->getRegInfo();
11451   Register incr = MI.getOperand(3).getReg();
11452   bool IsSignExtended = Register::isVirtualRegister(incr) &&
11453     isSignExtended(*RegInfo.getVRegDef(incr), TII);
11454 
11455   if (CmpOpcode == PPC::CMPW && !IsSignExtended) {
11456     Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11457     BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg)
11458         .addReg(MI.getOperand(3).getReg());
11459     MI.getOperand(3).setReg(ValueReg);
11460   }
11461   // If we support part-word atomic mnemonics, just use them
11462   if (Subtarget.hasPartwordAtomics())
11463     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11464                             CmpPred);
11465 
11466   // In 64 bit mode we have to use 64 bits for addresses, even though the
11467   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11468   // registers without caring whether they're 32 or 64, but here we're
11469   // doing actual arithmetic on the addresses.
11470   bool is64bit = Subtarget.isPPC64();
11471   bool isLittleEndian = Subtarget.isLittleEndian();
11472   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11473 
11474   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11475   MachineFunction::iterator It = ++BB->getIterator();
11476 
11477   Register dest = MI.getOperand(0).getReg();
11478   Register ptrA = MI.getOperand(1).getReg();
11479   Register ptrB = MI.getOperand(2).getReg();
11480 
11481   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11482   MachineBasicBlock *loop2MBB =
11483       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11484   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11485   F->insert(It, loopMBB);
11486   if (CmpOpcode)
11487     F->insert(It, loop2MBB);
11488   F->insert(It, exitMBB);
11489   exitMBB->splice(exitMBB->begin(), BB,
11490                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11491   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11492 
11493   const TargetRegisterClass *RC =
11494       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11495   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11496 
11497   Register PtrReg = RegInfo.createVirtualRegister(RC);
11498   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11499   Register ShiftReg =
11500       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11501   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11502   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11503   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11504   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11505   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11506   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11507   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11508   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11509   Register SrwDestReg = RegInfo.createVirtualRegister(GPRC);
11510   Register Ptr1Reg;
11511   Register TmpReg =
11512       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11513 
11514   //  thisMBB:
11515   //   ...
11516   //   fallthrough --> loopMBB
11517   BB->addSuccessor(loopMBB);
11518 
11519   // The 4-byte load must be aligned, while a char or short may be
11520   // anywhere in the word.  Hence all this nasty bookkeeping code.
11521   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11522   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11523   //   xori shift, shift1, 24 [16]
11524   //   rlwinm ptr, ptr1, 0, 0, 29
11525   //   slw incr2, incr, shift
11526   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11527   //   slw mask, mask2, shift
11528   //  loopMBB:
11529   //   lwarx tmpDest, ptr
11530   //   add tmp, tmpDest, incr2
11531   //   andc tmp2, tmpDest, mask
11532   //   and tmp3, tmp, mask
11533   //   or tmp4, tmp3, tmp2
11534   //   stwcx. tmp4, ptr
11535   //   bne- loopMBB
11536   //   fallthrough --> exitMBB
11537   //   srw SrwDest, tmpDest, shift
11538   //   rlwinm SrwDest, SrwDest, 0, 24 [16], 31
11539   if (ptrA != ZeroReg) {
11540     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11541     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11542         .addReg(ptrA)
11543         .addReg(ptrB);
11544   } else {
11545     Ptr1Reg = ptrB;
11546   }
11547   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11548   // mode.
11549   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11550       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11551       .addImm(3)
11552       .addImm(27)
11553       .addImm(is8bit ? 28 : 27);
11554   if (!isLittleEndian)
11555     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11556         .addReg(Shift1Reg)
11557         .addImm(is8bit ? 24 : 16);
11558   if (is64bit)
11559     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11560         .addReg(Ptr1Reg)
11561         .addImm(0)
11562         .addImm(61);
11563   else
11564     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11565         .addReg(Ptr1Reg)
11566         .addImm(0)
11567         .addImm(0)
11568         .addImm(29);
11569   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11570   if (is8bit)
11571     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11572   else {
11573     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11574     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11575         .addReg(Mask3Reg)
11576         .addImm(65535);
11577   }
11578   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11579       .addReg(Mask2Reg)
11580       .addReg(ShiftReg);
11581 
11582   BB = loopMBB;
11583   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11584       .addReg(ZeroReg)
11585       .addReg(PtrReg);
11586   if (BinOpcode)
11587     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11588         .addReg(Incr2Reg)
11589         .addReg(TmpDestReg);
11590   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11591       .addReg(TmpDestReg)
11592       .addReg(MaskReg);
11593   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11594   if (CmpOpcode) {
11595     // For unsigned comparisons, we can directly compare the shifted values.
11596     // For signed comparisons we shift and sign extend.
11597     Register SReg = RegInfo.createVirtualRegister(GPRC);
11598     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11599         .addReg(TmpDestReg)
11600         .addReg(MaskReg);
11601     unsigned ValueReg = SReg;
11602     unsigned CmpReg = Incr2Reg;
11603     if (CmpOpcode == PPC::CMPW) {
11604       ValueReg = RegInfo.createVirtualRegister(GPRC);
11605       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11606           .addReg(SReg)
11607           .addReg(ShiftReg);
11608       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11609       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11610           .addReg(ValueReg);
11611       ValueReg = ValueSReg;
11612       CmpReg = incr;
11613     }
11614     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11615         .addReg(CmpReg)
11616         .addReg(ValueReg);
11617     BuildMI(BB, dl, TII->get(PPC::BCC))
11618         .addImm(CmpPred)
11619         .addReg(PPC::CR0)
11620         .addMBB(exitMBB);
11621     BB->addSuccessor(loop2MBB);
11622     BB->addSuccessor(exitMBB);
11623     BB = loop2MBB;
11624   }
11625   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11626   BuildMI(BB, dl, TII->get(PPC::STWCX))
11627       .addReg(Tmp4Reg)
11628       .addReg(ZeroReg)
11629       .addReg(PtrReg);
11630   BuildMI(BB, dl, TII->get(PPC::BCC))
11631       .addImm(PPC::PRED_NE)
11632       .addReg(PPC::CR0)
11633       .addMBB(loopMBB);
11634   BB->addSuccessor(loopMBB);
11635   BB->addSuccessor(exitMBB);
11636 
11637   //  exitMBB:
11638   //   ...
11639   BB = exitMBB;
11640   // Since the shift amount is not a constant, we need to clear
11641   // the upper bits with a separate RLWINM.
11642   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest)
11643       .addReg(SrwDestReg)
11644       .addImm(0)
11645       .addImm(is8bit ? 24 : 16)
11646       .addImm(31);
11647   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg)
11648       .addReg(TmpDestReg)
11649       .addReg(ShiftReg);
11650   return BB;
11651 }
11652 
11653 llvm::MachineBasicBlock *
11654 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11655                                     MachineBasicBlock *MBB) const {
11656   DebugLoc DL = MI.getDebugLoc();
11657   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11658   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11659 
11660   MachineFunction *MF = MBB->getParent();
11661   MachineRegisterInfo &MRI = MF->getRegInfo();
11662 
11663   const BasicBlock *BB = MBB->getBasicBlock();
11664   MachineFunction::iterator I = ++MBB->getIterator();
11665 
11666   Register DstReg = MI.getOperand(0).getReg();
11667   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11668   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11669   Register mainDstReg = MRI.createVirtualRegister(RC);
11670   Register restoreDstReg = MRI.createVirtualRegister(RC);
11671 
11672   MVT PVT = getPointerTy(MF->getDataLayout());
11673   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11674          "Invalid Pointer Size!");
11675   // For v = setjmp(buf), we generate
11676   //
11677   // thisMBB:
11678   //  SjLjSetup mainMBB
11679   //  bl mainMBB
11680   //  v_restore = 1
11681   //  b sinkMBB
11682   //
11683   // mainMBB:
11684   //  buf[LabelOffset] = LR
11685   //  v_main = 0
11686   //
11687   // sinkMBB:
11688   //  v = phi(main, restore)
11689   //
11690 
11691   MachineBasicBlock *thisMBB = MBB;
11692   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11693   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11694   MF->insert(I, mainMBB);
11695   MF->insert(I, sinkMBB);
11696 
11697   MachineInstrBuilder MIB;
11698 
11699   // Transfer the remainder of BB and its successor edges to sinkMBB.
11700   sinkMBB->splice(sinkMBB->begin(), MBB,
11701                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11702   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11703 
11704   // Note that the structure of the jmp_buf used here is not compatible
11705   // with that used by libc, and is not designed to be. Specifically, it
11706   // stores only those 'reserved' registers that LLVM does not otherwise
11707   // understand how to spill. Also, by convention, by the time this
11708   // intrinsic is called, Clang has already stored the frame address in the
11709   // first slot of the buffer and stack address in the third. Following the
11710   // X86 target code, we'll store the jump address in the second slot. We also
11711   // need to save the TOC pointer (R2) to handle jumps between shared
11712   // libraries, and that will be stored in the fourth slot. The thread
11713   // identifier (R13) is not affected.
11714 
11715   // thisMBB:
11716   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11717   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11718   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11719 
11720   // Prepare IP either in reg.
11721   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11722   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11723   Register BufReg = MI.getOperand(1).getReg();
11724 
11725   if (Subtarget.is64BitELFABI()) {
11726     setUsesTOCBasePtr(*MBB->getParent());
11727     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11728               .addReg(PPC::X2)
11729               .addImm(TOCOffset)
11730               .addReg(BufReg)
11731               .cloneMemRefs(MI);
11732   }
11733 
11734   // Naked functions never have a base pointer, and so we use r1. For all
11735   // other functions, this decision must be delayed until during PEI.
11736   unsigned BaseReg;
11737   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11738     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11739   else
11740     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11741 
11742   MIB = BuildMI(*thisMBB, MI, DL,
11743                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11744             .addReg(BaseReg)
11745             .addImm(BPOffset)
11746             .addReg(BufReg)
11747             .cloneMemRefs(MI);
11748 
11749   // Setup
11750   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11751   MIB.addRegMask(TRI->getNoPreservedMask());
11752 
11753   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11754 
11755   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11756           .addMBB(mainMBB);
11757   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11758 
11759   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11760   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11761 
11762   // mainMBB:
11763   //  mainDstReg = 0
11764   MIB =
11765       BuildMI(mainMBB, DL,
11766               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11767 
11768   // Store IP
11769   if (Subtarget.isPPC64()) {
11770     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11771             .addReg(LabelReg)
11772             .addImm(LabelOffset)
11773             .addReg(BufReg);
11774   } else {
11775     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11776             .addReg(LabelReg)
11777             .addImm(LabelOffset)
11778             .addReg(BufReg);
11779   }
11780   MIB.cloneMemRefs(MI);
11781 
11782   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11783   mainMBB->addSuccessor(sinkMBB);
11784 
11785   // sinkMBB:
11786   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11787           TII->get(PPC::PHI), DstReg)
11788     .addReg(mainDstReg).addMBB(mainMBB)
11789     .addReg(restoreDstReg).addMBB(thisMBB);
11790 
11791   MI.eraseFromParent();
11792   return sinkMBB;
11793 }
11794 
11795 MachineBasicBlock *
11796 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11797                                      MachineBasicBlock *MBB) const {
11798   DebugLoc DL = MI.getDebugLoc();
11799   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11800 
11801   MachineFunction *MF = MBB->getParent();
11802   MachineRegisterInfo &MRI = MF->getRegInfo();
11803 
11804   MVT PVT = getPointerTy(MF->getDataLayout());
11805   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11806          "Invalid Pointer Size!");
11807 
11808   const TargetRegisterClass *RC =
11809     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11810   Register Tmp = MRI.createVirtualRegister(RC);
11811   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11812   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11813   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11814   unsigned BP =
11815       (PVT == MVT::i64)
11816           ? PPC::X30
11817           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11818                                                               : PPC::R30);
11819 
11820   MachineInstrBuilder MIB;
11821 
11822   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11823   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11824   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11825   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11826 
11827   Register BufReg = MI.getOperand(0).getReg();
11828 
11829   // Reload FP (the jumped-to function may not have had a
11830   // frame pointer, and if so, then its r31 will be restored
11831   // as necessary).
11832   if (PVT == MVT::i64) {
11833     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11834             .addImm(0)
11835             .addReg(BufReg);
11836   } else {
11837     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11838             .addImm(0)
11839             .addReg(BufReg);
11840   }
11841   MIB.cloneMemRefs(MI);
11842 
11843   // Reload IP
11844   if (PVT == MVT::i64) {
11845     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11846             .addImm(LabelOffset)
11847             .addReg(BufReg);
11848   } else {
11849     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11850             .addImm(LabelOffset)
11851             .addReg(BufReg);
11852   }
11853   MIB.cloneMemRefs(MI);
11854 
11855   // Reload SP
11856   if (PVT == MVT::i64) {
11857     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11858             .addImm(SPOffset)
11859             .addReg(BufReg);
11860   } else {
11861     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11862             .addImm(SPOffset)
11863             .addReg(BufReg);
11864   }
11865   MIB.cloneMemRefs(MI);
11866 
11867   // Reload BP
11868   if (PVT == MVT::i64) {
11869     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11870             .addImm(BPOffset)
11871             .addReg(BufReg);
11872   } else {
11873     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11874             .addImm(BPOffset)
11875             .addReg(BufReg);
11876   }
11877   MIB.cloneMemRefs(MI);
11878 
11879   // Reload TOC
11880   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11881     setUsesTOCBasePtr(*MBB->getParent());
11882     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11883               .addImm(TOCOffset)
11884               .addReg(BufReg)
11885               .cloneMemRefs(MI);
11886   }
11887 
11888   // Jump
11889   BuildMI(*MBB, MI, DL,
11890           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11891   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11892 
11893   MI.eraseFromParent();
11894   return MBB;
11895 }
11896 
11897 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11898   // If the function specifically requests inline stack probes, emit them.
11899   if (MF.getFunction().hasFnAttribute("probe-stack"))
11900     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11901            "inline-asm";
11902   return false;
11903 }
11904 
11905 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11906   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11907   unsigned StackAlign = TFI->getStackAlignment();
11908   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11909          "Unexpected stack alignment");
11910   // The default stack probe size is 4096 if the function has no
11911   // stack-probe-size attribute.
11912   unsigned StackProbeSize = 4096;
11913   const Function &Fn = MF.getFunction();
11914   if (Fn.hasFnAttribute("stack-probe-size"))
11915     Fn.getFnAttribute("stack-probe-size")
11916         .getValueAsString()
11917         .getAsInteger(0, StackProbeSize);
11918   // Round down to the stack alignment.
11919   StackProbeSize &= ~(StackAlign - 1);
11920   return StackProbeSize ? StackProbeSize : StackAlign;
11921 }
11922 
11923 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11924 // into three phases. In the first phase, it uses pseudo instruction
11925 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11926 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11927 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11928 // MaxCallFrameSize so that it can calculate correct data area pointer.
11929 MachineBasicBlock *
11930 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11931                                     MachineBasicBlock *MBB) const {
11932   const bool isPPC64 = Subtarget.isPPC64();
11933   MachineFunction *MF = MBB->getParent();
11934   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11935   DebugLoc DL = MI.getDebugLoc();
11936   const unsigned ProbeSize = getStackProbeSize(*MF);
11937   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11938   MachineRegisterInfo &MRI = MF->getRegInfo();
11939   // The CFG of probing stack looks as
11940   //         +-----+
11941   //         | MBB |
11942   //         +--+--+
11943   //            |
11944   //       +----v----+
11945   //  +--->+ TestMBB +---+
11946   //  |    +----+----+   |
11947   //  |         |        |
11948   //  |   +-----v----+   |
11949   //  +---+ BlockMBB |   |
11950   //      +----------+   |
11951   //                     |
11952   //       +---------+   |
11953   //       | TailMBB +<--+
11954   //       +---------+
11955   // In MBB, calculate previous frame pointer and final stack pointer.
11956   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11957   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11958   // TailMBB is spliced via \p MI.
11959   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11960   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11961   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11962 
11963   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11964   MF->insert(MBBIter, TestMBB);
11965   MF->insert(MBBIter, BlockMBB);
11966   MF->insert(MBBIter, TailMBB);
11967 
11968   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11969   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11970 
11971   Register DstReg = MI.getOperand(0).getReg();
11972   Register NegSizeReg = MI.getOperand(1).getReg();
11973   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11974   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11975   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11976   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11977 
11978   // Since value of NegSizeReg might be realigned in prologepilog, insert a
11979   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
11980   // NegSize.
11981   unsigned ProbeOpc;
11982   if (!MRI.hasOneNonDBGUse(NegSizeReg))
11983     ProbeOpc =
11984         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
11985   else
11986     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
11987     // and NegSizeReg will be allocated in the same phyreg to avoid
11988     // redundant copy when NegSizeReg has only one use which is current MI and
11989     // will be replaced by PREPARE_PROBED_ALLOCA then.
11990     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
11991                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
11992   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
11993       .addDef(ActualNegSizeReg)
11994       .addReg(NegSizeReg)
11995       .add(MI.getOperand(2))
11996       .add(MI.getOperand(3));
11997 
11998   // Calculate final stack pointer, which equals to SP + ActualNegSize.
11999   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
12000           FinalStackPtr)
12001       .addReg(SPReg)
12002       .addReg(ActualNegSizeReg);
12003 
12004   // Materialize a scratch register for update.
12005   int64_t NegProbeSize = -(int64_t)ProbeSize;
12006   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
12007   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12008   if (!isInt<16>(NegProbeSize)) {
12009     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12010     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
12011         .addImm(NegProbeSize >> 16);
12012     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
12013             ScratchReg)
12014         .addReg(TempReg)
12015         .addImm(NegProbeSize & 0xFFFF);
12016   } else
12017     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
12018         .addImm(NegProbeSize);
12019 
12020   {
12021     // Probing leading residual part.
12022     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12023     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
12024         .addReg(ActualNegSizeReg)
12025         .addReg(ScratchReg);
12026     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12027     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
12028         .addReg(Div)
12029         .addReg(ScratchReg);
12030     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12031     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
12032         .addReg(Mul)
12033         .addReg(ActualNegSizeReg);
12034     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
12035         .addReg(FramePointer)
12036         .addReg(SPReg)
12037         .addReg(NegMod);
12038   }
12039 
12040   {
12041     // Remaining part should be multiple of ProbeSize.
12042     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
12043     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
12044         .addReg(SPReg)
12045         .addReg(FinalStackPtr);
12046     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
12047         .addImm(PPC::PRED_EQ)
12048         .addReg(CmpResult)
12049         .addMBB(TailMBB);
12050     TestMBB->addSuccessor(BlockMBB);
12051     TestMBB->addSuccessor(TailMBB);
12052   }
12053 
12054   {
12055     // Touch the block.
12056     // |P...|P...|P...
12057     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
12058         .addReg(FramePointer)
12059         .addReg(SPReg)
12060         .addReg(ScratchReg);
12061     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
12062     BlockMBB->addSuccessor(TestMBB);
12063   }
12064 
12065   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
12066   // DYNAREAOFFSET pseudo instruction to get the future result.
12067   Register MaxCallFrameSizeReg =
12068       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12069   BuildMI(TailMBB, DL,
12070           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
12071           MaxCallFrameSizeReg)
12072       .add(MI.getOperand(2))
12073       .add(MI.getOperand(3));
12074   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
12075       .addReg(SPReg)
12076       .addReg(MaxCallFrameSizeReg);
12077 
12078   // Splice instructions after MI to TailMBB.
12079   TailMBB->splice(TailMBB->end(), MBB,
12080                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
12081   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
12082   MBB->addSuccessor(TestMBB);
12083 
12084   // Delete the pseudo instruction.
12085   MI.eraseFromParent();
12086 
12087   ++NumDynamicAllocaProbed;
12088   return TailMBB;
12089 }
12090 
12091 MachineBasicBlock *
12092 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
12093                                                MachineBasicBlock *BB) const {
12094   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
12095       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
12096     if (Subtarget.is64BitELFABI() &&
12097         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
12098         !Subtarget.isUsingPCRelativeCalls()) {
12099       // Call lowering should have added an r2 operand to indicate a dependence
12100       // on the TOC base pointer value. It can't however, because there is no
12101       // way to mark the dependence as implicit there, and so the stackmap code
12102       // will confuse it with a regular operand. Instead, add the dependence
12103       // here.
12104       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
12105     }
12106 
12107     return emitPatchPoint(MI, BB);
12108   }
12109 
12110   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
12111       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
12112     return emitEHSjLjSetJmp(MI, BB);
12113   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
12114              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
12115     return emitEHSjLjLongJmp(MI, BB);
12116   }
12117 
12118   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12119 
12120   // To "insert" these instructions we actually have to insert their
12121   // control-flow patterns.
12122   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12123   MachineFunction::iterator It = ++BB->getIterator();
12124 
12125   MachineFunction *F = BB->getParent();
12126   MachineRegisterInfo &MRI = F->getRegInfo();
12127 
12128   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12129       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
12130       MI.getOpcode() == PPC::SELECT_I8) {
12131     SmallVector<MachineOperand, 2> Cond;
12132     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12133         MI.getOpcode() == PPC::SELECT_CC_I8)
12134       Cond.push_back(MI.getOperand(4));
12135     else
12136       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
12137     Cond.push_back(MI.getOperand(1));
12138 
12139     DebugLoc dl = MI.getDebugLoc();
12140     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
12141                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
12142   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
12143              MI.getOpcode() == PPC::SELECT_CC_F8 ||
12144              MI.getOpcode() == PPC::SELECT_CC_F16 ||
12145              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
12146              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
12147              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
12148              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
12149              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
12150              MI.getOpcode() == PPC::SELECT_CC_SPE ||
12151              MI.getOpcode() == PPC::SELECT_F4 ||
12152              MI.getOpcode() == PPC::SELECT_F8 ||
12153              MI.getOpcode() == PPC::SELECT_F16 ||
12154              MI.getOpcode() == PPC::SELECT_SPE ||
12155              MI.getOpcode() == PPC::SELECT_SPE4 ||
12156              MI.getOpcode() == PPC::SELECT_VRRC ||
12157              MI.getOpcode() == PPC::SELECT_VSFRC ||
12158              MI.getOpcode() == PPC::SELECT_VSSRC ||
12159              MI.getOpcode() == PPC::SELECT_VSRC) {
12160     // The incoming instruction knows the destination vreg to set, the
12161     // condition code register to branch on, the true/false values to
12162     // select between, and a branch opcode to use.
12163 
12164     //  thisMBB:
12165     //  ...
12166     //   TrueVal = ...
12167     //   cmpTY ccX, r1, r2
12168     //   bCC copy1MBB
12169     //   fallthrough --> copy0MBB
12170     MachineBasicBlock *thisMBB = BB;
12171     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12172     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12173     DebugLoc dl = MI.getDebugLoc();
12174     F->insert(It, copy0MBB);
12175     F->insert(It, sinkMBB);
12176 
12177     // Transfer the remainder of BB and its successor edges to sinkMBB.
12178     sinkMBB->splice(sinkMBB->begin(), BB,
12179                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12180     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12181 
12182     // Next, add the true and fallthrough blocks as its successors.
12183     BB->addSuccessor(copy0MBB);
12184     BB->addSuccessor(sinkMBB);
12185 
12186     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
12187         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
12188         MI.getOpcode() == PPC::SELECT_F16 ||
12189         MI.getOpcode() == PPC::SELECT_SPE4 ||
12190         MI.getOpcode() == PPC::SELECT_SPE ||
12191         MI.getOpcode() == PPC::SELECT_VRRC ||
12192         MI.getOpcode() == PPC::SELECT_VSFRC ||
12193         MI.getOpcode() == PPC::SELECT_VSSRC ||
12194         MI.getOpcode() == PPC::SELECT_VSRC) {
12195       BuildMI(BB, dl, TII->get(PPC::BC))
12196           .addReg(MI.getOperand(1).getReg())
12197           .addMBB(sinkMBB);
12198     } else {
12199       unsigned SelectPred = MI.getOperand(4).getImm();
12200       BuildMI(BB, dl, TII->get(PPC::BCC))
12201           .addImm(SelectPred)
12202           .addReg(MI.getOperand(1).getReg())
12203           .addMBB(sinkMBB);
12204     }
12205 
12206     //  copy0MBB:
12207     //   %FalseValue = ...
12208     //   # fallthrough to sinkMBB
12209     BB = copy0MBB;
12210 
12211     // Update machine-CFG edges
12212     BB->addSuccessor(sinkMBB);
12213 
12214     //  sinkMBB:
12215     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12216     //  ...
12217     BB = sinkMBB;
12218     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
12219         .addReg(MI.getOperand(3).getReg())
12220         .addMBB(copy0MBB)
12221         .addReg(MI.getOperand(2).getReg())
12222         .addMBB(thisMBB);
12223   } else if (MI.getOpcode() == PPC::ReadTB) {
12224     // To read the 64-bit time-base register on a 32-bit target, we read the
12225     // two halves. Should the counter have wrapped while it was being read, we
12226     // need to try again.
12227     // ...
12228     // readLoop:
12229     // mfspr Rx,TBU # load from TBU
12230     // mfspr Ry,TB  # load from TB
12231     // mfspr Rz,TBU # load from TBU
12232     // cmpw crX,Rx,Rz # check if 'old'='new'
12233     // bne readLoop   # branch if they're not equal
12234     // ...
12235 
12236     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
12237     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12238     DebugLoc dl = MI.getDebugLoc();
12239     F->insert(It, readMBB);
12240     F->insert(It, sinkMBB);
12241 
12242     // Transfer the remainder of BB and its successor edges to sinkMBB.
12243     sinkMBB->splice(sinkMBB->begin(), BB,
12244                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12245     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12246 
12247     BB->addSuccessor(readMBB);
12248     BB = readMBB;
12249 
12250     MachineRegisterInfo &RegInfo = F->getRegInfo();
12251     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
12252     Register LoReg = MI.getOperand(0).getReg();
12253     Register HiReg = MI.getOperand(1).getReg();
12254 
12255     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
12256     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
12257     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
12258 
12259     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12260 
12261     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
12262         .addReg(HiReg)
12263         .addReg(ReadAgainReg);
12264     BuildMI(BB, dl, TII->get(PPC::BCC))
12265         .addImm(PPC::PRED_NE)
12266         .addReg(CmpReg)
12267         .addMBB(readMBB);
12268 
12269     BB->addSuccessor(readMBB);
12270     BB->addSuccessor(sinkMBB);
12271   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
12272     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
12273   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
12274     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
12275   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
12276     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
12277   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
12278     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
12279 
12280   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
12281     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
12282   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
12283     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
12284   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
12285     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
12286   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
12287     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
12288 
12289   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
12290     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
12291   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
12292     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
12293   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
12294     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
12295   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
12296     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
12297 
12298   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
12299     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
12300   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
12301     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
12302   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
12303     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
12304   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
12305     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
12306 
12307   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
12308     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
12309   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
12310     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
12311   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
12312     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
12313   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
12314     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
12315 
12316   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
12317     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
12318   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
12319     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
12320   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
12321     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
12322   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
12323     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
12324 
12325   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
12326     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
12327   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
12328     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
12329   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
12330     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
12331   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
12332     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
12333 
12334   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
12335     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
12336   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
12337     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
12338   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
12339     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
12340   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
12341     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
12342 
12343   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
12344     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
12345   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
12346     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
12347   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
12348     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
12349   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
12350     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
12351 
12352   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
12353     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
12354   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
12355     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
12356   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
12357     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
12358   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
12359     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
12360 
12361   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
12362     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
12363   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
12364     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
12365   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
12366     BB = EmitAtomicBinary(MI, BB, 4, 0);
12367   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
12368     BB = EmitAtomicBinary(MI, BB, 8, 0);
12369   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
12370            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
12371            (Subtarget.hasPartwordAtomics() &&
12372             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
12373            (Subtarget.hasPartwordAtomics() &&
12374             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
12375     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
12376 
12377     auto LoadMnemonic = PPC::LDARX;
12378     auto StoreMnemonic = PPC::STDCX;
12379     switch (MI.getOpcode()) {
12380     default:
12381       llvm_unreachable("Compare and swap of unknown size");
12382     case PPC::ATOMIC_CMP_SWAP_I8:
12383       LoadMnemonic = PPC::LBARX;
12384       StoreMnemonic = PPC::STBCX;
12385       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12386       break;
12387     case PPC::ATOMIC_CMP_SWAP_I16:
12388       LoadMnemonic = PPC::LHARX;
12389       StoreMnemonic = PPC::STHCX;
12390       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12391       break;
12392     case PPC::ATOMIC_CMP_SWAP_I32:
12393       LoadMnemonic = PPC::LWARX;
12394       StoreMnemonic = PPC::STWCX;
12395       break;
12396     case PPC::ATOMIC_CMP_SWAP_I64:
12397       LoadMnemonic = PPC::LDARX;
12398       StoreMnemonic = PPC::STDCX;
12399       break;
12400     }
12401     Register dest = MI.getOperand(0).getReg();
12402     Register ptrA = MI.getOperand(1).getReg();
12403     Register ptrB = MI.getOperand(2).getReg();
12404     Register oldval = MI.getOperand(3).getReg();
12405     Register newval = MI.getOperand(4).getReg();
12406     DebugLoc dl = MI.getDebugLoc();
12407 
12408     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12409     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12410     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12411     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12412     F->insert(It, loop1MBB);
12413     F->insert(It, loop2MBB);
12414     F->insert(It, midMBB);
12415     F->insert(It, exitMBB);
12416     exitMBB->splice(exitMBB->begin(), BB,
12417                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12418     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12419 
12420     //  thisMBB:
12421     //   ...
12422     //   fallthrough --> loopMBB
12423     BB->addSuccessor(loop1MBB);
12424 
12425     // loop1MBB:
12426     //   l[bhwd]arx dest, ptr
12427     //   cmp[wd] dest, oldval
12428     //   bne- midMBB
12429     // loop2MBB:
12430     //   st[bhwd]cx. newval, ptr
12431     //   bne- loopMBB
12432     //   b exitBB
12433     // midMBB:
12434     //   st[bhwd]cx. dest, ptr
12435     // exitBB:
12436     BB = loop1MBB;
12437     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12438     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12439         .addReg(oldval)
12440         .addReg(dest);
12441     BuildMI(BB, dl, TII->get(PPC::BCC))
12442         .addImm(PPC::PRED_NE)
12443         .addReg(PPC::CR0)
12444         .addMBB(midMBB);
12445     BB->addSuccessor(loop2MBB);
12446     BB->addSuccessor(midMBB);
12447 
12448     BB = loop2MBB;
12449     BuildMI(BB, dl, TII->get(StoreMnemonic))
12450         .addReg(newval)
12451         .addReg(ptrA)
12452         .addReg(ptrB);
12453     BuildMI(BB, dl, TII->get(PPC::BCC))
12454         .addImm(PPC::PRED_NE)
12455         .addReg(PPC::CR0)
12456         .addMBB(loop1MBB);
12457     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12458     BB->addSuccessor(loop1MBB);
12459     BB->addSuccessor(exitMBB);
12460 
12461     BB = midMBB;
12462     BuildMI(BB, dl, TII->get(StoreMnemonic))
12463         .addReg(dest)
12464         .addReg(ptrA)
12465         .addReg(ptrB);
12466     BB->addSuccessor(exitMBB);
12467 
12468     //  exitMBB:
12469     //   ...
12470     BB = exitMBB;
12471   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12472              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12473     // We must use 64-bit registers for addresses when targeting 64-bit,
12474     // since we're actually doing arithmetic on them.  Other registers
12475     // can be 32-bit.
12476     bool is64bit = Subtarget.isPPC64();
12477     bool isLittleEndian = Subtarget.isLittleEndian();
12478     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12479 
12480     Register dest = MI.getOperand(0).getReg();
12481     Register ptrA = MI.getOperand(1).getReg();
12482     Register ptrB = MI.getOperand(2).getReg();
12483     Register oldval = MI.getOperand(3).getReg();
12484     Register newval = MI.getOperand(4).getReg();
12485     DebugLoc dl = MI.getDebugLoc();
12486 
12487     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12488     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12489     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12490     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12491     F->insert(It, loop1MBB);
12492     F->insert(It, loop2MBB);
12493     F->insert(It, midMBB);
12494     F->insert(It, exitMBB);
12495     exitMBB->splice(exitMBB->begin(), BB,
12496                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12497     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12498 
12499     MachineRegisterInfo &RegInfo = F->getRegInfo();
12500     const TargetRegisterClass *RC =
12501         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12502     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12503 
12504     Register PtrReg = RegInfo.createVirtualRegister(RC);
12505     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12506     Register ShiftReg =
12507         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12508     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12509     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12510     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12511     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12512     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12513     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12514     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12515     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12516     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12517     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12518     Register Ptr1Reg;
12519     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12520     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12521     //  thisMBB:
12522     //   ...
12523     //   fallthrough --> loopMBB
12524     BB->addSuccessor(loop1MBB);
12525 
12526     // The 4-byte load must be aligned, while a char or short may be
12527     // anywhere in the word.  Hence all this nasty bookkeeping code.
12528     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12529     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12530     //   xori shift, shift1, 24 [16]
12531     //   rlwinm ptr, ptr1, 0, 0, 29
12532     //   slw newval2, newval, shift
12533     //   slw oldval2, oldval,shift
12534     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12535     //   slw mask, mask2, shift
12536     //   and newval3, newval2, mask
12537     //   and oldval3, oldval2, mask
12538     // loop1MBB:
12539     //   lwarx tmpDest, ptr
12540     //   and tmp, tmpDest, mask
12541     //   cmpw tmp, oldval3
12542     //   bne- midMBB
12543     // loop2MBB:
12544     //   andc tmp2, tmpDest, mask
12545     //   or tmp4, tmp2, newval3
12546     //   stwcx. tmp4, ptr
12547     //   bne- loop1MBB
12548     //   b exitBB
12549     // midMBB:
12550     //   stwcx. tmpDest, ptr
12551     // exitBB:
12552     //   srw dest, tmpDest, shift
12553     if (ptrA != ZeroReg) {
12554       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12555       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12556           .addReg(ptrA)
12557           .addReg(ptrB);
12558     } else {
12559       Ptr1Reg = ptrB;
12560     }
12561 
12562     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12563     // mode.
12564     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12565         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12566         .addImm(3)
12567         .addImm(27)
12568         .addImm(is8bit ? 28 : 27);
12569     if (!isLittleEndian)
12570       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12571           .addReg(Shift1Reg)
12572           .addImm(is8bit ? 24 : 16);
12573     if (is64bit)
12574       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12575           .addReg(Ptr1Reg)
12576           .addImm(0)
12577           .addImm(61);
12578     else
12579       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12580           .addReg(Ptr1Reg)
12581           .addImm(0)
12582           .addImm(0)
12583           .addImm(29);
12584     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12585         .addReg(newval)
12586         .addReg(ShiftReg);
12587     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12588         .addReg(oldval)
12589         .addReg(ShiftReg);
12590     if (is8bit)
12591       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12592     else {
12593       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12594       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12595           .addReg(Mask3Reg)
12596           .addImm(65535);
12597     }
12598     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12599         .addReg(Mask2Reg)
12600         .addReg(ShiftReg);
12601     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12602         .addReg(NewVal2Reg)
12603         .addReg(MaskReg);
12604     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12605         .addReg(OldVal2Reg)
12606         .addReg(MaskReg);
12607 
12608     BB = loop1MBB;
12609     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12610         .addReg(ZeroReg)
12611         .addReg(PtrReg);
12612     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12613         .addReg(TmpDestReg)
12614         .addReg(MaskReg);
12615     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12616         .addReg(TmpReg)
12617         .addReg(OldVal3Reg);
12618     BuildMI(BB, dl, TII->get(PPC::BCC))
12619         .addImm(PPC::PRED_NE)
12620         .addReg(PPC::CR0)
12621         .addMBB(midMBB);
12622     BB->addSuccessor(loop2MBB);
12623     BB->addSuccessor(midMBB);
12624 
12625     BB = loop2MBB;
12626     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12627         .addReg(TmpDestReg)
12628         .addReg(MaskReg);
12629     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12630         .addReg(Tmp2Reg)
12631         .addReg(NewVal3Reg);
12632     BuildMI(BB, dl, TII->get(PPC::STWCX))
12633         .addReg(Tmp4Reg)
12634         .addReg(ZeroReg)
12635         .addReg(PtrReg);
12636     BuildMI(BB, dl, TII->get(PPC::BCC))
12637         .addImm(PPC::PRED_NE)
12638         .addReg(PPC::CR0)
12639         .addMBB(loop1MBB);
12640     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12641     BB->addSuccessor(loop1MBB);
12642     BB->addSuccessor(exitMBB);
12643 
12644     BB = midMBB;
12645     BuildMI(BB, dl, TII->get(PPC::STWCX))
12646         .addReg(TmpDestReg)
12647         .addReg(ZeroReg)
12648         .addReg(PtrReg);
12649     BB->addSuccessor(exitMBB);
12650 
12651     //  exitMBB:
12652     //   ...
12653     BB = exitMBB;
12654     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12655         .addReg(TmpReg)
12656         .addReg(ShiftReg);
12657   } else if (MI.getOpcode() == PPC::FADDrtz) {
12658     // This pseudo performs an FADD with rounding mode temporarily forced
12659     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12660     // is not modeled at the SelectionDAG level.
12661     Register Dest = MI.getOperand(0).getReg();
12662     Register Src1 = MI.getOperand(1).getReg();
12663     Register Src2 = MI.getOperand(2).getReg();
12664     DebugLoc dl = MI.getDebugLoc();
12665 
12666     MachineRegisterInfo &RegInfo = F->getRegInfo();
12667     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12668 
12669     // Save FPSCR value.
12670     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12671 
12672     // Set rounding mode to round-to-zero.
12673     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12674         .addImm(31)
12675         .addReg(PPC::RM, RegState::ImplicitDefine);
12676 
12677     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12678         .addImm(30)
12679         .addReg(PPC::RM, RegState::ImplicitDefine);
12680 
12681     // Perform addition.
12682     auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
12683                    .addReg(Src1)
12684                    .addReg(Src2);
12685     if (MI.getFlag(MachineInstr::NoFPExcept))
12686       MIB.setMIFlag(MachineInstr::NoFPExcept);
12687 
12688     // Restore FPSCR value.
12689     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12690   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12691              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12692              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12693              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12694     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12695                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12696                           ? PPC::ANDI8_rec
12697                           : PPC::ANDI_rec;
12698     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12699                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12700 
12701     MachineRegisterInfo &RegInfo = F->getRegInfo();
12702     Register Dest = RegInfo.createVirtualRegister(
12703         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12704 
12705     DebugLoc Dl = MI.getDebugLoc();
12706     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12707         .addReg(MI.getOperand(1).getReg())
12708         .addImm(1);
12709     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12710             MI.getOperand(0).getReg())
12711         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12712   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12713     DebugLoc Dl = MI.getDebugLoc();
12714     MachineRegisterInfo &RegInfo = F->getRegInfo();
12715     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12716     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12717     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12718             MI.getOperand(0).getReg())
12719         .addReg(CRReg);
12720   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12721     DebugLoc Dl = MI.getDebugLoc();
12722     unsigned Imm = MI.getOperand(1).getImm();
12723     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12724     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12725             MI.getOperand(0).getReg())
12726         .addReg(PPC::CR0EQ);
12727   } else if (MI.getOpcode() == PPC::SETRNDi) {
12728     DebugLoc dl = MI.getDebugLoc();
12729     Register OldFPSCRReg = MI.getOperand(0).getReg();
12730 
12731     // Save FPSCR value.
12732     if (MRI.use_empty(OldFPSCRReg))
12733       BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
12734     else
12735       BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12736 
12737     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12738     // the following settings:
12739     //   00 Round to nearest
12740     //   01 Round to 0
12741     //   10 Round to +inf
12742     //   11 Round to -inf
12743 
12744     // When the operand is immediate, using the two least significant bits of
12745     // the immediate to set the bits 62:63 of FPSCR.
12746     unsigned Mode = MI.getOperand(1).getImm();
12747     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12748         .addImm(31)
12749         .addReg(PPC::RM, RegState::ImplicitDefine);
12750 
12751     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12752         .addImm(30)
12753         .addReg(PPC::RM, RegState::ImplicitDefine);
12754   } else if (MI.getOpcode() == PPC::SETRND) {
12755     DebugLoc dl = MI.getDebugLoc();
12756 
12757     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12758     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12759     // If the target doesn't have DirectMove, we should use stack to do the
12760     // conversion, because the target doesn't have the instructions like mtvsrd
12761     // or mfvsrd to do this conversion directly.
12762     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12763       if (Subtarget.hasDirectMove()) {
12764         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12765           .addReg(SrcReg);
12766       } else {
12767         // Use stack to do the register copy.
12768         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12769         MachineRegisterInfo &RegInfo = F->getRegInfo();
12770         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12771         if (RC == &PPC::F8RCRegClass) {
12772           // Copy register from F8RCRegClass to G8RCRegclass.
12773           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12774                  "Unsupported RegClass.");
12775 
12776           StoreOp = PPC::STFD;
12777           LoadOp = PPC::LD;
12778         } else {
12779           // Copy register from G8RCRegClass to F8RCRegclass.
12780           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12781                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12782                  "Unsupported RegClass.");
12783         }
12784 
12785         MachineFrameInfo &MFI = F->getFrameInfo();
12786         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12787 
12788         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12789             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12790             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12791             MFI.getObjectAlign(FrameIdx));
12792 
12793         // Store the SrcReg into the stack.
12794         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12795           .addReg(SrcReg)
12796           .addImm(0)
12797           .addFrameIndex(FrameIdx)
12798           .addMemOperand(MMOStore);
12799 
12800         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12801             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12802             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12803             MFI.getObjectAlign(FrameIdx));
12804 
12805         // Load from the stack where SrcReg is stored, and save to DestReg,
12806         // so we have done the RegClass conversion from RegClass::SrcReg to
12807         // RegClass::DestReg.
12808         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12809           .addImm(0)
12810           .addFrameIndex(FrameIdx)
12811           .addMemOperand(MMOLoad);
12812       }
12813     };
12814 
12815     Register OldFPSCRReg = MI.getOperand(0).getReg();
12816 
12817     // Save FPSCR value.
12818     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12819 
12820     // When the operand is gprc register, use two least significant bits of the
12821     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12822     //
12823     // copy OldFPSCRTmpReg, OldFPSCRReg
12824     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12825     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12826     // copy NewFPSCRReg, NewFPSCRTmpReg
12827     // mtfsf 255, NewFPSCRReg
12828     MachineOperand SrcOp = MI.getOperand(1);
12829     MachineRegisterInfo &RegInfo = F->getRegInfo();
12830     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12831 
12832     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12833 
12834     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12835     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12836 
12837     // The first operand of INSERT_SUBREG should be a register which has
12838     // subregisters, we only care about its RegClass, so we should use an
12839     // IMPLICIT_DEF register.
12840     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12841     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12842       .addReg(ImDefReg)
12843       .add(SrcOp)
12844       .addImm(1);
12845 
12846     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12847     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12848       .addReg(OldFPSCRTmpReg)
12849       .addReg(ExtSrcReg)
12850       .addImm(0)
12851       .addImm(62);
12852 
12853     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12854     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12855 
12856     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12857     // bits of FPSCR.
12858     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12859       .addImm(255)
12860       .addReg(NewFPSCRReg)
12861       .addImm(0)
12862       .addImm(0);
12863   } else if (MI.getOpcode() == PPC::SETFLM) {
12864     DebugLoc Dl = MI.getDebugLoc();
12865 
12866     // Result of setflm is previous FPSCR content, so we need to save it first.
12867     Register OldFPSCRReg = MI.getOperand(0).getReg();
12868     if (MRI.use_empty(OldFPSCRReg))
12869       BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
12870     else
12871       BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12872 
12873     // Put bits in 32:63 to FPSCR.
12874     Register NewFPSCRReg = MI.getOperand(1).getReg();
12875     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12876         .addImm(255)
12877         .addReg(NewFPSCRReg)
12878         .addImm(0)
12879         .addImm(0);
12880   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12881              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12882     return emitProbedAlloca(MI, BB);
12883   } else if (MI.getOpcode() == PPC::SPLIT_QUADWORD) {
12884     DebugLoc DL = MI.getDebugLoc();
12885     Register Src = MI.getOperand(2).getReg();
12886     Register Lo = MI.getOperand(0).getReg();
12887     Register Hi = MI.getOperand(1).getReg();
12888     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12889         .addDef(Lo)
12890         .addUse(Src, 0, PPC::sub_gp8_x1);
12891     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12892         .addDef(Hi)
12893         .addUse(Src, 0, PPC::sub_gp8_x0);
12894   } else if (MI.getOpcode() == PPC::LQX_PSEUDO ||
12895              MI.getOpcode() == PPC::STQX_PSEUDO) {
12896     DebugLoc DL = MI.getDebugLoc();
12897     // Ptr is used as the ptr_rc_no_r0 part
12898     // of LQ/STQ's memory operand and adding result of RA and RB,
12899     // so it has to be g8rc_and_g8rc_nox0.
12900     Register Ptr =
12901         F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
12902     Register Val = MI.getOperand(0).getReg();
12903     Register RA = MI.getOperand(1).getReg();
12904     Register RB = MI.getOperand(2).getReg();
12905     BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB);
12906     BuildMI(*BB, MI, DL,
12907             MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ)
12908                                               : TII->get(PPC::STQ))
12909         .addReg(Val, MI.getOpcode() == PPC::LQX_PSEUDO ? RegState::Define : 0)
12910         .addImm(0)
12911         .addReg(Ptr);
12912   } else {
12913     llvm_unreachable("Unexpected instr type to insert");
12914   }
12915 
12916   MI.eraseFromParent(); // The pseudo instruction is gone now.
12917   return BB;
12918 }
12919 
12920 //===----------------------------------------------------------------------===//
12921 // Target Optimization Hooks
12922 //===----------------------------------------------------------------------===//
12923 
12924 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12925   // For the estimates, convergence is quadratic, so we essentially double the
12926   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12927   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12928   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12929   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12930   if (VT.getScalarType() == MVT::f64)
12931     RefinementSteps++;
12932   return RefinementSteps;
12933 }
12934 
12935 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
12936                                             const DenormalMode &Mode) const {
12937   // We only have VSX Vector Test for software Square Root.
12938   EVT VT = Op.getValueType();
12939   if (!isTypeLegal(MVT::i1) ||
12940       (VT != MVT::f64 &&
12941        ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
12942     return TargetLowering::getSqrtInputTest(Op, DAG, Mode);
12943 
12944   SDLoc DL(Op);
12945   // The output register of FTSQRT is CR field.
12946   SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
12947   // ftsqrt BF,FRB
12948   // Let e_b be the unbiased exponent of the double-precision
12949   // floating-point operand in register FRB.
12950   // fe_flag is set to 1 if either of the following conditions occurs.
12951   //   - The double-precision floating-point operand in register FRB is a zero,
12952   //     a NaN, or an infinity, or a negative value.
12953   //   - e_b is less than or equal to -970.
12954   // Otherwise fe_flag is set to 0.
12955   // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
12956   // not eligible for iteration. (zero/negative/infinity/nan or unbiased
12957   // exponent is less than -970)
12958   SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
12959   return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
12960                                     FTSQRT, SRIdxVal),
12961                  0);
12962 }
12963 
12964 SDValue
12965 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
12966                                                SelectionDAG &DAG) const {
12967   // We only have VSX Vector Square Root.
12968   EVT VT = Op.getValueType();
12969   if (VT != MVT::f64 &&
12970       ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
12971     return TargetLowering::getSqrtResultForDenormInput(Op, DAG);
12972 
12973   return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
12974 }
12975 
12976 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12977                                            int Enabled, int &RefinementSteps,
12978                                            bool &UseOneConstNR,
12979                                            bool Reciprocal) const {
12980   EVT VT = Operand.getValueType();
12981   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12982       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12983       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12984       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12985     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12986       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12987 
12988     // The Newton-Raphson computation with a single constant does not provide
12989     // enough accuracy on some CPUs.
12990     UseOneConstNR = !Subtarget.needsTwoConstNR();
12991     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12992   }
12993   return SDValue();
12994 }
12995 
12996 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12997                                             int Enabled,
12998                                             int &RefinementSteps) const {
12999   EVT VT = Operand.getValueType();
13000   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
13001       (VT == MVT::f64 && Subtarget.hasFRE()) ||
13002       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
13003       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
13004     if (RefinementSteps == ReciprocalEstimate::Unspecified)
13005       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
13006     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
13007   }
13008   return SDValue();
13009 }
13010 
13011 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
13012   // Note: This functionality is used only when unsafe-fp-math is enabled, and
13013   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
13014   // enabled for division), this functionality is redundant with the default
13015   // combiner logic (once the division -> reciprocal/multiply transformation
13016   // has taken place). As a result, this matters more for older cores than for
13017   // newer ones.
13018 
13019   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
13020   // reciprocal if there are two or more FDIVs (for embedded cores with only
13021   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
13022   switch (Subtarget.getCPUDirective()) {
13023   default:
13024     return 3;
13025   case PPC::DIR_440:
13026   case PPC::DIR_A2:
13027   case PPC::DIR_E500:
13028   case PPC::DIR_E500mc:
13029   case PPC::DIR_E5500:
13030     return 2;
13031   }
13032 }
13033 
13034 // isConsecutiveLSLoc needs to work even if all adds have not yet been
13035 // collapsed, and so we need to look through chains of them.
13036 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
13037                                      int64_t& Offset, SelectionDAG &DAG) {
13038   if (DAG.isBaseWithConstantOffset(Loc)) {
13039     Base = Loc.getOperand(0);
13040     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
13041 
13042     // The base might itself be a base plus an offset, and if so, accumulate
13043     // that as well.
13044     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
13045   }
13046 }
13047 
13048 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
13049                             unsigned Bytes, int Dist,
13050                             SelectionDAG &DAG) {
13051   if (VT.getSizeInBits() / 8 != Bytes)
13052     return false;
13053 
13054   SDValue BaseLoc = Base->getBasePtr();
13055   if (Loc.getOpcode() == ISD::FrameIndex) {
13056     if (BaseLoc.getOpcode() != ISD::FrameIndex)
13057       return false;
13058     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
13059     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
13060     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
13061     int FS  = MFI.getObjectSize(FI);
13062     int BFS = MFI.getObjectSize(BFI);
13063     if (FS != BFS || FS != (int)Bytes) return false;
13064     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
13065   }
13066 
13067   SDValue Base1 = Loc, Base2 = BaseLoc;
13068   int64_t Offset1 = 0, Offset2 = 0;
13069   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
13070   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
13071   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
13072     return true;
13073 
13074   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13075   const GlobalValue *GV1 = nullptr;
13076   const GlobalValue *GV2 = nullptr;
13077   Offset1 = 0;
13078   Offset2 = 0;
13079   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
13080   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
13081   if (isGA1 && isGA2 && GV1 == GV2)
13082     return Offset1 == (Offset2 + Dist*Bytes);
13083   return false;
13084 }
13085 
13086 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
13087 // not enforce equality of the chain operands.
13088 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
13089                             unsigned Bytes, int Dist,
13090                             SelectionDAG &DAG) {
13091   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
13092     EVT VT = LS->getMemoryVT();
13093     SDValue Loc = LS->getBasePtr();
13094     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
13095   }
13096 
13097   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
13098     EVT VT;
13099     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13100     default: return false;
13101     case Intrinsic::ppc_altivec_lvx:
13102     case Intrinsic::ppc_altivec_lvxl:
13103     case Intrinsic::ppc_vsx_lxvw4x:
13104     case Intrinsic::ppc_vsx_lxvw4x_be:
13105       VT = MVT::v4i32;
13106       break;
13107     case Intrinsic::ppc_vsx_lxvd2x:
13108     case Intrinsic::ppc_vsx_lxvd2x_be:
13109       VT = MVT::v2f64;
13110       break;
13111     case Intrinsic::ppc_altivec_lvebx:
13112       VT = MVT::i8;
13113       break;
13114     case Intrinsic::ppc_altivec_lvehx:
13115       VT = MVT::i16;
13116       break;
13117     case Intrinsic::ppc_altivec_lvewx:
13118       VT = MVT::i32;
13119       break;
13120     }
13121 
13122     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
13123   }
13124 
13125   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
13126     EVT VT;
13127     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13128     default: return false;
13129     case Intrinsic::ppc_altivec_stvx:
13130     case Intrinsic::ppc_altivec_stvxl:
13131     case Intrinsic::ppc_vsx_stxvw4x:
13132       VT = MVT::v4i32;
13133       break;
13134     case Intrinsic::ppc_vsx_stxvd2x:
13135       VT = MVT::v2f64;
13136       break;
13137     case Intrinsic::ppc_vsx_stxvw4x_be:
13138       VT = MVT::v4i32;
13139       break;
13140     case Intrinsic::ppc_vsx_stxvd2x_be:
13141       VT = MVT::v2f64;
13142       break;
13143     case Intrinsic::ppc_altivec_stvebx:
13144       VT = MVT::i8;
13145       break;
13146     case Intrinsic::ppc_altivec_stvehx:
13147       VT = MVT::i16;
13148       break;
13149     case Intrinsic::ppc_altivec_stvewx:
13150       VT = MVT::i32;
13151       break;
13152     }
13153 
13154     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
13155   }
13156 
13157   return false;
13158 }
13159 
13160 // Return true is there is a nearyby consecutive load to the one provided
13161 // (regardless of alignment). We search up and down the chain, looking though
13162 // token factors and other loads (but nothing else). As a result, a true result
13163 // indicates that it is safe to create a new consecutive load adjacent to the
13164 // load provided.
13165 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
13166   SDValue Chain = LD->getChain();
13167   EVT VT = LD->getMemoryVT();
13168 
13169   SmallSet<SDNode *, 16> LoadRoots;
13170   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
13171   SmallSet<SDNode *, 16> Visited;
13172 
13173   // First, search up the chain, branching to follow all token-factor operands.
13174   // If we find a consecutive load, then we're done, otherwise, record all
13175   // nodes just above the top-level loads and token factors.
13176   while (!Queue.empty()) {
13177     SDNode *ChainNext = Queue.pop_back_val();
13178     if (!Visited.insert(ChainNext).second)
13179       continue;
13180 
13181     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
13182       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13183         return true;
13184 
13185       if (!Visited.count(ChainLD->getChain().getNode()))
13186         Queue.push_back(ChainLD->getChain().getNode());
13187     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
13188       for (const SDUse &O : ChainNext->ops())
13189         if (!Visited.count(O.getNode()))
13190           Queue.push_back(O.getNode());
13191     } else
13192       LoadRoots.insert(ChainNext);
13193   }
13194 
13195   // Second, search down the chain, starting from the top-level nodes recorded
13196   // in the first phase. These top-level nodes are the nodes just above all
13197   // loads and token factors. Starting with their uses, recursively look though
13198   // all loads (just the chain uses) and token factors to find a consecutive
13199   // load.
13200   Visited.clear();
13201   Queue.clear();
13202 
13203   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
13204        IE = LoadRoots.end(); I != IE; ++I) {
13205     Queue.push_back(*I);
13206 
13207     while (!Queue.empty()) {
13208       SDNode *LoadRoot = Queue.pop_back_val();
13209       if (!Visited.insert(LoadRoot).second)
13210         continue;
13211 
13212       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
13213         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13214           return true;
13215 
13216       for (SDNode *U : LoadRoot->uses())
13217         if (((isa<MemSDNode>(U) &&
13218               cast<MemSDNode>(U)->getChain().getNode() == LoadRoot) ||
13219              U->getOpcode() == ISD::TokenFactor) &&
13220             !Visited.count(U))
13221           Queue.push_back(U);
13222     }
13223   }
13224 
13225   return false;
13226 }
13227 
13228 /// This function is called when we have proved that a SETCC node can be replaced
13229 /// by subtraction (and other supporting instructions) so that the result of
13230 /// comparison is kept in a GPR instead of CR. This function is purely for
13231 /// codegen purposes and has some flags to guide the codegen process.
13232 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
13233                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
13234   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13235 
13236   // Zero extend the operands to the largest legal integer. Originally, they
13237   // must be of a strictly smaller size.
13238   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
13239                          DAG.getConstant(Size, DL, MVT::i32));
13240   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
13241                          DAG.getConstant(Size, DL, MVT::i32));
13242 
13243   // Swap if needed. Depends on the condition code.
13244   if (Swap)
13245     std::swap(Op0, Op1);
13246 
13247   // Subtract extended integers.
13248   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
13249 
13250   // Move the sign bit to the least significant position and zero out the rest.
13251   // Now the least significant bit carries the result of original comparison.
13252   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
13253                              DAG.getConstant(Size - 1, DL, MVT::i32));
13254   auto Final = Shifted;
13255 
13256   // Complement the result if needed. Based on the condition code.
13257   if (Complement)
13258     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
13259                         DAG.getConstant(1, DL, MVT::i64));
13260 
13261   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
13262 }
13263 
13264 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
13265                                                   DAGCombinerInfo &DCI) const {
13266   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13267 
13268   SelectionDAG &DAG = DCI.DAG;
13269   SDLoc DL(N);
13270 
13271   // Size of integers being compared has a critical role in the following
13272   // analysis, so we prefer to do this when all types are legal.
13273   if (!DCI.isAfterLegalizeDAG())
13274     return SDValue();
13275 
13276   // If all users of SETCC extend its value to a legal integer type
13277   // then we replace SETCC with a subtraction
13278   for (const SDNode *U : N->uses())
13279     if (U->getOpcode() != ISD::ZERO_EXTEND)
13280       return SDValue();
13281 
13282   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13283   auto OpSize = N->getOperand(0).getValueSizeInBits();
13284 
13285   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
13286 
13287   if (OpSize < Size) {
13288     switch (CC) {
13289     default: break;
13290     case ISD::SETULT:
13291       return generateEquivalentSub(N, Size, false, false, DL, DAG);
13292     case ISD::SETULE:
13293       return generateEquivalentSub(N, Size, true, true, DL, DAG);
13294     case ISD::SETUGT:
13295       return generateEquivalentSub(N, Size, false, true, DL, DAG);
13296     case ISD::SETUGE:
13297       return generateEquivalentSub(N, Size, true, false, DL, DAG);
13298     }
13299   }
13300 
13301   return SDValue();
13302 }
13303 
13304 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
13305                                                   DAGCombinerInfo &DCI) const {
13306   SelectionDAG &DAG = DCI.DAG;
13307   SDLoc dl(N);
13308 
13309   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
13310   // If we're tracking CR bits, we need to be careful that we don't have:
13311   //   trunc(binary-ops(zext(x), zext(y)))
13312   // or
13313   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
13314   // such that we're unnecessarily moving things into GPRs when it would be
13315   // better to keep them in CR bits.
13316 
13317   // Note that trunc here can be an actual i1 trunc, or can be the effective
13318   // truncation that comes from a setcc or select_cc.
13319   if (N->getOpcode() == ISD::TRUNCATE &&
13320       N->getValueType(0) != MVT::i1)
13321     return SDValue();
13322 
13323   if (N->getOperand(0).getValueType() != MVT::i32 &&
13324       N->getOperand(0).getValueType() != MVT::i64)
13325     return SDValue();
13326 
13327   if (N->getOpcode() == ISD::SETCC ||
13328       N->getOpcode() == ISD::SELECT_CC) {
13329     // If we're looking at a comparison, then we need to make sure that the
13330     // high bits (all except for the first) don't matter the result.
13331     ISD::CondCode CC =
13332       cast<CondCodeSDNode>(N->getOperand(
13333         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
13334     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
13335 
13336     if (ISD::isSignedIntSetCC(CC)) {
13337       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
13338           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
13339         return SDValue();
13340     } else if (ISD::isUnsignedIntSetCC(CC)) {
13341       if (!DAG.MaskedValueIsZero(N->getOperand(0),
13342                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
13343           !DAG.MaskedValueIsZero(N->getOperand(1),
13344                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
13345         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
13346                                              : SDValue());
13347     } else {
13348       // This is neither a signed nor an unsigned comparison, just make sure
13349       // that the high bits are equal.
13350       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
13351       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
13352 
13353       // We don't really care about what is known about the first bit (if
13354       // anything), so pretend that it is known zero for both to ensure they can
13355       // be compared as constants.
13356       Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
13357       Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
13358 
13359       if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
13360           Op1Known.getConstant() != Op2Known.getConstant())
13361         return SDValue();
13362     }
13363   }
13364 
13365   // We now know that the higher-order bits are irrelevant, we just need to
13366   // make sure that all of the intermediate operations are bit operations, and
13367   // all inputs are extensions.
13368   if (N->getOperand(0).getOpcode() != ISD::AND &&
13369       N->getOperand(0).getOpcode() != ISD::OR  &&
13370       N->getOperand(0).getOpcode() != ISD::XOR &&
13371       N->getOperand(0).getOpcode() != ISD::SELECT &&
13372       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
13373       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
13374       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
13375       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
13376       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
13377     return SDValue();
13378 
13379   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
13380       N->getOperand(1).getOpcode() != ISD::AND &&
13381       N->getOperand(1).getOpcode() != ISD::OR  &&
13382       N->getOperand(1).getOpcode() != ISD::XOR &&
13383       N->getOperand(1).getOpcode() != ISD::SELECT &&
13384       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
13385       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
13386       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
13387       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
13388       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
13389     return SDValue();
13390 
13391   SmallVector<SDValue, 4> Inputs;
13392   SmallVector<SDValue, 8> BinOps, PromOps;
13393   SmallPtrSet<SDNode *, 16> Visited;
13394 
13395   for (unsigned i = 0; i < 2; ++i) {
13396     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13397           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13398           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13399           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13400         isa<ConstantSDNode>(N->getOperand(i)))
13401       Inputs.push_back(N->getOperand(i));
13402     else
13403       BinOps.push_back(N->getOperand(i));
13404 
13405     if (N->getOpcode() == ISD::TRUNCATE)
13406       break;
13407   }
13408 
13409   // Visit all inputs, collect all binary operations (and, or, xor and
13410   // select) that are all fed by extensions.
13411   while (!BinOps.empty()) {
13412     SDValue BinOp = BinOps.pop_back_val();
13413 
13414     if (!Visited.insert(BinOp.getNode()).second)
13415       continue;
13416 
13417     PromOps.push_back(BinOp);
13418 
13419     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13420       // The condition of the select is not promoted.
13421       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13422         continue;
13423       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13424         continue;
13425 
13426       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13427             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13428             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13429            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13430           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13431         Inputs.push_back(BinOp.getOperand(i));
13432       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13433                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13434                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13435                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13436                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
13437                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13438                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13439                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13440                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
13441         BinOps.push_back(BinOp.getOperand(i));
13442       } else {
13443         // We have an input that is not an extension or another binary
13444         // operation; we'll abort this transformation.
13445         return SDValue();
13446       }
13447     }
13448   }
13449 
13450   // Make sure that this is a self-contained cluster of operations (which
13451   // is not quite the same thing as saying that everything has only one
13452   // use).
13453   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13454     if (isa<ConstantSDNode>(Inputs[i]))
13455       continue;
13456 
13457     for (const SDNode *User : Inputs[i].getNode()->uses()) {
13458       if (User != N && !Visited.count(User))
13459         return SDValue();
13460 
13461       // Make sure that we're not going to promote the non-output-value
13462       // operand(s) or SELECT or SELECT_CC.
13463       // FIXME: Although we could sometimes handle this, and it does occur in
13464       // practice that one of the condition inputs to the select is also one of
13465       // the outputs, we currently can't deal with this.
13466       if (User->getOpcode() == ISD::SELECT) {
13467         if (User->getOperand(0) == Inputs[i])
13468           return SDValue();
13469       } else if (User->getOpcode() == ISD::SELECT_CC) {
13470         if (User->getOperand(0) == Inputs[i] ||
13471             User->getOperand(1) == Inputs[i])
13472           return SDValue();
13473       }
13474     }
13475   }
13476 
13477   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13478     for (const SDNode *User : PromOps[i].getNode()->uses()) {
13479       if (User != N && !Visited.count(User))
13480         return SDValue();
13481 
13482       // Make sure that we're not going to promote the non-output-value
13483       // operand(s) or SELECT or SELECT_CC.
13484       // FIXME: Although we could sometimes handle this, and it does occur in
13485       // practice that one of the condition inputs to the select is also one of
13486       // the outputs, we currently can't deal with this.
13487       if (User->getOpcode() == ISD::SELECT) {
13488         if (User->getOperand(0) == PromOps[i])
13489           return SDValue();
13490       } else if (User->getOpcode() == ISD::SELECT_CC) {
13491         if (User->getOperand(0) == PromOps[i] ||
13492             User->getOperand(1) == PromOps[i])
13493           return SDValue();
13494       }
13495     }
13496   }
13497 
13498   // Replace all inputs with the extension operand.
13499   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13500     // Constants may have users outside the cluster of to-be-promoted nodes,
13501     // and so we need to replace those as we do the promotions.
13502     if (isa<ConstantSDNode>(Inputs[i]))
13503       continue;
13504     else
13505       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13506   }
13507 
13508   std::list<HandleSDNode> PromOpHandles;
13509   for (auto &PromOp : PromOps)
13510     PromOpHandles.emplace_back(PromOp);
13511 
13512   // Replace all operations (these are all the same, but have a different
13513   // (i1) return type). DAG.getNode will validate that the types of
13514   // a binary operator match, so go through the list in reverse so that
13515   // we've likely promoted both operands first. Any intermediate truncations or
13516   // extensions disappear.
13517   while (!PromOpHandles.empty()) {
13518     SDValue PromOp = PromOpHandles.back().getValue();
13519     PromOpHandles.pop_back();
13520 
13521     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13522         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13523         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13524         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13525       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13526           PromOp.getOperand(0).getValueType() != MVT::i1) {
13527         // The operand is not yet ready (see comment below).
13528         PromOpHandles.emplace_front(PromOp);
13529         continue;
13530       }
13531 
13532       SDValue RepValue = PromOp.getOperand(0);
13533       if (isa<ConstantSDNode>(RepValue))
13534         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13535 
13536       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13537       continue;
13538     }
13539 
13540     unsigned C;
13541     switch (PromOp.getOpcode()) {
13542     default:             C = 0; break;
13543     case ISD::SELECT:    C = 1; break;
13544     case ISD::SELECT_CC: C = 2; break;
13545     }
13546 
13547     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13548          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13549         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13550          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13551       // The to-be-promoted operands of this node have not yet been
13552       // promoted (this should be rare because we're going through the
13553       // list backward, but if one of the operands has several users in
13554       // this cluster of to-be-promoted nodes, it is possible).
13555       PromOpHandles.emplace_front(PromOp);
13556       continue;
13557     }
13558 
13559     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13560                                 PromOp.getNode()->op_end());
13561 
13562     // If there are any constant inputs, make sure they're replaced now.
13563     for (unsigned i = 0; i < 2; ++i)
13564       if (isa<ConstantSDNode>(Ops[C+i]))
13565         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13566 
13567     DAG.ReplaceAllUsesOfValueWith(PromOp,
13568       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13569   }
13570 
13571   // Now we're left with the initial truncation itself.
13572   if (N->getOpcode() == ISD::TRUNCATE)
13573     return N->getOperand(0);
13574 
13575   // Otherwise, this is a comparison. The operands to be compared have just
13576   // changed type (to i1), but everything else is the same.
13577   return SDValue(N, 0);
13578 }
13579 
13580 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13581                                                   DAGCombinerInfo &DCI) const {
13582   SelectionDAG &DAG = DCI.DAG;
13583   SDLoc dl(N);
13584 
13585   // If we're tracking CR bits, we need to be careful that we don't have:
13586   //   zext(binary-ops(trunc(x), trunc(y)))
13587   // or
13588   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13589   // such that we're unnecessarily moving things into CR bits that can more
13590   // efficiently stay in GPRs. Note that if we're not certain that the high
13591   // bits are set as required by the final extension, we still may need to do
13592   // some masking to get the proper behavior.
13593 
13594   // This same functionality is important on PPC64 when dealing with
13595   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13596   // the return values of functions. Because it is so similar, it is handled
13597   // here as well.
13598 
13599   if (N->getValueType(0) != MVT::i32 &&
13600       N->getValueType(0) != MVT::i64)
13601     return SDValue();
13602 
13603   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13604         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13605     return SDValue();
13606 
13607   if (N->getOperand(0).getOpcode() != ISD::AND &&
13608       N->getOperand(0).getOpcode() != ISD::OR  &&
13609       N->getOperand(0).getOpcode() != ISD::XOR &&
13610       N->getOperand(0).getOpcode() != ISD::SELECT &&
13611       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13612     return SDValue();
13613 
13614   SmallVector<SDValue, 4> Inputs;
13615   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13616   SmallPtrSet<SDNode *, 16> Visited;
13617 
13618   // Visit all inputs, collect all binary operations (and, or, xor and
13619   // select) that are all fed by truncations.
13620   while (!BinOps.empty()) {
13621     SDValue BinOp = BinOps.pop_back_val();
13622 
13623     if (!Visited.insert(BinOp.getNode()).second)
13624       continue;
13625 
13626     PromOps.push_back(BinOp);
13627 
13628     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13629       // The condition of the select is not promoted.
13630       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13631         continue;
13632       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13633         continue;
13634 
13635       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13636           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13637         Inputs.push_back(BinOp.getOperand(i));
13638       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13639                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13640                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13641                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13642                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13643         BinOps.push_back(BinOp.getOperand(i));
13644       } else {
13645         // We have an input that is not a truncation or another binary
13646         // operation; we'll abort this transformation.
13647         return SDValue();
13648       }
13649     }
13650   }
13651 
13652   // The operands of a select that must be truncated when the select is
13653   // promoted because the operand is actually part of the to-be-promoted set.
13654   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13655 
13656   // Make sure that this is a self-contained cluster of operations (which
13657   // is not quite the same thing as saying that everything has only one
13658   // use).
13659   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13660     if (isa<ConstantSDNode>(Inputs[i]))
13661       continue;
13662 
13663     for (SDNode *User : Inputs[i].getNode()->uses()) {
13664       if (User != N && !Visited.count(User))
13665         return SDValue();
13666 
13667       // If we're going to promote the non-output-value operand(s) or SELECT or
13668       // SELECT_CC, record them for truncation.
13669       if (User->getOpcode() == ISD::SELECT) {
13670         if (User->getOperand(0) == Inputs[i])
13671           SelectTruncOp[0].insert(std::make_pair(User,
13672                                     User->getOperand(0).getValueType()));
13673       } else if (User->getOpcode() == ISD::SELECT_CC) {
13674         if (User->getOperand(0) == Inputs[i])
13675           SelectTruncOp[0].insert(std::make_pair(User,
13676                                     User->getOperand(0).getValueType()));
13677         if (User->getOperand(1) == Inputs[i])
13678           SelectTruncOp[1].insert(std::make_pair(User,
13679                                     User->getOperand(1).getValueType()));
13680       }
13681     }
13682   }
13683 
13684   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13685     for (SDNode *User : PromOps[i].getNode()->uses()) {
13686       if (User != N && !Visited.count(User))
13687         return SDValue();
13688 
13689       // If we're going to promote the non-output-value operand(s) or SELECT or
13690       // SELECT_CC, record them for truncation.
13691       if (User->getOpcode() == ISD::SELECT) {
13692         if (User->getOperand(0) == PromOps[i])
13693           SelectTruncOp[0].insert(std::make_pair(User,
13694                                     User->getOperand(0).getValueType()));
13695       } else if (User->getOpcode() == ISD::SELECT_CC) {
13696         if (User->getOperand(0) == PromOps[i])
13697           SelectTruncOp[0].insert(std::make_pair(User,
13698                                     User->getOperand(0).getValueType()));
13699         if (User->getOperand(1) == PromOps[i])
13700           SelectTruncOp[1].insert(std::make_pair(User,
13701                                     User->getOperand(1).getValueType()));
13702       }
13703     }
13704   }
13705 
13706   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13707   bool ReallyNeedsExt = false;
13708   if (N->getOpcode() != ISD::ANY_EXTEND) {
13709     // If all of the inputs are not already sign/zero extended, then
13710     // we'll still need to do that at the end.
13711     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13712       if (isa<ConstantSDNode>(Inputs[i]))
13713         continue;
13714 
13715       unsigned OpBits =
13716         Inputs[i].getOperand(0).getValueSizeInBits();
13717       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13718 
13719       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13720            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13721                                   APInt::getHighBitsSet(OpBits,
13722                                                         OpBits-PromBits))) ||
13723           (N->getOpcode() == ISD::SIGN_EXTEND &&
13724            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13725              (OpBits-(PromBits-1)))) {
13726         ReallyNeedsExt = true;
13727         break;
13728       }
13729     }
13730   }
13731 
13732   // Replace all inputs, either with the truncation operand, or a
13733   // truncation or extension to the final output type.
13734   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13735     // Constant inputs need to be replaced with the to-be-promoted nodes that
13736     // use them because they might have users outside of the cluster of
13737     // promoted nodes.
13738     if (isa<ConstantSDNode>(Inputs[i]))
13739       continue;
13740 
13741     SDValue InSrc = Inputs[i].getOperand(0);
13742     if (Inputs[i].getValueType() == N->getValueType(0))
13743       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13744     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13745       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13746         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13747     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13748       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13749         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13750     else
13751       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13752         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13753   }
13754 
13755   std::list<HandleSDNode> PromOpHandles;
13756   for (auto &PromOp : PromOps)
13757     PromOpHandles.emplace_back(PromOp);
13758 
13759   // Replace all operations (these are all the same, but have a different
13760   // (promoted) return type). DAG.getNode will validate that the types of
13761   // a binary operator match, so go through the list in reverse so that
13762   // we've likely promoted both operands first.
13763   while (!PromOpHandles.empty()) {
13764     SDValue PromOp = PromOpHandles.back().getValue();
13765     PromOpHandles.pop_back();
13766 
13767     unsigned C;
13768     switch (PromOp.getOpcode()) {
13769     default:             C = 0; break;
13770     case ISD::SELECT:    C = 1; break;
13771     case ISD::SELECT_CC: C = 2; break;
13772     }
13773 
13774     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13775          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13776         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13777          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13778       // The to-be-promoted operands of this node have not yet been
13779       // promoted (this should be rare because we're going through the
13780       // list backward, but if one of the operands has several users in
13781       // this cluster of to-be-promoted nodes, it is possible).
13782       PromOpHandles.emplace_front(PromOp);
13783       continue;
13784     }
13785 
13786     // For SELECT and SELECT_CC nodes, we do a similar check for any
13787     // to-be-promoted comparison inputs.
13788     if (PromOp.getOpcode() == ISD::SELECT ||
13789         PromOp.getOpcode() == ISD::SELECT_CC) {
13790       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13791            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13792           (SelectTruncOp[1].count(PromOp.getNode()) &&
13793            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13794         PromOpHandles.emplace_front(PromOp);
13795         continue;
13796       }
13797     }
13798 
13799     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13800                                 PromOp.getNode()->op_end());
13801 
13802     // If this node has constant inputs, then they'll need to be promoted here.
13803     for (unsigned i = 0; i < 2; ++i) {
13804       if (!isa<ConstantSDNode>(Ops[C+i]))
13805         continue;
13806       if (Ops[C+i].getValueType() == N->getValueType(0))
13807         continue;
13808 
13809       if (N->getOpcode() == ISD::SIGN_EXTEND)
13810         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13811       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13812         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13813       else
13814         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13815     }
13816 
13817     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13818     // truncate them again to the original value type.
13819     if (PromOp.getOpcode() == ISD::SELECT ||
13820         PromOp.getOpcode() == ISD::SELECT_CC) {
13821       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13822       if (SI0 != SelectTruncOp[0].end())
13823         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13824       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13825       if (SI1 != SelectTruncOp[1].end())
13826         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13827     }
13828 
13829     DAG.ReplaceAllUsesOfValueWith(PromOp,
13830       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13831   }
13832 
13833   // Now we're left with the initial extension itself.
13834   if (!ReallyNeedsExt)
13835     return N->getOperand(0);
13836 
13837   // To zero extend, just mask off everything except for the first bit (in the
13838   // i1 case).
13839   if (N->getOpcode() == ISD::ZERO_EXTEND)
13840     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13841                        DAG.getConstant(APInt::getLowBitsSet(
13842                                          N->getValueSizeInBits(0), PromBits),
13843                                        dl, N->getValueType(0)));
13844 
13845   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13846          "Invalid extension type");
13847   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13848   SDValue ShiftCst =
13849       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13850   return DAG.getNode(
13851       ISD::SRA, dl, N->getValueType(0),
13852       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13853       ShiftCst);
13854 }
13855 
13856 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13857                                         DAGCombinerInfo &DCI) const {
13858   assert(N->getOpcode() == ISD::SETCC &&
13859          "Should be called with a SETCC node");
13860 
13861   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13862   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13863     SDValue LHS = N->getOperand(0);
13864     SDValue RHS = N->getOperand(1);
13865 
13866     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13867     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13868         LHS.hasOneUse())
13869       std::swap(LHS, RHS);
13870 
13871     // x == 0-y --> x+y == 0
13872     // x != 0-y --> x+y != 0
13873     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13874         RHS.hasOneUse()) {
13875       SDLoc DL(N);
13876       SelectionDAG &DAG = DCI.DAG;
13877       EVT VT = N->getValueType(0);
13878       EVT OpVT = LHS.getValueType();
13879       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13880       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13881     }
13882   }
13883 
13884   return DAGCombineTruncBoolExt(N, DCI);
13885 }
13886 
13887 // Is this an extending load from an f32 to an f64?
13888 static bool isFPExtLoad(SDValue Op) {
13889   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13890     return LD->getExtensionType() == ISD::EXTLOAD &&
13891       Op.getValueType() == MVT::f64;
13892   return false;
13893 }
13894 
13895 /// Reduces the number of fp-to-int conversion when building a vector.
13896 ///
13897 /// If this vector is built out of floating to integer conversions,
13898 /// transform it to a vector built out of floating point values followed by a
13899 /// single floating to integer conversion of the vector.
13900 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13901 /// becomes (fptosi (build_vector ($A, $B, ...)))
13902 SDValue PPCTargetLowering::
13903 combineElementTruncationToVectorTruncation(SDNode *N,
13904                                            DAGCombinerInfo &DCI) const {
13905   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13906          "Should be called with a BUILD_VECTOR node");
13907 
13908   SelectionDAG &DAG = DCI.DAG;
13909   SDLoc dl(N);
13910 
13911   SDValue FirstInput = N->getOperand(0);
13912   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13913          "The input operand must be an fp-to-int conversion.");
13914 
13915   // This combine happens after legalization so the fp_to_[su]i nodes are
13916   // already converted to PPCSISD nodes.
13917   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13918   if (FirstConversion == PPCISD::FCTIDZ ||
13919       FirstConversion == PPCISD::FCTIDUZ ||
13920       FirstConversion == PPCISD::FCTIWZ ||
13921       FirstConversion == PPCISD::FCTIWUZ) {
13922     bool IsSplat = true;
13923     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13924       FirstConversion == PPCISD::FCTIWUZ;
13925     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13926     SmallVector<SDValue, 4> Ops;
13927     EVT TargetVT = N->getValueType(0);
13928     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13929       SDValue NextOp = N->getOperand(i);
13930       if (NextOp.getOpcode() != PPCISD::MFVSR)
13931         return SDValue();
13932       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13933       if (NextConversion != FirstConversion)
13934         return SDValue();
13935       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13936       // This is not valid if the input was originally double precision. It is
13937       // also not profitable to do unless this is an extending load in which
13938       // case doing this combine will allow us to combine consecutive loads.
13939       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13940         return SDValue();
13941       if (N->getOperand(i) != FirstInput)
13942         IsSplat = false;
13943     }
13944 
13945     // If this is a splat, we leave it as-is since there will be only a single
13946     // fp-to-int conversion followed by a splat of the integer. This is better
13947     // for 32-bit and smaller ints and neutral for 64-bit ints.
13948     if (IsSplat)
13949       return SDValue();
13950 
13951     // Now that we know we have the right type of node, get its operands
13952     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13953       SDValue In = N->getOperand(i).getOperand(0);
13954       if (Is32Bit) {
13955         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13956         // here, we know that all inputs are extending loads so this is safe).
13957         if (In.isUndef())
13958           Ops.push_back(DAG.getUNDEF(SrcVT));
13959         else {
13960           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13961                                       MVT::f32, In.getOperand(0),
13962                                       DAG.getIntPtrConstant(1, dl));
13963           Ops.push_back(Trunc);
13964         }
13965       } else
13966         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13967     }
13968 
13969     unsigned Opcode;
13970     if (FirstConversion == PPCISD::FCTIDZ ||
13971         FirstConversion == PPCISD::FCTIWZ)
13972       Opcode = ISD::FP_TO_SINT;
13973     else
13974       Opcode = ISD::FP_TO_UINT;
13975 
13976     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13977     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13978     return DAG.getNode(Opcode, dl, TargetVT, BV);
13979   }
13980   return SDValue();
13981 }
13982 
13983 /// Reduce the number of loads when building a vector.
13984 ///
13985 /// Building a vector out of multiple loads can be converted to a load
13986 /// of the vector type if the loads are consecutive. If the loads are
13987 /// consecutive but in descending order, a shuffle is added at the end
13988 /// to reorder the vector.
13989 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13990   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13991          "Should be called with a BUILD_VECTOR node");
13992 
13993   SDLoc dl(N);
13994 
13995   // Return early for non byte-sized type, as they can't be consecutive.
13996   if (!N->getValueType(0).getVectorElementType().isByteSized())
13997     return SDValue();
13998 
13999   bool InputsAreConsecutiveLoads = true;
14000   bool InputsAreReverseConsecutive = true;
14001   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
14002   SDValue FirstInput = N->getOperand(0);
14003   bool IsRoundOfExtLoad = false;
14004 
14005   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
14006       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
14007     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
14008     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
14009   }
14010   // Not a build vector of (possibly fp_rounded) loads.
14011   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
14012       N->getNumOperands() == 1)
14013     return SDValue();
14014 
14015   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
14016     // If any inputs are fp_round(extload), they all must be.
14017     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
14018       return SDValue();
14019 
14020     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
14021       N->getOperand(i);
14022     if (NextInput.getOpcode() != ISD::LOAD)
14023       return SDValue();
14024 
14025     SDValue PreviousInput =
14026       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
14027     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
14028     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
14029 
14030     // If any inputs are fp_round(extload), they all must be.
14031     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
14032       return SDValue();
14033 
14034     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
14035       InputsAreConsecutiveLoads = false;
14036     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
14037       InputsAreReverseConsecutive = false;
14038 
14039     // Exit early if the loads are neither consecutive nor reverse consecutive.
14040     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
14041       return SDValue();
14042   }
14043 
14044   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
14045          "The loads cannot be both consecutive and reverse consecutive.");
14046 
14047   SDValue FirstLoadOp =
14048     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
14049   SDValue LastLoadOp =
14050     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
14051                        N->getOperand(N->getNumOperands()-1);
14052 
14053   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
14054   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
14055   if (InputsAreConsecutiveLoads) {
14056     assert(LD1 && "Input needs to be a LoadSDNode.");
14057     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
14058                        LD1->getBasePtr(), LD1->getPointerInfo(),
14059                        LD1->getAlignment());
14060   }
14061   if (InputsAreReverseConsecutive) {
14062     assert(LDL && "Input needs to be a LoadSDNode.");
14063     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
14064                                LDL->getBasePtr(), LDL->getPointerInfo(),
14065                                LDL->getAlignment());
14066     SmallVector<int, 16> Ops;
14067     for (int i = N->getNumOperands() - 1; i >= 0; i--)
14068       Ops.push_back(i);
14069 
14070     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
14071                                 DAG.getUNDEF(N->getValueType(0)), Ops);
14072   }
14073   return SDValue();
14074 }
14075 
14076 // This function adds the required vector_shuffle needed to get
14077 // the elements of the vector extract in the correct position
14078 // as specified by the CorrectElems encoding.
14079 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
14080                                       SDValue Input, uint64_t Elems,
14081                                       uint64_t CorrectElems) {
14082   SDLoc dl(N);
14083 
14084   unsigned NumElems = Input.getValueType().getVectorNumElements();
14085   SmallVector<int, 16> ShuffleMask(NumElems, -1);
14086 
14087   // Knowing the element indices being extracted from the original
14088   // vector and the order in which they're being inserted, just put
14089   // them at element indices required for the instruction.
14090   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14091     if (DAG.getDataLayout().isLittleEndian())
14092       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
14093     else
14094       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
14095     CorrectElems = CorrectElems >> 8;
14096     Elems = Elems >> 8;
14097   }
14098 
14099   SDValue Shuffle =
14100       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
14101                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
14102 
14103   EVT VT = N->getValueType(0);
14104   SDValue Conv = DAG.getBitcast(VT, Shuffle);
14105 
14106   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
14107                                Input.getValueType().getVectorElementType(),
14108                                VT.getVectorNumElements());
14109   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
14110                      DAG.getValueType(ExtVT));
14111 }
14112 
14113 // Look for build vector patterns where input operands come from sign
14114 // extended vector_extract elements of specific indices. If the correct indices
14115 // aren't used, add a vector shuffle to fix up the indices and create
14116 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
14117 // during instruction selection.
14118 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
14119   // This array encodes the indices that the vector sign extend instructions
14120   // extract from when extending from one type to another for both BE and LE.
14121   // The right nibble of each byte corresponds to the LE incides.
14122   // and the left nibble of each byte corresponds to the BE incides.
14123   // For example: 0x3074B8FC  byte->word
14124   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
14125   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
14126   // For example: 0x000070F8  byte->double word
14127   // For LE: the allowed indices are: 0x0,0x8
14128   // For BE: the allowed indices are: 0x7,0xF
14129   uint64_t TargetElems[] = {
14130       0x3074B8FC, // b->w
14131       0x000070F8, // b->d
14132       0x10325476, // h->w
14133       0x00003074, // h->d
14134       0x00001032, // w->d
14135   };
14136 
14137   uint64_t Elems = 0;
14138   int Index;
14139   SDValue Input;
14140 
14141   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
14142     if (!Op)
14143       return false;
14144     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
14145         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
14146       return false;
14147 
14148     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
14149     // of the right width.
14150     SDValue Extract = Op.getOperand(0);
14151     if (Extract.getOpcode() == ISD::ANY_EXTEND)
14152       Extract = Extract.getOperand(0);
14153     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14154       return false;
14155 
14156     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
14157     if (!ExtOp)
14158       return false;
14159 
14160     Index = ExtOp->getZExtValue();
14161     if (Input && Input != Extract.getOperand(0))
14162       return false;
14163 
14164     if (!Input)
14165       Input = Extract.getOperand(0);
14166 
14167     Elems = Elems << 8;
14168     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
14169     Elems |= Index;
14170 
14171     return true;
14172   };
14173 
14174   // If the build vector operands aren't sign extended vector extracts,
14175   // of the same input vector, then return.
14176   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14177     if (!isSExtOfVecExtract(N->getOperand(i))) {
14178       return SDValue();
14179     }
14180   }
14181 
14182   // If the vector extract indicies are not correct, add the appropriate
14183   // vector_shuffle.
14184   int TgtElemArrayIdx;
14185   int InputSize = Input.getValueType().getScalarSizeInBits();
14186   int OutputSize = N->getValueType(0).getScalarSizeInBits();
14187   if (InputSize + OutputSize == 40)
14188     TgtElemArrayIdx = 0;
14189   else if (InputSize + OutputSize == 72)
14190     TgtElemArrayIdx = 1;
14191   else if (InputSize + OutputSize == 48)
14192     TgtElemArrayIdx = 2;
14193   else if (InputSize + OutputSize == 80)
14194     TgtElemArrayIdx = 3;
14195   else if (InputSize + OutputSize == 96)
14196     TgtElemArrayIdx = 4;
14197   else
14198     return SDValue();
14199 
14200   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
14201   CorrectElems = DAG.getDataLayout().isLittleEndian()
14202                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
14203                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
14204   if (Elems != CorrectElems) {
14205     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
14206   }
14207 
14208   // Regular lowering will catch cases where a shuffle is not needed.
14209   return SDValue();
14210 }
14211 
14212 // Look for the pattern of a load from a narrow width to i128, feeding
14213 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
14214 // (LXVRZX). This node represents a zero extending load that will be matched
14215 // to the Load VSX Vector Rightmost instructions.
14216 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
14217   SDLoc DL(N);
14218 
14219   // This combine is only eligible for a BUILD_VECTOR of v1i128.
14220   if (N->getValueType(0) != MVT::v1i128)
14221     return SDValue();
14222 
14223   SDValue Operand = N->getOperand(0);
14224   // Proceed with the transformation if the operand to the BUILD_VECTOR
14225   // is a load instruction.
14226   if (Operand.getOpcode() != ISD::LOAD)
14227     return SDValue();
14228 
14229   auto *LD = cast<LoadSDNode>(Operand);
14230   EVT MemoryType = LD->getMemoryVT();
14231 
14232   // This transformation is only valid if the we are loading either a byte,
14233   // halfword, word, or doubleword.
14234   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
14235                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
14236 
14237   // Ensure that the load from the narrow width is being zero extended to i128.
14238   if (!ValidLDType ||
14239       (LD->getExtensionType() != ISD::ZEXTLOAD &&
14240        LD->getExtensionType() != ISD::EXTLOAD))
14241     return SDValue();
14242 
14243   SDValue LoadOps[] = {
14244       LD->getChain(), LD->getBasePtr(),
14245       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
14246 
14247   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
14248                                  DAG.getVTList(MVT::v1i128, MVT::Other),
14249                                  LoadOps, MemoryType, LD->getMemOperand());
14250 }
14251 
14252 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
14253                                                  DAGCombinerInfo &DCI) const {
14254   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14255          "Should be called with a BUILD_VECTOR node");
14256 
14257   SelectionDAG &DAG = DCI.DAG;
14258   SDLoc dl(N);
14259 
14260   if (!Subtarget.hasVSX())
14261     return SDValue();
14262 
14263   // The target independent DAG combiner will leave a build_vector of
14264   // float-to-int conversions intact. We can generate MUCH better code for
14265   // a float-to-int conversion of a vector of floats.
14266   SDValue FirstInput = N->getOperand(0);
14267   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
14268     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
14269     if (Reduced)
14270       return Reduced;
14271   }
14272 
14273   // If we're building a vector out of consecutive loads, just load that
14274   // vector type.
14275   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
14276   if (Reduced)
14277     return Reduced;
14278 
14279   // If we're building a vector out of extended elements from another vector
14280   // we have P9 vector integer extend instructions. The code assumes legal
14281   // input types (i.e. it can't handle things like v4i16) so do not run before
14282   // legalization.
14283   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
14284     Reduced = combineBVOfVecSExt(N, DAG);
14285     if (Reduced)
14286       return Reduced;
14287   }
14288 
14289   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
14290   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
14291   // is a load from <valid narrow width> to i128.
14292   if (Subtarget.isISA3_1()) {
14293     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
14294     if (BVOfZLoad)
14295       return BVOfZLoad;
14296   }
14297 
14298   if (N->getValueType(0) != MVT::v2f64)
14299     return SDValue();
14300 
14301   // Looking for:
14302   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
14303   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
14304       FirstInput.getOpcode() != ISD::UINT_TO_FP)
14305     return SDValue();
14306   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
14307       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
14308     return SDValue();
14309   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
14310     return SDValue();
14311 
14312   SDValue Ext1 = FirstInput.getOperand(0);
14313   SDValue Ext2 = N->getOperand(1).getOperand(0);
14314   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14315      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14316     return SDValue();
14317 
14318   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
14319   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
14320   if (!Ext1Op || !Ext2Op)
14321     return SDValue();
14322   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
14323       Ext1.getOperand(0) != Ext2.getOperand(0))
14324     return SDValue();
14325 
14326   int FirstElem = Ext1Op->getZExtValue();
14327   int SecondElem = Ext2Op->getZExtValue();
14328   int SubvecIdx;
14329   if (FirstElem == 0 && SecondElem == 1)
14330     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
14331   else if (FirstElem == 2 && SecondElem == 3)
14332     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
14333   else
14334     return SDValue();
14335 
14336   SDValue SrcVec = Ext1.getOperand(0);
14337   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
14338     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
14339   return DAG.getNode(NodeType, dl, MVT::v2f64,
14340                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
14341 }
14342 
14343 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
14344                                               DAGCombinerInfo &DCI) const {
14345   assert((N->getOpcode() == ISD::SINT_TO_FP ||
14346           N->getOpcode() == ISD::UINT_TO_FP) &&
14347          "Need an int -> FP conversion node here");
14348 
14349   if (useSoftFloat() || !Subtarget.has64BitSupport())
14350     return SDValue();
14351 
14352   SelectionDAG &DAG = DCI.DAG;
14353   SDLoc dl(N);
14354   SDValue Op(N, 0);
14355 
14356   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
14357   // from the hardware.
14358   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
14359     return SDValue();
14360   if (!Op.getOperand(0).getValueType().isSimple())
14361     return SDValue();
14362   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
14363       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
14364     return SDValue();
14365 
14366   SDValue FirstOperand(Op.getOperand(0));
14367   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
14368     (FirstOperand.getValueType() == MVT::i8 ||
14369      FirstOperand.getValueType() == MVT::i16);
14370   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
14371     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
14372     bool DstDouble = Op.getValueType() == MVT::f64;
14373     unsigned ConvOp = Signed ?
14374       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
14375       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
14376     SDValue WidthConst =
14377       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
14378                             dl, false);
14379     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
14380     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
14381     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
14382                                          DAG.getVTList(MVT::f64, MVT::Other),
14383                                          Ops, MVT::i8, LDN->getMemOperand());
14384 
14385     // For signed conversion, we need to sign-extend the value in the VSR
14386     if (Signed) {
14387       SDValue ExtOps[] = { Ld, WidthConst };
14388       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
14389       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
14390     } else
14391       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
14392   }
14393 
14394 
14395   // For i32 intermediate values, unfortunately, the conversion functions
14396   // leave the upper 32 bits of the value are undefined. Within the set of
14397   // scalar instructions, we have no method for zero- or sign-extending the
14398   // value. Thus, we cannot handle i32 intermediate values here.
14399   if (Op.getOperand(0).getValueType() == MVT::i32)
14400     return SDValue();
14401 
14402   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
14403          "UINT_TO_FP is supported only with FPCVT");
14404 
14405   // If we have FCFIDS, then use it when converting to single-precision.
14406   // Otherwise, convert to double-precision and then round.
14407   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14408                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
14409                                                             : PPCISD::FCFIDS)
14410                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
14411                                                             : PPCISD::FCFID);
14412   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14413                   ? MVT::f32
14414                   : MVT::f64;
14415 
14416   // If we're converting from a float, to an int, and back to a float again,
14417   // then we don't need the store/load pair at all.
14418   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
14419        Subtarget.hasFPCVT()) ||
14420       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
14421     SDValue Src = Op.getOperand(0).getOperand(0);
14422     if (Src.getValueType() == MVT::f32) {
14423       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
14424       DCI.AddToWorklist(Src.getNode());
14425     } else if (Src.getValueType() != MVT::f64) {
14426       // Make sure that we don't pick up a ppc_fp128 source value.
14427       return SDValue();
14428     }
14429 
14430     unsigned FCTOp =
14431       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
14432                                                         PPCISD::FCTIDUZ;
14433 
14434     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
14435     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
14436 
14437     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
14438       FP = DAG.getNode(ISD::FP_ROUND, dl,
14439                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
14440       DCI.AddToWorklist(FP.getNode());
14441     }
14442 
14443     return FP;
14444   }
14445 
14446   return SDValue();
14447 }
14448 
14449 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
14450 // builtins) into loads with swaps.
14451 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
14452                                               DAGCombinerInfo &DCI) const {
14453   SelectionDAG &DAG = DCI.DAG;
14454   SDLoc dl(N);
14455   SDValue Chain;
14456   SDValue Base;
14457   MachineMemOperand *MMO;
14458 
14459   switch (N->getOpcode()) {
14460   default:
14461     llvm_unreachable("Unexpected opcode for little endian VSX load");
14462   case ISD::LOAD: {
14463     LoadSDNode *LD = cast<LoadSDNode>(N);
14464     Chain = LD->getChain();
14465     Base = LD->getBasePtr();
14466     MMO = LD->getMemOperand();
14467     // If the MMO suggests this isn't a load of a full vector, leave
14468     // things alone.  For a built-in, we have to make the change for
14469     // correctness, so if there is a size problem that will be a bug.
14470     if (MMO->getSize() < 16)
14471       return SDValue();
14472     break;
14473   }
14474   case ISD::INTRINSIC_W_CHAIN: {
14475     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14476     Chain = Intrin->getChain();
14477     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
14478     // us what we want. Get operand 2 instead.
14479     Base = Intrin->getOperand(2);
14480     MMO = Intrin->getMemOperand();
14481     break;
14482   }
14483   }
14484 
14485   MVT VecTy = N->getValueType(0).getSimpleVT();
14486 
14487   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
14488   // aligned and the type is a vector with elements up to 4 bytes
14489   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14490       VecTy.getScalarSizeInBits() <= 32) {
14491     return SDValue();
14492   }
14493 
14494   SDValue LoadOps[] = { Chain, Base };
14495   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14496                                          DAG.getVTList(MVT::v2f64, MVT::Other),
14497                                          LoadOps, MVT::v2f64, MMO);
14498 
14499   DCI.AddToWorklist(Load.getNode());
14500   Chain = Load.getValue(1);
14501   SDValue Swap = DAG.getNode(
14502       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14503   DCI.AddToWorklist(Swap.getNode());
14504 
14505   // Add a bitcast if the resulting load type doesn't match v2f64.
14506   if (VecTy != MVT::v2f64) {
14507     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14508     DCI.AddToWorklist(N.getNode());
14509     // Package {bitcast value, swap's chain} to match Load's shape.
14510     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14511                        N, Swap.getValue(1));
14512   }
14513 
14514   return Swap;
14515 }
14516 
14517 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14518 // builtins) into stores with swaps.
14519 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14520                                                DAGCombinerInfo &DCI) const {
14521   SelectionDAG &DAG = DCI.DAG;
14522   SDLoc dl(N);
14523   SDValue Chain;
14524   SDValue Base;
14525   unsigned SrcOpnd;
14526   MachineMemOperand *MMO;
14527 
14528   switch (N->getOpcode()) {
14529   default:
14530     llvm_unreachable("Unexpected opcode for little endian VSX store");
14531   case ISD::STORE: {
14532     StoreSDNode *ST = cast<StoreSDNode>(N);
14533     Chain = ST->getChain();
14534     Base = ST->getBasePtr();
14535     MMO = ST->getMemOperand();
14536     SrcOpnd = 1;
14537     // If the MMO suggests this isn't a store of a full vector, leave
14538     // things alone.  For a built-in, we have to make the change for
14539     // correctness, so if there is a size problem that will be a bug.
14540     if (MMO->getSize() < 16)
14541       return SDValue();
14542     break;
14543   }
14544   case ISD::INTRINSIC_VOID: {
14545     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14546     Chain = Intrin->getChain();
14547     // Intrin->getBasePtr() oddly does not get what we want.
14548     Base = Intrin->getOperand(3);
14549     MMO = Intrin->getMemOperand();
14550     SrcOpnd = 2;
14551     break;
14552   }
14553   }
14554 
14555   SDValue Src = N->getOperand(SrcOpnd);
14556   MVT VecTy = Src.getValueType().getSimpleVT();
14557 
14558   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14559   // aligned and the type is a vector with elements up to 4 bytes
14560   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14561       VecTy.getScalarSizeInBits() <= 32) {
14562     return SDValue();
14563   }
14564 
14565   // All stores are done as v2f64 and possible bit cast.
14566   if (VecTy != MVT::v2f64) {
14567     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14568     DCI.AddToWorklist(Src.getNode());
14569   }
14570 
14571   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14572                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14573   DCI.AddToWorklist(Swap.getNode());
14574   Chain = Swap.getValue(1);
14575   SDValue StoreOps[] = { Chain, Swap, Base };
14576   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14577                                           DAG.getVTList(MVT::Other),
14578                                           StoreOps, VecTy, MMO);
14579   DCI.AddToWorklist(Store.getNode());
14580   return Store;
14581 }
14582 
14583 // Handle DAG combine for STORE (FP_TO_INT F).
14584 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14585                                                DAGCombinerInfo &DCI) const {
14586 
14587   SelectionDAG &DAG = DCI.DAG;
14588   SDLoc dl(N);
14589   unsigned Opcode = N->getOperand(1).getOpcode();
14590 
14591   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14592          && "Not a FP_TO_INT Instruction!");
14593 
14594   SDValue Val = N->getOperand(1).getOperand(0);
14595   EVT Op1VT = N->getOperand(1).getValueType();
14596   EVT ResVT = Val.getValueType();
14597 
14598   if (!isTypeLegal(ResVT))
14599     return SDValue();
14600 
14601   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14602   bool ValidTypeForStoreFltAsInt =
14603         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14604          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14605 
14606   if (ResVT == MVT::f128 && !Subtarget.hasP9Vector())
14607     return SDValue();
14608 
14609   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14610       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14611     return SDValue();
14612 
14613   // Extend f32 values to f64
14614   if (ResVT.getScalarSizeInBits() == 32) {
14615     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14616     DCI.AddToWorklist(Val.getNode());
14617   }
14618 
14619   // Set signed or unsigned conversion opcode.
14620   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14621                           PPCISD::FP_TO_SINT_IN_VSR :
14622                           PPCISD::FP_TO_UINT_IN_VSR;
14623 
14624   Val = DAG.getNode(ConvOpcode,
14625                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14626   DCI.AddToWorklist(Val.getNode());
14627 
14628   // Set number of bytes being converted.
14629   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14630   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14631                     DAG.getIntPtrConstant(ByteSize, dl, false),
14632                     DAG.getValueType(Op1VT) };
14633 
14634   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14635           DAG.getVTList(MVT::Other), Ops,
14636           cast<StoreSDNode>(N)->getMemoryVT(),
14637           cast<StoreSDNode>(N)->getMemOperand());
14638 
14639   DCI.AddToWorklist(Val.getNode());
14640   return Val;
14641 }
14642 
14643 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14644   // Check that the source of the element keeps flipping
14645   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14646   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14647   for (int i = 1, e = Mask.size(); i < e; i++) {
14648     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14649       return false;
14650     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14651       return false;
14652     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14653   }
14654   return true;
14655 }
14656 
14657 static bool isSplatBV(SDValue Op) {
14658   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14659     return false;
14660   SDValue FirstOp;
14661 
14662   // Find first non-undef input.
14663   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14664     FirstOp = Op.getOperand(i);
14665     if (!FirstOp.isUndef())
14666       break;
14667   }
14668 
14669   // All inputs are undef or the same as the first non-undef input.
14670   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14671     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14672       return false;
14673   return true;
14674 }
14675 
14676 static SDValue isScalarToVec(SDValue Op) {
14677   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14678     return Op;
14679   if (Op.getOpcode() != ISD::BITCAST)
14680     return SDValue();
14681   Op = Op.getOperand(0);
14682   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14683     return Op;
14684   return SDValue();
14685 }
14686 
14687 // Fix up the shuffle mask to account for the fact that the result of
14688 // scalar_to_vector is not in lane zero. This just takes all values in
14689 // the ranges specified by the min/max indices and adds the number of
14690 // elements required to ensure each element comes from the respective
14691 // position in the valid lane.
14692 // On little endian, that's just the corresponding element in the other
14693 // half of the vector. On big endian, it is in the same half but right
14694 // justified rather than left justified in that half.
14695 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14696                                             int LHSMaxIdx, int RHSMinIdx,
14697                                             int RHSMaxIdx, int HalfVec,
14698                                             unsigned ValidLaneWidth,
14699                                             const PPCSubtarget &Subtarget) {
14700   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14701     int Idx = ShuffV[i];
14702     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14703       ShuffV[i] +=
14704           Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth;
14705   }
14706 }
14707 
14708 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14709 // the original is:
14710 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14711 // In such a case, just change the shuffle mask to extract the element
14712 // from the permuted index.
14713 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG,
14714                                const PPCSubtarget &Subtarget) {
14715   SDLoc dl(OrigSToV);
14716   EVT VT = OrigSToV.getValueType();
14717   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14718          "Expecting a SCALAR_TO_VECTOR here");
14719   SDValue Input = OrigSToV.getOperand(0);
14720 
14721   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14722     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14723     SDValue OrigVector = Input.getOperand(0);
14724 
14725     // Can't handle non-const element indices or different vector types
14726     // for the input to the extract and the output of the scalar_to_vector.
14727     if (Idx && VT == OrigVector.getValueType()) {
14728       unsigned NumElts = VT.getVectorNumElements();
14729       assert(
14730           NumElts > 1 &&
14731           "Cannot produce a permuted scalar_to_vector for one element vector");
14732       SmallVector<int, 16> NewMask(NumElts, -1);
14733       unsigned ResultInElt = NumElts / 2;
14734       ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1;
14735       NewMask[ResultInElt] = Idx->getZExtValue();
14736       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14737     }
14738   }
14739   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14740                      OrigSToV.getOperand(0));
14741 }
14742 
14743 // On little endian subtargets, combine shuffles such as:
14744 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14745 // into:
14746 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14747 // because the latter can be matched to a single instruction merge.
14748 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14749 // to put the value into element zero. Adjust the shuffle mask so that the
14750 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14751 // On big endian targets, this is still useful for SCALAR_TO_VECTOR
14752 // nodes with elements smaller than doubleword because all the ways
14753 // of getting scalar data into a vector register put the value in the
14754 // rightmost element of the left half of the vector.
14755 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14756                                                 SelectionDAG &DAG) const {
14757   SDValue LHS = SVN->getOperand(0);
14758   SDValue RHS = SVN->getOperand(1);
14759   auto Mask = SVN->getMask();
14760   int NumElts = LHS.getValueType().getVectorNumElements();
14761   SDValue Res(SVN, 0);
14762   SDLoc dl(SVN);
14763   bool IsLittleEndian = Subtarget.isLittleEndian();
14764 
14765   // On big endian targets this is only useful for subtargets with direct moves.
14766   // On little endian targets it would be useful for all subtargets with VSX.
14767   // However adding special handling for LE subtargets without direct moves
14768   // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8)
14769   // which includes direct moves.
14770   if (!Subtarget.hasDirectMove())
14771     return Res;
14772 
14773   // If this is not a shuffle of a shuffle and the first element comes from
14774   // the second vector, canonicalize to the commuted form. This will make it
14775   // more likely to match one of the single instruction patterns.
14776   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14777       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14778     std::swap(LHS, RHS);
14779     Res = DAG.getCommutedVectorShuffle(*SVN);
14780     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14781   }
14782 
14783   // Adjust the shuffle mask if either input vector comes from a
14784   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14785   // form (to prevent the need for a swap).
14786   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14787   SDValue SToVLHS = isScalarToVec(LHS);
14788   SDValue SToVRHS = isScalarToVec(RHS);
14789   if (SToVLHS || SToVRHS) {
14790     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14791                             : SToVRHS.getValueType().getVectorNumElements();
14792     int NumEltsOut = ShuffV.size();
14793     // The width of the "valid lane" (i.e. the lane that contains the value that
14794     // is vectorized) needs to be expressed in terms of the number of elements
14795     // of the shuffle. It is thereby the ratio of the values before and after
14796     // any bitcast.
14797     unsigned ValidLaneWidth =
14798         SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() /
14799                       LHS.getValueType().getScalarSizeInBits()
14800                 : SToVRHS.getValueType().getScalarSizeInBits() /
14801                       RHS.getValueType().getScalarSizeInBits();
14802 
14803     // Initially assume that neither input is permuted. These will be adjusted
14804     // accordingly if either input is.
14805     int LHSMaxIdx = -1;
14806     int RHSMinIdx = -1;
14807     int RHSMaxIdx = -1;
14808     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14809 
14810     // Get the permuted scalar to vector nodes for the source(s) that come from
14811     // ISD::SCALAR_TO_VECTOR.
14812     // On big endian systems, this only makes sense for element sizes smaller
14813     // than 64 bits since for 64-bit elements, all instructions already put
14814     // the value into element zero. Since scalar size of LHS and RHS may differ
14815     // after isScalarToVec, this should be checked using their own sizes.
14816     if (SToVLHS) {
14817       if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64)
14818         return Res;
14819       // Set up the values for the shuffle vector fixup.
14820       LHSMaxIdx = NumEltsOut / NumEltsIn;
14821       SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget);
14822       if (SToVLHS.getValueType() != LHS.getValueType())
14823         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14824       LHS = SToVLHS;
14825     }
14826     if (SToVRHS) {
14827       if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64)
14828         return Res;
14829       RHSMinIdx = NumEltsOut;
14830       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14831       SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget);
14832       if (SToVRHS.getValueType() != RHS.getValueType())
14833         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14834       RHS = SToVRHS;
14835     }
14836 
14837     // Fix up the shuffle mask to reflect where the desired element actually is.
14838     // The minimum and maximum indices that correspond to element zero for both
14839     // the LHS and RHS are computed and will control which shuffle mask entries
14840     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14841     // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted.
14842     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14843                                     HalfVec, ValidLaneWidth, Subtarget);
14844     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14845 
14846     // We may have simplified away the shuffle. We won't be able to do anything
14847     // further with it here.
14848     if (!isa<ShuffleVectorSDNode>(Res))
14849       return Res;
14850     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14851   }
14852 
14853   SDValue TheSplat = IsLittleEndian ? RHS : LHS;
14854   // The common case after we commuted the shuffle is that the RHS is a splat
14855   // and we have elements coming in from the splat at indices that are not
14856   // conducive to using a merge.
14857   // Example:
14858   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14859   if (!isSplatBV(TheSplat))
14860     return Res;
14861 
14862   // We are looking for a mask such that all even elements are from
14863   // one vector and all odd elements from the other.
14864   if (!isAlternatingShuffMask(Mask, NumElts))
14865     return Res;
14866 
14867   // Adjust the mask so we are pulling in the same index from the splat
14868   // as the index from the interesting vector in consecutive elements.
14869   if (IsLittleEndian) {
14870     // Example (even elements from first vector):
14871     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14872     if (Mask[0] < NumElts)
14873       for (int i = 1, e = Mask.size(); i < e; i += 2)
14874         ShuffV[i] = (ShuffV[i - 1] + NumElts);
14875     // Example (odd elements from first vector):
14876     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14877     else
14878       for (int i = 0, e = Mask.size(); i < e; i += 2)
14879         ShuffV[i] = (ShuffV[i + 1] + NumElts);
14880   } else {
14881     // Example (even elements from first vector):
14882     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1
14883     if (Mask[0] < NumElts)
14884       for (int i = 0, e = Mask.size(); i < e; i += 2)
14885         ShuffV[i] = ShuffV[i + 1] - NumElts;
14886     // Example (odd elements from first vector):
14887     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1
14888     else
14889       for (int i = 1, e = Mask.size(); i < e; i += 2)
14890         ShuffV[i] = ShuffV[i - 1] - NumElts;
14891   }
14892 
14893   // If the RHS has undefs, we need to remove them since we may have created
14894   // a shuffle that adds those instead of the splat value.
14895   SDValue SplatVal =
14896       cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue();
14897   TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal);
14898 
14899   if (IsLittleEndian)
14900     RHS = TheSplat;
14901   else
14902     LHS = TheSplat;
14903   return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14904 }
14905 
14906 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14907                                                 LSBaseSDNode *LSBase,
14908                                                 DAGCombinerInfo &DCI) const {
14909   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14910         "Not a reverse memop pattern!");
14911 
14912   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14913     auto Mask = SVN->getMask();
14914     int i = 0;
14915     auto I = Mask.rbegin();
14916     auto E = Mask.rend();
14917 
14918     for (; I != E; ++I) {
14919       if (*I != i)
14920         return false;
14921       i++;
14922     }
14923     return true;
14924   };
14925 
14926   SelectionDAG &DAG = DCI.DAG;
14927   EVT VT = SVN->getValueType(0);
14928 
14929   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14930     return SDValue();
14931 
14932   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14933   // See comment in PPCVSXSwapRemoval.cpp.
14934   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14935   if (!Subtarget.hasP9Vector())
14936     return SDValue();
14937 
14938   if(!IsElementReverse(SVN))
14939     return SDValue();
14940 
14941   if (LSBase->getOpcode() == ISD::LOAD) {
14942     // If the load return value 0 has more than one user except the
14943     // shufflevector instruction, it is not profitable to replace the
14944     // shufflevector with a reverse load.
14945     for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end();
14946          UI != UE; ++UI)
14947       if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE)
14948         return SDValue();
14949 
14950     SDLoc dl(LSBase);
14951     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14952     return DAG.getMemIntrinsicNode(
14953         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14954         LSBase->getMemoryVT(), LSBase->getMemOperand());
14955   }
14956 
14957   if (LSBase->getOpcode() == ISD::STORE) {
14958     // If there are other uses of the shuffle, the swap cannot be avoided.
14959     // Forcing the use of an X-Form (since swapped stores only have
14960     // X-Forms) without removing the swap is unprofitable.
14961     if (!SVN->hasOneUse())
14962       return SDValue();
14963 
14964     SDLoc dl(LSBase);
14965     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14966                           LSBase->getBasePtr()};
14967     return DAG.getMemIntrinsicNode(
14968         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14969         LSBase->getMemoryVT(), LSBase->getMemOperand());
14970   }
14971 
14972   llvm_unreachable("Expected a load or store node here");
14973 }
14974 
14975 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14976                                              DAGCombinerInfo &DCI) const {
14977   SelectionDAG &DAG = DCI.DAG;
14978   SDLoc dl(N);
14979   switch (N->getOpcode()) {
14980   default: break;
14981   case ISD::ADD:
14982     return combineADD(N, DCI);
14983   case ISD::SHL:
14984     return combineSHL(N, DCI);
14985   case ISD::SRA:
14986     return combineSRA(N, DCI);
14987   case ISD::SRL:
14988     return combineSRL(N, DCI);
14989   case ISD::MUL:
14990     return combineMUL(N, DCI);
14991   case ISD::FMA:
14992   case PPCISD::FNMSUB:
14993     return combineFMALike(N, DCI);
14994   case PPCISD::SHL:
14995     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14996         return N->getOperand(0);
14997     break;
14998   case PPCISD::SRL:
14999     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
15000         return N->getOperand(0);
15001     break;
15002   case PPCISD::SRA:
15003     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
15004       if (C->isZero() ||  //  0 >>s V -> 0.
15005           C->isAllOnes()) // -1 >>s V -> -1.
15006         return N->getOperand(0);
15007     }
15008     break;
15009   case ISD::SIGN_EXTEND:
15010   case ISD::ZERO_EXTEND:
15011   case ISD::ANY_EXTEND:
15012     return DAGCombineExtBoolTrunc(N, DCI);
15013   case ISD::TRUNCATE:
15014     return combineTRUNCATE(N, DCI);
15015   case ISD::SETCC:
15016     if (SDValue CSCC = combineSetCC(N, DCI))
15017       return CSCC;
15018     LLVM_FALLTHROUGH;
15019   case ISD::SELECT_CC:
15020     return DAGCombineTruncBoolExt(N, DCI);
15021   case ISD::SINT_TO_FP:
15022   case ISD::UINT_TO_FP:
15023     return combineFPToIntToFP(N, DCI);
15024   case ISD::VECTOR_SHUFFLE:
15025     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
15026       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
15027       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
15028     }
15029     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
15030   case ISD::STORE: {
15031 
15032     EVT Op1VT = N->getOperand(1).getValueType();
15033     unsigned Opcode = N->getOperand(1).getOpcode();
15034 
15035     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
15036       SDValue Val= combineStoreFPToInt(N, DCI);
15037       if (Val)
15038         return Val;
15039     }
15040 
15041     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
15042       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
15043       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
15044       if (Val)
15045         return Val;
15046     }
15047 
15048     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
15049     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
15050         N->getOperand(1).getNode()->hasOneUse() &&
15051         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
15052          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
15053 
15054       // STBRX can only handle simple types and it makes no sense to store less
15055       // two bytes in byte-reversed order.
15056       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
15057       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
15058         break;
15059 
15060       SDValue BSwapOp = N->getOperand(1).getOperand(0);
15061       // Do an any-extend to 32-bits if this is a half-word input.
15062       if (BSwapOp.getValueType() == MVT::i16)
15063         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
15064 
15065       // If the type of BSWAP operand is wider than stored memory width
15066       // it need to be shifted to the right side before STBRX.
15067       if (Op1VT.bitsGT(mVT)) {
15068         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
15069         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
15070                               DAG.getConstant(Shift, dl, MVT::i32));
15071         // Need to truncate if this is a bswap of i64 stored as i32/i16.
15072         if (Op1VT == MVT::i64)
15073           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
15074       }
15075 
15076       SDValue Ops[] = {
15077         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
15078       };
15079       return
15080         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
15081                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
15082                                 cast<StoreSDNode>(N)->getMemOperand());
15083     }
15084 
15085     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
15086     // So it can increase the chance of CSE constant construction.
15087     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
15088         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
15089       // Need to sign-extended to 64-bits to handle negative values.
15090       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
15091       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
15092                                     MemVT.getSizeInBits());
15093       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
15094 
15095       // DAG.getTruncStore() can't be used here because it doesn't accept
15096       // the general (base + offset) addressing mode.
15097       // So we use UpdateNodeOperands and setTruncatingStore instead.
15098       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
15099                              N->getOperand(3));
15100       cast<StoreSDNode>(N)->setTruncatingStore(true);
15101       return SDValue(N, 0);
15102     }
15103 
15104     // For little endian, VSX stores require generating xxswapd/lxvd2x.
15105     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15106     if (Op1VT.isSimple()) {
15107       MVT StoreVT = Op1VT.getSimpleVT();
15108       if (Subtarget.needsSwapsForVSXMemOps() &&
15109           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
15110            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
15111         return expandVSXStoreForLE(N, DCI);
15112     }
15113     break;
15114   }
15115   case ISD::LOAD: {
15116     LoadSDNode *LD = cast<LoadSDNode>(N);
15117     EVT VT = LD->getValueType(0);
15118 
15119     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15120     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15121     if (VT.isSimple()) {
15122       MVT LoadVT = VT.getSimpleVT();
15123       if (Subtarget.needsSwapsForVSXMemOps() &&
15124           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
15125            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
15126         return expandVSXLoadForLE(N, DCI);
15127     }
15128 
15129     // We sometimes end up with a 64-bit integer load, from which we extract
15130     // two single-precision floating-point numbers. This happens with
15131     // std::complex<float>, and other similar structures, because of the way we
15132     // canonicalize structure copies. However, if we lack direct moves,
15133     // then the final bitcasts from the extracted integer values to the
15134     // floating-point numbers turn into store/load pairs. Even with direct moves,
15135     // just loading the two floating-point numbers is likely better.
15136     auto ReplaceTwoFloatLoad = [&]() {
15137       if (VT != MVT::i64)
15138         return false;
15139 
15140       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
15141           LD->isVolatile())
15142         return false;
15143 
15144       //  We're looking for a sequence like this:
15145       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
15146       //      t16: i64 = srl t13, Constant:i32<32>
15147       //    t17: i32 = truncate t16
15148       //  t18: f32 = bitcast t17
15149       //    t19: i32 = truncate t13
15150       //  t20: f32 = bitcast t19
15151 
15152       if (!LD->hasNUsesOfValue(2, 0))
15153         return false;
15154 
15155       auto UI = LD->use_begin();
15156       while (UI.getUse().getResNo() != 0) ++UI;
15157       SDNode *Trunc = *UI++;
15158       while (UI.getUse().getResNo() != 0) ++UI;
15159       SDNode *RightShift = *UI;
15160       if (Trunc->getOpcode() != ISD::TRUNCATE)
15161         std::swap(Trunc, RightShift);
15162 
15163       if (Trunc->getOpcode() != ISD::TRUNCATE ||
15164           Trunc->getValueType(0) != MVT::i32 ||
15165           !Trunc->hasOneUse())
15166         return false;
15167       if (RightShift->getOpcode() != ISD::SRL ||
15168           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
15169           RightShift->getConstantOperandVal(1) != 32 ||
15170           !RightShift->hasOneUse())
15171         return false;
15172 
15173       SDNode *Trunc2 = *RightShift->use_begin();
15174       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
15175           Trunc2->getValueType(0) != MVT::i32 ||
15176           !Trunc2->hasOneUse())
15177         return false;
15178 
15179       SDNode *Bitcast = *Trunc->use_begin();
15180       SDNode *Bitcast2 = *Trunc2->use_begin();
15181 
15182       if (Bitcast->getOpcode() != ISD::BITCAST ||
15183           Bitcast->getValueType(0) != MVT::f32)
15184         return false;
15185       if (Bitcast2->getOpcode() != ISD::BITCAST ||
15186           Bitcast2->getValueType(0) != MVT::f32)
15187         return false;
15188 
15189       if (Subtarget.isLittleEndian())
15190         std::swap(Bitcast, Bitcast2);
15191 
15192       // Bitcast has the second float (in memory-layout order) and Bitcast2
15193       // has the first one.
15194 
15195       SDValue BasePtr = LD->getBasePtr();
15196       if (LD->isIndexed()) {
15197         assert(LD->getAddressingMode() == ISD::PRE_INC &&
15198                "Non-pre-inc AM on PPC?");
15199         BasePtr =
15200           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15201                       LD->getOffset());
15202       }
15203 
15204       auto MMOFlags =
15205           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
15206       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
15207                                       LD->getPointerInfo(), LD->getAlignment(),
15208                                       MMOFlags, LD->getAAInfo());
15209       SDValue AddPtr =
15210         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
15211                     BasePtr, DAG.getIntPtrConstant(4, dl));
15212       SDValue FloatLoad2 = DAG.getLoad(
15213           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
15214           LD->getPointerInfo().getWithOffset(4),
15215           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
15216 
15217       if (LD->isIndexed()) {
15218         // Note that DAGCombine should re-form any pre-increment load(s) from
15219         // what is produced here if that makes sense.
15220         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
15221       }
15222 
15223       DCI.CombineTo(Bitcast2, FloatLoad);
15224       DCI.CombineTo(Bitcast, FloatLoad2);
15225 
15226       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
15227                                     SDValue(FloatLoad2.getNode(), 1));
15228       return true;
15229     };
15230 
15231     if (ReplaceTwoFloatLoad())
15232       return SDValue(N, 0);
15233 
15234     EVT MemVT = LD->getMemoryVT();
15235     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
15236     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
15237     if (LD->isUnindexed() && VT.isVector() &&
15238         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
15239           // P8 and later hardware should just use LOAD.
15240           !Subtarget.hasP8Vector() &&
15241           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
15242            VT == MVT::v4f32))) &&
15243         LD->getAlign() < ABIAlignment) {
15244       // This is a type-legal unaligned Altivec load.
15245       SDValue Chain = LD->getChain();
15246       SDValue Ptr = LD->getBasePtr();
15247       bool isLittleEndian = Subtarget.isLittleEndian();
15248 
15249       // This implements the loading of unaligned vectors as described in
15250       // the venerable Apple Velocity Engine overview. Specifically:
15251       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
15252       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
15253       //
15254       // The general idea is to expand a sequence of one or more unaligned
15255       // loads into an alignment-based permutation-control instruction (lvsl
15256       // or lvsr), a series of regular vector loads (which always truncate
15257       // their input address to an aligned address), and a series of
15258       // permutations.  The results of these permutations are the requested
15259       // loaded values.  The trick is that the last "extra" load is not taken
15260       // from the address you might suspect (sizeof(vector) bytes after the
15261       // last requested load), but rather sizeof(vector) - 1 bytes after the
15262       // last requested vector. The point of this is to avoid a page fault if
15263       // the base address happened to be aligned. This works because if the
15264       // base address is aligned, then adding less than a full vector length
15265       // will cause the last vector in the sequence to be (re)loaded.
15266       // Otherwise, the next vector will be fetched as you might suspect was
15267       // necessary.
15268 
15269       // We might be able to reuse the permutation generation from
15270       // a different base address offset from this one by an aligned amount.
15271       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
15272       // optimization later.
15273       Intrinsic::ID Intr, IntrLD, IntrPerm;
15274       MVT PermCntlTy, PermTy, LDTy;
15275       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15276                             : Intrinsic::ppc_altivec_lvsl;
15277       IntrLD = Intrinsic::ppc_altivec_lvx;
15278       IntrPerm = Intrinsic::ppc_altivec_vperm;
15279       PermCntlTy = MVT::v16i8;
15280       PermTy = MVT::v4i32;
15281       LDTy = MVT::v4i32;
15282 
15283       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
15284 
15285       // Create the new MMO for the new base load. It is like the original MMO,
15286       // but represents an area in memory almost twice the vector size centered
15287       // on the original address. If the address is unaligned, we might start
15288       // reading up to (sizeof(vector)-1) bytes below the address of the
15289       // original unaligned load.
15290       MachineFunction &MF = DAG.getMachineFunction();
15291       MachineMemOperand *BaseMMO =
15292         MF.getMachineMemOperand(LD->getMemOperand(),
15293                                 -(long)MemVT.getStoreSize()+1,
15294                                 2*MemVT.getStoreSize()-1);
15295 
15296       // Create the new base load.
15297       SDValue LDXIntID =
15298           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
15299       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
15300       SDValue BaseLoad =
15301         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15302                                 DAG.getVTList(PermTy, MVT::Other),
15303                                 BaseLoadOps, LDTy, BaseMMO);
15304 
15305       // Note that the value of IncOffset (which is provided to the next
15306       // load's pointer info offset value, and thus used to calculate the
15307       // alignment), and the value of IncValue (which is actually used to
15308       // increment the pointer value) are different! This is because we
15309       // require the next load to appear to be aligned, even though it
15310       // is actually offset from the base pointer by a lesser amount.
15311       int IncOffset = VT.getSizeInBits() / 8;
15312       int IncValue = IncOffset;
15313 
15314       // Walk (both up and down) the chain looking for another load at the real
15315       // (aligned) offset (the alignment of the other load does not matter in
15316       // this case). If found, then do not use the offset reduction trick, as
15317       // that will prevent the loads from being later combined (as they would
15318       // otherwise be duplicates).
15319       if (!findConsecutiveLoad(LD, DAG))
15320         --IncValue;
15321 
15322       SDValue Increment =
15323           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
15324       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15325 
15326       MachineMemOperand *ExtraMMO =
15327         MF.getMachineMemOperand(LD->getMemOperand(),
15328                                 1, 2*MemVT.getStoreSize()-1);
15329       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
15330       SDValue ExtraLoad =
15331         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15332                                 DAG.getVTList(PermTy, MVT::Other),
15333                                 ExtraLoadOps, LDTy, ExtraMMO);
15334 
15335       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15336         BaseLoad.getValue(1), ExtraLoad.getValue(1));
15337 
15338       // Because vperm has a big-endian bias, we must reverse the order
15339       // of the input vectors and complement the permute control vector
15340       // when generating little endian code.  We have already handled the
15341       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
15342       // and ExtraLoad here.
15343       SDValue Perm;
15344       if (isLittleEndian)
15345         Perm = BuildIntrinsicOp(IntrPerm,
15346                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
15347       else
15348         Perm = BuildIntrinsicOp(IntrPerm,
15349                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
15350 
15351       if (VT != PermTy)
15352         Perm = Subtarget.hasAltivec()
15353                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
15354                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
15355                                  DAG.getTargetConstant(1, dl, MVT::i64));
15356                                // second argument is 1 because this rounding
15357                                // is always exact.
15358 
15359       // The output of the permutation is our loaded result, the TokenFactor is
15360       // our new chain.
15361       DCI.CombineTo(N, Perm, TF);
15362       return SDValue(N, 0);
15363     }
15364     }
15365     break;
15366     case ISD::INTRINSIC_WO_CHAIN: {
15367       bool isLittleEndian = Subtarget.isLittleEndian();
15368       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15369       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15370                                            : Intrinsic::ppc_altivec_lvsl);
15371       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
15372         SDValue Add = N->getOperand(1);
15373 
15374         int Bits = 4 /* 16 byte alignment */;
15375 
15376         if (DAG.MaskedValueIsZero(Add->getOperand(1),
15377                                   APInt::getAllOnes(Bits /* alignment */)
15378                                       .zext(Add.getScalarValueSizeInBits()))) {
15379           SDNode *BasePtr = Add->getOperand(0).getNode();
15380           for (SDNode *U : BasePtr->uses()) {
15381             if (U->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15382                 cast<ConstantSDNode>(U->getOperand(0))->getZExtValue() == IID) {
15383               // We've found another LVSL/LVSR, and this address is an aligned
15384               // multiple of that one. The results will be the same, so use the
15385               // one we've just found instead.
15386 
15387               return SDValue(U, 0);
15388             }
15389           }
15390         }
15391 
15392         if (isa<ConstantSDNode>(Add->getOperand(1))) {
15393           SDNode *BasePtr = Add->getOperand(0).getNode();
15394           for (SDNode *U : BasePtr->uses()) {
15395             if (U->getOpcode() == ISD::ADD &&
15396                 isa<ConstantSDNode>(U->getOperand(1)) &&
15397                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
15398                  cast<ConstantSDNode>(U->getOperand(1))->getZExtValue()) %
15399                         (1ULL << Bits) ==
15400                     0) {
15401               SDNode *OtherAdd = U;
15402               for (SDNode *V : OtherAdd->uses()) {
15403                 if (V->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15404                     cast<ConstantSDNode>(V->getOperand(0))->getZExtValue() ==
15405                         IID) {
15406                   return SDValue(V, 0);
15407                 }
15408               }
15409             }
15410           }
15411         }
15412       }
15413 
15414       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
15415       // Expose the vabsduw/h/b opportunity for down stream
15416       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
15417           (IID == Intrinsic::ppc_altivec_vmaxsw ||
15418            IID == Intrinsic::ppc_altivec_vmaxsh ||
15419            IID == Intrinsic::ppc_altivec_vmaxsb)) {
15420         SDValue V1 = N->getOperand(1);
15421         SDValue V2 = N->getOperand(2);
15422         if ((V1.getSimpleValueType() == MVT::v4i32 ||
15423              V1.getSimpleValueType() == MVT::v8i16 ||
15424              V1.getSimpleValueType() == MVT::v16i8) &&
15425             V1.getSimpleValueType() == V2.getSimpleValueType()) {
15426           // (0-a, a)
15427           if (V1.getOpcode() == ISD::SUB &&
15428               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
15429               V1.getOperand(1) == V2) {
15430             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
15431           }
15432           // (a, 0-a)
15433           if (V2.getOpcode() == ISD::SUB &&
15434               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
15435               V2.getOperand(1) == V1) {
15436             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15437           }
15438           // (x-y, y-x)
15439           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
15440               V1.getOperand(0) == V2.getOperand(1) &&
15441               V1.getOperand(1) == V2.getOperand(0)) {
15442             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15443           }
15444         }
15445       }
15446     }
15447 
15448     break;
15449   case ISD::INTRINSIC_W_CHAIN:
15450     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15451     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15452     if (Subtarget.needsSwapsForVSXMemOps()) {
15453       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15454       default:
15455         break;
15456       case Intrinsic::ppc_vsx_lxvw4x:
15457       case Intrinsic::ppc_vsx_lxvd2x:
15458         return expandVSXLoadForLE(N, DCI);
15459       }
15460     }
15461     break;
15462   case ISD::INTRINSIC_VOID:
15463     // For little endian, VSX stores require generating xxswapd/stxvd2x.
15464     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15465     if (Subtarget.needsSwapsForVSXMemOps()) {
15466       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15467       default:
15468         break;
15469       case Intrinsic::ppc_vsx_stxvw4x:
15470       case Intrinsic::ppc_vsx_stxvd2x:
15471         return expandVSXStoreForLE(N, DCI);
15472       }
15473     }
15474     break;
15475   case ISD::BSWAP: {
15476     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
15477     // For subtargets without LDBRX, we can still do better than the default
15478     // expansion even for 64-bit BSWAP (LOAD).
15479     bool Is64BitBswapOn64BitTgt =
15480         Subtarget.isPPC64() && N->getValueType(0) == MVT::i64;
15481     bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) &&
15482                                N->getOperand(0).hasOneUse();
15483     if (IsSingleUseNormalLd &&
15484         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
15485          (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) {
15486       SDValue Load = N->getOperand(0);
15487       LoadSDNode *LD = cast<LoadSDNode>(Load);
15488       // Create the byte-swapping load.
15489       SDValue Ops[] = {
15490         LD->getChain(),    // Chain
15491         LD->getBasePtr(),  // Ptr
15492         DAG.getValueType(N->getValueType(0)) // VT
15493       };
15494       SDValue BSLoad =
15495         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
15496                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
15497                                               MVT::i64 : MVT::i32, MVT::Other),
15498                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
15499 
15500       // If this is an i16 load, insert the truncate.
15501       SDValue ResVal = BSLoad;
15502       if (N->getValueType(0) == MVT::i16)
15503         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
15504 
15505       // First, combine the bswap away.  This makes the value produced by the
15506       // load dead.
15507       DCI.CombineTo(N, ResVal);
15508 
15509       // Next, combine the load away, we give it a bogus result value but a real
15510       // chain result.  The result value is dead because the bswap is dead.
15511       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
15512 
15513       // Return N so it doesn't get rechecked!
15514       return SDValue(N, 0);
15515     }
15516     // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only
15517     // before legalization so that the BUILD_PAIR is handled correctly.
15518     if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt ||
15519         !IsSingleUseNormalLd)
15520       return SDValue();
15521     LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0));
15522 
15523     // Can't split volatile or atomic loads.
15524     if (!LD->isSimple())
15525       return SDValue();
15526     SDValue BasePtr = LD->getBasePtr();
15527     SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr,
15528                              LD->getPointerInfo(), LD->getAlignment());
15529     Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo);
15530     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15531                           DAG.getIntPtrConstant(4, dl));
15532     MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand(
15533         LD->getMemOperand(), 4, 4);
15534     SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO);
15535     Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi);
15536     SDValue Res;
15537     if (Subtarget.isLittleEndian())
15538       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo);
15539     else
15540       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
15541     SDValue TF =
15542         DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15543                     Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1));
15544     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF);
15545     return Res;
15546   }
15547   case PPCISD::VCMP:
15548     // If a VCMP_rec node already exists with exactly the same operands as this
15549     // node, use its result instead of this node (VCMP_rec computes both a CR6
15550     // and a normal output).
15551     //
15552     if (!N->getOperand(0).hasOneUse() &&
15553         !N->getOperand(1).hasOneUse() &&
15554         !N->getOperand(2).hasOneUse()) {
15555 
15556       // Scan all of the users of the LHS, looking for VCMP_rec's that match.
15557       SDNode *VCMPrecNode = nullptr;
15558 
15559       SDNode *LHSN = N->getOperand(0).getNode();
15560       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
15561            UI != E; ++UI)
15562         if (UI->getOpcode() == PPCISD::VCMP_rec &&
15563             UI->getOperand(1) == N->getOperand(1) &&
15564             UI->getOperand(2) == N->getOperand(2) &&
15565             UI->getOperand(0) == N->getOperand(0)) {
15566           VCMPrecNode = *UI;
15567           break;
15568         }
15569 
15570       // If there is no VCMP_rec node, or if the flag value has a single use,
15571       // don't transform this.
15572       if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
15573         break;
15574 
15575       // Look at the (necessarily single) use of the flag value.  If it has a
15576       // chain, this transformation is more complex.  Note that multiple things
15577       // could use the value result, which we should ignore.
15578       SDNode *FlagUser = nullptr;
15579       for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
15580            FlagUser == nullptr; ++UI) {
15581         assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
15582         SDNode *User = *UI;
15583         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
15584           if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
15585             FlagUser = User;
15586             break;
15587           }
15588         }
15589       }
15590 
15591       // If the user is a MFOCRF instruction, we know this is safe.
15592       // Otherwise we give up for right now.
15593       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
15594         return SDValue(VCMPrecNode, 0);
15595     }
15596     break;
15597   case ISD::BRCOND: {
15598     SDValue Cond = N->getOperand(1);
15599     SDValue Target = N->getOperand(2);
15600 
15601     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15602         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15603           Intrinsic::loop_decrement) {
15604 
15605       // We now need to make the intrinsic dead (it cannot be instruction
15606       // selected).
15607       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15608       assert(Cond.getNode()->hasOneUse() &&
15609              "Counter decrement has more than one use");
15610 
15611       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15612                          N->getOperand(0), Target);
15613     }
15614   }
15615   break;
15616   case ISD::BR_CC: {
15617     // If this is a branch on an altivec predicate comparison, lower this so
15618     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15619     // lowering is done pre-legalize, because the legalizer lowers the predicate
15620     // compare down to code that is difficult to reassemble.
15621     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15622     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15623 
15624     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15625     // value. If so, pass-through the AND to get to the intrinsic.
15626     if (LHS.getOpcode() == ISD::AND &&
15627         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15628         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15629           Intrinsic::loop_decrement &&
15630         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15631         !isNullConstant(LHS.getOperand(1)))
15632       LHS = LHS.getOperand(0);
15633 
15634     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15635         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15636           Intrinsic::loop_decrement &&
15637         isa<ConstantSDNode>(RHS)) {
15638       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15639              "Counter decrement comparison is not EQ or NE");
15640 
15641       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15642       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15643                     (CC == ISD::SETNE && !Val);
15644 
15645       // We now need to make the intrinsic dead (it cannot be instruction
15646       // selected).
15647       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15648       assert(LHS.getNode()->hasOneUse() &&
15649              "Counter decrement has more than one use");
15650 
15651       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15652                          N->getOperand(0), N->getOperand(4));
15653     }
15654 
15655     int CompareOpc;
15656     bool isDot;
15657 
15658     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15659         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15660         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15661       assert(isDot && "Can't compare against a vector result!");
15662 
15663       // If this is a comparison against something other than 0/1, then we know
15664       // that the condition is never/always true.
15665       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15666       if (Val != 0 && Val != 1) {
15667         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15668           return N->getOperand(0);
15669         // Always !=, turn it into an unconditional branch.
15670         return DAG.getNode(ISD::BR, dl, MVT::Other,
15671                            N->getOperand(0), N->getOperand(4));
15672       }
15673 
15674       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15675 
15676       // Create the PPCISD altivec 'dot' comparison node.
15677       SDValue Ops[] = {
15678         LHS.getOperand(2),  // LHS of compare
15679         LHS.getOperand(3),  // RHS of compare
15680         DAG.getConstant(CompareOpc, dl, MVT::i32)
15681       };
15682       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15683       SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
15684 
15685       // Unpack the result based on how the target uses it.
15686       PPC::Predicate CompOpc;
15687       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15688       default:  // Can't happen, don't crash on invalid number though.
15689       case 0:   // Branch on the value of the EQ bit of CR6.
15690         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15691         break;
15692       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15693         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15694         break;
15695       case 2:   // Branch on the value of the LT bit of CR6.
15696         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15697         break;
15698       case 3:   // Branch on the inverted value of the LT bit of CR6.
15699         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15700         break;
15701       }
15702 
15703       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15704                          DAG.getConstant(CompOpc, dl, MVT::i32),
15705                          DAG.getRegister(PPC::CR6, MVT::i32),
15706                          N->getOperand(4), CompNode.getValue(1));
15707     }
15708     break;
15709   }
15710   case ISD::BUILD_VECTOR:
15711     return DAGCombineBuildVector(N, DCI);
15712   case ISD::ABS:
15713     return combineABS(N, DCI);
15714   case ISD::VSELECT:
15715     return combineVSelect(N, DCI);
15716   }
15717 
15718   return SDValue();
15719 }
15720 
15721 SDValue
15722 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15723                                  SelectionDAG &DAG,
15724                                  SmallVectorImpl<SDNode *> &Created) const {
15725   // fold (sdiv X, pow2)
15726   EVT VT = N->getValueType(0);
15727   if (VT == MVT::i64 && !Subtarget.isPPC64())
15728     return SDValue();
15729   if ((VT != MVT::i32 && VT != MVT::i64) ||
15730       !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()))
15731     return SDValue();
15732 
15733   SDLoc DL(N);
15734   SDValue N0 = N->getOperand(0);
15735 
15736   bool IsNegPow2 = Divisor.isNegatedPowerOf2();
15737   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15738   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15739 
15740   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15741   Created.push_back(Op.getNode());
15742 
15743   if (IsNegPow2) {
15744     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15745     Created.push_back(Op.getNode());
15746   }
15747 
15748   return Op;
15749 }
15750 
15751 //===----------------------------------------------------------------------===//
15752 // Inline Assembly Support
15753 //===----------------------------------------------------------------------===//
15754 
15755 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15756                                                       KnownBits &Known,
15757                                                       const APInt &DemandedElts,
15758                                                       const SelectionDAG &DAG,
15759                                                       unsigned Depth) const {
15760   Known.resetAll();
15761   switch (Op.getOpcode()) {
15762   default: break;
15763   case PPCISD::LBRX: {
15764     // lhbrx is known to have the top bits cleared out.
15765     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15766       Known.Zero = 0xFFFF0000;
15767     break;
15768   }
15769   case ISD::INTRINSIC_WO_CHAIN: {
15770     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15771     default: break;
15772     case Intrinsic::ppc_altivec_vcmpbfp_p:
15773     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15774     case Intrinsic::ppc_altivec_vcmpequb_p:
15775     case Intrinsic::ppc_altivec_vcmpequh_p:
15776     case Intrinsic::ppc_altivec_vcmpequw_p:
15777     case Intrinsic::ppc_altivec_vcmpequd_p:
15778     case Intrinsic::ppc_altivec_vcmpequq_p:
15779     case Intrinsic::ppc_altivec_vcmpgefp_p:
15780     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15781     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15782     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15783     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15784     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15785     case Intrinsic::ppc_altivec_vcmpgtsq_p:
15786     case Intrinsic::ppc_altivec_vcmpgtub_p:
15787     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15788     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15789     case Intrinsic::ppc_altivec_vcmpgtud_p:
15790     case Intrinsic::ppc_altivec_vcmpgtuq_p:
15791       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15792       break;
15793     }
15794     break;
15795   }
15796   case ISD::INTRINSIC_W_CHAIN: {
15797     switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
15798     default:
15799       break;
15800     case Intrinsic::ppc_load2r:
15801       // Top bits are cleared for load2r (which is the same as lhbrx).
15802       Known.Zero = 0xFFFF0000;
15803       break;
15804     }
15805     break;
15806   }
15807   }
15808 }
15809 
15810 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15811   switch (Subtarget.getCPUDirective()) {
15812   default: break;
15813   case PPC::DIR_970:
15814   case PPC::DIR_PWR4:
15815   case PPC::DIR_PWR5:
15816   case PPC::DIR_PWR5X:
15817   case PPC::DIR_PWR6:
15818   case PPC::DIR_PWR6X:
15819   case PPC::DIR_PWR7:
15820   case PPC::DIR_PWR8:
15821   case PPC::DIR_PWR9:
15822   case PPC::DIR_PWR10:
15823   case PPC::DIR_PWR_FUTURE: {
15824     if (!ML)
15825       break;
15826 
15827     if (!DisableInnermostLoopAlign32) {
15828       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15829       // so that we can decrease cache misses and branch-prediction misses.
15830       // Actual alignment of the loop will depend on the hotness check and other
15831       // logic in alignBlocks.
15832       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15833         return Align(32);
15834     }
15835 
15836     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15837 
15838     // For small loops (between 5 and 8 instructions), align to a 32-byte
15839     // boundary so that the entire loop fits in one instruction-cache line.
15840     uint64_t LoopSize = 0;
15841     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15842       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15843         LoopSize += TII->getInstSizeInBytes(*J);
15844         if (LoopSize > 32)
15845           break;
15846       }
15847 
15848     if (LoopSize > 16 && LoopSize <= 32)
15849       return Align(32);
15850 
15851     break;
15852   }
15853   }
15854 
15855   return TargetLowering::getPrefLoopAlignment(ML);
15856 }
15857 
15858 /// getConstraintType - Given a constraint, return the type of
15859 /// constraint it is for this target.
15860 PPCTargetLowering::ConstraintType
15861 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15862   if (Constraint.size() == 1) {
15863     switch (Constraint[0]) {
15864     default: break;
15865     case 'b':
15866     case 'r':
15867     case 'f':
15868     case 'd':
15869     case 'v':
15870     case 'y':
15871       return C_RegisterClass;
15872     case 'Z':
15873       // FIXME: While Z does indicate a memory constraint, it specifically
15874       // indicates an r+r address (used in conjunction with the 'y' modifier
15875       // in the replacement string). Currently, we're forcing the base
15876       // register to be r0 in the asm printer (which is interpreted as zero)
15877       // and forming the complete address in the second register. This is
15878       // suboptimal.
15879       return C_Memory;
15880     }
15881   } else if (Constraint == "wc") { // individual CR bits.
15882     return C_RegisterClass;
15883   } else if (Constraint == "wa" || Constraint == "wd" ||
15884              Constraint == "wf" || Constraint == "ws" ||
15885              Constraint == "wi" || Constraint == "ww") {
15886     return C_RegisterClass; // VSX registers.
15887   }
15888   return TargetLowering::getConstraintType(Constraint);
15889 }
15890 
15891 /// Examine constraint type and operand type and determine a weight value.
15892 /// This object must already have been set up with the operand type
15893 /// and the current alternative constraint selected.
15894 TargetLowering::ConstraintWeight
15895 PPCTargetLowering::getSingleConstraintMatchWeight(
15896     AsmOperandInfo &info, const char *constraint) const {
15897   ConstraintWeight weight = CW_Invalid;
15898   Value *CallOperandVal = info.CallOperandVal;
15899     // If we don't have a value, we can't do a match,
15900     // but allow it at the lowest weight.
15901   if (!CallOperandVal)
15902     return CW_Default;
15903   Type *type = CallOperandVal->getType();
15904 
15905   // Look at the constraint type.
15906   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15907     return CW_Register; // an individual CR bit.
15908   else if ((StringRef(constraint) == "wa" ||
15909             StringRef(constraint) == "wd" ||
15910             StringRef(constraint) == "wf") &&
15911            type->isVectorTy())
15912     return CW_Register;
15913   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15914     return CW_Register; // just hold 64-bit integers data.
15915   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15916     return CW_Register;
15917   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15918     return CW_Register;
15919 
15920   switch (*constraint) {
15921   default:
15922     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15923     break;
15924   case 'b':
15925     if (type->isIntegerTy())
15926       weight = CW_Register;
15927     break;
15928   case 'f':
15929     if (type->isFloatTy())
15930       weight = CW_Register;
15931     break;
15932   case 'd':
15933     if (type->isDoubleTy())
15934       weight = CW_Register;
15935     break;
15936   case 'v':
15937     if (type->isVectorTy())
15938       weight = CW_Register;
15939     break;
15940   case 'y':
15941     weight = CW_Register;
15942     break;
15943   case 'Z':
15944     weight = CW_Memory;
15945     break;
15946   }
15947   return weight;
15948 }
15949 
15950 std::pair<unsigned, const TargetRegisterClass *>
15951 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15952                                                 StringRef Constraint,
15953                                                 MVT VT) const {
15954   if (Constraint.size() == 1) {
15955     // GCC RS6000 Constraint Letters
15956     switch (Constraint[0]) {
15957     case 'b':   // R1-R31
15958       if (VT == MVT::i64 && Subtarget.isPPC64())
15959         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15960       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15961     case 'r':   // R0-R31
15962       if (VT == MVT::i64 && Subtarget.isPPC64())
15963         return std::make_pair(0U, &PPC::G8RCRegClass);
15964       return std::make_pair(0U, &PPC::GPRCRegClass);
15965     // 'd' and 'f' constraints are both defined to be "the floating point
15966     // registers", where one is for 32-bit and the other for 64-bit. We don't
15967     // really care overly much here so just give them all the same reg classes.
15968     case 'd':
15969     case 'f':
15970       if (Subtarget.hasSPE()) {
15971         if (VT == MVT::f32 || VT == MVT::i32)
15972           return std::make_pair(0U, &PPC::GPRCRegClass);
15973         if (VT == MVT::f64 || VT == MVT::i64)
15974           return std::make_pair(0U, &PPC::SPERCRegClass);
15975       } else {
15976         if (VT == MVT::f32 || VT == MVT::i32)
15977           return std::make_pair(0U, &PPC::F4RCRegClass);
15978         if (VT == MVT::f64 || VT == MVT::i64)
15979           return std::make_pair(0U, &PPC::F8RCRegClass);
15980       }
15981       break;
15982     case 'v':
15983       if (Subtarget.hasAltivec() && VT.isVector())
15984         return std::make_pair(0U, &PPC::VRRCRegClass);
15985       else if (Subtarget.hasVSX())
15986         // Scalars in Altivec registers only make sense with VSX.
15987         return std::make_pair(0U, &PPC::VFRCRegClass);
15988       break;
15989     case 'y':   // crrc
15990       return std::make_pair(0U, &PPC::CRRCRegClass);
15991     }
15992   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15993     // An individual CR bit.
15994     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15995   } else if ((Constraint == "wa" || Constraint == "wd" ||
15996              Constraint == "wf" || Constraint == "wi") &&
15997              Subtarget.hasVSX()) {
15998     // A VSX register for either a scalar (FP) or vector. There is no
15999     // support for single precision scalars on subtargets prior to Power8.
16000     if (VT.isVector())
16001       return std::make_pair(0U, &PPC::VSRCRegClass);
16002     if (VT == MVT::f32 && Subtarget.hasP8Vector())
16003       return std::make_pair(0U, &PPC::VSSRCRegClass);
16004     return std::make_pair(0U, &PPC::VSFRCRegClass);
16005   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
16006     if (VT == MVT::f32 && Subtarget.hasP8Vector())
16007       return std::make_pair(0U, &PPC::VSSRCRegClass);
16008     else
16009       return std::make_pair(0U, &PPC::VSFRCRegClass);
16010   } else if (Constraint == "lr") {
16011     if (VT == MVT::i64)
16012       return std::make_pair(0U, &PPC::LR8RCRegClass);
16013     else
16014       return std::make_pair(0U, &PPC::LRRCRegClass);
16015   }
16016 
16017   // Handle special cases of physical registers that are not properly handled
16018   // by the base class.
16019   if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
16020     // If we name a VSX register, we can't defer to the base class because it
16021     // will not recognize the correct register (their names will be VSL{0-31}
16022     // and V{0-31} so they won't match). So we match them here.
16023     if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
16024       int VSNum = atoi(Constraint.data() + 3);
16025       assert(VSNum >= 0 && VSNum <= 63 &&
16026              "Attempted to access a vsr out of range");
16027       if (VSNum < 32)
16028         return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
16029       return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
16030     }
16031 
16032     // For float registers, we can't defer to the base class as it will match
16033     // the SPILLTOVSRRC class.
16034     if (Constraint.size() > 3 && Constraint[1] == 'f') {
16035       int RegNum = atoi(Constraint.data() + 2);
16036       if (RegNum > 31 || RegNum < 0)
16037         report_fatal_error("Invalid floating point register number");
16038       if (VT == MVT::f32 || VT == MVT::i32)
16039         return Subtarget.hasSPE()
16040                    ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
16041                    : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
16042       if (VT == MVT::f64 || VT == MVT::i64)
16043         return Subtarget.hasSPE()
16044                    ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
16045                    : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
16046     }
16047   }
16048 
16049   std::pair<unsigned, const TargetRegisterClass *> R =
16050       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
16051 
16052   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
16053   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
16054   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
16055   // register.
16056   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
16057   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
16058   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
16059       PPC::GPRCRegClass.contains(R.first))
16060     return std::make_pair(TRI->getMatchingSuperReg(R.first,
16061                             PPC::sub_32, &PPC::G8RCRegClass),
16062                           &PPC::G8RCRegClass);
16063 
16064   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
16065   if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) {
16066     R.first = PPC::CR0;
16067     R.second = &PPC::CRRCRegClass;
16068   }
16069   // FIXME: This warning should ideally be emitted in the front end.
16070   const auto &TM = getTargetMachine();
16071   if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) {
16072     if (((R.first >= PPC::V20 && R.first <= PPC::V31) ||
16073          (R.first >= PPC::VF20 && R.first <= PPC::VF31)) &&
16074         (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass))
16075       errs() << "warning: vector registers 20 to 32 are reserved in the "
16076                 "default AIX AltiVec ABI and cannot be used\n";
16077   }
16078 
16079   return R;
16080 }
16081 
16082 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16083 /// vector.  If it is invalid, don't add anything to Ops.
16084 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16085                                                      std::string &Constraint,
16086                                                      std::vector<SDValue>&Ops,
16087                                                      SelectionDAG &DAG) const {
16088   SDValue Result;
16089 
16090   // Only support length 1 constraints.
16091   if (Constraint.length() > 1) return;
16092 
16093   char Letter = Constraint[0];
16094   switch (Letter) {
16095   default: break;
16096   case 'I':
16097   case 'J':
16098   case 'K':
16099   case 'L':
16100   case 'M':
16101   case 'N':
16102   case 'O':
16103   case 'P': {
16104     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
16105     if (!CST) return; // Must be an immediate to match.
16106     SDLoc dl(Op);
16107     int64_t Value = CST->getSExtValue();
16108     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
16109                          // numbers are printed as such.
16110     switch (Letter) {
16111     default: llvm_unreachable("Unknown constraint letter!");
16112     case 'I':  // "I" is a signed 16-bit constant.
16113       if (isInt<16>(Value))
16114         Result = DAG.getTargetConstant(Value, dl, TCVT);
16115       break;
16116     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
16117       if (isShiftedUInt<16, 16>(Value))
16118         Result = DAG.getTargetConstant(Value, dl, TCVT);
16119       break;
16120     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
16121       if (isShiftedInt<16, 16>(Value))
16122         Result = DAG.getTargetConstant(Value, dl, TCVT);
16123       break;
16124     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
16125       if (isUInt<16>(Value))
16126         Result = DAG.getTargetConstant(Value, dl, TCVT);
16127       break;
16128     case 'M':  // "M" is a constant that is greater than 31.
16129       if (Value > 31)
16130         Result = DAG.getTargetConstant(Value, dl, TCVT);
16131       break;
16132     case 'N':  // "N" is a positive constant that is an exact power of two.
16133       if (Value > 0 && isPowerOf2_64(Value))
16134         Result = DAG.getTargetConstant(Value, dl, TCVT);
16135       break;
16136     case 'O':  // "O" is the constant zero.
16137       if (Value == 0)
16138         Result = DAG.getTargetConstant(Value, dl, TCVT);
16139       break;
16140     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
16141       if (isInt<16>(-Value))
16142         Result = DAG.getTargetConstant(Value, dl, TCVT);
16143       break;
16144     }
16145     break;
16146   }
16147   }
16148 
16149   if (Result.getNode()) {
16150     Ops.push_back(Result);
16151     return;
16152   }
16153 
16154   // Handle standard constraint letters.
16155   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16156 }
16157 
16158 // isLegalAddressingMode - Return true if the addressing mode represented
16159 // by AM is legal for this target, for a load/store of the specified type.
16160 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
16161                                               const AddrMode &AM, Type *Ty,
16162                                               unsigned AS,
16163                                               Instruction *I) const {
16164   // Vector type r+i form is supported since power9 as DQ form. We don't check
16165   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
16166   // imm form is preferred and the offset can be adjusted to use imm form later
16167   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
16168   // max offset to check legal addressing mode, we should be a little aggressive
16169   // to contain other offsets for that LSRUse.
16170   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
16171     return false;
16172 
16173   // PPC allows a sign-extended 16-bit immediate field.
16174   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
16175     return false;
16176 
16177   // No global is ever allowed as a base.
16178   if (AM.BaseGV)
16179     return false;
16180 
16181   // PPC only support r+r,
16182   switch (AM.Scale) {
16183   case 0:  // "r+i" or just "i", depending on HasBaseReg.
16184     break;
16185   case 1:
16186     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
16187       return false;
16188     // Otherwise we have r+r or r+i.
16189     break;
16190   case 2:
16191     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
16192       return false;
16193     // Allow 2*r as r+r.
16194     break;
16195   default:
16196     // No other scales are supported.
16197     return false;
16198   }
16199 
16200   return true;
16201 }
16202 
16203 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
16204                                            SelectionDAG &DAG) const {
16205   MachineFunction &MF = DAG.getMachineFunction();
16206   MachineFrameInfo &MFI = MF.getFrameInfo();
16207   MFI.setReturnAddressIsTaken(true);
16208 
16209   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16210     return SDValue();
16211 
16212   SDLoc dl(Op);
16213   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16214 
16215   // Make sure the function does not optimize away the store of the RA to
16216   // the stack.
16217   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
16218   FuncInfo->setLRStoreRequired();
16219   bool isPPC64 = Subtarget.isPPC64();
16220   auto PtrVT = getPointerTy(MF.getDataLayout());
16221 
16222   if (Depth > 0) {
16223     // The link register (return address) is saved in the caller's frame
16224     // not the callee's stack frame. So we must get the caller's frame
16225     // address and load the return address at the LR offset from there.
16226     SDValue FrameAddr =
16227         DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16228                     LowerFRAMEADDR(Op, DAG), MachinePointerInfo());
16229     SDValue Offset =
16230         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
16231                         isPPC64 ? MVT::i64 : MVT::i32);
16232     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16233                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
16234                        MachinePointerInfo());
16235   }
16236 
16237   // Just load the return address off the stack.
16238   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
16239   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
16240                      MachinePointerInfo());
16241 }
16242 
16243 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
16244                                           SelectionDAG &DAG) const {
16245   SDLoc dl(Op);
16246   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16247 
16248   MachineFunction &MF = DAG.getMachineFunction();
16249   MachineFrameInfo &MFI = MF.getFrameInfo();
16250   MFI.setFrameAddressIsTaken(true);
16251 
16252   EVT PtrVT = getPointerTy(MF.getDataLayout());
16253   bool isPPC64 = PtrVT == MVT::i64;
16254 
16255   // Naked functions never have a frame pointer, and so we use r1. For all
16256   // other functions, this decision must be delayed until during PEI.
16257   unsigned FrameReg;
16258   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
16259     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
16260   else
16261     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
16262 
16263   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
16264                                          PtrVT);
16265   while (Depth--)
16266     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16267                             FrameAddr, MachinePointerInfo());
16268   return FrameAddr;
16269 }
16270 
16271 // FIXME? Maybe this could be a TableGen attribute on some registers and
16272 // this table could be generated automatically from RegInfo.
16273 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
16274                                               const MachineFunction &MF) const {
16275   bool isPPC64 = Subtarget.isPPC64();
16276 
16277   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
16278   if (!is64Bit && VT != LLT::scalar(32))
16279     report_fatal_error("Invalid register global variable type");
16280 
16281   Register Reg = StringSwitch<Register>(RegName)
16282                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
16283                      .Case("r2", isPPC64 ? Register() : PPC::R2)
16284                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
16285                      .Default(Register());
16286 
16287   if (Reg)
16288     return Reg;
16289   report_fatal_error("Invalid register name global variable");
16290 }
16291 
16292 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
16293   // 32-bit SVR4 ABI access everything as got-indirect.
16294   if (Subtarget.is32BitELFABI())
16295     return true;
16296 
16297   // AIX accesses everything indirectly through the TOC, which is similar to
16298   // the GOT.
16299   if (Subtarget.isAIXABI())
16300     return true;
16301 
16302   CodeModel::Model CModel = getTargetMachine().getCodeModel();
16303   // If it is small or large code model, module locals are accessed
16304   // indirectly by loading their address from .toc/.got.
16305   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
16306     return true;
16307 
16308   // JumpTable and BlockAddress are accessed as got-indirect.
16309   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
16310     return true;
16311 
16312   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
16313     return Subtarget.isGVIndirectSymbol(G->getGlobal());
16314 
16315   return false;
16316 }
16317 
16318 bool
16319 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
16320   // The PowerPC target isn't yet aware of offsets.
16321   return false;
16322 }
16323 
16324 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
16325                                            const CallInst &I,
16326                                            MachineFunction &MF,
16327                                            unsigned Intrinsic) const {
16328   switch (Intrinsic) {
16329   case Intrinsic::ppc_atomicrmw_xchg_i128:
16330   case Intrinsic::ppc_atomicrmw_add_i128:
16331   case Intrinsic::ppc_atomicrmw_sub_i128:
16332   case Intrinsic::ppc_atomicrmw_nand_i128:
16333   case Intrinsic::ppc_atomicrmw_and_i128:
16334   case Intrinsic::ppc_atomicrmw_or_i128:
16335   case Intrinsic::ppc_atomicrmw_xor_i128:
16336   case Intrinsic::ppc_cmpxchg_i128:
16337     Info.opc = ISD::INTRINSIC_W_CHAIN;
16338     Info.memVT = MVT::i128;
16339     Info.ptrVal = I.getArgOperand(0);
16340     Info.offset = 0;
16341     Info.align = Align(16);
16342     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
16343                  MachineMemOperand::MOVolatile;
16344     return true;
16345   case Intrinsic::ppc_atomic_load_i128:
16346     Info.opc = ISD::INTRINSIC_W_CHAIN;
16347     Info.memVT = MVT::i128;
16348     Info.ptrVal = I.getArgOperand(0);
16349     Info.offset = 0;
16350     Info.align = Align(16);
16351     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16352     return true;
16353   case Intrinsic::ppc_atomic_store_i128:
16354     Info.opc = ISD::INTRINSIC_VOID;
16355     Info.memVT = MVT::i128;
16356     Info.ptrVal = I.getArgOperand(2);
16357     Info.offset = 0;
16358     Info.align = Align(16);
16359     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16360     return true;
16361   case Intrinsic::ppc_altivec_lvx:
16362   case Intrinsic::ppc_altivec_lvxl:
16363   case Intrinsic::ppc_altivec_lvebx:
16364   case Intrinsic::ppc_altivec_lvehx:
16365   case Intrinsic::ppc_altivec_lvewx:
16366   case Intrinsic::ppc_vsx_lxvd2x:
16367   case Intrinsic::ppc_vsx_lxvw4x:
16368   case Intrinsic::ppc_vsx_lxvd2x_be:
16369   case Intrinsic::ppc_vsx_lxvw4x_be:
16370   case Intrinsic::ppc_vsx_lxvl:
16371   case Intrinsic::ppc_vsx_lxvll: {
16372     EVT VT;
16373     switch (Intrinsic) {
16374     case Intrinsic::ppc_altivec_lvebx:
16375       VT = MVT::i8;
16376       break;
16377     case Intrinsic::ppc_altivec_lvehx:
16378       VT = MVT::i16;
16379       break;
16380     case Intrinsic::ppc_altivec_lvewx:
16381       VT = MVT::i32;
16382       break;
16383     case Intrinsic::ppc_vsx_lxvd2x:
16384     case Intrinsic::ppc_vsx_lxvd2x_be:
16385       VT = MVT::v2f64;
16386       break;
16387     default:
16388       VT = MVT::v4i32;
16389       break;
16390     }
16391 
16392     Info.opc = ISD::INTRINSIC_W_CHAIN;
16393     Info.memVT = VT;
16394     Info.ptrVal = I.getArgOperand(0);
16395     Info.offset = -VT.getStoreSize()+1;
16396     Info.size = 2*VT.getStoreSize()-1;
16397     Info.align = Align(1);
16398     Info.flags = MachineMemOperand::MOLoad;
16399     return true;
16400   }
16401   case Intrinsic::ppc_altivec_stvx:
16402   case Intrinsic::ppc_altivec_stvxl:
16403   case Intrinsic::ppc_altivec_stvebx:
16404   case Intrinsic::ppc_altivec_stvehx:
16405   case Intrinsic::ppc_altivec_stvewx:
16406   case Intrinsic::ppc_vsx_stxvd2x:
16407   case Intrinsic::ppc_vsx_stxvw4x:
16408   case Intrinsic::ppc_vsx_stxvd2x_be:
16409   case Intrinsic::ppc_vsx_stxvw4x_be:
16410   case Intrinsic::ppc_vsx_stxvl:
16411   case Intrinsic::ppc_vsx_stxvll: {
16412     EVT VT;
16413     switch (Intrinsic) {
16414     case Intrinsic::ppc_altivec_stvebx:
16415       VT = MVT::i8;
16416       break;
16417     case Intrinsic::ppc_altivec_stvehx:
16418       VT = MVT::i16;
16419       break;
16420     case Intrinsic::ppc_altivec_stvewx:
16421       VT = MVT::i32;
16422       break;
16423     case Intrinsic::ppc_vsx_stxvd2x:
16424     case Intrinsic::ppc_vsx_stxvd2x_be:
16425       VT = MVT::v2f64;
16426       break;
16427     default:
16428       VT = MVT::v4i32;
16429       break;
16430     }
16431 
16432     Info.opc = ISD::INTRINSIC_VOID;
16433     Info.memVT = VT;
16434     Info.ptrVal = I.getArgOperand(1);
16435     Info.offset = -VT.getStoreSize()+1;
16436     Info.size = 2*VT.getStoreSize()-1;
16437     Info.align = Align(1);
16438     Info.flags = MachineMemOperand::MOStore;
16439     return true;
16440   }
16441   default:
16442     break;
16443   }
16444 
16445   return false;
16446 }
16447 
16448 /// It returns EVT::Other if the type should be determined using generic
16449 /// target-independent logic.
16450 EVT PPCTargetLowering::getOptimalMemOpType(
16451     const MemOp &Op, const AttributeList &FuncAttributes) const {
16452   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
16453     // We should use Altivec/VSX loads and stores when available. For unaligned
16454     // addresses, unaligned VSX loads are only fast starting with the P8.
16455     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
16456         (Op.isAligned(Align(16)) ||
16457          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
16458       return MVT::v4i32;
16459   }
16460 
16461   if (Subtarget.isPPC64()) {
16462     return MVT::i64;
16463   }
16464 
16465   return MVT::i32;
16466 }
16467 
16468 /// Returns true if it is beneficial to convert a load of a constant
16469 /// to just the constant itself.
16470 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16471                                                           Type *Ty) const {
16472   assert(Ty->isIntegerTy());
16473 
16474   unsigned BitSize = Ty->getPrimitiveSizeInBits();
16475   return !(BitSize == 0 || BitSize > 64);
16476 }
16477 
16478 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16479   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16480     return false;
16481   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16482   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16483   return NumBits1 == 64 && NumBits2 == 32;
16484 }
16485 
16486 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16487   if (!VT1.isInteger() || !VT2.isInteger())
16488     return false;
16489   unsigned NumBits1 = VT1.getSizeInBits();
16490   unsigned NumBits2 = VT2.getSizeInBits();
16491   return NumBits1 == 64 && NumBits2 == 32;
16492 }
16493 
16494 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16495   // Generally speaking, zexts are not free, but they are free when they can be
16496   // folded with other operations.
16497   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
16498     EVT MemVT = LD->getMemoryVT();
16499     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
16500          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
16501         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
16502          LD->getExtensionType() == ISD::ZEXTLOAD))
16503       return true;
16504   }
16505 
16506   // FIXME: Add other cases...
16507   //  - 32-bit shifts with a zext to i64
16508   //  - zext after ctlz, bswap, etc.
16509   //  - zext after and by a constant mask
16510 
16511   return TargetLowering::isZExtFree(Val, VT2);
16512 }
16513 
16514 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
16515   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
16516          "invalid fpext types");
16517   // Extending to float128 is not free.
16518   if (DestVT == MVT::f128)
16519     return false;
16520   return true;
16521 }
16522 
16523 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16524   return isInt<16>(Imm) || isUInt<16>(Imm);
16525 }
16526 
16527 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16528   return isInt<16>(Imm) || isUInt<16>(Imm);
16529 }
16530 
16531 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align,
16532                                                        MachineMemOperand::Flags,
16533                                                        bool *Fast) const {
16534   if (DisablePPCUnaligned)
16535     return false;
16536 
16537   // PowerPC supports unaligned memory access for simple non-vector types.
16538   // Although accessing unaligned addresses is not as efficient as accessing
16539   // aligned addresses, it is generally more efficient than manual expansion,
16540   // and generally only traps for software emulation when crossing page
16541   // boundaries.
16542 
16543   if (!VT.isSimple())
16544     return false;
16545 
16546   if (VT.isFloatingPoint() && !VT.isVector() &&
16547       !Subtarget.allowsUnalignedFPAccess())
16548     return false;
16549 
16550   if (VT.getSimpleVT().isVector()) {
16551     if (Subtarget.hasVSX()) {
16552       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
16553           VT != MVT::v4f32 && VT != MVT::v4i32)
16554         return false;
16555     } else {
16556       return false;
16557     }
16558   }
16559 
16560   if (VT == MVT::ppcf128)
16561     return false;
16562 
16563   if (Fast)
16564     *Fast = true;
16565 
16566   return true;
16567 }
16568 
16569 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
16570                                                SDValue C) const {
16571   // Check integral scalar types.
16572   if (!VT.isScalarInteger())
16573     return false;
16574   if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
16575     if (!ConstNode->getAPIntValue().isSignedIntN(64))
16576       return false;
16577     // This transformation will generate >= 2 operations. But the following
16578     // cases will generate <= 2 instructions during ISEL. So exclude them.
16579     // 1. If the constant multiplier fits 16 bits, it can be handled by one
16580     // HW instruction, ie. MULLI
16581     // 2. If the multiplier after shifted fits 16 bits, an extra shift
16582     // instruction is needed than case 1, ie. MULLI and RLDICR
16583     int64_t Imm = ConstNode->getSExtValue();
16584     unsigned Shift = countTrailingZeros<uint64_t>(Imm);
16585     Imm >>= Shift;
16586     if (isInt<16>(Imm))
16587       return false;
16588     uint64_t UImm = static_cast<uint64_t>(Imm);
16589     if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
16590         isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
16591       return true;
16592   }
16593   return false;
16594 }
16595 
16596 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16597                                                    EVT VT) const {
16598   return isFMAFasterThanFMulAndFAdd(
16599       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
16600 }
16601 
16602 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
16603                                                    Type *Ty) const {
16604   switch (Ty->getScalarType()->getTypeID()) {
16605   case Type::FloatTyID:
16606   case Type::DoubleTyID:
16607     return true;
16608   case Type::FP128TyID:
16609     return Subtarget.hasP9Vector();
16610   default:
16611     return false;
16612   }
16613 }
16614 
16615 // FIXME: add more patterns which are not profitable to hoist.
16616 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
16617   if (!I->hasOneUse())
16618     return true;
16619 
16620   Instruction *User = I->user_back();
16621   assert(User && "A single use instruction with no uses.");
16622 
16623   switch (I->getOpcode()) {
16624   case Instruction::FMul: {
16625     // Don't break FMA, PowerPC prefers FMA.
16626     if (User->getOpcode() != Instruction::FSub &&
16627         User->getOpcode() != Instruction::FAdd)
16628       return true;
16629 
16630     const TargetOptions &Options = getTargetMachine().Options;
16631     const Function *F = I->getFunction();
16632     const DataLayout &DL = F->getParent()->getDataLayout();
16633     Type *Ty = User->getOperand(0)->getType();
16634 
16635     return !(
16636         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
16637         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
16638         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
16639   }
16640   case Instruction::Load: {
16641     // Don't break "store (load float*)" pattern, this pattern will be combined
16642     // to "store (load int32)" in later InstCombine pass. See function
16643     // combineLoadToOperationType. On PowerPC, loading a float point takes more
16644     // cycles than loading a 32 bit integer.
16645     LoadInst *LI = cast<LoadInst>(I);
16646     // For the loads that combineLoadToOperationType does nothing, like
16647     // ordered load, it should be profitable to hoist them.
16648     // For swifterror load, it can only be used for pointer to pointer type, so
16649     // later type check should get rid of this case.
16650     if (!LI->isUnordered())
16651       return true;
16652 
16653     if (User->getOpcode() != Instruction::Store)
16654       return true;
16655 
16656     if (I->getType()->getTypeID() != Type::FloatTyID)
16657       return true;
16658 
16659     return false;
16660   }
16661   default:
16662     return true;
16663   }
16664   return true;
16665 }
16666 
16667 const MCPhysReg *
16668 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
16669   // LR is a callee-save register, but we must treat it as clobbered by any call
16670   // site. Hence we include LR in the scratch registers, which are in turn added
16671   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
16672   // to CTR, which is used by any indirect call.
16673   static const MCPhysReg ScratchRegs[] = {
16674     PPC::X12, PPC::LR8, PPC::CTR8, 0
16675   };
16676 
16677   return ScratchRegs;
16678 }
16679 
16680 Register PPCTargetLowering::getExceptionPointerRegister(
16681     const Constant *PersonalityFn) const {
16682   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
16683 }
16684 
16685 Register PPCTargetLowering::getExceptionSelectorRegister(
16686     const Constant *PersonalityFn) const {
16687   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
16688 }
16689 
16690 bool
16691 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
16692                      EVT VT , unsigned DefinedValues) const {
16693   if (VT == MVT::v2i64)
16694     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
16695 
16696   if (Subtarget.hasVSX())
16697     return true;
16698 
16699   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
16700 }
16701 
16702 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16703   if (DisableILPPref || Subtarget.enableMachineScheduler())
16704     return TargetLowering::getSchedulingPreference(N);
16705 
16706   return Sched::ILP;
16707 }
16708 
16709 // Create a fast isel object.
16710 FastISel *
16711 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16712                                   const TargetLibraryInfo *LibInfo) const {
16713   return PPC::createFastISel(FuncInfo, LibInfo);
16714 }
16715 
16716 // 'Inverted' means the FMA opcode after negating one multiplicand.
16717 // For example, (fma -a b c) = (fnmsub a b c)
16718 static unsigned invertFMAOpcode(unsigned Opc) {
16719   switch (Opc) {
16720   default:
16721     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16722   case ISD::FMA:
16723     return PPCISD::FNMSUB;
16724   case PPCISD::FNMSUB:
16725     return ISD::FMA;
16726   }
16727 }
16728 
16729 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16730                                                 bool LegalOps, bool OptForSize,
16731                                                 NegatibleCost &Cost,
16732                                                 unsigned Depth) const {
16733   if (Depth > SelectionDAG::MaxRecursionDepth)
16734     return SDValue();
16735 
16736   unsigned Opc = Op.getOpcode();
16737   EVT VT = Op.getValueType();
16738   SDNodeFlags Flags = Op.getNode()->getFlags();
16739 
16740   switch (Opc) {
16741   case PPCISD::FNMSUB:
16742     if (!Op.hasOneUse() || !isTypeLegal(VT))
16743       break;
16744 
16745     const TargetOptions &Options = getTargetMachine().Options;
16746     SDValue N0 = Op.getOperand(0);
16747     SDValue N1 = Op.getOperand(1);
16748     SDValue N2 = Op.getOperand(2);
16749     SDLoc Loc(Op);
16750 
16751     NegatibleCost N2Cost = NegatibleCost::Expensive;
16752     SDValue NegN2 =
16753         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16754 
16755     if (!NegN2)
16756       return SDValue();
16757 
16758     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16759     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16760     // These transformations may change sign of zeroes. For example,
16761     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16762     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16763       // Try and choose the cheaper one to negate.
16764       NegatibleCost N0Cost = NegatibleCost::Expensive;
16765       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16766                                            N0Cost, Depth + 1);
16767 
16768       NegatibleCost N1Cost = NegatibleCost::Expensive;
16769       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16770                                            N1Cost, Depth + 1);
16771 
16772       if (NegN0 && N0Cost <= N1Cost) {
16773         Cost = std::min(N0Cost, N2Cost);
16774         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16775       } else if (NegN1) {
16776         Cost = std::min(N1Cost, N2Cost);
16777         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16778       }
16779     }
16780 
16781     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16782     if (isOperationLegal(ISD::FMA, VT)) {
16783       Cost = N2Cost;
16784       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16785     }
16786 
16787     break;
16788   }
16789 
16790   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16791                                               Cost, Depth);
16792 }
16793 
16794 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16795 bool PPCTargetLowering::useLoadStackGuardNode() const {
16796   if (!Subtarget.isTargetLinux())
16797     return TargetLowering::useLoadStackGuardNode();
16798   return true;
16799 }
16800 
16801 // Override to disable global variable loading on Linux and insert AIX canary
16802 // word declaration.
16803 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16804   if (Subtarget.isAIXABI()) {
16805     M.getOrInsertGlobal(AIXSSPCanaryWordName,
16806                         Type::getInt8PtrTy(M.getContext()));
16807     return;
16808   }
16809   if (!Subtarget.isTargetLinux())
16810     return TargetLowering::insertSSPDeclarations(M);
16811 }
16812 
16813 Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const {
16814   if (Subtarget.isAIXABI())
16815     return M.getGlobalVariable(AIXSSPCanaryWordName);
16816   return TargetLowering::getSDagStackGuard(M);
16817 }
16818 
16819 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16820                                      bool ForCodeSize) const {
16821   if (!VT.isSimple() || !Subtarget.hasVSX())
16822     return false;
16823 
16824   switch(VT.getSimpleVT().SimpleTy) {
16825   default:
16826     // For FP types that are currently not supported by PPC backend, return
16827     // false. Examples: f16, f80.
16828     return false;
16829   case MVT::f32:
16830   case MVT::f64:
16831     if (Subtarget.hasPrefixInstrs()) {
16832       // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP.
16833       return true;
16834     }
16835     LLVM_FALLTHROUGH;
16836   case MVT::ppcf128:
16837     return Imm.isPosZero();
16838   }
16839 }
16840 
16841 // For vector shift operation op, fold
16842 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16843 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16844                                   SelectionDAG &DAG) {
16845   SDValue N0 = N->getOperand(0);
16846   SDValue N1 = N->getOperand(1);
16847   EVT VT = N0.getValueType();
16848   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16849   unsigned Opcode = N->getOpcode();
16850   unsigned TargetOpcode;
16851 
16852   switch (Opcode) {
16853   default:
16854     llvm_unreachable("Unexpected shift operation");
16855   case ISD::SHL:
16856     TargetOpcode = PPCISD::SHL;
16857     break;
16858   case ISD::SRL:
16859     TargetOpcode = PPCISD::SRL;
16860     break;
16861   case ISD::SRA:
16862     TargetOpcode = PPCISD::SRA;
16863     break;
16864   }
16865 
16866   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16867       N1->getOpcode() == ISD::AND)
16868     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16869       if (Mask->getZExtValue() == OpSizeInBits - 1)
16870         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16871 
16872   return SDValue();
16873 }
16874 
16875 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16876   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16877     return Value;
16878 
16879   SDValue N0 = N->getOperand(0);
16880   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16881   if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
16882       N0.getOpcode() != ISD::SIGN_EXTEND ||
16883       N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
16884       N->getValueType(0) != MVT::i64)
16885     return SDValue();
16886 
16887   // We can't save an operation here if the value is already extended, and
16888   // the existing shift is easier to combine.
16889   SDValue ExtsSrc = N0.getOperand(0);
16890   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16891       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16892     return SDValue();
16893 
16894   SDLoc DL(N0);
16895   SDValue ShiftBy = SDValue(CN1, 0);
16896   // We want the shift amount to be i32 on the extswli, but the shift could
16897   // have an i64.
16898   if (ShiftBy.getValueType() == MVT::i64)
16899     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16900 
16901   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16902                          ShiftBy);
16903 }
16904 
16905 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16906   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16907     return Value;
16908 
16909   return SDValue();
16910 }
16911 
16912 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16913   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16914     return Value;
16915 
16916   return SDValue();
16917 }
16918 
16919 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16920 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16921 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16922 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16923 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16924                                  const PPCSubtarget &Subtarget) {
16925   if (!Subtarget.isPPC64())
16926     return SDValue();
16927 
16928   SDValue LHS = N->getOperand(0);
16929   SDValue RHS = N->getOperand(1);
16930 
16931   auto isZextOfCompareWithConstant = [](SDValue Op) {
16932     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16933         Op.getValueType() != MVT::i64)
16934       return false;
16935 
16936     SDValue Cmp = Op.getOperand(0);
16937     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16938         Cmp.getOperand(0).getValueType() != MVT::i64)
16939       return false;
16940 
16941     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
16942       int64_t NegConstant = 0 - Constant->getSExtValue();
16943       // Due to the limitations of the addi instruction,
16944       // -C is required to be [-32768, 32767].
16945       return isInt<16>(NegConstant);
16946     }
16947 
16948     return false;
16949   };
16950 
16951   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
16952   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16953 
16954   // If there is a pattern, canonicalize a zext operand to the RHS.
16955   if (LHSHasPattern && !RHSHasPattern)
16956     std::swap(LHS, RHS);
16957   else if (!LHSHasPattern && !RHSHasPattern)
16958     return SDValue();
16959 
16960   SDLoc DL(N);
16961   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16962   SDValue Cmp = RHS.getOperand(0);
16963   SDValue Z = Cmp.getOperand(0);
16964   auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1));
16965   int64_t NegConstant = 0 - Constant->getSExtValue();
16966 
16967   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16968   default: break;
16969   case ISD::SETNE: {
16970     //                                 when C == 0
16971     //                             --> addze X, (addic Z, -1).carry
16972     //                            /
16973     // add X, (zext(setne Z, C))--
16974     //                            \    when -32768 <= -C <= 32767 && C != 0
16975     //                             --> addze X, (addic (addi Z, -C), -1).carry
16976     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16977                               DAG.getConstant(NegConstant, DL, MVT::i64));
16978     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16979     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16980                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16981     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16982                        SDValue(Addc.getNode(), 1));
16983     }
16984   case ISD::SETEQ: {
16985     //                                 when C == 0
16986     //                             --> addze X, (subfic Z, 0).carry
16987     //                            /
16988     // add X, (zext(sete  Z, C))--
16989     //                            \    when -32768 <= -C <= 32767 && C != 0
16990     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16991     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16992                               DAG.getConstant(NegConstant, DL, MVT::i64));
16993     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16994     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16995                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16996     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16997                        SDValue(Subc.getNode(), 1));
16998     }
16999   }
17000 
17001   return SDValue();
17002 }
17003 
17004 // Transform
17005 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
17006 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
17007 // In this case both C1 and C2 must be known constants.
17008 // C1+C2 must fit into a 34 bit signed integer.
17009 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
17010                                           const PPCSubtarget &Subtarget) {
17011   if (!Subtarget.isUsingPCRelativeCalls())
17012     return SDValue();
17013 
17014   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
17015   // If we find that node try to cast the Global Address and the Constant.
17016   SDValue LHS = N->getOperand(0);
17017   SDValue RHS = N->getOperand(1);
17018 
17019   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
17020     std::swap(LHS, RHS);
17021 
17022   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
17023     return SDValue();
17024 
17025   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
17026   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
17027   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
17028 
17029   // Check that both casts succeeded.
17030   if (!GSDN || !ConstNode)
17031     return SDValue();
17032 
17033   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
17034   SDLoc DL(GSDN);
17035 
17036   // The signed int offset needs to fit in 34 bits.
17037   if (!isInt<34>(NewOffset))
17038     return SDValue();
17039 
17040   // The new global address is a copy of the old global address except
17041   // that it has the updated Offset.
17042   SDValue GA =
17043       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
17044                                  NewOffset, GSDN->getTargetFlags());
17045   SDValue MatPCRel =
17046       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
17047   return MatPCRel;
17048 }
17049 
17050 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
17051   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
17052     return Value;
17053 
17054   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
17055     return Value;
17056 
17057   return SDValue();
17058 }
17059 
17060 // Detect TRUNCATE operations on bitcasts of float128 values.
17061 // What we are looking for here is the situtation where we extract a subset
17062 // of bits from a 128 bit float.
17063 // This can be of two forms:
17064 // 1) BITCAST of f128 feeding TRUNCATE
17065 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
17066 // The reason this is required is because we do not have a legal i128 type
17067 // and so we want to prevent having to store the f128 and then reload part
17068 // of it.
17069 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
17070                                            DAGCombinerInfo &DCI) const {
17071   // If we are using CRBits then try that first.
17072   if (Subtarget.useCRBits()) {
17073     // Check if CRBits did anything and return that if it did.
17074     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
17075       return CRTruncValue;
17076   }
17077 
17078   SDLoc dl(N);
17079   SDValue Op0 = N->getOperand(0);
17080 
17081   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
17082   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
17083     EVT VT = N->getValueType(0);
17084     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17085       return SDValue();
17086     SDValue Sub = Op0.getOperand(0);
17087     if (Sub.getOpcode() == ISD::SUB) {
17088       SDValue SubOp0 = Sub.getOperand(0);
17089       SDValue SubOp1 = Sub.getOperand(1);
17090       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
17091           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
17092         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
17093                                SubOp1.getOperand(0),
17094                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
17095       }
17096     }
17097   }
17098 
17099   // Looking for a truncate of i128 to i64.
17100   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
17101     return SDValue();
17102 
17103   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
17104 
17105   // SRL feeding TRUNCATE.
17106   if (Op0.getOpcode() == ISD::SRL) {
17107     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
17108     // The right shift has to be by 64 bits.
17109     if (!ConstNode || ConstNode->getZExtValue() != 64)
17110       return SDValue();
17111 
17112     // Switch the element number to extract.
17113     EltToExtract = EltToExtract ? 0 : 1;
17114     // Update Op0 past the SRL.
17115     Op0 = Op0.getOperand(0);
17116   }
17117 
17118   // BITCAST feeding a TRUNCATE possibly via SRL.
17119   if (Op0.getOpcode() == ISD::BITCAST &&
17120       Op0.getValueType() == MVT::i128 &&
17121       Op0.getOperand(0).getValueType() == MVT::f128) {
17122     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
17123     return DCI.DAG.getNode(
17124         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
17125         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
17126   }
17127   return SDValue();
17128 }
17129 
17130 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
17131   SelectionDAG &DAG = DCI.DAG;
17132 
17133   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
17134   if (!ConstOpOrElement)
17135     return SDValue();
17136 
17137   // An imul is usually smaller than the alternative sequence for legal type.
17138   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
17139       isOperationLegal(ISD::MUL, N->getValueType(0)))
17140     return SDValue();
17141 
17142   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
17143     switch (this->Subtarget.getCPUDirective()) {
17144     default:
17145       // TODO: enhance the condition for subtarget before pwr8
17146       return false;
17147     case PPC::DIR_PWR8:
17148       //  type        mul     add    shl
17149       // scalar        4       1      1
17150       // vector        7       2      2
17151       return true;
17152     case PPC::DIR_PWR9:
17153     case PPC::DIR_PWR10:
17154     case PPC::DIR_PWR_FUTURE:
17155       //  type        mul     add    shl
17156       // scalar        5       2      2
17157       // vector        7       2      2
17158 
17159       // The cycle RATIO of related operations are showed as a table above.
17160       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
17161       // scalar and vector type. For 2 instrs patterns, add/sub + shl
17162       // are 4, it is always profitable; but for 3 instrs patterns
17163       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
17164       // So we should only do it for vector type.
17165       return IsAddOne && IsNeg ? VT.isVector() : true;
17166     }
17167   };
17168 
17169   EVT VT = N->getValueType(0);
17170   SDLoc DL(N);
17171 
17172   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
17173   bool IsNeg = MulAmt.isNegative();
17174   APInt MulAmtAbs = MulAmt.abs();
17175 
17176   if ((MulAmtAbs - 1).isPowerOf2()) {
17177     // (mul x, 2^N + 1) => (add (shl x, N), x)
17178     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
17179 
17180     if (!IsProfitable(IsNeg, true, VT))
17181       return SDValue();
17182 
17183     SDValue Op0 = N->getOperand(0);
17184     SDValue Op1 =
17185         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17186                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
17187     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
17188 
17189     if (!IsNeg)
17190       return Res;
17191 
17192     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
17193   } else if ((MulAmtAbs + 1).isPowerOf2()) {
17194     // (mul x, 2^N - 1) => (sub (shl x, N), x)
17195     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
17196 
17197     if (!IsProfitable(IsNeg, false, VT))
17198       return SDValue();
17199 
17200     SDValue Op0 = N->getOperand(0);
17201     SDValue Op1 =
17202         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17203                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
17204 
17205     if (!IsNeg)
17206       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
17207     else
17208       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
17209 
17210   } else {
17211     return SDValue();
17212   }
17213 }
17214 
17215 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
17216 // in combiner since we need to check SD flags and other subtarget features.
17217 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
17218                                           DAGCombinerInfo &DCI) const {
17219   SDValue N0 = N->getOperand(0);
17220   SDValue N1 = N->getOperand(1);
17221   SDValue N2 = N->getOperand(2);
17222   SDNodeFlags Flags = N->getFlags();
17223   EVT VT = N->getValueType(0);
17224   SelectionDAG &DAG = DCI.DAG;
17225   const TargetOptions &Options = getTargetMachine().Options;
17226   unsigned Opc = N->getOpcode();
17227   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
17228   bool LegalOps = !DCI.isBeforeLegalizeOps();
17229   SDLoc Loc(N);
17230 
17231   if (!isOperationLegal(ISD::FMA, VT))
17232     return SDValue();
17233 
17234   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
17235   // since (fnmsub a b c)=-0 while c-ab=+0.
17236   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
17237     return SDValue();
17238 
17239   // (fma (fneg a) b c) => (fnmsub a b c)
17240   // (fnmsub (fneg a) b c) => (fma a b c)
17241   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
17242     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
17243 
17244   // (fma a (fneg b) c) => (fnmsub a b c)
17245   // (fnmsub a (fneg b) c) => (fma a b c)
17246   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
17247     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
17248 
17249   return SDValue();
17250 }
17251 
17252 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
17253   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
17254   if (!Subtarget.is64BitELFABI())
17255     return false;
17256 
17257   // If not a tail call then no need to proceed.
17258   if (!CI->isTailCall())
17259     return false;
17260 
17261   // If sibling calls have been disabled and tail-calls aren't guaranteed
17262   // there is no reason to duplicate.
17263   auto &TM = getTargetMachine();
17264   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
17265     return false;
17266 
17267   // Can't tail call a function called indirectly, or if it has variadic args.
17268   const Function *Callee = CI->getCalledFunction();
17269   if (!Callee || Callee->isVarArg())
17270     return false;
17271 
17272   // Make sure the callee and caller calling conventions are eligible for tco.
17273   const Function *Caller = CI->getParent()->getParent();
17274   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
17275                                            CI->getCallingConv()))
17276       return false;
17277 
17278   // If the function is local then we have a good chance at tail-calling it
17279   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
17280 }
17281 
17282 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
17283   if (!Subtarget.hasVSX())
17284     return false;
17285   if (Subtarget.hasP9Vector() && VT == MVT::f128)
17286     return true;
17287   return VT == MVT::f32 || VT == MVT::f64 ||
17288     VT == MVT::v4f32 || VT == MVT::v2f64;
17289 }
17290 
17291 bool PPCTargetLowering::
17292 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
17293   const Value *Mask = AndI.getOperand(1);
17294   // If the mask is suitable for andi. or andis. we should sink the and.
17295   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
17296     // Can't handle constants wider than 64-bits.
17297     if (CI->getBitWidth() > 64)
17298       return false;
17299     int64_t ConstVal = CI->getZExtValue();
17300     return isUInt<16>(ConstVal) ||
17301       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
17302   }
17303 
17304   // For non-constant masks, we can always use the record-form and.
17305   return true;
17306 }
17307 
17308 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
17309 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
17310 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
17311 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
17312 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
17313 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
17314   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
17315   assert(Subtarget.hasP9Altivec() &&
17316          "Only combine this when P9 altivec supported!");
17317   EVT VT = N->getValueType(0);
17318   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17319     return SDValue();
17320 
17321   SelectionDAG &DAG = DCI.DAG;
17322   SDLoc dl(N);
17323   if (N->getOperand(0).getOpcode() == ISD::SUB) {
17324     // Even for signed integers, if it's known to be positive (as signed
17325     // integer) due to zero-extended inputs.
17326     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
17327     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
17328     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
17329          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
17330         (SubOpcd1 == ISD::ZERO_EXTEND ||
17331          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
17332       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17333                          N->getOperand(0)->getOperand(0),
17334                          N->getOperand(0)->getOperand(1),
17335                          DAG.getTargetConstant(0, dl, MVT::i32));
17336     }
17337 
17338     // For type v4i32, it can be optimized with xvnegsp + vabsduw
17339     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
17340         N->getOperand(0).hasOneUse()) {
17341       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17342                          N->getOperand(0)->getOperand(0),
17343                          N->getOperand(0)->getOperand(1),
17344                          DAG.getTargetConstant(1, dl, MVT::i32));
17345     }
17346   }
17347 
17348   return SDValue();
17349 }
17350 
17351 // For type v4i32/v8ii16/v16i8, transform
17352 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
17353 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
17354 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
17355 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
17356 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
17357                                           DAGCombinerInfo &DCI) const {
17358   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
17359   assert(Subtarget.hasP9Altivec() &&
17360          "Only combine this when P9 altivec supported!");
17361 
17362   SelectionDAG &DAG = DCI.DAG;
17363   SDLoc dl(N);
17364   SDValue Cond = N->getOperand(0);
17365   SDValue TrueOpnd = N->getOperand(1);
17366   SDValue FalseOpnd = N->getOperand(2);
17367   EVT VT = N->getOperand(1).getValueType();
17368 
17369   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
17370       FalseOpnd.getOpcode() != ISD::SUB)
17371     return SDValue();
17372 
17373   // ABSD only available for type v4i32/v8i16/v16i8
17374   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17375     return SDValue();
17376 
17377   // At least to save one more dependent computation
17378   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
17379     return SDValue();
17380 
17381   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17382 
17383   // Can only handle unsigned comparison here
17384   switch (CC) {
17385   default:
17386     return SDValue();
17387   case ISD::SETUGT:
17388   case ISD::SETUGE:
17389     break;
17390   case ISD::SETULT:
17391   case ISD::SETULE:
17392     std::swap(TrueOpnd, FalseOpnd);
17393     break;
17394   }
17395 
17396   SDValue CmpOpnd1 = Cond.getOperand(0);
17397   SDValue CmpOpnd2 = Cond.getOperand(1);
17398 
17399   // SETCC CmpOpnd1 CmpOpnd2 cond
17400   // TrueOpnd = CmpOpnd1 - CmpOpnd2
17401   // FalseOpnd = CmpOpnd2 - CmpOpnd1
17402   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
17403       TrueOpnd.getOperand(1) == CmpOpnd2 &&
17404       FalseOpnd.getOperand(0) == CmpOpnd2 &&
17405       FalseOpnd.getOperand(1) == CmpOpnd1) {
17406     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
17407                        CmpOpnd1, CmpOpnd2,
17408                        DAG.getTargetConstant(0, dl, MVT::i32));
17409   }
17410 
17411   return SDValue();
17412 }
17413 
17414 /// getAddrModeForFlags - Based on the set of address flags, select the most
17415 /// optimal instruction format to match by.
17416 PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const {
17417   // This is not a node we should be handling here.
17418   if (Flags == PPC::MOF_None)
17419     return PPC::AM_None;
17420   // Unaligned D-Forms are tried first, followed by the aligned D-Forms.
17421   for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm))
17422     if ((Flags & FlagSet) == FlagSet)
17423       return PPC::AM_DForm;
17424   for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm))
17425     if ((Flags & FlagSet) == FlagSet)
17426       return PPC::AM_DSForm;
17427   for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm))
17428     if ((Flags & FlagSet) == FlagSet)
17429       return PPC::AM_DQForm;
17430   for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm))
17431     if ((Flags & FlagSet) == FlagSet)
17432       return PPC::AM_PrefixDForm;
17433   // If no other forms are selected, return an X-Form as it is the most
17434   // general addressing mode.
17435   return PPC::AM_XForm;
17436 }
17437 
17438 /// Set alignment flags based on whether or not the Frame Index is aligned.
17439 /// Utilized when computing flags for address computation when selecting
17440 /// load and store instructions.
17441 static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet,
17442                                SelectionDAG &DAG) {
17443   bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR));
17444   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N);
17445   if (!FI)
17446     return;
17447   const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17448   unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value();
17449   // If this is (add $FI, $S16Imm), the alignment flags are already set
17450   // based on the immediate. We just need to clear the alignment flags
17451   // if the FI alignment is weaker.
17452   if ((FrameIndexAlign % 4) != 0)
17453     FlagSet &= ~PPC::MOF_RPlusSImm16Mult4;
17454   if ((FrameIndexAlign % 16) != 0)
17455     FlagSet &= ~PPC::MOF_RPlusSImm16Mult16;
17456   // If the address is a plain FrameIndex, set alignment flags based on
17457   // FI alignment.
17458   if (!IsAdd) {
17459     if ((FrameIndexAlign % 4) == 0)
17460       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17461     if ((FrameIndexAlign % 16) == 0)
17462       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17463   }
17464 }
17465 
17466 /// Given a node, compute flags that are used for address computation when
17467 /// selecting load and store instructions. The flags computed are stored in
17468 /// FlagSet. This function takes into account whether the node is a constant,
17469 /// an ADD, OR, or a constant, and computes the address flags accordingly.
17470 static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet,
17471                                               SelectionDAG &DAG) {
17472   // Set the alignment flags for the node depending on if the node is
17473   // 4-byte or 16-byte aligned.
17474   auto SetAlignFlagsForImm = [&](uint64_t Imm) {
17475     if ((Imm & 0x3) == 0)
17476       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17477     if ((Imm & 0xf) == 0)
17478       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17479   };
17480 
17481   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
17482     // All 32-bit constants can be computed as LIS + Disp.
17483     const APInt &ConstImm = CN->getAPIntValue();
17484     if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants.
17485       FlagSet |= PPC::MOF_AddrIsSImm32;
17486       SetAlignFlagsForImm(ConstImm.getZExtValue());
17487       setAlignFlagsForFI(N, FlagSet, DAG);
17488     }
17489     if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants.
17490       FlagSet |= PPC::MOF_RPlusSImm34;
17491     else // Let constant materialization handle large constants.
17492       FlagSet |= PPC::MOF_NotAddNorCst;
17493   } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) {
17494     // This address can be represented as an addition of:
17495     // - Register + Imm16 (possibly a multiple of 4/16)
17496     // - Register + Imm34
17497     // - Register + PPCISD::Lo
17498     // - Register + Register
17499     // In any case, we won't have to match this as Base + Zero.
17500     SDValue RHS = N.getOperand(1);
17501     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) {
17502       const APInt &ConstImm = CN->getAPIntValue();
17503       if (ConstImm.isSignedIntN(16)) {
17504         FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates.
17505         SetAlignFlagsForImm(ConstImm.getZExtValue());
17506         setAlignFlagsForFI(N, FlagSet, DAG);
17507       }
17508       if (ConstImm.isSignedIntN(34))
17509         FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates.
17510       else
17511         FlagSet |= PPC::MOF_RPlusR; // Register.
17512     } else if (RHS.getOpcode() == PPCISD::Lo &&
17513                !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue())
17514       FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo.
17515     else
17516       FlagSet |= PPC::MOF_RPlusR;
17517   } else { // The address computation is not a constant or an addition.
17518     setAlignFlagsForFI(N, FlagSet, DAG);
17519     FlagSet |= PPC::MOF_NotAddNorCst;
17520   }
17521 }
17522 
17523 static bool isPCRelNode(SDValue N) {
17524   return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR ||
17525       isValidPCRelNode<ConstantPoolSDNode>(N) ||
17526       isValidPCRelNode<GlobalAddressSDNode>(N) ||
17527       isValidPCRelNode<JumpTableSDNode>(N) ||
17528       isValidPCRelNode<BlockAddressSDNode>(N));
17529 }
17530 
17531 /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute
17532 /// the address flags of the load/store instruction that is to be matched.
17533 unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N,
17534                                            SelectionDAG &DAG) const {
17535   unsigned FlagSet = PPC::MOF_None;
17536 
17537   // Compute subtarget flags.
17538   if (!Subtarget.hasP9Vector())
17539     FlagSet |= PPC::MOF_SubtargetBeforeP9;
17540   else {
17541     FlagSet |= PPC::MOF_SubtargetP9;
17542     if (Subtarget.hasPrefixInstrs())
17543       FlagSet |= PPC::MOF_SubtargetP10;
17544   }
17545   if (Subtarget.hasSPE())
17546     FlagSet |= PPC::MOF_SubtargetSPE;
17547 
17548   // Check if we have a PCRel node and return early.
17549   if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N))
17550     return FlagSet;
17551 
17552   // If the node is the paired load/store intrinsics, compute flags for
17553   // address computation and return early.
17554   unsigned ParentOp = Parent->getOpcode();
17555   if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) ||
17556                                (ParentOp == ISD::INTRINSIC_VOID))) {
17557     unsigned ID = cast<ConstantSDNode>(Parent->getOperand(1))->getZExtValue();
17558     if ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) {
17559       SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp)
17560                              ? Parent->getOperand(2)
17561                              : Parent->getOperand(3);
17562       computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG);
17563       FlagSet |= PPC::MOF_Vector;
17564       return FlagSet;
17565     }
17566   }
17567 
17568   // Mark this as something we don't want to handle here if it is atomic
17569   // or pre-increment instruction.
17570   if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent))
17571     if (LSB->isIndexed())
17572       return PPC::MOF_None;
17573 
17574   // Compute in-memory type flags. This is based on if there are scalars,
17575   // floats or vectors.
17576   const MemSDNode *MN = dyn_cast<MemSDNode>(Parent);
17577   assert(MN && "Parent should be a MemSDNode!");
17578   EVT MemVT = MN->getMemoryVT();
17579   unsigned Size = MemVT.getSizeInBits();
17580   if (MemVT.isScalarInteger()) {
17581     assert(Size <= 128 &&
17582            "Not expecting scalar integers larger than 16 bytes!");
17583     if (Size < 32)
17584       FlagSet |= PPC::MOF_SubWordInt;
17585     else if (Size == 32)
17586       FlagSet |= PPC::MOF_WordInt;
17587     else
17588       FlagSet |= PPC::MOF_DoubleWordInt;
17589   } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors.
17590     if (Size == 128)
17591       FlagSet |= PPC::MOF_Vector;
17592     else if (Size == 256) {
17593       assert(Subtarget.pairedVectorMemops() &&
17594              "256-bit vectors are only available when paired vector memops is "
17595              "enabled!");
17596       FlagSet |= PPC::MOF_Vector;
17597     } else
17598       llvm_unreachable("Not expecting illegal vectors!");
17599   } else { // Floating point type: can be scalar, f128 or vector types.
17600     if (Size == 32 || Size == 64)
17601       FlagSet |= PPC::MOF_ScalarFloat;
17602     else if (MemVT == MVT::f128 || MemVT.isVector())
17603       FlagSet |= PPC::MOF_Vector;
17604     else
17605       llvm_unreachable("Not expecting illegal scalar floats!");
17606   }
17607 
17608   // Compute flags for address computation.
17609   computeFlagsForAddressComputation(N, FlagSet, DAG);
17610 
17611   // Compute type extension flags.
17612   if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) {
17613     switch (LN->getExtensionType()) {
17614     case ISD::SEXTLOAD:
17615       FlagSet |= PPC::MOF_SExt;
17616       break;
17617     case ISD::EXTLOAD:
17618     case ISD::ZEXTLOAD:
17619       FlagSet |= PPC::MOF_ZExt;
17620       break;
17621     case ISD::NON_EXTLOAD:
17622       FlagSet |= PPC::MOF_NoExt;
17623       break;
17624     }
17625   } else
17626     FlagSet |= PPC::MOF_NoExt;
17627 
17628   // For integers, no extension is the same as zero extension.
17629   // We set the extension mode to zero extension so we don't have
17630   // to add separate entries in AddrModesMap for loads and stores.
17631   if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) {
17632     FlagSet |= PPC::MOF_ZExt;
17633     FlagSet &= ~PPC::MOF_NoExt;
17634   }
17635 
17636   // If we don't have prefixed instructions, 34-bit constants should be
17637   // treated as PPC::MOF_NotAddNorCst so they can match D-Forms.
17638   bool IsNonP1034BitConst =
17639       ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) &
17640        FlagSet) == PPC::MOF_RPlusSImm34;
17641   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR &&
17642       IsNonP1034BitConst)
17643     FlagSet |= PPC::MOF_NotAddNorCst;
17644 
17645   return FlagSet;
17646 }
17647 
17648 /// SelectForceXFormMode - Given the specified address, force it to be
17649 /// represented as an indexed [r+r] operation (an XForm instruction).
17650 PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp,
17651                                                       SDValue &Base,
17652                                                       SelectionDAG &DAG) const {
17653 
17654   PPC::AddrMode Mode = PPC::AM_XForm;
17655   int16_t ForceXFormImm = 0;
17656   if (provablyDisjointOr(DAG, N) &&
17657       !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) {
17658     Disp = N.getOperand(0);
17659     Base = N.getOperand(1);
17660     return Mode;
17661   }
17662 
17663   // If the address is the result of an add, we will utilize the fact that the
17664   // address calculation includes an implicit add.  However, we can reduce
17665   // register pressure if we do not materialize a constant just for use as the
17666   // index register.  We only get rid of the add if it is not an add of a
17667   // value and a 16-bit signed constant and both have a single use.
17668   if (N.getOpcode() == ISD::ADD &&
17669       (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) ||
17670        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
17671     Disp = N.getOperand(0);
17672     Base = N.getOperand(1);
17673     return Mode;
17674   }
17675 
17676   // Otherwise, use R0 as the base register.
17677   Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17678                          N.getValueType());
17679   Base = N;
17680 
17681   return Mode;
17682 }
17683 
17684 bool PPCTargetLowering::splitValueIntoRegisterParts(
17685     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
17686     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
17687   EVT ValVT = Val.getValueType();
17688   // If we are splitting a scalar integer into f64 parts (i.e. so they
17689   // can be placed into VFRC registers), we need to zero extend and
17690   // bitcast the values. This will ensure the value is placed into a
17691   // VSR using direct moves or stack operations as needed.
17692   if (PartVT == MVT::f64 &&
17693       (ValVT == MVT::i32 || ValVT == MVT::i16 || ValVT == MVT::i8)) {
17694     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
17695     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Val);
17696     Parts[0] = Val;
17697     return true;
17698   }
17699   return false;
17700 }
17701 
17702 // If we happen to match to an aligned D-Form, check if the Frame Index is
17703 // adequately aligned. If it is not, reset the mode to match to X-Form.
17704 static void setXFormForUnalignedFI(SDValue N, unsigned Flags,
17705                                    PPC::AddrMode &Mode) {
17706   if (!isa<FrameIndexSDNode>(N))
17707     return;
17708   if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) ||
17709       (Mode == PPC::AM_DQForm && !(Flags & PPC::MOF_RPlusSImm16Mult16)))
17710     Mode = PPC::AM_XForm;
17711 }
17712 
17713 /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode),
17714 /// compute the address flags of the node, get the optimal address mode based
17715 /// on the flags, and set the Base and Disp based on the address mode.
17716 PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent,
17717                                                        SDValue N, SDValue &Disp,
17718                                                        SDValue &Base,
17719                                                        SelectionDAG &DAG,
17720                                                        MaybeAlign Align) const {
17721   SDLoc DL(Parent);
17722 
17723   // Compute the address flags.
17724   unsigned Flags = computeMOFlags(Parent, N, DAG);
17725 
17726   // Get the optimal address mode based on the Flags.
17727   PPC::AddrMode Mode = getAddrModeForFlags(Flags);
17728 
17729   // If the address mode is DS-Form or DQ-Form, check if the FI is aligned.
17730   // Select an X-Form load if it is not.
17731   setXFormForUnalignedFI(N, Flags, Mode);
17732 
17733   // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node.
17734   if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) {
17735     assert(Subtarget.isUsingPCRelativeCalls() &&
17736            "Must be using PC-Relative calls when a valid PC-Relative node is "
17737            "present!");
17738     Mode = PPC::AM_PCRel;
17739   }
17740 
17741   // Set Base and Disp accordingly depending on the address mode.
17742   switch (Mode) {
17743   case PPC::AM_DForm:
17744   case PPC::AM_DSForm:
17745   case PPC::AM_DQForm: {
17746     // This is a register plus a 16-bit immediate. The base will be the
17747     // register and the displacement will be the immediate unless it
17748     // isn't sufficiently aligned.
17749     if (Flags & PPC::MOF_RPlusSImm16) {
17750       SDValue Op0 = N.getOperand(0);
17751       SDValue Op1 = N.getOperand(1);
17752       int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue();
17753       if (!Align || isAligned(*Align, Imm)) {
17754         Disp = DAG.getTargetConstant(Imm, DL, N.getValueType());
17755         Base = Op0;
17756         if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) {
17757           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17758           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17759         }
17760         break;
17761       }
17762     }
17763     // This is a register plus the @lo relocation. The base is the register
17764     // and the displacement is the global address.
17765     else if (Flags & PPC::MOF_RPlusLo) {
17766       Disp = N.getOperand(1).getOperand(0); // The global address.
17767       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
17768              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
17769              Disp.getOpcode() == ISD::TargetConstantPool ||
17770              Disp.getOpcode() == ISD::TargetJumpTable);
17771       Base = N.getOperand(0);
17772       break;
17773     }
17774     // This is a constant address at most 32 bits. The base will be
17775     // zero or load-immediate-shifted and the displacement will be
17776     // the low 16 bits of the address.
17777     else if (Flags & PPC::MOF_AddrIsSImm32) {
17778       auto *CN = cast<ConstantSDNode>(N);
17779       EVT CNType = CN->getValueType(0);
17780       uint64_t CNImm = CN->getZExtValue();
17781       // If this address fits entirely in a 16-bit sext immediate field, codegen
17782       // this as "d, 0".
17783       int16_t Imm;
17784       if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) {
17785         Disp = DAG.getTargetConstant(Imm, DL, CNType);
17786         Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17787                                CNType);
17788         break;
17789       }
17790       // Handle 32-bit sext immediate with LIS + Addr mode.
17791       if ((CNType == MVT::i32 || isInt<32>(CNImm)) &&
17792           (!Align || isAligned(*Align, CNImm))) {
17793         int32_t Addr = (int32_t)CNImm;
17794         // Otherwise, break this down into LIS + Disp.
17795         Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32);
17796         Base =
17797             DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32);
17798         uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8;
17799         Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0);
17800         break;
17801       }
17802     }
17803     // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable.
17804     Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout()));
17805     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
17806       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17807       fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17808     } else
17809       Base = N;
17810     break;
17811   }
17812   case PPC::AM_PrefixDForm: {
17813     int64_t Imm34 = 0;
17814     unsigned Opcode = N.getOpcode();
17815     if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) &&
17816         (isIntS34Immediate(N.getOperand(1), Imm34))) {
17817       // N is an Add/OR Node, and it's operand is a 34-bit signed immediate.
17818       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
17819       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
17820         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17821       else
17822         Base = N.getOperand(0);
17823     } else if (isIntS34Immediate(N, Imm34)) {
17824       // The address is a 34-bit signed immediate.
17825       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
17826       Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
17827     }
17828     break;
17829   }
17830   case PPC::AM_PCRel: {
17831     // When selecting PC-Relative instructions, "Base" is not utilized as
17832     // we select the address as [PC+imm].
17833     Disp = N;
17834     break;
17835   }
17836   case PPC::AM_None:
17837     break;
17838   default: { // By default, X-Form is always available to be selected.
17839     // When a frame index is not aligned, we also match by XForm.
17840     FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N);
17841     Base = FI ? N : N.getOperand(1);
17842     Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17843                                 N.getValueType())
17844               : N.getOperand(0);
17845     break;
17846   }
17847   }
17848   return Mode;
17849 }
17850 
17851 CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC,
17852                                                  bool Return,
17853                                                  bool IsVarArg) const {
17854   switch (CC) {
17855   case CallingConv::Cold:
17856     return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS);
17857   default:
17858     return CC_PPC64_ELF_FIS;
17859   }
17860 }
17861 
17862 TargetLowering::AtomicExpansionKind
17863 PPCTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17864   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
17865   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
17866     return AtomicExpansionKind::MaskedIntrinsic;
17867   return TargetLowering::shouldExpandAtomicRMWInIR(AI);
17868 }
17869 
17870 TargetLowering::AtomicExpansionKind
17871 PPCTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
17872   unsigned Size = AI->getNewValOperand()->getType()->getPrimitiveSizeInBits();
17873   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
17874     return AtomicExpansionKind::MaskedIntrinsic;
17875   return TargetLowering::shouldExpandAtomicCmpXchgInIR(AI);
17876 }
17877 
17878 static Intrinsic::ID
17879 getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp) {
17880   switch (BinOp) {
17881   default:
17882     llvm_unreachable("Unexpected AtomicRMW BinOp");
17883   case AtomicRMWInst::Xchg:
17884     return Intrinsic::ppc_atomicrmw_xchg_i128;
17885   case AtomicRMWInst::Add:
17886     return Intrinsic::ppc_atomicrmw_add_i128;
17887   case AtomicRMWInst::Sub:
17888     return Intrinsic::ppc_atomicrmw_sub_i128;
17889   case AtomicRMWInst::And:
17890     return Intrinsic::ppc_atomicrmw_and_i128;
17891   case AtomicRMWInst::Or:
17892     return Intrinsic::ppc_atomicrmw_or_i128;
17893   case AtomicRMWInst::Xor:
17894     return Intrinsic::ppc_atomicrmw_xor_i128;
17895   case AtomicRMWInst::Nand:
17896     return Intrinsic::ppc_atomicrmw_nand_i128;
17897   }
17898 }
17899 
17900 Value *PPCTargetLowering::emitMaskedAtomicRMWIntrinsic(
17901     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
17902     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
17903   assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
17904          "Only support quadword now");
17905   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17906   Type *ValTy = AlignedAddr->getType()->getPointerElementType();
17907   assert(ValTy->getPrimitiveSizeInBits() == 128);
17908   Function *RMW = Intrinsic::getDeclaration(
17909       M, getIntrinsicForAtomicRMWBinOp128(AI->getOperation()));
17910   Type *Int64Ty = Type::getInt64Ty(M->getContext());
17911   Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo");
17912   Value *IncrHi =
17913       Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi");
17914   Value *Addr =
17915       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
17916   Value *LoHi = Builder.CreateCall(RMW, {Addr, IncrLo, IncrHi});
17917   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
17918   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
17919   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
17920   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
17921   return Builder.CreateOr(
17922       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
17923 }
17924 
17925 Value *PPCTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
17926     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
17927     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
17928   assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
17929          "Only support quadword now");
17930   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17931   Type *ValTy = AlignedAddr->getType()->getPointerElementType();
17932   assert(ValTy->getPrimitiveSizeInBits() == 128);
17933   Function *IntCmpXchg =
17934       Intrinsic::getDeclaration(M, Intrinsic::ppc_cmpxchg_i128);
17935   Type *Int64Ty = Type::getInt64Ty(M->getContext());
17936   Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo");
17937   Value *CmpHi =
17938       Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi");
17939   Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo");
17940   Value *NewHi =
17941       Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi");
17942   Value *Addr =
17943       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
17944   emitLeadingFence(Builder, CI, Ord);
17945   Value *LoHi =
17946       Builder.CreateCall(IntCmpXchg, {Addr, CmpLo, CmpHi, NewLo, NewHi});
17947   emitTrailingFence(Builder, CI, Ord);
17948   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
17949   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
17950   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
17951   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
17952   return Builder.CreateOr(
17953       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
17954 }
17955