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 
605   // To handle counter-based loop conditions.
606   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
607 
608   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
609   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
610   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
611   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
612 
613   // Comparisons that require checking two conditions.
614   if (Subtarget.hasSPE()) {
615     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
616     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
617     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
618     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
619   }
620   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
621   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
622   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
623   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
624   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
625   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
626   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
627   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
628   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
629   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
630   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
631   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
632 
633   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
634   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
635 
636   if (Subtarget.has64BitSupport()) {
637     // They also have instructions for converting between i64 and fp.
638     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
639     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
640     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
641     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
642     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
643     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
644     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
645     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
646     // This is just the low 32 bits of a (signed) fp->i64 conversion.
647     // We cannot do this with Promote because i64 is not a legal type.
648     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
649     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
650 
651     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
652       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
653       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
654     }
655   } else {
656     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
657     if (Subtarget.hasSPE()) {
658       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
659       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
660     } else {
661       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
662       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
663     }
664   }
665 
666   // With the instructions enabled under FPCVT, we can do everything.
667   if (Subtarget.hasFPCVT()) {
668     if (Subtarget.has64BitSupport()) {
669       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
670       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
671       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
672       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
673       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
674       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
675       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
676       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
677     }
678 
679     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
680     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
681     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
682     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
683     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
684     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
685     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
686     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
687   }
688 
689   if (Subtarget.use64BitRegs()) {
690     // 64-bit PowerPC implementations can support i64 types directly
691     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
692     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
693     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
694     // 64-bit PowerPC wants to expand i128 shifts itself.
695     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
696     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
697     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
698   } else {
699     // 32-bit PowerPC wants to expand i64 shifts itself.
700     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
701     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
702     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
703   }
704 
705   // PowerPC has better expansions for funnel shifts than the generic
706   // TargetLowering::expandFunnelShift.
707   if (Subtarget.has64BitSupport()) {
708     setOperationAction(ISD::FSHL, MVT::i64, Custom);
709     setOperationAction(ISD::FSHR, MVT::i64, Custom);
710   }
711   setOperationAction(ISD::FSHL, MVT::i32, Custom);
712   setOperationAction(ISD::FSHR, MVT::i32, Custom);
713 
714   if (Subtarget.hasVSX()) {
715     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
716     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
717     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
718     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
719   }
720 
721   if (Subtarget.hasAltivec()) {
722     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
723       setOperationAction(ISD::SADDSAT, VT, Legal);
724       setOperationAction(ISD::SSUBSAT, VT, Legal);
725       setOperationAction(ISD::UADDSAT, VT, Legal);
726       setOperationAction(ISD::USUBSAT, VT, Legal);
727     }
728     // First set operation action for all vector types to expand. Then we
729     // will selectively turn on ones that can be effectively codegen'd.
730     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
731       // add/sub are legal for all supported vector VT's.
732       setOperationAction(ISD::ADD, VT, Legal);
733       setOperationAction(ISD::SUB, VT, Legal);
734 
735       // For v2i64, these are only valid with P8Vector. This is corrected after
736       // the loop.
737       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
738         setOperationAction(ISD::SMAX, VT, Legal);
739         setOperationAction(ISD::SMIN, VT, Legal);
740         setOperationAction(ISD::UMAX, VT, Legal);
741         setOperationAction(ISD::UMIN, VT, Legal);
742       }
743       else {
744         setOperationAction(ISD::SMAX, VT, Expand);
745         setOperationAction(ISD::SMIN, VT, Expand);
746         setOperationAction(ISD::UMAX, VT, Expand);
747         setOperationAction(ISD::UMIN, VT, Expand);
748       }
749 
750       if (Subtarget.hasVSX()) {
751         setOperationAction(ISD::FMAXNUM, VT, Legal);
752         setOperationAction(ISD::FMINNUM, VT, Legal);
753       }
754 
755       // Vector instructions introduced in P8
756       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
757         setOperationAction(ISD::CTPOP, VT, Legal);
758         setOperationAction(ISD::CTLZ, VT, Legal);
759       }
760       else {
761         setOperationAction(ISD::CTPOP, VT, Expand);
762         setOperationAction(ISD::CTLZ, VT, Expand);
763       }
764 
765       // Vector instructions introduced in P9
766       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
767         setOperationAction(ISD::CTTZ, VT, Legal);
768       else
769         setOperationAction(ISD::CTTZ, VT, Expand);
770 
771       // We promote all shuffles to v16i8.
772       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
773       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
774 
775       // We promote all non-typed operations to v4i32.
776       setOperationAction(ISD::AND   , VT, Promote);
777       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
778       setOperationAction(ISD::OR    , VT, Promote);
779       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
780       setOperationAction(ISD::XOR   , VT, Promote);
781       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
782       setOperationAction(ISD::LOAD  , VT, Promote);
783       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
784       setOperationAction(ISD::SELECT, VT, Promote);
785       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
786       setOperationAction(ISD::VSELECT, VT, Legal);
787       setOperationAction(ISD::SELECT_CC, VT, Promote);
788       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
789       setOperationAction(ISD::STORE, VT, Promote);
790       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
791 
792       // No other operations are legal.
793       setOperationAction(ISD::MUL , VT, Expand);
794       setOperationAction(ISD::SDIV, VT, Expand);
795       setOperationAction(ISD::SREM, VT, Expand);
796       setOperationAction(ISD::UDIV, VT, Expand);
797       setOperationAction(ISD::UREM, VT, Expand);
798       setOperationAction(ISD::FDIV, VT, Expand);
799       setOperationAction(ISD::FREM, VT, Expand);
800       setOperationAction(ISD::FNEG, VT, Expand);
801       setOperationAction(ISD::FSQRT, VT, Expand);
802       setOperationAction(ISD::FLOG, VT, Expand);
803       setOperationAction(ISD::FLOG10, VT, Expand);
804       setOperationAction(ISD::FLOG2, VT, Expand);
805       setOperationAction(ISD::FEXP, VT, Expand);
806       setOperationAction(ISD::FEXP2, VT, Expand);
807       setOperationAction(ISD::FSIN, VT, Expand);
808       setOperationAction(ISD::FCOS, VT, Expand);
809       setOperationAction(ISD::FABS, VT, Expand);
810       setOperationAction(ISD::FFLOOR, VT, Expand);
811       setOperationAction(ISD::FCEIL,  VT, Expand);
812       setOperationAction(ISD::FTRUNC, VT, Expand);
813       setOperationAction(ISD::FRINT,  VT, Expand);
814       setOperationAction(ISD::FNEARBYINT, VT, Expand);
815       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
816       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
817       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
818       setOperationAction(ISD::MULHU, VT, Expand);
819       setOperationAction(ISD::MULHS, VT, Expand);
820       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
821       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
822       setOperationAction(ISD::UDIVREM, VT, Expand);
823       setOperationAction(ISD::SDIVREM, VT, Expand);
824       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
825       setOperationAction(ISD::FPOW, VT, Expand);
826       setOperationAction(ISD::BSWAP, VT, Expand);
827       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
828       setOperationAction(ISD::ROTL, VT, Expand);
829       setOperationAction(ISD::ROTR, VT, Expand);
830 
831       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
832         setTruncStoreAction(VT, InnerVT, Expand);
833         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
834         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
835         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
836       }
837     }
838     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
839     if (!Subtarget.hasP8Vector()) {
840       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
841       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
842       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
843       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
844     }
845 
846     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
847     // with merges, splats, etc.
848     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
849 
850     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
851     // are cheap, so handle them before they get expanded to scalar.
852     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
853     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
854     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
855     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
856     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
857 
858     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
859     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
860     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
861     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
862     setOperationAction(ISD::SELECT, MVT::v4i32,
863                        Subtarget.useCRBits() ? Legal : Expand);
864     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
865     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
866     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
867     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
868     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
869     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
870     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
871     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
872     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
873     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
874     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
875     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
876     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
877 
878     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
879     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
880     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
881     if (Subtarget.hasAltivec())
882       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
883         setOperationAction(ISD::ROTL, VT, Legal);
884     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
885     if (Subtarget.hasP8Altivec())
886       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
887 
888     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
889     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
890     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
891     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
892 
893     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
894     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
895 
896     if (Subtarget.hasVSX()) {
897       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
898       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
899       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
900     }
901 
902     if (Subtarget.hasP8Altivec())
903       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
904     else
905       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
906 
907     if (Subtarget.isISA3_1()) {
908       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
909       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
910       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
911       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
912       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
913       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
914       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
915       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
916       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
917       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
918       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
919       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
920       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
921       setOperationAction(ISD::UREM, MVT::v1i128, Legal);
922       setOperationAction(ISD::SREM, MVT::v1i128, Legal);
923       setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
924       setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
925       setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
926     }
927 
928     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
929     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
930 
931     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
932     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
933 
934     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
935     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
936     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
937     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
938 
939     // Altivec does not contain unordered floating-point compare instructions
940     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
941     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
942     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
943     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
944 
945     if (Subtarget.hasVSX()) {
946       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
947       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
948       if (Subtarget.hasP8Vector()) {
949         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
950         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
951       }
952       if (Subtarget.hasDirectMove() && isPPC64) {
953         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
954         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
955         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
956         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
957         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
958         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
959         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
960         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
961       }
962       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
963 
964       // The nearbyint variants are not allowed to raise the inexact exception
965       // so we can only code-gen them with unsafe math.
966       if (TM.Options.UnsafeFPMath) {
967         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
968         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
969       }
970 
971       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
972       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
973       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
974       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
975       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
976       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
977       setOperationAction(ISD::FROUND, MVT::f64, Legal);
978       setOperationAction(ISD::FRINT, MVT::f64, Legal);
979 
980       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
981       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
982       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
983       setOperationAction(ISD::FROUND, MVT::f32, Legal);
984       setOperationAction(ISD::FRINT, MVT::f32, Legal);
985 
986       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
987       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
988 
989       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
990       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
991 
992       // Share the Altivec comparison restrictions.
993       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
994       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
995       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
996       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
997 
998       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
999       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
1000 
1001       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
1002 
1003       if (Subtarget.hasP8Vector())
1004         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
1005 
1006       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
1007 
1008       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
1009       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
1010       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
1011 
1012       if (Subtarget.hasP8Altivec()) {
1013         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1014         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
1015         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1016 
1017         // 128 bit shifts can be accomplished via 3 instructions for SHL and
1018         // SRL, but not for SRA because of the instructions available:
1019         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1020         // doing
1021         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
1022         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
1023         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1024 
1025         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
1026       }
1027       else {
1028         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
1029         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1030         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1031 
1032         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1033 
1034         // VSX v2i64 only supports non-arithmetic operations.
1035         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1036         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1037       }
1038 
1039       if (Subtarget.isISA3_1())
1040         setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1041       else
1042         setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1043 
1044       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1045       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1046       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1047       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1048 
1049       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
1050 
1051       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1052       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1053       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1054       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1055       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1056       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1057       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1058       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1059 
1060       // Custom handling for partial vectors of integers converted to
1061       // floating point. We already have optimal handling for v2i32 through
1062       // the DAG combine, so those aren't necessary.
1063       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1064       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1065       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1066       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1067       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1068       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1069       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1070       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1071       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1072       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1073       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1074       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1075       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1076       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1077       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1078       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1079 
1080       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1081       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1082       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1083       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1084       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1085       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1086 
1087       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1088       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1089 
1090       // Handle constrained floating-point operations of vector.
1091       // The predictor is `hasVSX` because altivec instruction has
1092       // no exception but VSX vector instruction has.
1093       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1094       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1095       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1096       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1097       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1098       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1099       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1100       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1101       setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
1102       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1103       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1104       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1105       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1106 
1107       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1108       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1109       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1110       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1111       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1112       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1113       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1114       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1115       setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
1116       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1117       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1118       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1119       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1120 
1121       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1122       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1123 
1124       for (MVT FPT : MVT::fp_valuetypes())
1125         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1126 
1127       // Expand the SELECT to SELECT_CC
1128       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1129 
1130       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1131       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1132 
1133       // No implementation for these ops for PowerPC.
1134       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1135       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1136       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1137       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1138       setOperationAction(ISD::FREM, MVT::f128, Expand);
1139     }
1140 
1141     if (Subtarget.hasP8Altivec()) {
1142       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1143       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1144     }
1145 
1146     if (Subtarget.hasP9Vector()) {
1147       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1148       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1149 
1150       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1151       // SRL, but not for SRA because of the instructions available:
1152       // VS{RL} and VS{RL}O.
1153       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1154       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1155       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1156 
1157       setOperationAction(ISD::FADD, MVT::f128, Legal);
1158       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1159       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1160       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1161       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1162 
1163       setOperationAction(ISD::FMA, MVT::f128, Legal);
1164       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1165       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1166       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1167       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1168       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1169       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1170 
1171       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1172       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1173       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1174       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1175       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1176       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1177 
1178       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1179       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1180       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1181 
1182       // Handle constrained floating-point operations of fp128
1183       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1184       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1185       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1186       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1187       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1188       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1189       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1190       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1191       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1192       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1193       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1194       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1195       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1196       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1197       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1198       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1199       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1200       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1201       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1202       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1203     } else if (Subtarget.hasVSX()) {
1204       setOperationAction(ISD::LOAD, MVT::f128, Promote);
1205       setOperationAction(ISD::STORE, MVT::f128, Promote);
1206 
1207       AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
1208       AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
1209 
1210       // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1211       // fp_to_uint and int_to_fp.
1212       setOperationAction(ISD::FADD, MVT::f128, LibCall);
1213       setOperationAction(ISD::FSUB, MVT::f128, LibCall);
1214 
1215       setOperationAction(ISD::FMUL, MVT::f128, Expand);
1216       setOperationAction(ISD::FDIV, MVT::f128, Expand);
1217       setOperationAction(ISD::FNEG, MVT::f128, Expand);
1218       setOperationAction(ISD::FABS, MVT::f128, Expand);
1219       setOperationAction(ISD::FSQRT, MVT::f128, Expand);
1220       setOperationAction(ISD::FMA, MVT::f128, Expand);
1221       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
1222 
1223       // Expand the fp_extend if the target type is fp128.
1224       setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand);
1225       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand);
1226 
1227       // Expand the fp_round if the source type is fp128.
1228       for (MVT VT : {MVT::f32, MVT::f64}) {
1229         setOperationAction(ISD::FP_ROUND, VT, Custom);
1230         setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom);
1231       }
1232 
1233       setOperationAction(ISD::SETCC, MVT::f128, Custom);
1234       setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
1235       setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
1236       setOperationAction(ISD::BR_CC, MVT::f128, Expand);
1237 
1238       // Lower following f128 select_cc pattern:
1239       // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
1240       setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
1241 
1242       // We need to handle f128 SELECT_CC with integer result type.
1243       setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1244       setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand);
1245     }
1246 
1247     if (Subtarget.hasP9Altivec()) {
1248       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1249       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1250 
1251       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1252       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1253       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1254       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1255       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1256       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1257       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1258     }
1259 
1260     if (Subtarget.isISA3_1())
1261       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1262   }
1263 
1264   if (Subtarget.pairedVectorMemops()) {
1265     addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1266     setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1267     setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1268   }
1269   if (Subtarget.hasMMA()) {
1270     addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1271     setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1272     setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1273     setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom);
1274   }
1275 
1276   if (Subtarget.has64BitSupport())
1277     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1278 
1279   if (Subtarget.isISA3_1())
1280     setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1281 
1282   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1283 
1284   if (!isPPC64) {
1285     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1286     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1287   }
1288 
1289   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics()) {
1290     setMaxAtomicSizeInBitsSupported(128);
1291     setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
1292     setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom);
1293     setOperationAction(ISD::INTRINSIC_VOID, MVT::i128, Custom);
1294   }
1295 
1296   setBooleanContents(ZeroOrOneBooleanContent);
1297 
1298   if (Subtarget.hasAltivec()) {
1299     // Altivec instructions set fields to all zeros or all ones.
1300     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1301   }
1302 
1303   if (!isPPC64) {
1304     // These libcalls are not available in 32-bit.
1305     setLibcallName(RTLIB::SHL_I128, nullptr);
1306     setLibcallName(RTLIB::SRL_I128, nullptr);
1307     setLibcallName(RTLIB::SRA_I128, nullptr);
1308     setLibcallName(RTLIB::MULO_I64, nullptr);
1309   }
1310 
1311   if (!isPPC64)
1312     setMaxAtomicSizeInBitsSupported(32);
1313 
1314   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1315 
1316   // We have target-specific dag combine patterns for the following nodes:
1317   setTargetDAGCombine(ISD::ADD);
1318   setTargetDAGCombine(ISD::SHL);
1319   setTargetDAGCombine(ISD::SRA);
1320   setTargetDAGCombine(ISD::SRL);
1321   setTargetDAGCombine(ISD::MUL);
1322   setTargetDAGCombine(ISD::FMA);
1323   setTargetDAGCombine(ISD::SINT_TO_FP);
1324   setTargetDAGCombine(ISD::BUILD_VECTOR);
1325   if (Subtarget.hasFPCVT())
1326     setTargetDAGCombine(ISD::UINT_TO_FP);
1327   setTargetDAGCombine(ISD::LOAD);
1328   setTargetDAGCombine(ISD::STORE);
1329   setTargetDAGCombine(ISD::BR_CC);
1330   if (Subtarget.useCRBits())
1331     setTargetDAGCombine(ISD::BRCOND);
1332   setTargetDAGCombine(ISD::BSWAP);
1333   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1334   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1335   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1336 
1337   setTargetDAGCombine(ISD::SIGN_EXTEND);
1338   setTargetDAGCombine(ISD::ZERO_EXTEND);
1339   setTargetDAGCombine(ISD::ANY_EXTEND);
1340 
1341   setTargetDAGCombine(ISD::TRUNCATE);
1342   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1343 
1344 
1345   if (Subtarget.useCRBits()) {
1346     setTargetDAGCombine(ISD::TRUNCATE);
1347     setTargetDAGCombine(ISD::SETCC);
1348     setTargetDAGCombine(ISD::SELECT_CC);
1349   }
1350 
1351   if (Subtarget.hasP9Altivec()) {
1352     setTargetDAGCombine(ISD::ABS);
1353     setTargetDAGCombine(ISD::VSELECT);
1354   }
1355 
1356   setLibcallName(RTLIB::LOG_F128, "logf128");
1357   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1358   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1359   setLibcallName(RTLIB::EXP_F128, "expf128");
1360   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1361   setLibcallName(RTLIB::SIN_F128, "sinf128");
1362   setLibcallName(RTLIB::COS_F128, "cosf128");
1363   setLibcallName(RTLIB::POW_F128, "powf128");
1364   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1365   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1366   setLibcallName(RTLIB::REM_F128, "fmodf128");
1367   setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1368   setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1369   setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1370   setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1371   setLibcallName(RTLIB::ROUND_F128, "roundf128");
1372   setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1373   setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1374   setLibcallName(RTLIB::RINT_F128, "rintf128");
1375   setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1376   setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1377   setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1378   setLibcallName(RTLIB::FMA_F128, "fmaf128");
1379 
1380   // With 32 condition bits, we don't need to sink (and duplicate) compares
1381   // aggressively in CodeGenPrep.
1382   if (Subtarget.useCRBits()) {
1383     setHasMultipleConditionRegisters();
1384     setJumpIsExpensive();
1385   }
1386 
1387   setMinFunctionAlignment(Align(4));
1388 
1389   switch (Subtarget.getCPUDirective()) {
1390   default: break;
1391   case PPC::DIR_970:
1392   case PPC::DIR_A2:
1393   case PPC::DIR_E500:
1394   case PPC::DIR_E500mc:
1395   case PPC::DIR_E5500:
1396   case PPC::DIR_PWR4:
1397   case PPC::DIR_PWR5:
1398   case PPC::DIR_PWR5X:
1399   case PPC::DIR_PWR6:
1400   case PPC::DIR_PWR6X:
1401   case PPC::DIR_PWR7:
1402   case PPC::DIR_PWR8:
1403   case PPC::DIR_PWR9:
1404   case PPC::DIR_PWR10:
1405   case PPC::DIR_PWR_FUTURE:
1406     setPrefLoopAlignment(Align(16));
1407     setPrefFunctionAlignment(Align(16));
1408     break;
1409   }
1410 
1411   if (Subtarget.enableMachineScheduler())
1412     setSchedulingPreference(Sched::Source);
1413   else
1414     setSchedulingPreference(Sched::Hybrid);
1415 
1416   computeRegisterProperties(STI.getRegisterInfo());
1417 
1418   // The Freescale cores do better with aggressive inlining of memcpy and
1419   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1420   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1421       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1422     MaxStoresPerMemset = 32;
1423     MaxStoresPerMemsetOptSize = 16;
1424     MaxStoresPerMemcpy = 32;
1425     MaxStoresPerMemcpyOptSize = 8;
1426     MaxStoresPerMemmove = 32;
1427     MaxStoresPerMemmoveOptSize = 8;
1428   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1429     // The A2 also benefits from (very) aggressive inlining of memcpy and
1430     // friends. The overhead of a the function call, even when warm, can be
1431     // over one hundred cycles.
1432     MaxStoresPerMemset = 128;
1433     MaxStoresPerMemcpy = 128;
1434     MaxStoresPerMemmove = 128;
1435     MaxLoadsPerMemcmp = 128;
1436   } else {
1437     MaxLoadsPerMemcmp = 8;
1438     MaxLoadsPerMemcmpOptSize = 4;
1439   }
1440 
1441   IsStrictFPEnabled = true;
1442 
1443   // Let the subtarget (CPU) decide if a predictable select is more expensive
1444   // than the corresponding branch. This information is used in CGP to decide
1445   // when to convert selects into branches.
1446   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1447 }
1448 
1449 // *********************************** NOTE ************************************
1450 // For selecting load and store instructions, the addressing modes are defined
1451 // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
1452 // patterns to match the load the store instructions.
1453 //
1454 // The TD definitions for the addressing modes correspond to their respective
1455 // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
1456 // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
1457 // address mode flags of a particular node. Afterwards, the computed address
1458 // flags are passed into getAddrModeForFlags() in order to retrieve the optimal
1459 // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
1460 // accordingly, based on the preferred addressing mode.
1461 //
1462 // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
1463 // MemOpFlags contains all the possible flags that can be used to compute the
1464 // optimal addressing mode for load and store instructions.
1465 // AddrMode contains all the possible load and store addressing modes available
1466 // on Power (such as DForm, DSForm, DQForm, XForm, etc.)
1467 //
1468 // When adding new load and store instructions, it is possible that new address
1469 // flags may need to be added into MemOpFlags, and a new addressing mode will
1470 // need to be added to AddrMode. An entry of the new addressing mode (consisting
1471 // of the minimal and main distinguishing address flags for the new load/store
1472 // instructions) will need to be added into initializeAddrModeMap() below.
1473 // Finally, when adding new addressing modes, the getAddrModeForFlags() will
1474 // need to be updated to account for selecting the optimal addressing mode.
1475 // *****************************************************************************
1476 /// Initialize the map that relates the different addressing modes of the load
1477 /// and store instructions to a set of flags. This ensures the load/store
1478 /// instruction is correctly matched during instruction selection.
1479 void PPCTargetLowering::initializeAddrModeMap() {
1480   AddrModesMap[PPC::AM_DForm] = {
1481       // LWZ, STW
1482       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt,
1483       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt,
1484       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1485       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1486       // LBZ, LHZ, STB, STH
1487       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1488       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1489       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1490       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1491       // LHA
1492       PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1493       PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1494       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1495       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1496       // LFS, LFD, STFS, STFD
1497       PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1498       PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1499       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1500       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1501   };
1502   AddrModesMap[PPC::AM_DSForm] = {
1503       // LWA
1504       PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt,
1505       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1506       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1507       // LD, STD
1508       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt,
1509       PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt,
1510       PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt,
1511       // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
1512       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1513       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1514       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1515   };
1516   AddrModesMap[PPC::AM_DQForm] = {
1517       // LXV, STXV
1518       PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1519       PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1520       PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1521   };
1522   AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 |
1523                                        PPC::MOF_SubtargetP10};
1524   // TODO: Add mapping for quadword load/store.
1525 }
1526 
1527 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1528 /// the desired ByVal argument alignment.
1529 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1530   if (MaxAlign == MaxMaxAlign)
1531     return;
1532   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1533     if (MaxMaxAlign >= 32 &&
1534         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1535       MaxAlign = Align(32);
1536     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1537              MaxAlign < 16)
1538       MaxAlign = Align(16);
1539   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1540     Align EltAlign;
1541     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1542     if (EltAlign > MaxAlign)
1543       MaxAlign = EltAlign;
1544   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1545     for (auto *EltTy : STy->elements()) {
1546       Align EltAlign;
1547       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1548       if (EltAlign > MaxAlign)
1549         MaxAlign = EltAlign;
1550       if (MaxAlign == MaxMaxAlign)
1551         break;
1552     }
1553   }
1554 }
1555 
1556 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1557 /// function arguments in the caller parameter area.
1558 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1559                                                   const DataLayout &DL) const {
1560   // 16byte and wider vectors are passed on 16byte boundary.
1561   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1562   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1563   if (Subtarget.hasAltivec())
1564     getMaxByValAlign(Ty, Alignment, Align(16));
1565   return Alignment.value();
1566 }
1567 
1568 bool PPCTargetLowering::useSoftFloat() const {
1569   return Subtarget.useSoftFloat();
1570 }
1571 
1572 bool PPCTargetLowering::hasSPE() const {
1573   return Subtarget.hasSPE();
1574 }
1575 
1576 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1577   return VT.isScalarInteger();
1578 }
1579 
1580 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1581   switch ((PPCISD::NodeType)Opcode) {
1582   case PPCISD::FIRST_NUMBER:    break;
1583   case PPCISD::FSEL:            return "PPCISD::FSEL";
1584   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1585   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1586   case PPCISD::FCFID:           return "PPCISD::FCFID";
1587   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1588   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1589   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1590   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1591   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1592   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1593   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1594   case PPCISD::FP_TO_UINT_IN_VSR:
1595                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1596   case PPCISD::FP_TO_SINT_IN_VSR:
1597                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1598   case PPCISD::FRE:             return "PPCISD::FRE";
1599   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1600   case PPCISD::FTSQRT:
1601     return "PPCISD::FTSQRT";
1602   case PPCISD::FSQRT:
1603     return "PPCISD::FSQRT";
1604   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1605   case PPCISD::VPERM:           return "PPCISD::VPERM";
1606   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1607   case PPCISD::XXSPLTI_SP_TO_DP:
1608     return "PPCISD::XXSPLTI_SP_TO_DP";
1609   case PPCISD::XXSPLTI32DX:
1610     return "PPCISD::XXSPLTI32DX";
1611   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1612   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1613   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1614   case PPCISD::CMPB:            return "PPCISD::CMPB";
1615   case PPCISD::Hi:              return "PPCISD::Hi";
1616   case PPCISD::Lo:              return "PPCISD::Lo";
1617   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1618   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1619   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1620   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1621   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1622   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1623   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1624   case PPCISD::SRL:             return "PPCISD::SRL";
1625   case PPCISD::SRA:             return "PPCISD::SRA";
1626   case PPCISD::SHL:             return "PPCISD::SHL";
1627   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1628   case PPCISD::CALL:            return "PPCISD::CALL";
1629   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1630   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1631   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1632   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1633   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1634   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1635   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1636   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1637   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1638   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1639   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1640   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1641   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1642   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1643   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1644   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1645     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1646   case PPCISD::ANDI_rec_1_EQ_BIT:
1647     return "PPCISD::ANDI_rec_1_EQ_BIT";
1648   case PPCISD::ANDI_rec_1_GT_BIT:
1649     return "PPCISD::ANDI_rec_1_GT_BIT";
1650   case PPCISD::VCMP:            return "PPCISD::VCMP";
1651   case PPCISD::VCMP_rec:        return "PPCISD::VCMP_rec";
1652   case PPCISD::LBRX:            return "PPCISD::LBRX";
1653   case PPCISD::STBRX:           return "PPCISD::STBRX";
1654   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1655   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1656   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1657   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1658   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1659   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1660   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1661   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1662   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1663   case PPCISD::ST_VSR_SCAL_INT:
1664                                 return "PPCISD::ST_VSR_SCAL_INT";
1665   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1666   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1667   case PPCISD::BDZ:             return "PPCISD::BDZ";
1668   case PPCISD::MFFS:            return "PPCISD::MFFS";
1669   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1670   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1671   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1672   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1673   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1674   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1675   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1676   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1677   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1678   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1679   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1680   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1681   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1682   case PPCISD::TLSGD_AIX:       return "PPCISD::TLSGD_AIX";
1683   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1684   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1685   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1686   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1687   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1688   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1689   case PPCISD::PADDI_DTPREL:
1690     return "PPCISD::PADDI_DTPREL";
1691   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1692   case PPCISD::SC:              return "PPCISD::SC";
1693   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1694   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1695   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1696   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1697   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1698   case PPCISD::VABSD:           return "PPCISD::VABSD";
1699   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1700   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1701   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1702   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1703   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1704   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1705   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1706   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1707     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1708   case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1709     return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1710   case PPCISD::ACC_BUILD:       return "PPCISD::ACC_BUILD";
1711   case PPCISD::PAIR_BUILD:      return "PPCISD::PAIR_BUILD";
1712   case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1713   case PPCISD::XXMFACC:         return "PPCISD::XXMFACC";
1714   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1715   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1716   case PPCISD::STRICT_FADDRTZ:
1717     return "PPCISD::STRICT_FADDRTZ";
1718   case PPCISD::STRICT_FCTIDZ:
1719     return "PPCISD::STRICT_FCTIDZ";
1720   case PPCISD::STRICT_FCTIWZ:
1721     return "PPCISD::STRICT_FCTIWZ";
1722   case PPCISD::STRICT_FCTIDUZ:
1723     return "PPCISD::STRICT_FCTIDUZ";
1724   case PPCISD::STRICT_FCTIWUZ:
1725     return "PPCISD::STRICT_FCTIWUZ";
1726   case PPCISD::STRICT_FCFID:
1727     return "PPCISD::STRICT_FCFID";
1728   case PPCISD::STRICT_FCFIDU:
1729     return "PPCISD::STRICT_FCFIDU";
1730   case PPCISD::STRICT_FCFIDS:
1731     return "PPCISD::STRICT_FCFIDS";
1732   case PPCISD::STRICT_FCFIDUS:
1733     return "PPCISD::STRICT_FCFIDUS";
1734   case PPCISD::LXVRZX:          return "PPCISD::LXVRZX";
1735   }
1736   return nullptr;
1737 }
1738 
1739 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1740                                           EVT VT) const {
1741   if (!VT.isVector())
1742     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1743 
1744   return VT.changeVectorElementTypeToInteger();
1745 }
1746 
1747 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1748   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1749   return true;
1750 }
1751 
1752 //===----------------------------------------------------------------------===//
1753 // Node matching predicates, for use by the tblgen matching code.
1754 //===----------------------------------------------------------------------===//
1755 
1756 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1757 static bool isFloatingPointZero(SDValue Op) {
1758   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1759     return CFP->getValueAPF().isZero();
1760   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1761     // Maybe this has already been legalized into the constant pool?
1762     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1763       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1764         return CFP->getValueAPF().isZero();
1765   }
1766   return false;
1767 }
1768 
1769 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1770 /// true if Op is undef or if it matches the specified value.
1771 static bool isConstantOrUndef(int Op, int Val) {
1772   return Op < 0 || Op == Val;
1773 }
1774 
1775 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1776 /// VPKUHUM instruction.
1777 /// The ShuffleKind distinguishes between big-endian operations with
1778 /// two different inputs (0), either-endian operations with two identical
1779 /// inputs (1), and little-endian operations with two different inputs (2).
1780 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1781 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1782                                SelectionDAG &DAG) {
1783   bool IsLE = DAG.getDataLayout().isLittleEndian();
1784   if (ShuffleKind == 0) {
1785     if (IsLE)
1786       return false;
1787     for (unsigned i = 0; i != 16; ++i)
1788       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1789         return false;
1790   } else if (ShuffleKind == 2) {
1791     if (!IsLE)
1792       return false;
1793     for (unsigned i = 0; i != 16; ++i)
1794       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1795         return false;
1796   } else if (ShuffleKind == 1) {
1797     unsigned j = IsLE ? 0 : 1;
1798     for (unsigned i = 0; i != 8; ++i)
1799       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1800           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1801         return false;
1802   }
1803   return true;
1804 }
1805 
1806 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1807 /// VPKUWUM instruction.
1808 /// The ShuffleKind distinguishes between big-endian operations with
1809 /// two different inputs (0), either-endian operations with two identical
1810 /// inputs (1), and little-endian operations with two different inputs (2).
1811 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1812 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1813                                SelectionDAG &DAG) {
1814   bool IsLE = DAG.getDataLayout().isLittleEndian();
1815   if (ShuffleKind == 0) {
1816     if (IsLE)
1817       return false;
1818     for (unsigned i = 0; i != 16; i += 2)
1819       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1820           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1821         return false;
1822   } else if (ShuffleKind == 2) {
1823     if (!IsLE)
1824       return false;
1825     for (unsigned i = 0; i != 16; i += 2)
1826       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1827           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1828         return false;
1829   } else if (ShuffleKind == 1) {
1830     unsigned j = IsLE ? 0 : 2;
1831     for (unsigned i = 0; i != 8; i += 2)
1832       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1833           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1834           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1835           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1836         return false;
1837   }
1838   return true;
1839 }
1840 
1841 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1842 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1843 /// current subtarget.
1844 ///
1845 /// The ShuffleKind distinguishes between big-endian operations with
1846 /// two different inputs (0), either-endian operations with two identical
1847 /// inputs (1), and little-endian operations with two different inputs (2).
1848 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1849 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1850                                SelectionDAG &DAG) {
1851   const PPCSubtarget& Subtarget =
1852       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1853   if (!Subtarget.hasP8Vector())
1854     return false;
1855 
1856   bool IsLE = DAG.getDataLayout().isLittleEndian();
1857   if (ShuffleKind == 0) {
1858     if (IsLE)
1859       return false;
1860     for (unsigned i = 0; i != 16; i += 4)
1861       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1862           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1863           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1864           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1865         return false;
1866   } else if (ShuffleKind == 2) {
1867     if (!IsLE)
1868       return false;
1869     for (unsigned i = 0; i != 16; i += 4)
1870       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1871           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1872           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1873           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1874         return false;
1875   } else if (ShuffleKind == 1) {
1876     unsigned j = IsLE ? 0 : 4;
1877     for (unsigned i = 0; i != 8; i += 4)
1878       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1879           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1880           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1881           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1882           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1883           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1884           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1885           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1886         return false;
1887   }
1888   return true;
1889 }
1890 
1891 /// isVMerge - Common function, used to match vmrg* shuffles.
1892 ///
1893 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1894                      unsigned LHSStart, unsigned RHSStart) {
1895   if (N->getValueType(0) != MVT::v16i8)
1896     return false;
1897   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1898          "Unsupported merge size!");
1899 
1900   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1901     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1902       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1903                              LHSStart+j+i*UnitSize) ||
1904           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1905                              RHSStart+j+i*UnitSize))
1906         return false;
1907     }
1908   return true;
1909 }
1910 
1911 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1912 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1913 /// The ShuffleKind distinguishes between big-endian merges with two
1914 /// different inputs (0), either-endian merges with two identical inputs (1),
1915 /// and little-endian merges with two different inputs (2).  For the latter,
1916 /// the input operands are swapped (see PPCInstrAltivec.td).
1917 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1918                              unsigned ShuffleKind, SelectionDAG &DAG) {
1919   if (DAG.getDataLayout().isLittleEndian()) {
1920     if (ShuffleKind == 1) // unary
1921       return isVMerge(N, UnitSize, 0, 0);
1922     else if (ShuffleKind == 2) // swapped
1923       return isVMerge(N, UnitSize, 0, 16);
1924     else
1925       return false;
1926   } else {
1927     if (ShuffleKind == 1) // unary
1928       return isVMerge(N, UnitSize, 8, 8);
1929     else if (ShuffleKind == 0) // normal
1930       return isVMerge(N, UnitSize, 8, 24);
1931     else
1932       return false;
1933   }
1934 }
1935 
1936 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1937 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1938 /// The ShuffleKind distinguishes between big-endian merges with two
1939 /// different inputs (0), either-endian merges with two identical inputs (1),
1940 /// and little-endian merges with two different inputs (2).  For the latter,
1941 /// the input operands are swapped (see PPCInstrAltivec.td).
1942 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1943                              unsigned ShuffleKind, SelectionDAG &DAG) {
1944   if (DAG.getDataLayout().isLittleEndian()) {
1945     if (ShuffleKind == 1) // unary
1946       return isVMerge(N, UnitSize, 8, 8);
1947     else if (ShuffleKind == 2) // swapped
1948       return isVMerge(N, UnitSize, 8, 24);
1949     else
1950       return false;
1951   } else {
1952     if (ShuffleKind == 1) // unary
1953       return isVMerge(N, UnitSize, 0, 0);
1954     else if (ShuffleKind == 0) // normal
1955       return isVMerge(N, UnitSize, 0, 16);
1956     else
1957       return false;
1958   }
1959 }
1960 
1961 /**
1962  * Common function used to match vmrgew and vmrgow shuffles
1963  *
1964  * The indexOffset determines whether to look for even or odd words in
1965  * the shuffle mask. This is based on the of the endianness of the target
1966  * machine.
1967  *   - Little Endian:
1968  *     - Use offset of 0 to check for odd elements
1969  *     - Use offset of 4 to check for even elements
1970  *   - Big Endian:
1971  *     - Use offset of 0 to check for even elements
1972  *     - Use offset of 4 to check for odd elements
1973  * A detailed description of the vector element ordering for little endian and
1974  * big endian can be found at
1975  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1976  * Targeting your applications - what little endian and big endian IBM XL C/C++
1977  * compiler differences mean to you
1978  *
1979  * The mask to the shuffle vector instruction specifies the indices of the
1980  * elements from the two input vectors to place in the result. The elements are
1981  * numbered in array-access order, starting with the first vector. These vectors
1982  * are always of type v16i8, thus each vector will contain 16 elements of size
1983  * 8. More info on the shuffle vector can be found in the
1984  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1985  * Language Reference.
1986  *
1987  * The RHSStartValue indicates whether the same input vectors are used (unary)
1988  * or two different input vectors are used, based on the following:
1989  *   - If the instruction uses the same vector for both inputs, the range of the
1990  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1991  *     be 0.
1992  *   - If the instruction has two different vectors then the range of the
1993  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1994  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1995  *     to 31 specify elements in the second vector).
1996  *
1997  * \param[in] N The shuffle vector SD Node to analyze
1998  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1999  * \param[in] RHSStartValue Specifies the starting index for the righthand input
2000  * vector to the shuffle_vector instruction
2001  * \return true iff this shuffle vector represents an even or odd word merge
2002  */
2003 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
2004                      unsigned RHSStartValue) {
2005   if (N->getValueType(0) != MVT::v16i8)
2006     return false;
2007 
2008   for (unsigned i = 0; i < 2; ++i)
2009     for (unsigned j = 0; j < 4; ++j)
2010       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
2011                              i*RHSStartValue+j+IndexOffset) ||
2012           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
2013                              i*RHSStartValue+j+IndexOffset+8))
2014         return false;
2015   return true;
2016 }
2017 
2018 /**
2019  * Determine if the specified shuffle mask is suitable for the vmrgew or
2020  * vmrgow instructions.
2021  *
2022  * \param[in] N The shuffle vector SD Node to analyze
2023  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
2024  * \param[in] ShuffleKind Identify the type of merge:
2025  *   - 0 = big-endian merge with two different inputs;
2026  *   - 1 = either-endian merge with two identical inputs;
2027  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
2028  *     little-endian merges).
2029  * \param[in] DAG The current SelectionDAG
2030  * \return true iff this shuffle mask
2031  */
2032 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
2033                               unsigned ShuffleKind, SelectionDAG &DAG) {
2034   if (DAG.getDataLayout().isLittleEndian()) {
2035     unsigned indexOffset = CheckEven ? 4 : 0;
2036     if (ShuffleKind == 1) // Unary
2037       return isVMerge(N, indexOffset, 0);
2038     else if (ShuffleKind == 2) // swapped
2039       return isVMerge(N, indexOffset, 16);
2040     else
2041       return false;
2042   }
2043   else {
2044     unsigned indexOffset = CheckEven ? 0 : 4;
2045     if (ShuffleKind == 1) // Unary
2046       return isVMerge(N, indexOffset, 0);
2047     else if (ShuffleKind == 0) // Normal
2048       return isVMerge(N, indexOffset, 16);
2049     else
2050       return false;
2051   }
2052   return false;
2053 }
2054 
2055 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
2056 /// amount, otherwise return -1.
2057 /// The ShuffleKind distinguishes between big-endian operations with two
2058 /// different inputs (0), either-endian operations with two identical inputs
2059 /// (1), and little-endian operations with two different inputs (2).  For the
2060 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
2061 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
2062                              SelectionDAG &DAG) {
2063   if (N->getValueType(0) != MVT::v16i8)
2064     return -1;
2065 
2066   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2067 
2068   // Find the first non-undef value in the shuffle mask.
2069   unsigned i;
2070   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
2071     /*search*/;
2072 
2073   if (i == 16) return -1;  // all undef.
2074 
2075   // Otherwise, check to see if the rest of the elements are consecutively
2076   // numbered from this value.
2077   unsigned ShiftAmt = SVOp->getMaskElt(i);
2078   if (ShiftAmt < i) return -1;
2079 
2080   ShiftAmt -= i;
2081   bool isLE = DAG.getDataLayout().isLittleEndian();
2082 
2083   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
2084     // Check the rest of the elements to see if they are consecutive.
2085     for (++i; i != 16; ++i)
2086       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2087         return -1;
2088   } else if (ShuffleKind == 1) {
2089     // Check the rest of the elements to see if they are consecutive.
2090     for (++i; i != 16; ++i)
2091       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
2092         return -1;
2093   } else
2094     return -1;
2095 
2096   if (isLE)
2097     ShiftAmt = 16 - ShiftAmt;
2098 
2099   return ShiftAmt;
2100 }
2101 
2102 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2103 /// specifies a splat of a single element that is suitable for input to
2104 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2105 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
2106   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
2107          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2108 
2109   // The consecutive indices need to specify an element, not part of two
2110   // different elements.  So abandon ship early if this isn't the case.
2111   if (N->getMaskElt(0) % EltSize != 0)
2112     return false;
2113 
2114   // This is a splat operation if each element of the permute is the same, and
2115   // if the value doesn't reference the second vector.
2116   unsigned ElementBase = N->getMaskElt(0);
2117 
2118   // FIXME: Handle UNDEF elements too!
2119   if (ElementBase >= 16)
2120     return false;
2121 
2122   // Check that the indices are consecutive, in the case of a multi-byte element
2123   // splatted with a v16i8 mask.
2124   for (unsigned i = 1; i != EltSize; ++i)
2125     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2126       return false;
2127 
2128   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2129     if (N->getMaskElt(i) < 0) continue;
2130     for (unsigned j = 0; j != EltSize; ++j)
2131       if (N->getMaskElt(i+j) != N->getMaskElt(j))
2132         return false;
2133   }
2134   return true;
2135 }
2136 
2137 /// Check that the mask is shuffling N byte elements. Within each N byte
2138 /// element of the mask, the indices could be either in increasing or
2139 /// decreasing order as long as they are consecutive.
2140 /// \param[in] N the shuffle vector SD Node to analyze
2141 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2142 /// Word/DoubleWord/QuadWord).
2143 /// \param[in] StepLen the delta indices number among the N byte element, if
2144 /// the mask is in increasing/decreasing order then it is 1/-1.
2145 /// \return true iff the mask is shuffling N byte elements.
2146 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2147                                    int StepLen) {
2148   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2149          "Unexpected element width.");
2150   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2151 
2152   unsigned NumOfElem = 16 / Width;
2153   unsigned MaskVal[16]; //  Width is never greater than 16
2154   for (unsigned i = 0; i < NumOfElem; ++i) {
2155     MaskVal[0] = N->getMaskElt(i * Width);
2156     if ((StepLen == 1) && (MaskVal[0] % Width)) {
2157       return false;
2158     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2159       return false;
2160     }
2161 
2162     for (unsigned int j = 1; j < Width; ++j) {
2163       MaskVal[j] = N->getMaskElt(i * Width + j);
2164       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2165         return false;
2166       }
2167     }
2168   }
2169 
2170   return true;
2171 }
2172 
2173 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2174                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2175   if (!isNByteElemShuffleMask(N, 4, 1))
2176     return false;
2177 
2178   // Now we look at mask elements 0,4,8,12
2179   unsigned M0 = N->getMaskElt(0) / 4;
2180   unsigned M1 = N->getMaskElt(4) / 4;
2181   unsigned M2 = N->getMaskElt(8) / 4;
2182   unsigned M3 = N->getMaskElt(12) / 4;
2183   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2184   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2185 
2186   // Below, let H and L be arbitrary elements of the shuffle mask
2187   // where H is in the range [4,7] and L is in the range [0,3].
2188   // H, 1, 2, 3 or L, 5, 6, 7
2189   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2190       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2191     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2192     InsertAtByte = IsLE ? 12 : 0;
2193     Swap = M0 < 4;
2194     return true;
2195   }
2196   // 0, H, 2, 3 or 4, L, 6, 7
2197   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2198       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2199     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2200     InsertAtByte = IsLE ? 8 : 4;
2201     Swap = M1 < 4;
2202     return true;
2203   }
2204   // 0, 1, H, 3 or 4, 5, L, 7
2205   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2206       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2207     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2208     InsertAtByte = IsLE ? 4 : 8;
2209     Swap = M2 < 4;
2210     return true;
2211   }
2212   // 0, 1, 2, H or 4, 5, 6, L
2213   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2214       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2215     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2216     InsertAtByte = IsLE ? 0 : 12;
2217     Swap = M3 < 4;
2218     return true;
2219   }
2220 
2221   // If both vector operands for the shuffle are the same vector, the mask will
2222   // contain only elements from the first one and the second one will be undef.
2223   if (N->getOperand(1).isUndef()) {
2224     ShiftElts = 0;
2225     Swap = true;
2226     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2227     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2228       InsertAtByte = IsLE ? 12 : 0;
2229       return true;
2230     }
2231     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2232       InsertAtByte = IsLE ? 8 : 4;
2233       return true;
2234     }
2235     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2236       InsertAtByte = IsLE ? 4 : 8;
2237       return true;
2238     }
2239     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2240       InsertAtByte = IsLE ? 0 : 12;
2241       return true;
2242     }
2243   }
2244 
2245   return false;
2246 }
2247 
2248 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2249                                bool &Swap, bool IsLE) {
2250   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2251   // Ensure each byte index of the word is consecutive.
2252   if (!isNByteElemShuffleMask(N, 4, 1))
2253     return false;
2254 
2255   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2256   unsigned M0 = N->getMaskElt(0) / 4;
2257   unsigned M1 = N->getMaskElt(4) / 4;
2258   unsigned M2 = N->getMaskElt(8) / 4;
2259   unsigned M3 = N->getMaskElt(12) / 4;
2260 
2261   // If both vector operands for the shuffle are the same vector, the mask will
2262   // contain only elements from the first one and the second one will be undef.
2263   if (N->getOperand(1).isUndef()) {
2264     assert(M0 < 4 && "Indexing into an undef vector?");
2265     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2266       return false;
2267 
2268     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2269     Swap = false;
2270     return true;
2271   }
2272 
2273   // Ensure each word index of the ShuffleVector Mask is consecutive.
2274   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2275     return false;
2276 
2277   if (IsLE) {
2278     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2279       // Input vectors don't need to be swapped if the leading element
2280       // of the result is one of the 3 left elements of the second vector
2281       // (or if there is no shift to be done at all).
2282       Swap = false;
2283       ShiftElts = (8 - M0) % 8;
2284     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2285       // Input vectors need to be swapped if the leading element
2286       // of the result is one of the 3 left elements of the first vector
2287       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2288       Swap = true;
2289       ShiftElts = (4 - M0) % 4;
2290     }
2291 
2292     return true;
2293   } else {                                          // BE
2294     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2295       // Input vectors don't need to be swapped if the leading element
2296       // of the result is one of the 4 elements of the first vector.
2297       Swap = false;
2298       ShiftElts = M0;
2299     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2300       // Input vectors need to be swapped if the leading element
2301       // of the result is one of the 4 elements of the right vector.
2302       Swap = true;
2303       ShiftElts = M0 - 4;
2304     }
2305 
2306     return true;
2307   }
2308 }
2309 
2310 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2311   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2312 
2313   if (!isNByteElemShuffleMask(N, Width, -1))
2314     return false;
2315 
2316   for (int i = 0; i < 16; i += Width)
2317     if (N->getMaskElt(i) != i + Width - 1)
2318       return false;
2319 
2320   return true;
2321 }
2322 
2323 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2324   return isXXBRShuffleMaskHelper(N, 2);
2325 }
2326 
2327 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2328   return isXXBRShuffleMaskHelper(N, 4);
2329 }
2330 
2331 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2332   return isXXBRShuffleMaskHelper(N, 8);
2333 }
2334 
2335 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2336   return isXXBRShuffleMaskHelper(N, 16);
2337 }
2338 
2339 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2340 /// if the inputs to the instruction should be swapped and set \p DM to the
2341 /// value for the immediate.
2342 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2343 /// AND element 0 of the result comes from the first input (LE) or second input
2344 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2345 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2346 /// mask.
2347 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2348                                bool &Swap, bool IsLE) {
2349   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2350 
2351   // Ensure each byte index of the double word is consecutive.
2352   if (!isNByteElemShuffleMask(N, 8, 1))
2353     return false;
2354 
2355   unsigned M0 = N->getMaskElt(0) / 8;
2356   unsigned M1 = N->getMaskElt(8) / 8;
2357   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2358 
2359   // If both vector operands for the shuffle are the same vector, the mask will
2360   // contain only elements from the first one and the second one will be undef.
2361   if (N->getOperand(1).isUndef()) {
2362     if ((M0 | M1) < 2) {
2363       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2364       Swap = false;
2365       return true;
2366     } else
2367       return false;
2368   }
2369 
2370   if (IsLE) {
2371     if (M0 > 1 && M1 < 2) {
2372       Swap = false;
2373     } else if (M0 < 2 && M1 > 1) {
2374       M0 = (M0 + 2) % 4;
2375       M1 = (M1 + 2) % 4;
2376       Swap = true;
2377     } else
2378       return false;
2379 
2380     // Note: if control flow comes here that means Swap is already set above
2381     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2382     return true;
2383   } else { // BE
2384     if (M0 < 2 && M1 > 1) {
2385       Swap = false;
2386     } else if (M0 > 1 && M1 < 2) {
2387       M0 = (M0 + 2) % 4;
2388       M1 = (M1 + 2) % 4;
2389       Swap = true;
2390     } else
2391       return false;
2392 
2393     // Note: if control flow comes here that means Swap is already set above
2394     DM = (M0 << 1) + (M1 & 1);
2395     return true;
2396   }
2397 }
2398 
2399 
2400 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2401 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2402 /// elements are counted from the left of the vector register).
2403 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2404                                          SelectionDAG &DAG) {
2405   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2406   assert(isSplatShuffleMask(SVOp, EltSize));
2407   if (DAG.getDataLayout().isLittleEndian())
2408     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2409   else
2410     return SVOp->getMaskElt(0) / EltSize;
2411 }
2412 
2413 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2414 /// by using a vspltis[bhw] instruction of the specified element size, return
2415 /// the constant being splatted.  The ByteSize field indicates the number of
2416 /// bytes of each element [124] -> [bhw].
2417 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2418   SDValue OpVal(nullptr, 0);
2419 
2420   // If ByteSize of the splat is bigger than the element size of the
2421   // build_vector, then we have a case where we are checking for a splat where
2422   // multiple elements of the buildvector are folded together into a single
2423   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2424   unsigned EltSize = 16/N->getNumOperands();
2425   if (EltSize < ByteSize) {
2426     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2427     SDValue UniquedVals[4];
2428     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2429 
2430     // See if all of the elements in the buildvector agree across.
2431     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2432       if (N->getOperand(i).isUndef()) continue;
2433       // If the element isn't a constant, bail fully out.
2434       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2435 
2436       if (!UniquedVals[i&(Multiple-1)].getNode())
2437         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2438       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2439         return SDValue();  // no match.
2440     }
2441 
2442     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2443     // either constant or undef values that are identical for each chunk.  See
2444     // if these chunks can form into a larger vspltis*.
2445 
2446     // Check to see if all of the leading entries are either 0 or -1.  If
2447     // neither, then this won't fit into the immediate field.
2448     bool LeadingZero = true;
2449     bool LeadingOnes = true;
2450     for (unsigned i = 0; i != Multiple-1; ++i) {
2451       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2452 
2453       LeadingZero &= isNullConstant(UniquedVals[i]);
2454       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2455     }
2456     // Finally, check the least significant entry.
2457     if (LeadingZero) {
2458       if (!UniquedVals[Multiple-1].getNode())
2459         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2460       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2461       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2462         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2463     }
2464     if (LeadingOnes) {
2465       if (!UniquedVals[Multiple-1].getNode())
2466         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2467       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2468       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2469         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2470     }
2471 
2472     return SDValue();
2473   }
2474 
2475   // Check to see if this buildvec has a single non-undef value in its elements.
2476   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2477     if (N->getOperand(i).isUndef()) continue;
2478     if (!OpVal.getNode())
2479       OpVal = N->getOperand(i);
2480     else if (OpVal != N->getOperand(i))
2481       return SDValue();
2482   }
2483 
2484   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2485 
2486   unsigned ValSizeInBytes = EltSize;
2487   uint64_t Value = 0;
2488   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2489     Value = CN->getZExtValue();
2490   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2491     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2492     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2493   }
2494 
2495   // If the splat value is larger than the element value, then we can never do
2496   // this splat.  The only case that we could fit the replicated bits into our
2497   // immediate field for would be zero, and we prefer to use vxor for it.
2498   if (ValSizeInBytes < ByteSize) return SDValue();
2499 
2500   // If the element value is larger than the splat value, check if it consists
2501   // of a repeated bit pattern of size ByteSize.
2502   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2503     return SDValue();
2504 
2505   // Properly sign extend the value.
2506   int MaskVal = SignExtend32(Value, ByteSize * 8);
2507 
2508   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2509   if (MaskVal == 0) return SDValue();
2510 
2511   // Finally, if this value fits in a 5 bit sext field, return it
2512   if (SignExtend32<5>(MaskVal) == MaskVal)
2513     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2514   return SDValue();
2515 }
2516 
2517 //===----------------------------------------------------------------------===//
2518 //  Addressing Mode Selection
2519 //===----------------------------------------------------------------------===//
2520 
2521 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2522 /// or 64-bit immediate, and if the value can be accurately represented as a
2523 /// sign extension from a 16-bit value.  If so, this returns true and the
2524 /// immediate.
2525 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2526   if (!isa<ConstantSDNode>(N))
2527     return false;
2528 
2529   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2530   if (N->getValueType(0) == MVT::i32)
2531     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2532   else
2533     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2534 }
2535 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2536   return isIntS16Immediate(Op.getNode(), Imm);
2537 }
2538 
2539 /// Used when computing address flags for selecting loads and stores.
2540 /// If we have an OR, check if the LHS and RHS are provably disjoint.
2541 /// An OR of two provably disjoint values is equivalent to an ADD.
2542 /// Most PPC load/store instructions compute the effective address as a sum,
2543 /// so doing this conversion is useful.
2544 static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
2545   if (N.getOpcode() != ISD::OR)
2546     return false;
2547   KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2548   if (!LHSKnown.Zero.getBoolValue())
2549     return false;
2550   KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2551   return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
2552 }
2553 
2554 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2555 /// be represented as an indexed [r+r] operation.
2556 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2557                                                SDValue &Index,
2558                                                SelectionDAG &DAG) const {
2559   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2560       UI != E; ++UI) {
2561     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2562       if (Memop->getMemoryVT() == MVT::f64) {
2563           Base = N.getOperand(0);
2564           Index = N.getOperand(1);
2565           return true;
2566       }
2567     }
2568   }
2569   return false;
2570 }
2571 
2572 /// isIntS34Immediate - This method tests if value of node given can be
2573 /// accurately represented as a sign extension from a 34-bit value.  If so,
2574 /// this returns true and the immediate.
2575 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2576   if (!isa<ConstantSDNode>(N))
2577     return false;
2578 
2579   Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2580   return isInt<34>(Imm);
2581 }
2582 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2583   return isIntS34Immediate(Op.getNode(), Imm);
2584 }
2585 
2586 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2587 /// can be represented as an indexed [r+r] operation.  Returns false if it
2588 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2589 /// non-zero and N can be represented by a base register plus a signed 16-bit
2590 /// displacement, make a more precise judgement by checking (displacement % \p
2591 /// EncodingAlignment).
2592 bool PPCTargetLowering::SelectAddressRegReg(
2593     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2594     MaybeAlign EncodingAlignment) const {
2595   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2596   // a [pc+imm].
2597   if (SelectAddressPCRel(N, Base))
2598     return false;
2599 
2600   int16_t Imm = 0;
2601   if (N.getOpcode() == ISD::ADD) {
2602     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2603     // SPE load/store can only handle 8-bit offsets.
2604     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2605         return true;
2606     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2607         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2608       return false; // r+i
2609     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2610       return false;    // r+i
2611 
2612     Base = N.getOperand(0);
2613     Index = N.getOperand(1);
2614     return true;
2615   } else if (N.getOpcode() == ISD::OR) {
2616     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2617         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2618       return false; // r+i can fold it if we can.
2619 
2620     // If this is an or of disjoint bitfields, we can codegen this as an add
2621     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2622     // disjoint.
2623     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2624 
2625     if (LHSKnown.Zero.getBoolValue()) {
2626       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2627       // If all of the bits are known zero on the LHS or RHS, the add won't
2628       // carry.
2629       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2630         Base = N.getOperand(0);
2631         Index = N.getOperand(1);
2632         return true;
2633       }
2634     }
2635   }
2636 
2637   return false;
2638 }
2639 
2640 // If we happen to be doing an i64 load or store into a stack slot that has
2641 // less than a 4-byte alignment, then the frame-index elimination may need to
2642 // use an indexed load or store instruction (because the offset may not be a
2643 // multiple of 4). The extra register needed to hold the offset comes from the
2644 // register scavenger, and it is possible that the scavenger will need to use
2645 // an emergency spill slot. As a result, we need to make sure that a spill slot
2646 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2647 // stack slot.
2648 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2649   // FIXME: This does not handle the LWA case.
2650   if (VT != MVT::i64)
2651     return;
2652 
2653   // NOTE: We'll exclude negative FIs here, which come from argument
2654   // lowering, because there are no known test cases triggering this problem
2655   // using packed structures (or similar). We can remove this exclusion if
2656   // we find such a test case. The reason why this is so test-case driven is
2657   // because this entire 'fixup' is only to prevent crashes (from the
2658   // register scavenger) on not-really-valid inputs. For example, if we have:
2659   //   %a = alloca i1
2660   //   %b = bitcast i1* %a to i64*
2661   //   store i64* a, i64 b
2662   // then the store should really be marked as 'align 1', but is not. If it
2663   // were marked as 'align 1' then the indexed form would have been
2664   // instruction-selected initially, and the problem this 'fixup' is preventing
2665   // won't happen regardless.
2666   if (FrameIdx < 0)
2667     return;
2668 
2669   MachineFunction &MF = DAG.getMachineFunction();
2670   MachineFrameInfo &MFI = MF.getFrameInfo();
2671 
2672   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2673     return;
2674 
2675   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2676   FuncInfo->setHasNonRISpills();
2677 }
2678 
2679 /// Returns true if the address N can be represented by a base register plus
2680 /// a signed 16-bit displacement [r+imm], and if it is not better
2681 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2682 /// displacements that are multiples of that value.
2683 bool PPCTargetLowering::SelectAddressRegImm(
2684     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2685     MaybeAlign EncodingAlignment) const {
2686   // FIXME dl should come from parent load or store, not from address
2687   SDLoc dl(N);
2688 
2689   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2690   // a [pc+imm].
2691   if (SelectAddressPCRel(N, Base))
2692     return false;
2693 
2694   // If this can be more profitably realized as r+r, fail.
2695   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2696     return false;
2697 
2698   if (N.getOpcode() == ISD::ADD) {
2699     int16_t imm = 0;
2700     if (isIntS16Immediate(N.getOperand(1), imm) &&
2701         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2702       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2703       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2704         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2705         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2706       } else {
2707         Base = N.getOperand(0);
2708       }
2709       return true; // [r+i]
2710     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2711       // Match LOAD (ADD (X, Lo(G))).
2712       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2713              && "Cannot handle constant offsets yet!");
2714       Disp = N.getOperand(1).getOperand(0);  // The global address.
2715       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2716              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2717              Disp.getOpcode() == ISD::TargetConstantPool ||
2718              Disp.getOpcode() == ISD::TargetJumpTable);
2719       Base = N.getOperand(0);
2720       return true;  // [&g+r]
2721     }
2722   } else if (N.getOpcode() == ISD::OR) {
2723     int16_t imm = 0;
2724     if (isIntS16Immediate(N.getOperand(1), imm) &&
2725         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2726       // If this is an or of disjoint bitfields, we can codegen this as an add
2727       // (for better address arithmetic) if the LHS and RHS of the OR are
2728       // provably disjoint.
2729       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2730 
2731       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2732         // If all of the bits are known zero on the LHS or RHS, the add won't
2733         // carry.
2734         if (FrameIndexSDNode *FI =
2735               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2736           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2737           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2738         } else {
2739           Base = N.getOperand(0);
2740         }
2741         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2742         return true;
2743       }
2744     }
2745   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2746     // Loading from a constant address.
2747 
2748     // If this address fits entirely in a 16-bit sext immediate field, codegen
2749     // this as "d, 0"
2750     int16_t Imm;
2751     if (isIntS16Immediate(CN, Imm) &&
2752         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2753       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2754       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2755                              CN->getValueType(0));
2756       return true;
2757     }
2758 
2759     // Handle 32-bit sext immediates with LIS + addr mode.
2760     if ((CN->getValueType(0) == MVT::i32 ||
2761          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2762         (!EncodingAlignment ||
2763          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2764       int Addr = (int)CN->getZExtValue();
2765 
2766       // Otherwise, break this down into an LIS + disp.
2767       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2768 
2769       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2770                                    MVT::i32);
2771       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2772       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2773       return true;
2774     }
2775   }
2776 
2777   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2778   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2779     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2780     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2781   } else
2782     Base = N;
2783   return true;      // [r+0]
2784 }
2785 
2786 /// Similar to the 16-bit case but for instructions that take a 34-bit
2787 /// displacement field (prefixed loads/stores).
2788 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp,
2789                                               SDValue &Base,
2790                                               SelectionDAG &DAG) const {
2791   // Only on 64-bit targets.
2792   if (N.getValueType() != MVT::i64)
2793     return false;
2794 
2795   SDLoc dl(N);
2796   int64_t Imm = 0;
2797 
2798   if (N.getOpcode() == ISD::ADD) {
2799     if (!isIntS34Immediate(N.getOperand(1), Imm))
2800       return false;
2801     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2802     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2803       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2804     else
2805       Base = N.getOperand(0);
2806     return true;
2807   }
2808 
2809   if (N.getOpcode() == ISD::OR) {
2810     if (!isIntS34Immediate(N.getOperand(1), Imm))
2811       return false;
2812     // If this is an or of disjoint bitfields, we can codegen this as an add
2813     // (for better address arithmetic) if the LHS and RHS of the OR are
2814     // provably disjoint.
2815     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2816     if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2817       return false;
2818     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2819       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2820     else
2821       Base = N.getOperand(0);
2822     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2823     return true;
2824   }
2825 
2826   if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2827     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2828     Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2829     return true;
2830   }
2831 
2832   return false;
2833 }
2834 
2835 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2836 /// represented as an indexed [r+r] operation.
2837 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2838                                                 SDValue &Index,
2839                                                 SelectionDAG &DAG) const {
2840   // Check to see if we can easily represent this as an [r+r] address.  This
2841   // will fail if it thinks that the address is more profitably represented as
2842   // reg+imm, e.g. where imm = 0.
2843   if (SelectAddressRegReg(N, Base, Index, DAG))
2844     return true;
2845 
2846   // If the address is the result of an add, we will utilize the fact that the
2847   // address calculation includes an implicit add.  However, we can reduce
2848   // register pressure if we do not materialize a constant just for use as the
2849   // index register.  We only get rid of the add if it is not an add of a
2850   // value and a 16-bit signed constant and both have a single use.
2851   int16_t imm = 0;
2852   if (N.getOpcode() == ISD::ADD &&
2853       (!isIntS16Immediate(N.getOperand(1), imm) ||
2854        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2855     Base = N.getOperand(0);
2856     Index = N.getOperand(1);
2857     return true;
2858   }
2859 
2860   // Otherwise, do it the hard way, using R0 as the base register.
2861   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2862                          N.getValueType());
2863   Index = N;
2864   return true;
2865 }
2866 
2867 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2868   Ty *PCRelCand = dyn_cast<Ty>(N);
2869   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2870 }
2871 
2872 /// Returns true if this address is a PC Relative address.
2873 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2874 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2875 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2876   // This is a materialize PC Relative node. Always select this as PC Relative.
2877   Base = N;
2878   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2879     return true;
2880   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2881       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2882       isValidPCRelNode<JumpTableSDNode>(N) ||
2883       isValidPCRelNode<BlockAddressSDNode>(N))
2884     return true;
2885   return false;
2886 }
2887 
2888 /// Returns true if we should use a direct load into vector instruction
2889 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2890 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2891 
2892   // If there are any other uses other than scalar to vector, then we should
2893   // keep it as a scalar load -> direct move pattern to prevent multiple
2894   // loads.
2895   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2896   if (!LD)
2897     return false;
2898 
2899   EVT MemVT = LD->getMemoryVT();
2900   if (!MemVT.isSimple())
2901     return false;
2902   switch(MemVT.getSimpleVT().SimpleTy) {
2903   case MVT::i64:
2904     break;
2905   case MVT::i32:
2906     if (!ST.hasP8Vector())
2907       return false;
2908     break;
2909   case MVT::i16:
2910   case MVT::i8:
2911     if (!ST.hasP9Vector())
2912       return false;
2913     break;
2914   default:
2915     return false;
2916   }
2917 
2918   SDValue LoadedVal(N, 0);
2919   if (!LoadedVal.hasOneUse())
2920     return false;
2921 
2922   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2923        UI != UE; ++UI)
2924     if (UI.getUse().get().getResNo() == 0 &&
2925         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2926         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2927       return false;
2928 
2929   return true;
2930 }
2931 
2932 /// getPreIndexedAddressParts - returns true by value, base pointer and
2933 /// offset pointer and addressing mode by reference if the node's address
2934 /// can be legally represented as pre-indexed load / store address.
2935 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2936                                                   SDValue &Offset,
2937                                                   ISD::MemIndexedMode &AM,
2938                                                   SelectionDAG &DAG) const {
2939   if (DisablePPCPreinc) return false;
2940 
2941   bool isLoad = true;
2942   SDValue Ptr;
2943   EVT VT;
2944   unsigned Alignment;
2945   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2946     Ptr = LD->getBasePtr();
2947     VT = LD->getMemoryVT();
2948     Alignment = LD->getAlignment();
2949   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2950     Ptr = ST->getBasePtr();
2951     VT  = ST->getMemoryVT();
2952     Alignment = ST->getAlignment();
2953     isLoad = false;
2954   } else
2955     return false;
2956 
2957   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2958   // instructions because we can fold these into a more efficient instruction
2959   // instead, (such as LXSD).
2960   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2961     return false;
2962   }
2963 
2964   // PowerPC doesn't have preinc load/store instructions for vectors
2965   if (VT.isVector())
2966     return false;
2967 
2968   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2969     // Common code will reject creating a pre-inc form if the base pointer
2970     // is a frame index, or if N is a store and the base pointer is either
2971     // the same as or a predecessor of the value being stored.  Check for
2972     // those situations here, and try with swapped Base/Offset instead.
2973     bool Swap = false;
2974 
2975     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2976       Swap = true;
2977     else if (!isLoad) {
2978       SDValue Val = cast<StoreSDNode>(N)->getValue();
2979       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2980         Swap = true;
2981     }
2982 
2983     if (Swap)
2984       std::swap(Base, Offset);
2985 
2986     AM = ISD::PRE_INC;
2987     return true;
2988   }
2989 
2990   // LDU/STU can only handle immediates that are a multiple of 4.
2991   if (VT != MVT::i64) {
2992     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2993       return false;
2994   } else {
2995     // LDU/STU need an address with at least 4-byte alignment.
2996     if (Alignment < 4)
2997       return false;
2998 
2999     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
3000       return false;
3001   }
3002 
3003   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3004     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
3005     // sext i32 to i64 when addr mode is r+i.
3006     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
3007         LD->getExtensionType() == ISD::SEXTLOAD &&
3008         isa<ConstantSDNode>(Offset))
3009       return false;
3010   }
3011 
3012   AM = ISD::PRE_INC;
3013   return true;
3014 }
3015 
3016 //===----------------------------------------------------------------------===//
3017 //  LowerOperation implementation
3018 //===----------------------------------------------------------------------===//
3019 
3020 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
3021 /// and LoOpFlags to the target MO flags.
3022 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
3023                                unsigned &HiOpFlags, unsigned &LoOpFlags,
3024                                const GlobalValue *GV = nullptr) {
3025   HiOpFlags = PPCII::MO_HA;
3026   LoOpFlags = PPCII::MO_LO;
3027 
3028   // Don't use the pic base if not in PIC relocation model.
3029   if (IsPIC) {
3030     HiOpFlags |= PPCII::MO_PIC_FLAG;
3031     LoOpFlags |= PPCII::MO_PIC_FLAG;
3032   }
3033 }
3034 
3035 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
3036                              SelectionDAG &DAG) {
3037   SDLoc DL(HiPart);
3038   EVT PtrVT = HiPart.getValueType();
3039   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
3040 
3041   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
3042   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
3043 
3044   // With PIC, the first instruction is actually "GR+hi(&G)".
3045   if (isPIC)
3046     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
3047                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
3048 
3049   // Generate non-pic code that has direct accesses to the constant pool.
3050   // The address of the global is just (hi(&g)+lo(&g)).
3051   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
3052 }
3053 
3054 static void setUsesTOCBasePtr(MachineFunction &MF) {
3055   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3056   FuncInfo->setUsesTOCBasePtr();
3057 }
3058 
3059 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
3060   setUsesTOCBasePtr(DAG.getMachineFunction());
3061 }
3062 
3063 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
3064                                        SDValue GA) const {
3065   const bool Is64Bit = Subtarget.isPPC64();
3066   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
3067   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
3068                         : Subtarget.isAIXABI()
3069                               ? DAG.getRegister(PPC::R2, VT)
3070                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
3071   SDValue Ops[] = { GA, Reg };
3072   return DAG.getMemIntrinsicNode(
3073       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
3074       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
3075       MachineMemOperand::MOLoad);
3076 }
3077 
3078 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
3079                                              SelectionDAG &DAG) const {
3080   EVT PtrVT = Op.getValueType();
3081   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3082   const Constant *C = CP->getConstVal();
3083 
3084   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3085   // The actual address of the GlobalValue is stored in the TOC.
3086   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3087     if (Subtarget.isUsingPCRelativeCalls()) {
3088       SDLoc DL(CP);
3089       EVT Ty = getPointerTy(DAG.getDataLayout());
3090       SDValue ConstPool = DAG.getTargetConstantPool(
3091           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
3092       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
3093     }
3094     setUsesTOCBasePtr(DAG);
3095     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
3096     return getTOCEntry(DAG, SDLoc(CP), GA);
3097   }
3098 
3099   unsigned MOHiFlag, MOLoFlag;
3100   bool IsPIC = isPositionIndependent();
3101   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3102 
3103   if (IsPIC && Subtarget.isSVR4ABI()) {
3104     SDValue GA =
3105         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
3106     return getTOCEntry(DAG, SDLoc(CP), GA);
3107   }
3108 
3109   SDValue CPIHi =
3110       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3111   SDValue CPILo =
3112       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3113   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3114 }
3115 
3116 // For 64-bit PowerPC, prefer the more compact relative encodings.
3117 // This trades 32 bits per jump table entry for one or two instructions
3118 // on the jump site.
3119 unsigned PPCTargetLowering::getJumpTableEncoding() const {
3120   if (isJumpTableRelative())
3121     return MachineJumpTableInfo::EK_LabelDifference32;
3122 
3123   return TargetLowering::getJumpTableEncoding();
3124 }
3125 
3126 bool PPCTargetLowering::isJumpTableRelative() const {
3127   if (UseAbsoluteJumpTables)
3128     return false;
3129   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3130     return true;
3131   return TargetLowering::isJumpTableRelative();
3132 }
3133 
3134 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
3135                                                     SelectionDAG &DAG) const {
3136   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3137     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3138 
3139   switch (getTargetMachine().getCodeModel()) {
3140   case CodeModel::Small:
3141   case CodeModel::Medium:
3142     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3143   default:
3144     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3145                        getPointerTy(DAG.getDataLayout()));
3146   }
3147 }
3148 
3149 const MCExpr *
3150 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
3151                                                 unsigned JTI,
3152                                                 MCContext &Ctx) const {
3153   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3154     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3155 
3156   switch (getTargetMachine().getCodeModel()) {
3157   case CodeModel::Small:
3158   case CodeModel::Medium:
3159     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3160   default:
3161     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3162   }
3163 }
3164 
3165 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3166   EVT PtrVT = Op.getValueType();
3167   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3168 
3169   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3170   if (Subtarget.isUsingPCRelativeCalls()) {
3171     SDLoc DL(JT);
3172     EVT Ty = getPointerTy(DAG.getDataLayout());
3173     SDValue GA =
3174         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3175     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3176     return MatAddr;
3177   }
3178 
3179   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3180   // The actual address of the GlobalValue is stored in the TOC.
3181   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3182     setUsesTOCBasePtr(DAG);
3183     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3184     return getTOCEntry(DAG, SDLoc(JT), GA);
3185   }
3186 
3187   unsigned MOHiFlag, MOLoFlag;
3188   bool IsPIC = isPositionIndependent();
3189   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3190 
3191   if (IsPIC && Subtarget.isSVR4ABI()) {
3192     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3193                                         PPCII::MO_PIC_FLAG);
3194     return getTOCEntry(DAG, SDLoc(GA), GA);
3195   }
3196 
3197   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3198   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3199   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3200 }
3201 
3202 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3203                                              SelectionDAG &DAG) const {
3204   EVT PtrVT = Op.getValueType();
3205   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3206   const BlockAddress *BA = BASDN->getBlockAddress();
3207 
3208   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3209   if (Subtarget.isUsingPCRelativeCalls()) {
3210     SDLoc DL(BASDN);
3211     EVT Ty = getPointerTy(DAG.getDataLayout());
3212     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3213                                            PPCII::MO_PCREL_FLAG);
3214     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3215     return MatAddr;
3216   }
3217 
3218   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3219   // The actual BlockAddress is stored in the TOC.
3220   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3221     setUsesTOCBasePtr(DAG);
3222     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3223     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3224   }
3225 
3226   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3227   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3228     return getTOCEntry(
3229         DAG, SDLoc(BASDN),
3230         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3231 
3232   unsigned MOHiFlag, MOLoFlag;
3233   bool IsPIC = isPositionIndependent();
3234   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3235   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3236   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3237   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3238 }
3239 
3240 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3241                                               SelectionDAG &DAG) const {
3242   if (Subtarget.isAIXABI())
3243     return LowerGlobalTLSAddressAIX(Op, DAG);
3244 
3245   return LowerGlobalTLSAddressLinux(Op, DAG);
3246 }
3247 
3248 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3249                                                     SelectionDAG &DAG) const {
3250   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3251 
3252   if (DAG.getTarget().useEmulatedTLS())
3253     report_fatal_error("Emulated TLS is not yet supported on AIX");
3254 
3255   SDLoc dl(GA);
3256   const GlobalValue *GV = GA->getGlobal();
3257   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3258 
3259   // The general-dynamic model is the only access model supported for now, so
3260   // all the GlobalTLSAddress nodes are lowered with this model.
3261   // We need to generate two TOC entries, one for the variable offset, one for
3262   // the region handle. The global address for the TOC entry of the region
3263   // handle is created with the MO_TLSGDM_FLAG flag and the global address
3264   // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG.
3265   SDValue VariableOffsetTGA =
3266       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3267   SDValue RegionHandleTGA =
3268       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG);
3269   SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3270   SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3271   return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3272                      RegionHandle);
3273 }
3274 
3275 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3276                                                       SelectionDAG &DAG) const {
3277   // FIXME: TLS addresses currently use medium model code sequences,
3278   // which is the most useful form.  Eventually support for small and
3279   // large models could be added if users need it, at the cost of
3280   // additional complexity.
3281   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3282   if (DAG.getTarget().useEmulatedTLS())
3283     return LowerToTLSEmulatedModel(GA, DAG);
3284 
3285   SDLoc dl(GA);
3286   const GlobalValue *GV = GA->getGlobal();
3287   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3288   bool is64bit = Subtarget.isPPC64();
3289   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3290   PICLevel::Level picLevel = M->getPICLevel();
3291 
3292   const TargetMachine &TM = getTargetMachine();
3293   TLSModel::Model Model = TM.getTLSModel(GV);
3294 
3295   if (Model == TLSModel::LocalExec) {
3296     if (Subtarget.isUsingPCRelativeCalls()) {
3297       SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3298       SDValue TGA = DAG.getTargetGlobalAddress(
3299           GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3300       SDValue MatAddr =
3301           DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3302       return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3303     }
3304 
3305     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3306                                                PPCII::MO_TPREL_HA);
3307     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3308                                                PPCII::MO_TPREL_LO);
3309     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3310                              : DAG.getRegister(PPC::R2, MVT::i32);
3311 
3312     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3313     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3314   }
3315 
3316   if (Model == TLSModel::InitialExec) {
3317     bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3318     SDValue TGA = DAG.getTargetGlobalAddress(
3319         GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3320     SDValue TGATLS = DAG.getTargetGlobalAddress(
3321         GV, dl, PtrVT, 0,
3322         IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3323     SDValue TPOffset;
3324     if (IsPCRel) {
3325       SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3326       TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3327                              MachinePointerInfo());
3328     } else {
3329       SDValue GOTPtr;
3330       if (is64bit) {
3331         setUsesTOCBasePtr(DAG);
3332         SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3333         GOTPtr =
3334             DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3335       } else {
3336         if (!TM.isPositionIndependent())
3337           GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3338         else if (picLevel == PICLevel::SmallPIC)
3339           GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3340         else
3341           GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3342       }
3343       TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3344     }
3345     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3346   }
3347 
3348   if (Model == TLSModel::GeneralDynamic) {
3349     if (Subtarget.isUsingPCRelativeCalls()) {
3350       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3351                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3352       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3353     }
3354 
3355     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3356     SDValue GOTPtr;
3357     if (is64bit) {
3358       setUsesTOCBasePtr(DAG);
3359       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3360       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3361                                    GOTReg, TGA);
3362     } else {
3363       if (picLevel == PICLevel::SmallPIC)
3364         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3365       else
3366         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3367     }
3368     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3369                        GOTPtr, TGA, TGA);
3370   }
3371 
3372   if (Model == TLSModel::LocalDynamic) {
3373     if (Subtarget.isUsingPCRelativeCalls()) {
3374       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3375                                                PPCII::MO_GOT_TLSLD_PCREL_FLAG);
3376       SDValue MatPCRel =
3377           DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3378       return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3379     }
3380 
3381     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3382     SDValue GOTPtr;
3383     if (is64bit) {
3384       setUsesTOCBasePtr(DAG);
3385       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3386       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3387                            GOTReg, TGA);
3388     } else {
3389       if (picLevel == PICLevel::SmallPIC)
3390         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3391       else
3392         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3393     }
3394     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3395                                   PtrVT, GOTPtr, TGA, TGA);
3396     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3397                                       PtrVT, TLSAddr, TGA);
3398     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3399   }
3400 
3401   llvm_unreachable("Unknown TLS model!");
3402 }
3403 
3404 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3405                                               SelectionDAG &DAG) const {
3406   EVT PtrVT = Op.getValueType();
3407   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3408   SDLoc DL(GSDN);
3409   const GlobalValue *GV = GSDN->getGlobal();
3410 
3411   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3412   // The actual address of the GlobalValue is stored in the TOC.
3413   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3414     if (Subtarget.isUsingPCRelativeCalls()) {
3415       EVT Ty = getPointerTy(DAG.getDataLayout());
3416       if (isAccessedAsGotIndirect(Op)) {
3417         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3418                                                 PPCII::MO_PCREL_FLAG |
3419                                                     PPCII::MO_GOT_FLAG);
3420         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3421         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3422                                    MachinePointerInfo());
3423         return Load;
3424       } else {
3425         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3426                                                 PPCII::MO_PCREL_FLAG);
3427         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3428       }
3429     }
3430     setUsesTOCBasePtr(DAG);
3431     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3432     return getTOCEntry(DAG, DL, GA);
3433   }
3434 
3435   unsigned MOHiFlag, MOLoFlag;
3436   bool IsPIC = isPositionIndependent();
3437   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3438 
3439   if (IsPIC && Subtarget.isSVR4ABI()) {
3440     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3441                                             GSDN->getOffset(),
3442                                             PPCII::MO_PIC_FLAG);
3443     return getTOCEntry(DAG, DL, GA);
3444   }
3445 
3446   SDValue GAHi =
3447     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3448   SDValue GALo =
3449     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3450 
3451   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3452 }
3453 
3454 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3455   bool IsStrict = Op->isStrictFPOpcode();
3456   ISD::CondCode CC =
3457       cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
3458   SDValue LHS = Op.getOperand(IsStrict ? 1 : 0);
3459   SDValue RHS = Op.getOperand(IsStrict ? 2 : 1);
3460   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
3461   EVT LHSVT = LHS.getValueType();
3462   SDLoc dl(Op);
3463 
3464   // Soften the setcc with libcall if it is fp128.
3465   if (LHSVT == MVT::f128) {
3466     assert(!Subtarget.hasP9Vector() &&
3467            "SETCC for f128 is already legal under Power9!");
3468     softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain,
3469                         Op->getOpcode() == ISD::STRICT_FSETCCS);
3470     if (RHS.getNode())
3471       LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS,
3472                         DAG.getCondCode(CC));
3473     if (IsStrict)
3474       return DAG.getMergeValues({LHS, Chain}, dl);
3475     return LHS;
3476   }
3477 
3478   assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!");
3479 
3480   if (Op.getValueType() == MVT::v2i64) {
3481     // When the operands themselves are v2i64 values, we need to do something
3482     // special because VSX has no underlying comparison operations for these.
3483     if (LHS.getValueType() == MVT::v2i64) {
3484       // Equality can be handled by casting to the legal type for Altivec
3485       // comparisons, everything else needs to be expanded.
3486       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3487         return DAG.getNode(
3488             ISD::BITCAST, dl, MVT::v2i64,
3489             DAG.getSetCC(dl, MVT::v4i32,
3490                          DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS),
3491                          DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC));
3492       }
3493 
3494       return SDValue();
3495     }
3496 
3497     // We handle most of these in the usual way.
3498     return Op;
3499   }
3500 
3501   // If we're comparing for equality to zero, expose the fact that this is
3502   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3503   // fold the new nodes.
3504   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3505     return V;
3506 
3507   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
3508     // Leave comparisons against 0 and -1 alone for now, since they're usually
3509     // optimized.  FIXME: revisit this when we can custom lower all setcc
3510     // optimizations.
3511     if (C->isAllOnes() || C->isZero())
3512       return SDValue();
3513   }
3514 
3515   // If we have an integer seteq/setne, turn it into a compare against zero
3516   // by xor'ing the rhs with the lhs, which is faster than setting a
3517   // condition register, reading it back out, and masking the correct bit.  The
3518   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3519   // the result to other bit-twiddling opportunities.
3520   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3521     EVT VT = Op.getValueType();
3522     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS);
3523     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3524   }
3525   return SDValue();
3526 }
3527 
3528 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3529   SDNode *Node = Op.getNode();
3530   EVT VT = Node->getValueType(0);
3531   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3532   SDValue InChain = Node->getOperand(0);
3533   SDValue VAListPtr = Node->getOperand(1);
3534   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3535   SDLoc dl(Node);
3536 
3537   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3538 
3539   // gpr_index
3540   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3541                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3542   InChain = GprIndex.getValue(1);
3543 
3544   if (VT == MVT::i64) {
3545     // Check if GprIndex is even
3546     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3547                                  DAG.getConstant(1, dl, MVT::i32));
3548     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3549                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3550     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3551                                           DAG.getConstant(1, dl, MVT::i32));
3552     // Align GprIndex to be even if it isn't
3553     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3554                            GprIndex);
3555   }
3556 
3557   // fpr index is 1 byte after gpr
3558   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3559                                DAG.getConstant(1, dl, MVT::i32));
3560 
3561   // fpr
3562   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3563                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3564   InChain = FprIndex.getValue(1);
3565 
3566   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3567                                        DAG.getConstant(8, dl, MVT::i32));
3568 
3569   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3570                                         DAG.getConstant(4, dl, MVT::i32));
3571 
3572   // areas
3573   SDValue OverflowArea =
3574       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3575   InChain = OverflowArea.getValue(1);
3576 
3577   SDValue RegSaveArea =
3578       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3579   InChain = RegSaveArea.getValue(1);
3580 
3581   // select overflow_area if index > 8
3582   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3583                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3584 
3585   // adjustment constant gpr_index * 4/8
3586   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3587                                     VT.isInteger() ? GprIndex : FprIndex,
3588                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3589                                                     MVT::i32));
3590 
3591   // OurReg = RegSaveArea + RegConstant
3592   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3593                                RegConstant);
3594 
3595   // Floating types are 32 bytes into RegSaveArea
3596   if (VT.isFloatingPoint())
3597     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3598                          DAG.getConstant(32, dl, MVT::i32));
3599 
3600   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3601   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3602                                    VT.isInteger() ? GprIndex : FprIndex,
3603                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3604                                                    MVT::i32));
3605 
3606   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3607                               VT.isInteger() ? VAListPtr : FprPtr,
3608                               MachinePointerInfo(SV), MVT::i8);
3609 
3610   // determine if we should load from reg_save_area or overflow_area
3611   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3612 
3613   // increase overflow_area by 4/8 if gpr/fpr > 8
3614   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3615                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3616                                           dl, MVT::i32));
3617 
3618   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3619                              OverflowAreaPlusN);
3620 
3621   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3622                               MachinePointerInfo(), MVT::i32);
3623 
3624   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3625 }
3626 
3627 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3628   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3629 
3630   // We have to copy the entire va_list struct:
3631   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3632   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3633                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3634                        false, true, false, MachinePointerInfo(),
3635                        MachinePointerInfo());
3636 }
3637 
3638 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3639                                                   SelectionDAG &DAG) const {
3640   if (Subtarget.isAIXABI())
3641     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3642 
3643   return Op.getOperand(0);
3644 }
3645 
3646 SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
3647   MachineFunction &MF = DAG.getMachineFunction();
3648   PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>();
3649 
3650   assert((Op.getOpcode() == ISD::INLINEASM ||
3651           Op.getOpcode() == ISD::INLINEASM_BR) &&
3652          "Expecting Inline ASM node.");
3653 
3654   // If an LR store is already known to be required then there is not point in
3655   // checking this ASM as well.
3656   if (MFI.isLRStoreRequired())
3657     return Op;
3658 
3659   // Inline ASM nodes have an optional last operand that is an incoming Flag of
3660   // type MVT::Glue. We want to ignore this last operand if that is the case.
3661   unsigned NumOps = Op.getNumOperands();
3662   if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue)
3663     --NumOps;
3664 
3665   // Check all operands that may contain the LR.
3666   for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
3667     unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue();
3668     unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
3669     ++i; // Skip the ID value.
3670 
3671     switch (InlineAsm::getKind(Flags)) {
3672     default:
3673       llvm_unreachable("Bad flags!");
3674     case InlineAsm::Kind_RegUse:
3675     case InlineAsm::Kind_Imm:
3676     case InlineAsm::Kind_Mem:
3677       i += NumVals;
3678       break;
3679     case InlineAsm::Kind_Clobber:
3680     case InlineAsm::Kind_RegDef:
3681     case InlineAsm::Kind_RegDefEarlyClobber: {
3682       for (; NumVals; --NumVals, ++i) {
3683         Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg();
3684         if (Reg != PPC::LR && Reg != PPC::LR8)
3685           continue;
3686         MFI.setLRStoreRequired();
3687         return Op;
3688       }
3689       break;
3690     }
3691     }
3692   }
3693 
3694   return Op;
3695 }
3696 
3697 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3698                                                 SelectionDAG &DAG) const {
3699   if (Subtarget.isAIXABI())
3700     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3701 
3702   SDValue Chain = Op.getOperand(0);
3703   SDValue Trmp = Op.getOperand(1); // trampoline
3704   SDValue FPtr = Op.getOperand(2); // nested function
3705   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3706   SDLoc dl(Op);
3707 
3708   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3709   bool isPPC64 = (PtrVT == MVT::i64);
3710   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3711 
3712   TargetLowering::ArgListTy Args;
3713   TargetLowering::ArgListEntry Entry;
3714 
3715   Entry.Ty = IntPtrTy;
3716   Entry.Node = Trmp; Args.push_back(Entry);
3717 
3718   // TrampSize == (isPPC64 ? 48 : 40);
3719   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3720                                isPPC64 ? MVT::i64 : MVT::i32);
3721   Args.push_back(Entry);
3722 
3723   Entry.Node = FPtr; Args.push_back(Entry);
3724   Entry.Node = Nest; Args.push_back(Entry);
3725 
3726   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3727   TargetLowering::CallLoweringInfo CLI(DAG);
3728   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3729       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3730       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3731 
3732   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3733   return CallResult.second;
3734 }
3735 
3736 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3737   MachineFunction &MF = DAG.getMachineFunction();
3738   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3739   EVT PtrVT = getPointerTy(MF.getDataLayout());
3740 
3741   SDLoc dl(Op);
3742 
3743   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3744     // vastart just stores the address of the VarArgsFrameIndex slot into the
3745     // memory location argument.
3746     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3747     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3748     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3749                         MachinePointerInfo(SV));
3750   }
3751 
3752   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3753   // We suppose the given va_list is already allocated.
3754   //
3755   // typedef struct {
3756   //  char gpr;     /* index into the array of 8 GPRs
3757   //                 * stored in the register save area
3758   //                 * gpr=0 corresponds to r3,
3759   //                 * gpr=1 to r4, etc.
3760   //                 */
3761   //  char fpr;     /* index into the array of 8 FPRs
3762   //                 * stored in the register save area
3763   //                 * fpr=0 corresponds to f1,
3764   //                 * fpr=1 to f2, etc.
3765   //                 */
3766   //  char *overflow_arg_area;
3767   //                /* location on stack that holds
3768   //                 * the next overflow argument
3769   //                 */
3770   //  char *reg_save_area;
3771   //               /* where r3:r10 and f1:f8 (if saved)
3772   //                * are stored
3773   //                */
3774   // } va_list[1];
3775 
3776   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3777   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3778   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3779                                             PtrVT);
3780   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3781                                  PtrVT);
3782 
3783   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3784   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3785 
3786   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3787   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3788 
3789   uint64_t FPROffset = 1;
3790   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3791 
3792   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3793 
3794   // Store first byte : number of int regs
3795   SDValue firstStore =
3796       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3797                         MachinePointerInfo(SV), MVT::i8);
3798   uint64_t nextOffset = FPROffset;
3799   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3800                                   ConstFPROffset);
3801 
3802   // Store second byte : number of float regs
3803   SDValue secondStore =
3804       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3805                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3806   nextOffset += StackOffset;
3807   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3808 
3809   // Store second word : arguments given on stack
3810   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3811                                     MachinePointerInfo(SV, nextOffset));
3812   nextOffset += FrameOffset;
3813   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3814 
3815   // Store third word : arguments given in registers
3816   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3817                       MachinePointerInfo(SV, nextOffset));
3818 }
3819 
3820 /// FPR - The set of FP registers that should be allocated for arguments
3821 /// on Darwin and AIX.
3822 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3823                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3824                                 PPC::F11, PPC::F12, PPC::F13};
3825 
3826 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3827 /// the stack.
3828 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3829                                        unsigned PtrByteSize) {
3830   unsigned ArgSize = ArgVT.getStoreSize();
3831   if (Flags.isByVal())
3832     ArgSize = Flags.getByValSize();
3833 
3834   // Round up to multiples of the pointer size, except for array members,
3835   // which are always packed.
3836   if (!Flags.isInConsecutiveRegs())
3837     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3838 
3839   return ArgSize;
3840 }
3841 
3842 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3843 /// on the stack.
3844 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3845                                          ISD::ArgFlagsTy Flags,
3846                                          unsigned PtrByteSize) {
3847   Align Alignment(PtrByteSize);
3848 
3849   // Altivec parameters are padded to a 16 byte boundary.
3850   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3851       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3852       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3853       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3854     Alignment = Align(16);
3855 
3856   // ByVal parameters are aligned as requested.
3857   if (Flags.isByVal()) {
3858     auto BVAlign = Flags.getNonZeroByValAlign();
3859     if (BVAlign > PtrByteSize) {
3860       if (BVAlign.value() % PtrByteSize != 0)
3861         llvm_unreachable(
3862             "ByVal alignment is not a multiple of the pointer size");
3863 
3864       Alignment = BVAlign;
3865     }
3866   }
3867 
3868   // Array members are always packed to their original alignment.
3869   if (Flags.isInConsecutiveRegs()) {
3870     // If the array member was split into multiple registers, the first
3871     // needs to be aligned to the size of the full type.  (Except for
3872     // ppcf128, which is only aligned as its f64 components.)
3873     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3874       Alignment = Align(OrigVT.getStoreSize());
3875     else
3876       Alignment = Align(ArgVT.getStoreSize());
3877   }
3878 
3879   return Alignment;
3880 }
3881 
3882 /// CalculateStackSlotUsed - Return whether this argument will use its
3883 /// stack slot (instead of being passed in registers).  ArgOffset,
3884 /// AvailableFPRs, and AvailableVRs must hold the current argument
3885 /// position, and will be updated to account for this argument.
3886 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3887                                    unsigned PtrByteSize, unsigned LinkageSize,
3888                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3889                                    unsigned &AvailableFPRs,
3890                                    unsigned &AvailableVRs) {
3891   bool UseMemory = false;
3892 
3893   // Respect alignment of argument on the stack.
3894   Align Alignment =
3895       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3896   ArgOffset = alignTo(ArgOffset, Alignment);
3897   // If there's no space left in the argument save area, we must
3898   // use memory (this check also catches zero-sized arguments).
3899   if (ArgOffset >= LinkageSize + ParamAreaSize)
3900     UseMemory = true;
3901 
3902   // Allocate argument on the stack.
3903   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3904   if (Flags.isInConsecutiveRegsLast())
3905     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3906   // If we overran the argument save area, we must use memory
3907   // (this check catches arguments passed partially in memory)
3908   if (ArgOffset > LinkageSize + ParamAreaSize)
3909     UseMemory = true;
3910 
3911   // However, if the argument is actually passed in an FPR or a VR,
3912   // we don't use memory after all.
3913   if (!Flags.isByVal()) {
3914     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3915       if (AvailableFPRs > 0) {
3916         --AvailableFPRs;
3917         return false;
3918       }
3919     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3920         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3921         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3922         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3923       if (AvailableVRs > 0) {
3924         --AvailableVRs;
3925         return false;
3926       }
3927   }
3928 
3929   return UseMemory;
3930 }
3931 
3932 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3933 /// ensure minimum alignment required for target.
3934 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3935                                      unsigned NumBytes) {
3936   return alignTo(NumBytes, Lowering->getStackAlign());
3937 }
3938 
3939 SDValue PPCTargetLowering::LowerFormalArguments(
3940     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3941     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3942     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3943   if (Subtarget.isAIXABI())
3944     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3945                                     InVals);
3946   if (Subtarget.is64BitELFABI())
3947     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3948                                        InVals);
3949   assert(Subtarget.is32BitELFABI());
3950   return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3951                                      InVals);
3952 }
3953 
3954 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3955     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3956     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3957     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3958 
3959   // 32-bit SVR4 ABI Stack Frame Layout:
3960   //              +-----------------------------------+
3961   //        +-->  |            Back chain             |
3962   //        |     +-----------------------------------+
3963   //        |     | Floating-point register save area |
3964   //        |     +-----------------------------------+
3965   //        |     |    General register save area     |
3966   //        |     +-----------------------------------+
3967   //        |     |          CR save word             |
3968   //        |     +-----------------------------------+
3969   //        |     |         VRSAVE save word          |
3970   //        |     +-----------------------------------+
3971   //        |     |         Alignment padding         |
3972   //        |     +-----------------------------------+
3973   //        |     |     Vector register save area     |
3974   //        |     +-----------------------------------+
3975   //        |     |       Local variable space        |
3976   //        |     +-----------------------------------+
3977   //        |     |        Parameter list area        |
3978   //        |     +-----------------------------------+
3979   //        |     |           LR save word            |
3980   //        |     +-----------------------------------+
3981   // SP-->  +---  |            Back chain             |
3982   //              +-----------------------------------+
3983   //
3984   // Specifications:
3985   //   System V Application Binary Interface PowerPC Processor Supplement
3986   //   AltiVec Technology Programming Interface Manual
3987 
3988   MachineFunction &MF = DAG.getMachineFunction();
3989   MachineFrameInfo &MFI = MF.getFrameInfo();
3990   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3991 
3992   EVT PtrVT = getPointerTy(MF.getDataLayout());
3993   // Potential tail calls could cause overwriting of argument stack slots.
3994   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3995                        (CallConv == CallingConv::Fast));
3996   const Align PtrAlign(4);
3997 
3998   // Assign locations to all of the incoming arguments.
3999   SmallVector<CCValAssign, 16> ArgLocs;
4000   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4001                  *DAG.getContext());
4002 
4003   // Reserve space for the linkage area on the stack.
4004   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4005   CCInfo.AllocateStack(LinkageSize, PtrAlign);
4006   if (useSoftFloat())
4007     CCInfo.PreAnalyzeFormalArguments(Ins);
4008 
4009   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
4010   CCInfo.clearWasPPCF128();
4011 
4012   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4013     CCValAssign &VA = ArgLocs[i];
4014 
4015     // Arguments stored in registers.
4016     if (VA.isRegLoc()) {
4017       const TargetRegisterClass *RC;
4018       EVT ValVT = VA.getValVT();
4019 
4020       switch (ValVT.getSimpleVT().SimpleTy) {
4021         default:
4022           llvm_unreachable("ValVT not supported by formal arguments Lowering");
4023         case MVT::i1:
4024         case MVT::i32:
4025           RC = &PPC::GPRCRegClass;
4026           break;
4027         case MVT::f32:
4028           if (Subtarget.hasP8Vector())
4029             RC = &PPC::VSSRCRegClass;
4030           else if (Subtarget.hasSPE())
4031             RC = &PPC::GPRCRegClass;
4032           else
4033             RC = &PPC::F4RCRegClass;
4034           break;
4035         case MVT::f64:
4036           if (Subtarget.hasVSX())
4037             RC = &PPC::VSFRCRegClass;
4038           else if (Subtarget.hasSPE())
4039             // SPE passes doubles in GPR pairs.
4040             RC = &PPC::GPRCRegClass;
4041           else
4042             RC = &PPC::F8RCRegClass;
4043           break;
4044         case MVT::v16i8:
4045         case MVT::v8i16:
4046         case MVT::v4i32:
4047           RC = &PPC::VRRCRegClass;
4048           break;
4049         case MVT::v4f32:
4050           RC = &PPC::VRRCRegClass;
4051           break;
4052         case MVT::v2f64:
4053         case MVT::v2i64:
4054           RC = &PPC::VRRCRegClass;
4055           break;
4056       }
4057 
4058       SDValue ArgValue;
4059       // Transform the arguments stored in physical registers into
4060       // virtual ones.
4061       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
4062         assert(i + 1 < e && "No second half of double precision argument");
4063         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
4064         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
4065         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
4066         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
4067         if (!Subtarget.isLittleEndian())
4068           std::swap (ArgValueLo, ArgValueHi);
4069         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
4070                                ArgValueHi);
4071       } else {
4072         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4073         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
4074                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
4075         if (ValVT == MVT::i1)
4076           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
4077       }
4078 
4079       InVals.push_back(ArgValue);
4080     } else {
4081       // Argument stored in memory.
4082       assert(VA.isMemLoc());
4083 
4084       // Get the extended size of the argument type in stack
4085       unsigned ArgSize = VA.getLocVT().getStoreSize();
4086       // Get the actual size of the argument type
4087       unsigned ObjSize = VA.getValVT().getStoreSize();
4088       unsigned ArgOffset = VA.getLocMemOffset();
4089       // Stack objects in PPC32 are right justified.
4090       ArgOffset += ArgSize - ObjSize;
4091       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
4092 
4093       // Create load nodes to retrieve arguments from the stack.
4094       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4095       InVals.push_back(
4096           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
4097     }
4098   }
4099 
4100   // Assign locations to all of the incoming aggregate by value arguments.
4101   // Aggregates passed by value are stored in the local variable space of the
4102   // caller's stack frame, right above the parameter list area.
4103   SmallVector<CCValAssign, 16> ByValArgLocs;
4104   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4105                       ByValArgLocs, *DAG.getContext());
4106 
4107   // Reserve stack space for the allocations in CCInfo.
4108   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
4109 
4110   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
4111 
4112   // Area that is at least reserved in the caller of this function.
4113   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
4114   MinReservedArea = std::max(MinReservedArea, LinkageSize);
4115 
4116   // Set the size that is at least reserved in caller of this function.  Tail
4117   // call optimized function's reserved stack space needs to be aligned so that
4118   // taking the difference between two stack areas will result in an aligned
4119   // stack.
4120   MinReservedArea =
4121       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4122   FuncInfo->setMinReservedArea(MinReservedArea);
4123 
4124   SmallVector<SDValue, 8> MemOps;
4125 
4126   // If the function takes variable number of arguments, make a frame index for
4127   // the start of the first vararg value... for expansion of llvm.va_start.
4128   if (isVarArg) {
4129     static const MCPhysReg GPArgRegs[] = {
4130       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4131       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4132     };
4133     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
4134 
4135     static const MCPhysReg FPArgRegs[] = {
4136       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
4137       PPC::F8
4138     };
4139     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
4140 
4141     if (useSoftFloat() || hasSPE())
4142        NumFPArgRegs = 0;
4143 
4144     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
4145     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
4146 
4147     // Make room for NumGPArgRegs and NumFPArgRegs.
4148     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
4149                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
4150 
4151     FuncInfo->setVarArgsStackOffset(
4152       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4153                             CCInfo.getNextStackOffset(), true));
4154 
4155     FuncInfo->setVarArgsFrameIndex(
4156         MFI.CreateStackObject(Depth, Align(8), false));
4157     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4158 
4159     // The fixed integer arguments of a variadic function are stored to the
4160     // VarArgsFrameIndex on the stack so that they may be loaded by
4161     // dereferencing the result of va_next.
4162     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
4163       // Get an existing live-in vreg, or add a new one.
4164       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
4165       if (!VReg)
4166         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
4167 
4168       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4169       SDValue Store =
4170           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4171       MemOps.push_back(Store);
4172       // Increment the address by four for the next argument to store
4173       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4174       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4175     }
4176 
4177     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
4178     // is set.
4179     // The double arguments are stored to the VarArgsFrameIndex
4180     // on the stack.
4181     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
4182       // Get an existing live-in vreg, or add a new one.
4183       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
4184       if (!VReg)
4185         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
4186 
4187       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
4188       SDValue Store =
4189           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4190       MemOps.push_back(Store);
4191       // Increment the address by eight for the next argument to store
4192       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
4193                                          PtrVT);
4194       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4195     }
4196   }
4197 
4198   if (!MemOps.empty())
4199     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4200 
4201   return Chain;
4202 }
4203 
4204 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4205 // value to MVT::i64 and then truncate to the correct register size.
4206 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
4207                                              EVT ObjectVT, SelectionDAG &DAG,
4208                                              SDValue ArgVal,
4209                                              const SDLoc &dl) const {
4210   if (Flags.isSExt())
4211     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
4212                          DAG.getValueType(ObjectVT));
4213   else if (Flags.isZExt())
4214     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
4215                          DAG.getValueType(ObjectVT));
4216 
4217   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
4218 }
4219 
4220 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
4221     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4222     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4223     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4224   // TODO: add description of PPC stack frame format, or at least some docs.
4225   //
4226   bool isELFv2ABI = Subtarget.isELFv2ABI();
4227   bool isLittleEndian = Subtarget.isLittleEndian();
4228   MachineFunction &MF = DAG.getMachineFunction();
4229   MachineFrameInfo &MFI = MF.getFrameInfo();
4230   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4231 
4232   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4233          "fastcc not supported on varargs functions");
4234 
4235   EVT PtrVT = getPointerTy(MF.getDataLayout());
4236   // Potential tail calls could cause overwriting of argument stack slots.
4237   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4238                        (CallConv == CallingConv::Fast));
4239   unsigned PtrByteSize = 8;
4240   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4241 
4242   static const MCPhysReg GPR[] = {
4243     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4244     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4245   };
4246   static const MCPhysReg VR[] = {
4247     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4248     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4249   };
4250 
4251   const unsigned Num_GPR_Regs = array_lengthof(GPR);
4252   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4253   const unsigned Num_VR_Regs  = array_lengthof(VR);
4254 
4255   // Do a first pass over the arguments to determine whether the ABI
4256   // guarantees that our caller has allocated the parameter save area
4257   // on its stack frame.  In the ELFv1 ABI, this is always the case;
4258   // in the ELFv2 ABI, it is true if this is a vararg function or if
4259   // any parameter is located in a stack slot.
4260 
4261   bool HasParameterArea = !isELFv2ABI || isVarArg;
4262   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4263   unsigned NumBytes = LinkageSize;
4264   unsigned AvailableFPRs = Num_FPR_Regs;
4265   unsigned AvailableVRs = Num_VR_Regs;
4266   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4267     if (Ins[i].Flags.isNest())
4268       continue;
4269 
4270     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
4271                                PtrByteSize, LinkageSize, ParamAreaSize,
4272                                NumBytes, AvailableFPRs, AvailableVRs))
4273       HasParameterArea = true;
4274   }
4275 
4276   // Add DAG nodes to load the arguments or copy them out of registers.  On
4277   // entry to a function on PPC, the arguments start after the linkage area,
4278   // although the first ones are often in registers.
4279 
4280   unsigned ArgOffset = LinkageSize;
4281   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4282   SmallVector<SDValue, 8> MemOps;
4283   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4284   unsigned CurArgIdx = 0;
4285   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4286     SDValue ArgVal;
4287     bool needsLoad = false;
4288     EVT ObjectVT = Ins[ArgNo].VT;
4289     EVT OrigVT = Ins[ArgNo].ArgVT;
4290     unsigned ObjSize = ObjectVT.getStoreSize();
4291     unsigned ArgSize = ObjSize;
4292     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4293     if (Ins[ArgNo].isOrigArg()) {
4294       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4295       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4296     }
4297     // We re-align the argument offset for each argument, except when using the
4298     // fast calling convention, when we need to make sure we do that only when
4299     // we'll actually use a stack slot.
4300     unsigned CurArgOffset;
4301     Align Alignment;
4302     auto ComputeArgOffset = [&]() {
4303       /* Respect alignment of argument on the stack.  */
4304       Alignment =
4305           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4306       ArgOffset = alignTo(ArgOffset, Alignment);
4307       CurArgOffset = ArgOffset;
4308     };
4309 
4310     if (CallConv != CallingConv::Fast) {
4311       ComputeArgOffset();
4312 
4313       /* Compute GPR index associated with argument offset.  */
4314       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4315       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4316     }
4317 
4318     // FIXME the codegen can be much improved in some cases.
4319     // We do not have to keep everything in memory.
4320     if (Flags.isByVal()) {
4321       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4322 
4323       if (CallConv == CallingConv::Fast)
4324         ComputeArgOffset();
4325 
4326       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4327       ObjSize = Flags.getByValSize();
4328       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4329       // Empty aggregate parameters do not take up registers.  Examples:
4330       //   struct { } a;
4331       //   union  { } b;
4332       //   int c[0];
4333       // etc.  However, we have to provide a place-holder in InVals, so
4334       // pretend we have an 8-byte item at the current address for that
4335       // purpose.
4336       if (!ObjSize) {
4337         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4338         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4339         InVals.push_back(FIN);
4340         continue;
4341       }
4342 
4343       // Create a stack object covering all stack doublewords occupied
4344       // by the argument.  If the argument is (fully or partially) on
4345       // the stack, or if the argument is fully in registers but the
4346       // caller has allocated the parameter save anyway, we can refer
4347       // directly to the caller's stack frame.  Otherwise, create a
4348       // local copy in our own frame.
4349       int FI;
4350       if (HasParameterArea ||
4351           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4352         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4353       else
4354         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4355       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4356 
4357       // Handle aggregates smaller than 8 bytes.
4358       if (ObjSize < PtrByteSize) {
4359         // The value of the object is its address, which differs from the
4360         // address of the enclosing doubleword on big-endian systems.
4361         SDValue Arg = FIN;
4362         if (!isLittleEndian) {
4363           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4364           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4365         }
4366         InVals.push_back(Arg);
4367 
4368         if (GPR_idx != Num_GPR_Regs) {
4369           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4370           FuncInfo->addLiveInAttr(VReg, Flags);
4371           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4372           SDValue Store;
4373 
4374           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
4375             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
4376                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
4377             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4378                                       MachinePointerInfo(&*FuncArg), ObjType);
4379           } else {
4380             // For sizes that don't fit a truncating store (3, 5, 6, 7),
4381             // store the whole register as-is to the parameter save area
4382             // slot.
4383             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4384                                  MachinePointerInfo(&*FuncArg));
4385           }
4386 
4387           MemOps.push_back(Store);
4388         }
4389         // Whether we copied from a register or not, advance the offset
4390         // into the parameter save area by a full doubleword.
4391         ArgOffset += PtrByteSize;
4392         continue;
4393       }
4394 
4395       // The value of the object is its address, which is the address of
4396       // its first stack doubleword.
4397       InVals.push_back(FIN);
4398 
4399       // Store whatever pieces of the object are in registers to memory.
4400       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4401         if (GPR_idx == Num_GPR_Regs)
4402           break;
4403 
4404         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4405         FuncInfo->addLiveInAttr(VReg, Flags);
4406         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4407         SDValue Addr = FIN;
4408         if (j) {
4409           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4410           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4411         }
4412         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4413                                      MachinePointerInfo(&*FuncArg, j));
4414         MemOps.push_back(Store);
4415         ++GPR_idx;
4416       }
4417       ArgOffset += ArgSize;
4418       continue;
4419     }
4420 
4421     switch (ObjectVT.getSimpleVT().SimpleTy) {
4422     default: llvm_unreachable("Unhandled argument type!");
4423     case MVT::i1:
4424     case MVT::i32:
4425     case MVT::i64:
4426       if (Flags.isNest()) {
4427         // The 'nest' parameter, if any, is passed in R11.
4428         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4429         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4430 
4431         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4432           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4433 
4434         break;
4435       }
4436 
4437       // These can be scalar arguments or elements of an integer array type
4438       // passed directly.  Clang may use those instead of "byval" aggregate
4439       // types to avoid forcing arguments to memory unnecessarily.
4440       if (GPR_idx != Num_GPR_Regs) {
4441         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4442         FuncInfo->addLiveInAttr(VReg, Flags);
4443         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4444 
4445         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4446           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4447           // value to MVT::i64 and then truncate to the correct register size.
4448           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4449       } else {
4450         if (CallConv == CallingConv::Fast)
4451           ComputeArgOffset();
4452 
4453         needsLoad = true;
4454         ArgSize = PtrByteSize;
4455       }
4456       if (CallConv != CallingConv::Fast || needsLoad)
4457         ArgOffset += 8;
4458       break;
4459 
4460     case MVT::f32:
4461     case MVT::f64:
4462       // These can be scalar arguments or elements of a float array type
4463       // passed directly.  The latter are used to implement ELFv2 homogenous
4464       // float aggregates.
4465       if (FPR_idx != Num_FPR_Regs) {
4466         unsigned VReg;
4467 
4468         if (ObjectVT == MVT::f32)
4469           VReg = MF.addLiveIn(FPR[FPR_idx],
4470                               Subtarget.hasP8Vector()
4471                                   ? &PPC::VSSRCRegClass
4472                                   : &PPC::F4RCRegClass);
4473         else
4474           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4475                                                 ? &PPC::VSFRCRegClass
4476                                                 : &PPC::F8RCRegClass);
4477 
4478         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4479         ++FPR_idx;
4480       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4481         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4482         // once we support fp <-> gpr moves.
4483 
4484         // This can only ever happen in the presence of f32 array types,
4485         // since otherwise we never run out of FPRs before running out
4486         // of GPRs.
4487         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4488         FuncInfo->addLiveInAttr(VReg, Flags);
4489         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4490 
4491         if (ObjectVT == MVT::f32) {
4492           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4493             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4494                                  DAG.getConstant(32, dl, MVT::i32));
4495           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4496         }
4497 
4498         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4499       } else {
4500         if (CallConv == CallingConv::Fast)
4501           ComputeArgOffset();
4502 
4503         needsLoad = true;
4504       }
4505 
4506       // When passing an array of floats, the array occupies consecutive
4507       // space in the argument area; only round up to the next doubleword
4508       // at the end of the array.  Otherwise, each float takes 8 bytes.
4509       if (CallConv != CallingConv::Fast || needsLoad) {
4510         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4511         ArgOffset += ArgSize;
4512         if (Flags.isInConsecutiveRegsLast())
4513           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4514       }
4515       break;
4516     case MVT::v4f32:
4517     case MVT::v4i32:
4518     case MVT::v8i16:
4519     case MVT::v16i8:
4520     case MVT::v2f64:
4521     case MVT::v2i64:
4522     case MVT::v1i128:
4523     case MVT::f128:
4524       // These can be scalar arguments or elements of a vector array type
4525       // passed directly.  The latter are used to implement ELFv2 homogenous
4526       // vector aggregates.
4527       if (VR_idx != Num_VR_Regs) {
4528         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4529         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4530         ++VR_idx;
4531       } else {
4532         if (CallConv == CallingConv::Fast)
4533           ComputeArgOffset();
4534         needsLoad = true;
4535       }
4536       if (CallConv != CallingConv::Fast || needsLoad)
4537         ArgOffset += 16;
4538       break;
4539     }
4540 
4541     // We need to load the argument to a virtual register if we determined
4542     // above that we ran out of physical registers of the appropriate type.
4543     if (needsLoad) {
4544       if (ObjSize < ArgSize && !isLittleEndian)
4545         CurArgOffset += ArgSize - ObjSize;
4546       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4547       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4548       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4549     }
4550 
4551     InVals.push_back(ArgVal);
4552   }
4553 
4554   // Area that is at least reserved in the caller of this function.
4555   unsigned MinReservedArea;
4556   if (HasParameterArea)
4557     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4558   else
4559     MinReservedArea = LinkageSize;
4560 
4561   // Set the size that is at least reserved in caller of this function.  Tail
4562   // call optimized functions' reserved stack space needs to be aligned so that
4563   // taking the difference between two stack areas will result in an aligned
4564   // stack.
4565   MinReservedArea =
4566       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4567   FuncInfo->setMinReservedArea(MinReservedArea);
4568 
4569   // If the function takes variable number of arguments, make a frame index for
4570   // the start of the first vararg value... for expansion of llvm.va_start.
4571   // On ELFv2ABI spec, it writes:
4572   // C programs that are intended to be *portable* across different compilers
4573   // and architectures must use the header file <stdarg.h> to deal with variable
4574   // argument lists.
4575   if (isVarArg && MFI.hasVAStart()) {
4576     int Depth = ArgOffset;
4577 
4578     FuncInfo->setVarArgsFrameIndex(
4579       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4580     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4581 
4582     // If this function is vararg, store any remaining integer argument regs
4583     // to their spots on the stack so that they may be loaded by dereferencing
4584     // the result of va_next.
4585     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4586          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4587       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4588       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4589       SDValue Store =
4590           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4591       MemOps.push_back(Store);
4592       // Increment the address by four for the next argument to store
4593       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4594       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4595     }
4596   }
4597 
4598   if (!MemOps.empty())
4599     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4600 
4601   return Chain;
4602 }
4603 
4604 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4605 /// adjusted to accommodate the arguments for the tailcall.
4606 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4607                                    unsigned ParamSize) {
4608 
4609   if (!isTailCall) return 0;
4610 
4611   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4612   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4613   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4614   // Remember only if the new adjustment is bigger.
4615   if (SPDiff < FI->getTailCallSPDelta())
4616     FI->setTailCallSPDelta(SPDiff);
4617 
4618   return SPDiff;
4619 }
4620 
4621 static bool isFunctionGlobalAddress(SDValue Callee);
4622 
4623 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4624                               const TargetMachine &TM) {
4625   // It does not make sense to call callsShareTOCBase() with a caller that
4626   // is PC Relative since PC Relative callers do not have a TOC.
4627 #ifndef NDEBUG
4628   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4629   assert(!STICaller->isUsingPCRelativeCalls() &&
4630          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4631 #endif
4632 
4633   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4634   // don't have enough information to determine if the caller and callee share
4635   // the same  TOC base, so we have to pessimistically assume they don't for
4636   // correctness.
4637   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4638   if (!G)
4639     return false;
4640 
4641   const GlobalValue *GV = G->getGlobal();
4642 
4643   // If the callee is preemptable, then the static linker will use a plt-stub
4644   // which saves the toc to the stack, and needs a nop after the call
4645   // instruction to convert to a toc-restore.
4646   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4647     return false;
4648 
4649   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4650   // We may need a TOC restore in the situation where the caller requires a
4651   // valid TOC but the callee is PC Relative and does not.
4652   const Function *F = dyn_cast<Function>(GV);
4653   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4654 
4655   // If we have an Alias we can try to get the function from there.
4656   if (Alias) {
4657     const GlobalObject *GlobalObj = Alias->getBaseObject();
4658     F = dyn_cast<Function>(GlobalObj);
4659   }
4660 
4661   // If we still have no valid function pointer we do not have enough
4662   // information to determine if the callee uses PC Relative calls so we must
4663   // assume that it does.
4664   if (!F)
4665     return false;
4666 
4667   // If the callee uses PC Relative we cannot guarantee that the callee won't
4668   // clobber the TOC of the caller and so we must assume that the two
4669   // functions do not share a TOC base.
4670   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4671   if (STICallee->isUsingPCRelativeCalls())
4672     return false;
4673 
4674   // If the GV is not a strong definition then we need to assume it can be
4675   // replaced by another function at link time. The function that replaces
4676   // it may not share the same TOC as the caller since the callee may be
4677   // replaced by a PC Relative version of the same function.
4678   if (!GV->isStrongDefinitionForLinker())
4679     return false;
4680 
4681   // The medium and large code models are expected to provide a sufficiently
4682   // large TOC to provide all data addressing needs of a module with a
4683   // single TOC.
4684   if (CodeModel::Medium == TM.getCodeModel() ||
4685       CodeModel::Large == TM.getCodeModel())
4686     return true;
4687 
4688   // Any explicitly-specified sections and section prefixes must also match.
4689   // Also, if we're using -ffunction-sections, then each function is always in
4690   // a different section (the same is true for COMDAT functions).
4691   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4692       GV->getSection() != Caller->getSection())
4693     return false;
4694   if (const auto *F = dyn_cast<Function>(GV)) {
4695     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4696       return false;
4697   }
4698 
4699   return true;
4700 }
4701 
4702 static bool
4703 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4704                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4705   assert(Subtarget.is64BitELFABI());
4706 
4707   const unsigned PtrByteSize = 8;
4708   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4709 
4710   static const MCPhysReg GPR[] = {
4711     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4712     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4713   };
4714   static const MCPhysReg VR[] = {
4715     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4716     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4717   };
4718 
4719   const unsigned NumGPRs = array_lengthof(GPR);
4720   const unsigned NumFPRs = 13;
4721   const unsigned NumVRs = array_lengthof(VR);
4722   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4723 
4724   unsigned NumBytes = LinkageSize;
4725   unsigned AvailableFPRs = NumFPRs;
4726   unsigned AvailableVRs = NumVRs;
4727 
4728   for (const ISD::OutputArg& Param : Outs) {
4729     if (Param.Flags.isNest()) continue;
4730 
4731     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4732                                LinkageSize, ParamAreaSize, NumBytes,
4733                                AvailableFPRs, AvailableVRs))
4734       return true;
4735   }
4736   return false;
4737 }
4738 
4739 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4740   if (CB.arg_size() != CallerFn->arg_size())
4741     return false;
4742 
4743   auto CalleeArgIter = CB.arg_begin();
4744   auto CalleeArgEnd = CB.arg_end();
4745   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4746 
4747   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4748     const Value* CalleeArg = *CalleeArgIter;
4749     const Value* CallerArg = &(*CallerArgIter);
4750     if (CalleeArg == CallerArg)
4751       continue;
4752 
4753     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4754     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4755     //      }
4756     // 1st argument of callee is undef and has the same type as caller.
4757     if (CalleeArg->getType() == CallerArg->getType() &&
4758         isa<UndefValue>(CalleeArg))
4759       continue;
4760 
4761     return false;
4762   }
4763 
4764   return true;
4765 }
4766 
4767 // Returns true if TCO is possible between the callers and callees
4768 // calling conventions.
4769 static bool
4770 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4771                                     CallingConv::ID CalleeCC) {
4772   // Tail calls are possible with fastcc and ccc.
4773   auto isTailCallableCC  = [] (CallingConv::ID CC){
4774       return  CC == CallingConv::C || CC == CallingConv::Fast;
4775   };
4776   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4777     return false;
4778 
4779   // We can safely tail call both fastcc and ccc callees from a c calling
4780   // convention caller. If the caller is fastcc, we may have less stack space
4781   // than a non-fastcc caller with the same signature so disable tail-calls in
4782   // that case.
4783   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4784 }
4785 
4786 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4787     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4788     const SmallVectorImpl<ISD::OutputArg> &Outs,
4789     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4790   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4791 
4792   if (DisableSCO && !TailCallOpt) return false;
4793 
4794   // Variadic argument functions are not supported.
4795   if (isVarArg) return false;
4796 
4797   auto &Caller = DAG.getMachineFunction().getFunction();
4798   // Check that the calling conventions are compatible for tco.
4799   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4800     return false;
4801 
4802   // Caller contains any byval parameter is not supported.
4803   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4804     return false;
4805 
4806   // Callee contains any byval parameter is not supported, too.
4807   // Note: This is a quick work around, because in some cases, e.g.
4808   // caller's stack size > callee's stack size, we are still able to apply
4809   // sibling call optimization. For example, gcc is able to do SCO for caller1
4810   // in the following example, but not for caller2.
4811   //   struct test {
4812   //     long int a;
4813   //     char ary[56];
4814   //   } gTest;
4815   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4816   //     b->a = v.a;
4817   //     return 0;
4818   //   }
4819   //   void caller1(struct test a, struct test c, struct test *b) {
4820   //     callee(gTest, b); }
4821   //   void caller2(struct test *b) { callee(gTest, b); }
4822   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4823     return false;
4824 
4825   // If callee and caller use different calling conventions, we cannot pass
4826   // parameters on stack since offsets for the parameter area may be different.
4827   if (Caller.getCallingConv() != CalleeCC &&
4828       needStackSlotPassParameters(Subtarget, Outs))
4829     return false;
4830 
4831   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4832   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4833   // callee potentially have different TOC bases then we cannot tail call since
4834   // we need to restore the TOC pointer after the call.
4835   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4836   // We cannot guarantee this for indirect calls or calls to external functions.
4837   // When PC-Relative addressing is used, the concept of the TOC is no longer
4838   // applicable so this check is not required.
4839   // Check first for indirect calls.
4840   if (!Subtarget.isUsingPCRelativeCalls() &&
4841       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4842     return false;
4843 
4844   // Check if we share the TOC base.
4845   if (!Subtarget.isUsingPCRelativeCalls() &&
4846       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4847     return false;
4848 
4849   // TCO allows altering callee ABI, so we don't have to check further.
4850   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4851     return true;
4852 
4853   if (DisableSCO) return false;
4854 
4855   // If callee use the same argument list that caller is using, then we can
4856   // apply SCO on this case. If it is not, then we need to check if callee needs
4857   // stack for passing arguments.
4858   // PC Relative tail calls may not have a CallBase.
4859   // If there is no CallBase we cannot verify if we have the same argument
4860   // list so assume that we don't have the same argument list.
4861   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4862       needStackSlotPassParameters(Subtarget, Outs))
4863     return false;
4864   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4865     return false;
4866 
4867   return true;
4868 }
4869 
4870 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4871 /// for tail call optimization. Targets which want to do tail call
4872 /// optimization should implement this function.
4873 bool
4874 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4875                                                      CallingConv::ID CalleeCC,
4876                                                      bool isVarArg,
4877                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4878                                                      SelectionDAG& DAG) const {
4879   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4880     return false;
4881 
4882   // Variable argument functions are not supported.
4883   if (isVarArg)
4884     return false;
4885 
4886   MachineFunction &MF = DAG.getMachineFunction();
4887   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4888   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4889     // Functions containing by val parameters are not supported.
4890     for (unsigned i = 0; i != Ins.size(); i++) {
4891        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4892        if (Flags.isByVal()) return false;
4893     }
4894 
4895     // Non-PIC/GOT tail calls are supported.
4896     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4897       return true;
4898 
4899     // At the moment we can only do local tail calls (in same module, hidden
4900     // or protected) if we are generating PIC.
4901     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4902       return G->getGlobal()->hasHiddenVisibility()
4903           || G->getGlobal()->hasProtectedVisibility();
4904   }
4905 
4906   return false;
4907 }
4908 
4909 /// isCallCompatibleAddress - Return the immediate to use if the specified
4910 /// 32-bit value is representable in the immediate field of a BxA instruction.
4911 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4912   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4913   if (!C) return nullptr;
4914 
4915   int Addr = C->getZExtValue();
4916   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4917       SignExtend32<26>(Addr) != Addr)
4918     return nullptr;  // Top 6 bits have to be sext of immediate.
4919 
4920   return DAG
4921       .getConstant(
4922           (int)C->getZExtValue() >> 2, SDLoc(Op),
4923           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4924       .getNode();
4925 }
4926 
4927 namespace {
4928 
4929 struct TailCallArgumentInfo {
4930   SDValue Arg;
4931   SDValue FrameIdxOp;
4932   int FrameIdx = 0;
4933 
4934   TailCallArgumentInfo() = default;
4935 };
4936 
4937 } // end anonymous namespace
4938 
4939 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4940 static void StoreTailCallArgumentsToStackSlot(
4941     SelectionDAG &DAG, SDValue Chain,
4942     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4943     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4944   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4945     SDValue Arg = TailCallArgs[i].Arg;
4946     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4947     int FI = TailCallArgs[i].FrameIdx;
4948     // Store relative to framepointer.
4949     MemOpChains.push_back(DAG.getStore(
4950         Chain, dl, Arg, FIN,
4951         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4952   }
4953 }
4954 
4955 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4956 /// the appropriate stack slot for the tail call optimized function call.
4957 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4958                                              SDValue OldRetAddr, SDValue OldFP,
4959                                              int SPDiff, const SDLoc &dl) {
4960   if (SPDiff) {
4961     // Calculate the new stack slot for the return address.
4962     MachineFunction &MF = DAG.getMachineFunction();
4963     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4964     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4965     bool isPPC64 = Subtarget.isPPC64();
4966     int SlotSize = isPPC64 ? 8 : 4;
4967     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4968     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4969                                                          NewRetAddrLoc, true);
4970     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4971     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4972     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4973                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4974   }
4975   return Chain;
4976 }
4977 
4978 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4979 /// the position of the argument.
4980 static void
4981 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4982                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4983                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4984   int Offset = ArgOffset + SPDiff;
4985   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4986   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4987   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4988   SDValue FIN = DAG.getFrameIndex(FI, VT);
4989   TailCallArgumentInfo Info;
4990   Info.Arg = Arg;
4991   Info.FrameIdxOp = FIN;
4992   Info.FrameIdx = FI;
4993   TailCallArguments.push_back(Info);
4994 }
4995 
4996 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4997 /// stack slot. Returns the chain as result and the loaded frame pointers in
4998 /// LROpOut/FPOpout. Used when tail calling.
4999 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5000     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5001     SDValue &FPOpOut, const SDLoc &dl) const {
5002   if (SPDiff) {
5003     // Load the LR and FP stack slot for later adjusting.
5004     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5005     LROpOut = getReturnAddrFrameIndex(DAG);
5006     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5007     Chain = SDValue(LROpOut.getNode(), 1);
5008   }
5009   return Chain;
5010 }
5011 
5012 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5013 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5014 /// specified by the specific parameter attribute. The copy will be passed as
5015 /// a byval function parameter.
5016 /// Sometimes what we are copying is the end of a larger object, the part that
5017 /// does not fit in registers.
5018 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5019                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5020                                          SelectionDAG &DAG, const SDLoc &dl) {
5021   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5022   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5023                        Flags.getNonZeroByValAlign(), false, false, false,
5024                        MachinePointerInfo(), MachinePointerInfo());
5025 }
5026 
5027 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5028 /// tail calls.
5029 static void LowerMemOpCallTo(
5030     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5031     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5032     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5033     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5034   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5035   if (!isTailCall) {
5036     if (isVector) {
5037       SDValue StackPtr;
5038       if (isPPC64)
5039         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5040       else
5041         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5042       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5043                            DAG.getConstant(ArgOffset, dl, PtrVT));
5044     }
5045     MemOpChains.push_back(
5046         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5047     // Calculate and remember argument location.
5048   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5049                                   TailCallArguments);
5050 }
5051 
5052 static void
5053 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5054                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5055                 SDValue FPOp,
5056                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5057   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5058   // might overwrite each other in case of tail call optimization.
5059   SmallVector<SDValue, 8> MemOpChains2;
5060   // Do not flag preceding copytoreg stuff together with the following stuff.
5061   InFlag = SDValue();
5062   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5063                                     MemOpChains2, dl);
5064   if (!MemOpChains2.empty())
5065     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5066 
5067   // Store the return address to the appropriate stack slot.
5068   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5069 
5070   // Emit callseq_end just before tailcall node.
5071   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5072                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5073   InFlag = Chain.getValue(1);
5074 }
5075 
5076 // Is this global address that of a function that can be called by name? (as
5077 // opposed to something that must hold a descriptor for an indirect call).
5078 static bool isFunctionGlobalAddress(SDValue Callee) {
5079   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5080     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5081         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5082       return false;
5083 
5084     return G->getGlobal()->getValueType()->isFunctionTy();
5085   }
5086 
5087   return false;
5088 }
5089 
5090 SDValue PPCTargetLowering::LowerCallResult(
5091     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5092     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5093     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5094   SmallVector<CCValAssign, 16> RVLocs;
5095   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5096                     *DAG.getContext());
5097 
5098   CCRetInfo.AnalyzeCallResult(
5099       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5100                ? RetCC_PPC_Cold
5101                : RetCC_PPC);
5102 
5103   // Copy all of the result registers out of their specified physreg.
5104   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5105     CCValAssign &VA = RVLocs[i];
5106     assert(VA.isRegLoc() && "Can only return in registers!");
5107 
5108     SDValue Val;
5109 
5110     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5111       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5112                                       InFlag);
5113       Chain = Lo.getValue(1);
5114       InFlag = Lo.getValue(2);
5115       VA = RVLocs[++i]; // skip ahead to next loc
5116       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5117                                       InFlag);
5118       Chain = Hi.getValue(1);
5119       InFlag = Hi.getValue(2);
5120       if (!Subtarget.isLittleEndian())
5121         std::swap (Lo, Hi);
5122       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5123     } else {
5124       Val = DAG.getCopyFromReg(Chain, dl,
5125                                VA.getLocReg(), VA.getLocVT(), InFlag);
5126       Chain = Val.getValue(1);
5127       InFlag = Val.getValue(2);
5128     }
5129 
5130     switch (VA.getLocInfo()) {
5131     default: llvm_unreachable("Unknown loc info!");
5132     case CCValAssign::Full: break;
5133     case CCValAssign::AExt:
5134       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5135       break;
5136     case CCValAssign::ZExt:
5137       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5138                         DAG.getValueType(VA.getValVT()));
5139       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5140       break;
5141     case CCValAssign::SExt:
5142       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5143                         DAG.getValueType(VA.getValVT()));
5144       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5145       break;
5146     }
5147 
5148     InVals.push_back(Val);
5149   }
5150 
5151   return Chain;
5152 }
5153 
5154 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5155                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5156   // PatchPoint calls are not indirect.
5157   if (isPatchPoint)
5158     return false;
5159 
5160   if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee))
5161     return false;
5162 
5163   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5164   // becuase the immediate function pointer points to a descriptor instead of
5165   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5166   // pointer immediate points to the global entry point, while the BLA would
5167   // need to jump to the local entry point (see rL211174).
5168   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5169       isBLACompatibleAddress(Callee, DAG))
5170     return false;
5171 
5172   return true;
5173 }
5174 
5175 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5176 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5177   return Subtarget.isAIXABI() ||
5178          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5179 }
5180 
5181 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5182                               const Function &Caller,
5183                               const SDValue &Callee,
5184                               const PPCSubtarget &Subtarget,
5185                               const TargetMachine &TM) {
5186   if (CFlags.IsTailCall)
5187     return PPCISD::TC_RETURN;
5188 
5189   // This is a call through a function pointer.
5190   if (CFlags.IsIndirect) {
5191     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5192     // indirect calls. The save of the caller's TOC pointer to the stack will be
5193     // inserted into the DAG as part of call lowering. The restore of the TOC
5194     // pointer is modeled by using a pseudo instruction for the call opcode that
5195     // represents the 2 instruction sequence of an indirect branch and link,
5196     // immediately followed by a load of the TOC pointer from the the stack save
5197     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5198     // as it is not saved or used.
5199     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5200                                                : PPCISD::BCTRL;
5201   }
5202 
5203   if (Subtarget.isUsingPCRelativeCalls()) {
5204     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5205     return PPCISD::CALL_NOTOC;
5206   }
5207 
5208   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5209   // immediately following the call instruction if the caller and callee may
5210   // have different TOC bases. At link time if the linker determines the calls
5211   // may not share a TOC base, the call is redirected to a trampoline inserted
5212   // by the linker. The trampoline will (among other things) save the callers
5213   // TOC pointer at an ABI designated offset in the linkage area and the linker
5214   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5215   // into gpr2.
5216   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5217     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5218                                                   : PPCISD::CALL_NOP;
5219 
5220   return PPCISD::CALL;
5221 }
5222 
5223 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5224                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5225   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5226     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5227       return SDValue(Dest, 0);
5228 
5229   // Returns true if the callee is local, and false otherwise.
5230   auto isLocalCallee = [&]() {
5231     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5232     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5233     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5234 
5235     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5236            !dyn_cast_or_null<GlobalIFunc>(GV);
5237   };
5238 
5239   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5240   // a static relocation model causes some versions of GNU LD (2.17.50, at
5241   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5242   // built with secure-PLT.
5243   bool UsePlt =
5244       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5245       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5246 
5247   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5248     const TargetMachine &TM = Subtarget.getTargetMachine();
5249     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5250     MCSymbolXCOFF *S =
5251         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5252 
5253     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5254     return DAG.getMCSymbol(S, PtrVT);
5255   };
5256 
5257   if (isFunctionGlobalAddress(Callee)) {
5258     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5259 
5260     if (Subtarget.isAIXABI()) {
5261       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5262       return getAIXFuncEntryPointSymbolSDNode(GV);
5263     }
5264     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5265                                       UsePlt ? PPCII::MO_PLT : 0);
5266   }
5267 
5268   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5269     const char *SymName = S->getSymbol();
5270     if (Subtarget.isAIXABI()) {
5271       // If there exists a user-declared function whose name is the same as the
5272       // ExternalSymbol's, then we pick up the user-declared version.
5273       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5274       if (const Function *F =
5275               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5276         return getAIXFuncEntryPointSymbolSDNode(F);
5277 
5278       // On AIX, direct function calls reference the symbol for the function's
5279       // entry point, which is named by prepending a "." before the function's
5280       // C-linkage name. A Qualname is returned here because an external
5281       // function entry point is a csect with XTY_ER property.
5282       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5283         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5284         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5285             (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5286             XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER));
5287         return Sec->getQualNameSymbol();
5288       };
5289 
5290       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5291     }
5292     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5293                                        UsePlt ? PPCII::MO_PLT : 0);
5294   }
5295 
5296   // No transformation needed.
5297   assert(Callee.getNode() && "What no callee?");
5298   return Callee;
5299 }
5300 
5301 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5302   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5303          "Expected a CALLSEQ_STARTSDNode.");
5304 
5305   // The last operand is the chain, except when the node has glue. If the node
5306   // has glue, then the last operand is the glue, and the chain is the second
5307   // last operand.
5308   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5309   if (LastValue.getValueType() != MVT::Glue)
5310     return LastValue;
5311 
5312   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5313 }
5314 
5315 // Creates the node that moves a functions address into the count register
5316 // to prepare for an indirect call instruction.
5317 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5318                                 SDValue &Glue, SDValue &Chain,
5319                                 const SDLoc &dl) {
5320   SDValue MTCTROps[] = {Chain, Callee, Glue};
5321   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5322   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5323                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5324   // The glue is the second value produced.
5325   Glue = Chain.getValue(1);
5326 }
5327 
5328 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5329                                           SDValue &Glue, SDValue &Chain,
5330                                           SDValue CallSeqStart,
5331                                           const CallBase *CB, const SDLoc &dl,
5332                                           bool hasNest,
5333                                           const PPCSubtarget &Subtarget) {
5334   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5335   // entry point, but to the function descriptor (the function entry point
5336   // address is part of the function descriptor though).
5337   // The function descriptor is a three doubleword structure with the
5338   // following fields: function entry point, TOC base address and
5339   // environment pointer.
5340   // Thus for a call through a function pointer, the following actions need
5341   // to be performed:
5342   //   1. Save the TOC of the caller in the TOC save area of its stack
5343   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5344   //   2. Load the address of the function entry point from the function
5345   //      descriptor.
5346   //   3. Load the TOC of the callee from the function descriptor into r2.
5347   //   4. Load the environment pointer from the function descriptor into
5348   //      r11.
5349   //   5. Branch to the function entry point address.
5350   //   6. On return of the callee, the TOC of the caller needs to be
5351   //      restored (this is done in FinishCall()).
5352   //
5353   // The loads are scheduled at the beginning of the call sequence, and the
5354   // register copies are flagged together to ensure that no other
5355   // operations can be scheduled in between. E.g. without flagging the
5356   // copies together, a TOC access in the caller could be scheduled between
5357   // the assignment of the callee TOC and the branch to the callee, which leads
5358   // to incorrect code.
5359 
5360   // Start by loading the function address from the descriptor.
5361   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5362   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5363                       ? (MachineMemOperand::MODereferenceable |
5364                          MachineMemOperand::MOInvariant)
5365                       : MachineMemOperand::MONone;
5366 
5367   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5368 
5369   // Registers used in building the DAG.
5370   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5371   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5372 
5373   // Offsets of descriptor members.
5374   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5375   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5376 
5377   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5378   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5379 
5380   // One load for the functions entry point address.
5381   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5382                                     Alignment, MMOFlags);
5383 
5384   // One for loading the TOC anchor for the module that contains the called
5385   // function.
5386   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5387   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5388   SDValue TOCPtr =
5389       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5390                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5391 
5392   // One for loading the environment pointer.
5393   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5394   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5395   SDValue LoadEnvPtr =
5396       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5397                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5398 
5399 
5400   // Then copy the newly loaded TOC anchor to the TOC pointer.
5401   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5402   Chain = TOCVal.getValue(0);
5403   Glue = TOCVal.getValue(1);
5404 
5405   // If the function call has an explicit 'nest' parameter, it takes the
5406   // place of the environment pointer.
5407   assert((!hasNest || !Subtarget.isAIXABI()) &&
5408          "Nest parameter is not supported on AIX.");
5409   if (!hasNest) {
5410     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5411     Chain = EnvVal.getValue(0);
5412     Glue = EnvVal.getValue(1);
5413   }
5414 
5415   // The rest of the indirect call sequence is the same as the non-descriptor
5416   // DAG.
5417   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5418 }
5419 
5420 static void
5421 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5422                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5423                   SelectionDAG &DAG,
5424                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5425                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5426                   const PPCSubtarget &Subtarget) {
5427   const bool IsPPC64 = Subtarget.isPPC64();
5428   // MVT for a general purpose register.
5429   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5430 
5431   // First operand is always the chain.
5432   Ops.push_back(Chain);
5433 
5434   // If it's a direct call pass the callee as the second operand.
5435   if (!CFlags.IsIndirect)
5436     Ops.push_back(Callee);
5437   else {
5438     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5439 
5440     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5441     // on the stack (this would have been done in `LowerCall_64SVR4` or
5442     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5443     // represents both the indirect branch and a load that restores the TOC
5444     // pointer from the linkage area. The operand for the TOC restore is an add
5445     // of the TOC save offset to the stack pointer. This must be the second
5446     // operand: after the chain input but before any other variadic arguments.
5447     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5448     // saved or used.
5449     if (isTOCSaveRestoreRequired(Subtarget)) {
5450       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5451 
5452       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5453       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5454       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5455       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5456       Ops.push_back(AddTOC);
5457     }
5458 
5459     // Add the register used for the environment pointer.
5460     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5461       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5462                                     RegVT));
5463 
5464 
5465     // Add CTR register as callee so a bctr can be emitted later.
5466     if (CFlags.IsTailCall)
5467       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5468   }
5469 
5470   // If this is a tail call add stack pointer delta.
5471   if (CFlags.IsTailCall)
5472     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5473 
5474   // Add argument registers to the end of the list so that they are known live
5475   // into the call.
5476   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5477     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5478                                   RegsToPass[i].second.getValueType()));
5479 
5480   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5481   // no way to mark dependencies as implicit here.
5482   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5483   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5484        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5485     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5486 
5487   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5488   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5489     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5490 
5491   // Add a register mask operand representing the call-preserved registers.
5492   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5493   const uint32_t *Mask =
5494       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5495   assert(Mask && "Missing call preserved mask for calling convention");
5496   Ops.push_back(DAG.getRegisterMask(Mask));
5497 
5498   // If the glue is valid, it is the last operand.
5499   if (Glue.getNode())
5500     Ops.push_back(Glue);
5501 }
5502 
5503 SDValue PPCTargetLowering::FinishCall(
5504     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5505     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5506     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5507     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5508     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5509 
5510   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5511       Subtarget.isAIXABI())
5512     setUsesTOCBasePtr(DAG);
5513 
5514   unsigned CallOpc =
5515       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5516                     Subtarget, DAG.getTarget());
5517 
5518   if (!CFlags.IsIndirect)
5519     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5520   else if (Subtarget.usesFunctionDescriptors())
5521     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5522                                   dl, CFlags.HasNest, Subtarget);
5523   else
5524     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5525 
5526   // Build the operand list for the call instruction.
5527   SmallVector<SDValue, 8> Ops;
5528   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5529                     SPDiff, Subtarget);
5530 
5531   // Emit tail call.
5532   if (CFlags.IsTailCall) {
5533     // Indirect tail call when using PC Relative calls do not have the same
5534     // constraints.
5535     assert(((Callee.getOpcode() == ISD::Register &&
5536              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5537             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5538             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5539             isa<ConstantSDNode>(Callee) ||
5540             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5541            "Expecting a global address, external symbol, absolute value, "
5542            "register or an indirect tail call when PC Relative calls are "
5543            "used.");
5544     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5545     assert(CallOpc == PPCISD::TC_RETURN &&
5546            "Unexpected call opcode for a tail call.");
5547     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5548     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5549   }
5550 
5551   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5552   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5553   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5554   Glue = Chain.getValue(1);
5555 
5556   // When performing tail call optimization the callee pops its arguments off
5557   // the stack. Account for this here so these bytes can be pushed back on in
5558   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5559   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5560                          getTargetMachine().Options.GuaranteedTailCallOpt)
5561                             ? NumBytes
5562                             : 0;
5563 
5564   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5565                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5566                              Glue, dl);
5567   Glue = Chain.getValue(1);
5568 
5569   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5570                          DAG, InVals);
5571 }
5572 
5573 SDValue
5574 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5575                              SmallVectorImpl<SDValue> &InVals) const {
5576   SelectionDAG &DAG                     = CLI.DAG;
5577   SDLoc &dl                             = CLI.DL;
5578   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5579   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5580   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5581   SDValue Chain                         = CLI.Chain;
5582   SDValue Callee                        = CLI.Callee;
5583   bool &isTailCall                      = CLI.IsTailCall;
5584   CallingConv::ID CallConv              = CLI.CallConv;
5585   bool isVarArg                         = CLI.IsVarArg;
5586   bool isPatchPoint                     = CLI.IsPatchPoint;
5587   const CallBase *CB                    = CLI.CB;
5588 
5589   if (isTailCall) {
5590     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5591       isTailCall = false;
5592     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5593       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5594           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5595     else
5596       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5597                                                      Ins, DAG);
5598     if (isTailCall) {
5599       ++NumTailCalls;
5600       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5601         ++NumSiblingCalls;
5602 
5603       // PC Relative calls no longer guarantee that the callee is a Global
5604       // Address Node. The callee could be an indirect tail call in which
5605       // case the SDValue for the callee could be a load (to load the address
5606       // of a function pointer) or it may be a register copy (to move the
5607       // address of the callee from a function parameter into a virtual
5608       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5609       assert((Subtarget.isUsingPCRelativeCalls() ||
5610               isa<GlobalAddressSDNode>(Callee)) &&
5611              "Callee should be an llvm::Function object.");
5612 
5613       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5614                         << "\nTCO callee: ");
5615       LLVM_DEBUG(Callee.dump());
5616     }
5617   }
5618 
5619   if (!isTailCall && CB && CB->isMustTailCall())
5620     report_fatal_error("failed to perform tail call elimination on a call "
5621                        "site marked musttail");
5622 
5623   // When long calls (i.e. indirect calls) are always used, calls are always
5624   // made via function pointer. If we have a function name, first translate it
5625   // into a pointer.
5626   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5627       !isTailCall)
5628     Callee = LowerGlobalAddress(Callee, DAG);
5629 
5630   CallFlags CFlags(
5631       CallConv, isTailCall, isVarArg, isPatchPoint,
5632       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5633       // hasNest
5634       Subtarget.is64BitELFABI() &&
5635           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5636       CLI.NoMerge);
5637 
5638   if (Subtarget.isAIXABI())
5639     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5640                          InVals, CB);
5641 
5642   assert(Subtarget.isSVR4ABI());
5643   if (Subtarget.isPPC64())
5644     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5645                             InVals, CB);
5646   return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5647                           InVals, CB);
5648 }
5649 
5650 SDValue PPCTargetLowering::LowerCall_32SVR4(
5651     SDValue Chain, SDValue Callee, CallFlags CFlags,
5652     const SmallVectorImpl<ISD::OutputArg> &Outs,
5653     const SmallVectorImpl<SDValue> &OutVals,
5654     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5655     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5656     const CallBase *CB) const {
5657   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5658   // of the 32-bit SVR4 ABI stack frame layout.
5659 
5660   const CallingConv::ID CallConv = CFlags.CallConv;
5661   const bool IsVarArg = CFlags.IsVarArg;
5662   const bool IsTailCall = CFlags.IsTailCall;
5663 
5664   assert((CallConv == CallingConv::C ||
5665           CallConv == CallingConv::Cold ||
5666           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5667 
5668   const Align PtrAlign(4);
5669 
5670   MachineFunction &MF = DAG.getMachineFunction();
5671 
5672   // Mark this function as potentially containing a function that contains a
5673   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5674   // and restoring the callers stack pointer in this functions epilog. This is
5675   // done because by tail calling the called function might overwrite the value
5676   // in this function's (MF) stack pointer stack slot 0(SP).
5677   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5678       CallConv == CallingConv::Fast)
5679     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5680 
5681   // Count how many bytes are to be pushed on the stack, including the linkage
5682   // area, parameter list area and the part of the local variable space which
5683   // contains copies of aggregates which are passed by value.
5684 
5685   // Assign locations to all of the outgoing arguments.
5686   SmallVector<CCValAssign, 16> ArgLocs;
5687   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5688 
5689   // Reserve space for the linkage area on the stack.
5690   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5691                        PtrAlign);
5692   if (useSoftFloat())
5693     CCInfo.PreAnalyzeCallOperands(Outs);
5694 
5695   if (IsVarArg) {
5696     // Handle fixed and variable vector arguments differently.
5697     // Fixed vector arguments go into registers as long as registers are
5698     // available. Variable vector arguments always go into memory.
5699     unsigned NumArgs = Outs.size();
5700 
5701     for (unsigned i = 0; i != NumArgs; ++i) {
5702       MVT ArgVT = Outs[i].VT;
5703       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5704       bool Result;
5705 
5706       if (Outs[i].IsFixed) {
5707         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5708                                CCInfo);
5709       } else {
5710         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5711                                       ArgFlags, CCInfo);
5712       }
5713 
5714       if (Result) {
5715 #ifndef NDEBUG
5716         errs() << "Call operand #" << i << " has unhandled type "
5717              << EVT(ArgVT).getEVTString() << "\n";
5718 #endif
5719         llvm_unreachable(nullptr);
5720       }
5721     }
5722   } else {
5723     // All arguments are treated the same.
5724     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5725   }
5726   CCInfo.clearWasPPCF128();
5727 
5728   // Assign locations to all of the outgoing aggregate by value arguments.
5729   SmallVector<CCValAssign, 16> ByValArgLocs;
5730   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5731 
5732   // Reserve stack space for the allocations in CCInfo.
5733   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5734 
5735   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5736 
5737   // Size of the linkage area, parameter list area and the part of the local
5738   // space variable where copies of aggregates which are passed by value are
5739   // stored.
5740   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5741 
5742   // Calculate by how many bytes the stack has to be adjusted in case of tail
5743   // call optimization.
5744   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5745 
5746   // Adjust the stack pointer for the new arguments...
5747   // These operations are automatically eliminated by the prolog/epilog pass
5748   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5749   SDValue CallSeqStart = Chain;
5750 
5751   // Load the return address and frame pointer so it can be moved somewhere else
5752   // later.
5753   SDValue LROp, FPOp;
5754   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5755 
5756   // Set up a copy of the stack pointer for use loading and storing any
5757   // arguments that may not fit in the registers available for argument
5758   // passing.
5759   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5760 
5761   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5762   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5763   SmallVector<SDValue, 8> MemOpChains;
5764 
5765   bool seenFloatArg = false;
5766   // Walk the register/memloc assignments, inserting copies/loads.
5767   // i - Tracks the index into the list of registers allocated for the call
5768   // RealArgIdx - Tracks the index into the list of actual function arguments
5769   // j - Tracks the index into the list of byval arguments
5770   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5771        i != e;
5772        ++i, ++RealArgIdx) {
5773     CCValAssign &VA = ArgLocs[i];
5774     SDValue Arg = OutVals[RealArgIdx];
5775     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5776 
5777     if (Flags.isByVal()) {
5778       // Argument is an aggregate which is passed by value, thus we need to
5779       // create a copy of it in the local variable space of the current stack
5780       // frame (which is the stack frame of the caller) and pass the address of
5781       // this copy to the callee.
5782       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5783       CCValAssign &ByValVA = ByValArgLocs[j++];
5784       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5785 
5786       // Memory reserved in the local variable space of the callers stack frame.
5787       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5788 
5789       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5790       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5791                            StackPtr, PtrOff);
5792 
5793       // Create a copy of the argument in the local area of the current
5794       // stack frame.
5795       SDValue MemcpyCall =
5796         CreateCopyOfByValArgument(Arg, PtrOff,
5797                                   CallSeqStart.getNode()->getOperand(0),
5798                                   Flags, DAG, dl);
5799 
5800       // This must go outside the CALLSEQ_START..END.
5801       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5802                                                      SDLoc(MemcpyCall));
5803       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5804                              NewCallSeqStart.getNode());
5805       Chain = CallSeqStart = NewCallSeqStart;
5806 
5807       // Pass the address of the aggregate copy on the stack either in a
5808       // physical register or in the parameter list area of the current stack
5809       // frame to the callee.
5810       Arg = PtrOff;
5811     }
5812 
5813     // When useCRBits() is true, there can be i1 arguments.
5814     // It is because getRegisterType(MVT::i1) => MVT::i1,
5815     // and for other integer types getRegisterType() => MVT::i32.
5816     // Extend i1 and ensure callee will get i32.
5817     if (Arg.getValueType() == MVT::i1)
5818       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5819                         dl, MVT::i32, Arg);
5820 
5821     if (VA.isRegLoc()) {
5822       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5823       // Put argument in a physical register.
5824       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5825         bool IsLE = Subtarget.isLittleEndian();
5826         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5827                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5828         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5829         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5830                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5831         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5832                              SVal.getValue(0)));
5833       } else
5834         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5835     } else {
5836       // Put argument in the parameter list area of the current stack frame.
5837       assert(VA.isMemLoc());
5838       unsigned LocMemOffset = VA.getLocMemOffset();
5839 
5840       if (!IsTailCall) {
5841         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5842         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5843                              StackPtr, PtrOff);
5844 
5845         MemOpChains.push_back(
5846             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5847       } else {
5848         // Calculate and remember argument location.
5849         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5850                                  TailCallArguments);
5851       }
5852     }
5853   }
5854 
5855   if (!MemOpChains.empty())
5856     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5857 
5858   // Build a sequence of copy-to-reg nodes chained together with token chain
5859   // and flag operands which copy the outgoing args into the appropriate regs.
5860   SDValue InFlag;
5861   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5862     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5863                              RegsToPass[i].second, InFlag);
5864     InFlag = Chain.getValue(1);
5865   }
5866 
5867   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5868   // registers.
5869   if (IsVarArg) {
5870     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5871     SDValue Ops[] = { Chain, InFlag };
5872 
5873     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5874                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5875 
5876     InFlag = Chain.getValue(1);
5877   }
5878 
5879   if (IsTailCall)
5880     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5881                     TailCallArguments);
5882 
5883   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5884                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5885 }
5886 
5887 // Copy an argument into memory, being careful to do this outside the
5888 // call sequence for the call to which the argument belongs.
5889 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5890     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5891     SelectionDAG &DAG, const SDLoc &dl) const {
5892   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5893                         CallSeqStart.getNode()->getOperand(0),
5894                         Flags, DAG, dl);
5895   // The MEMCPY must go outside the CALLSEQ_START..END.
5896   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5897   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5898                                                  SDLoc(MemcpyCall));
5899   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5900                          NewCallSeqStart.getNode());
5901   return NewCallSeqStart;
5902 }
5903 
5904 SDValue PPCTargetLowering::LowerCall_64SVR4(
5905     SDValue Chain, SDValue Callee, CallFlags CFlags,
5906     const SmallVectorImpl<ISD::OutputArg> &Outs,
5907     const SmallVectorImpl<SDValue> &OutVals,
5908     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5909     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5910     const CallBase *CB) const {
5911   bool isELFv2ABI = Subtarget.isELFv2ABI();
5912   bool isLittleEndian = Subtarget.isLittleEndian();
5913   unsigned NumOps = Outs.size();
5914   bool IsSibCall = false;
5915   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5916 
5917   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5918   unsigned PtrByteSize = 8;
5919 
5920   MachineFunction &MF = DAG.getMachineFunction();
5921 
5922   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5923     IsSibCall = true;
5924 
5925   // Mark this function as potentially containing a function that contains a
5926   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5927   // and restoring the callers stack pointer in this functions epilog. This is
5928   // done because by tail calling the called function might overwrite the value
5929   // in this function's (MF) stack pointer stack slot 0(SP).
5930   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5931     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5932 
5933   assert(!(IsFastCall && CFlags.IsVarArg) &&
5934          "fastcc not supported on varargs functions");
5935 
5936   // Count how many bytes are to be pushed on the stack, including the linkage
5937   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5938   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5939   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5940   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5941   unsigned NumBytes = LinkageSize;
5942   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5943 
5944   static const MCPhysReg GPR[] = {
5945     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5946     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5947   };
5948   static const MCPhysReg VR[] = {
5949     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5950     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5951   };
5952 
5953   const unsigned NumGPRs = array_lengthof(GPR);
5954   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5955   const unsigned NumVRs  = array_lengthof(VR);
5956 
5957   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5958   // can be passed to the callee in registers.
5959   // For the fast calling convention, there is another check below.
5960   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5961   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5962   if (!HasParameterArea) {
5963     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5964     unsigned AvailableFPRs = NumFPRs;
5965     unsigned AvailableVRs = NumVRs;
5966     unsigned NumBytesTmp = NumBytes;
5967     for (unsigned i = 0; i != NumOps; ++i) {
5968       if (Outs[i].Flags.isNest()) continue;
5969       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5970                                  PtrByteSize, LinkageSize, ParamAreaSize,
5971                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
5972         HasParameterArea = true;
5973     }
5974   }
5975 
5976   // When using the fast calling convention, we don't provide backing for
5977   // arguments that will be in registers.
5978   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5979 
5980   // Avoid allocating parameter area for fastcc functions if all the arguments
5981   // can be passed in the registers.
5982   if (IsFastCall)
5983     HasParameterArea = false;
5984 
5985   // Add up all the space actually used.
5986   for (unsigned i = 0; i != NumOps; ++i) {
5987     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5988     EVT ArgVT = Outs[i].VT;
5989     EVT OrigVT = Outs[i].ArgVT;
5990 
5991     if (Flags.isNest())
5992       continue;
5993 
5994     if (IsFastCall) {
5995       if (Flags.isByVal()) {
5996         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5997         if (NumGPRsUsed > NumGPRs)
5998           HasParameterArea = true;
5999       } else {
6000         switch (ArgVT.getSimpleVT().SimpleTy) {
6001         default: llvm_unreachable("Unexpected ValueType for argument!");
6002         case MVT::i1:
6003         case MVT::i32:
6004         case MVT::i64:
6005           if (++NumGPRsUsed <= NumGPRs)
6006             continue;
6007           break;
6008         case MVT::v4i32:
6009         case MVT::v8i16:
6010         case MVT::v16i8:
6011         case MVT::v2f64:
6012         case MVT::v2i64:
6013         case MVT::v1i128:
6014         case MVT::f128:
6015           if (++NumVRsUsed <= NumVRs)
6016             continue;
6017           break;
6018         case MVT::v4f32:
6019           if (++NumVRsUsed <= NumVRs)
6020             continue;
6021           break;
6022         case MVT::f32:
6023         case MVT::f64:
6024           if (++NumFPRsUsed <= NumFPRs)
6025             continue;
6026           break;
6027         }
6028         HasParameterArea = true;
6029       }
6030     }
6031 
6032     /* Respect alignment of argument on the stack.  */
6033     auto Alignement =
6034         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6035     NumBytes = alignTo(NumBytes, Alignement);
6036 
6037     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6038     if (Flags.isInConsecutiveRegsLast())
6039       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6040   }
6041 
6042   unsigned NumBytesActuallyUsed = NumBytes;
6043 
6044   // In the old ELFv1 ABI,
6045   // the prolog code of the callee may store up to 8 GPR argument registers to
6046   // the stack, allowing va_start to index over them in memory if its varargs.
6047   // Because we cannot tell if this is needed on the caller side, we have to
6048   // conservatively assume that it is needed.  As such, make sure we have at
6049   // least enough stack space for the caller to store the 8 GPRs.
6050   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6051   // really requires memory operands, e.g. a vararg function.
6052   if (HasParameterArea)
6053     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6054   else
6055     NumBytes = LinkageSize;
6056 
6057   // Tail call needs the stack to be aligned.
6058   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6059     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6060 
6061   int SPDiff = 0;
6062 
6063   // Calculate by how many bytes the stack has to be adjusted in case of tail
6064   // call optimization.
6065   if (!IsSibCall)
6066     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6067 
6068   // To protect arguments on the stack from being clobbered in a tail call,
6069   // force all the loads to happen before doing any other lowering.
6070   if (CFlags.IsTailCall)
6071     Chain = DAG.getStackArgumentTokenFactor(Chain);
6072 
6073   // Adjust the stack pointer for the new arguments...
6074   // These operations are automatically eliminated by the prolog/epilog pass
6075   if (!IsSibCall)
6076     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6077   SDValue CallSeqStart = Chain;
6078 
6079   // Load the return address and frame pointer so it can be move somewhere else
6080   // later.
6081   SDValue LROp, FPOp;
6082   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6083 
6084   // Set up a copy of the stack pointer for use loading and storing any
6085   // arguments that may not fit in the registers available for argument
6086   // passing.
6087   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6088 
6089   // Figure out which arguments are going to go in registers, and which in
6090   // memory.  Also, if this is a vararg function, floating point operations
6091   // must be stored to our stack, and loaded into integer regs as well, if
6092   // any integer regs are available for argument passing.
6093   unsigned ArgOffset = LinkageSize;
6094 
6095   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6096   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6097 
6098   SmallVector<SDValue, 8> MemOpChains;
6099   for (unsigned i = 0; i != NumOps; ++i) {
6100     SDValue Arg = OutVals[i];
6101     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6102     EVT ArgVT = Outs[i].VT;
6103     EVT OrigVT = Outs[i].ArgVT;
6104 
6105     // PtrOff will be used to store the current argument to the stack if a
6106     // register cannot be found for it.
6107     SDValue PtrOff;
6108 
6109     // We re-align the argument offset for each argument, except when using the
6110     // fast calling convention, when we need to make sure we do that only when
6111     // we'll actually use a stack slot.
6112     auto ComputePtrOff = [&]() {
6113       /* Respect alignment of argument on the stack.  */
6114       auto Alignment =
6115           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6116       ArgOffset = alignTo(ArgOffset, Alignment);
6117 
6118       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6119 
6120       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6121     };
6122 
6123     if (!IsFastCall) {
6124       ComputePtrOff();
6125 
6126       /* Compute GPR index associated with argument offset.  */
6127       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6128       GPR_idx = std::min(GPR_idx, NumGPRs);
6129     }
6130 
6131     // Promote integers to 64-bit values.
6132     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6133       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6134       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6135       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6136     }
6137 
6138     // FIXME memcpy is used way more than necessary.  Correctness first.
6139     // Note: "by value" is code for passing a structure by value, not
6140     // basic types.
6141     if (Flags.isByVal()) {
6142       // Note: Size includes alignment padding, so
6143       //   struct x { short a; char b; }
6144       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6145       // These are the proper values we need for right-justifying the
6146       // aggregate in a parameter register.
6147       unsigned Size = Flags.getByValSize();
6148 
6149       // An empty aggregate parameter takes up no storage and no
6150       // registers.
6151       if (Size == 0)
6152         continue;
6153 
6154       if (IsFastCall)
6155         ComputePtrOff();
6156 
6157       // All aggregates smaller than 8 bytes must be passed right-justified.
6158       if (Size==1 || Size==2 || Size==4) {
6159         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6160         if (GPR_idx != NumGPRs) {
6161           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6162                                         MachinePointerInfo(), VT);
6163           MemOpChains.push_back(Load.getValue(1));
6164           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6165 
6166           ArgOffset += PtrByteSize;
6167           continue;
6168         }
6169       }
6170 
6171       if (GPR_idx == NumGPRs && Size < 8) {
6172         SDValue AddPtr = PtrOff;
6173         if (!isLittleEndian) {
6174           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6175                                           PtrOff.getValueType());
6176           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6177         }
6178         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6179                                                           CallSeqStart,
6180                                                           Flags, DAG, dl);
6181         ArgOffset += PtrByteSize;
6182         continue;
6183       }
6184       // Copy entire object into memory.  There are cases where gcc-generated
6185       // code assumes it is there, even if it could be put entirely into
6186       // registers.  (This is not what the doc says.)
6187 
6188       // FIXME: The above statement is likely due to a misunderstanding of the
6189       // documents.  All arguments must be copied into the parameter area BY
6190       // THE CALLEE in the event that the callee takes the address of any
6191       // formal argument.  That has not yet been implemented.  However, it is
6192       // reasonable to use the stack area as a staging area for the register
6193       // load.
6194 
6195       // Skip this for small aggregates, as we will use the same slot for a
6196       // right-justified copy, below.
6197       if (Size >= 8)
6198         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6199                                                           CallSeqStart,
6200                                                           Flags, DAG, dl);
6201 
6202       // When a register is available, pass a small aggregate right-justified.
6203       if (Size < 8 && GPR_idx != NumGPRs) {
6204         // The easiest way to get this right-justified in a register
6205         // is to copy the structure into the rightmost portion of a
6206         // local variable slot, then load the whole slot into the
6207         // register.
6208         // FIXME: The memcpy seems to produce pretty awful code for
6209         // small aggregates, particularly for packed ones.
6210         // FIXME: It would be preferable to use the slot in the
6211         // parameter save area instead of a new local variable.
6212         SDValue AddPtr = PtrOff;
6213         if (!isLittleEndian) {
6214           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6215           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6216         }
6217         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6218                                                           CallSeqStart,
6219                                                           Flags, DAG, dl);
6220 
6221         // Load the slot into the register.
6222         SDValue Load =
6223             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6224         MemOpChains.push_back(Load.getValue(1));
6225         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6226 
6227         // Done with this argument.
6228         ArgOffset += PtrByteSize;
6229         continue;
6230       }
6231 
6232       // For aggregates larger than PtrByteSize, copy the pieces of the
6233       // object that fit into registers from the parameter save area.
6234       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6235         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6236         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6237         if (GPR_idx != NumGPRs) {
6238           SDValue Load =
6239               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6240           MemOpChains.push_back(Load.getValue(1));
6241           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6242           ArgOffset += PtrByteSize;
6243         } else {
6244           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6245           break;
6246         }
6247       }
6248       continue;
6249     }
6250 
6251     switch (Arg.getSimpleValueType().SimpleTy) {
6252     default: llvm_unreachable("Unexpected ValueType for argument!");
6253     case MVT::i1:
6254     case MVT::i32:
6255     case MVT::i64:
6256       if (Flags.isNest()) {
6257         // The 'nest' parameter, if any, is passed in R11.
6258         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6259         break;
6260       }
6261 
6262       // These can be scalar arguments or elements of an integer array type
6263       // passed directly.  Clang may use those instead of "byval" aggregate
6264       // types to avoid forcing arguments to memory unnecessarily.
6265       if (GPR_idx != NumGPRs) {
6266         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6267       } else {
6268         if (IsFastCall)
6269           ComputePtrOff();
6270 
6271         assert(HasParameterArea &&
6272                "Parameter area must exist to pass an argument in memory.");
6273         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6274                          true, CFlags.IsTailCall, false, MemOpChains,
6275                          TailCallArguments, dl);
6276         if (IsFastCall)
6277           ArgOffset += PtrByteSize;
6278       }
6279       if (!IsFastCall)
6280         ArgOffset += PtrByteSize;
6281       break;
6282     case MVT::f32:
6283     case MVT::f64: {
6284       // These can be scalar arguments or elements of a float array type
6285       // passed directly.  The latter are used to implement ELFv2 homogenous
6286       // float aggregates.
6287 
6288       // Named arguments go into FPRs first, and once they overflow, the
6289       // remaining arguments go into GPRs and then the parameter save area.
6290       // Unnamed arguments for vararg functions always go to GPRs and
6291       // then the parameter save area.  For now, put all arguments to vararg
6292       // routines always in both locations (FPR *and* GPR or stack slot).
6293       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6294       bool NeededLoad = false;
6295 
6296       // First load the argument into the next available FPR.
6297       if (FPR_idx != NumFPRs)
6298         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6299 
6300       // Next, load the argument into GPR or stack slot if needed.
6301       if (!NeedGPROrStack)
6302         ;
6303       else if (GPR_idx != NumGPRs && !IsFastCall) {
6304         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6305         // once we support fp <-> gpr moves.
6306 
6307         // In the non-vararg case, this can only ever happen in the
6308         // presence of f32 array types, since otherwise we never run
6309         // out of FPRs before running out of GPRs.
6310         SDValue ArgVal;
6311 
6312         // Double values are always passed in a single GPR.
6313         if (Arg.getValueType() != MVT::f32) {
6314           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6315 
6316         // Non-array float values are extended and passed in a GPR.
6317         } else if (!Flags.isInConsecutiveRegs()) {
6318           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6319           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6320 
6321         // If we have an array of floats, we collect every odd element
6322         // together with its predecessor into one GPR.
6323         } else if (ArgOffset % PtrByteSize != 0) {
6324           SDValue Lo, Hi;
6325           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6326           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6327           if (!isLittleEndian)
6328             std::swap(Lo, Hi);
6329           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6330 
6331         // The final element, if even, goes into the first half of a GPR.
6332         } else if (Flags.isInConsecutiveRegsLast()) {
6333           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6334           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6335           if (!isLittleEndian)
6336             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6337                                  DAG.getConstant(32, dl, MVT::i32));
6338 
6339         // Non-final even elements are skipped; they will be handled
6340         // together the with subsequent argument on the next go-around.
6341         } else
6342           ArgVal = SDValue();
6343 
6344         if (ArgVal.getNode())
6345           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6346       } else {
6347         if (IsFastCall)
6348           ComputePtrOff();
6349 
6350         // Single-precision floating-point values are mapped to the
6351         // second (rightmost) word of the stack doubleword.
6352         if (Arg.getValueType() == MVT::f32 &&
6353             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6354           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6355           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6356         }
6357 
6358         assert(HasParameterArea &&
6359                "Parameter area must exist to pass an argument in memory.");
6360         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6361                          true, CFlags.IsTailCall, false, MemOpChains,
6362                          TailCallArguments, dl);
6363 
6364         NeededLoad = true;
6365       }
6366       // When passing an array of floats, the array occupies consecutive
6367       // space in the argument area; only round up to the next doubleword
6368       // at the end of the array.  Otherwise, each float takes 8 bytes.
6369       if (!IsFastCall || NeededLoad) {
6370         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6371                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6372         if (Flags.isInConsecutiveRegsLast())
6373           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6374       }
6375       break;
6376     }
6377     case MVT::v4f32:
6378     case MVT::v4i32:
6379     case MVT::v8i16:
6380     case MVT::v16i8:
6381     case MVT::v2f64:
6382     case MVT::v2i64:
6383     case MVT::v1i128:
6384     case MVT::f128:
6385       // These can be scalar arguments or elements of a vector array type
6386       // passed directly.  The latter are used to implement ELFv2 homogenous
6387       // vector aggregates.
6388 
6389       // For a varargs call, named arguments go into VRs or on the stack as
6390       // usual; unnamed arguments always go to the stack or the corresponding
6391       // GPRs when within range.  For now, we always put the value in both
6392       // locations (or even all three).
6393       if (CFlags.IsVarArg) {
6394         assert(HasParameterArea &&
6395                "Parameter area must exist if we have a varargs call.");
6396         // We could elide this store in the case where the object fits
6397         // entirely in R registers.  Maybe later.
6398         SDValue Store =
6399             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6400         MemOpChains.push_back(Store);
6401         if (VR_idx != NumVRs) {
6402           SDValue Load =
6403               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6404           MemOpChains.push_back(Load.getValue(1));
6405           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6406         }
6407         ArgOffset += 16;
6408         for (unsigned i=0; i<16; i+=PtrByteSize) {
6409           if (GPR_idx == NumGPRs)
6410             break;
6411           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6412                                    DAG.getConstant(i, dl, PtrVT));
6413           SDValue Load =
6414               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6415           MemOpChains.push_back(Load.getValue(1));
6416           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6417         }
6418         break;
6419       }
6420 
6421       // Non-varargs Altivec params go into VRs or on the stack.
6422       if (VR_idx != NumVRs) {
6423         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6424       } else {
6425         if (IsFastCall)
6426           ComputePtrOff();
6427 
6428         assert(HasParameterArea &&
6429                "Parameter area must exist to pass an argument in memory.");
6430         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6431                          true, CFlags.IsTailCall, true, MemOpChains,
6432                          TailCallArguments, dl);
6433         if (IsFastCall)
6434           ArgOffset += 16;
6435       }
6436 
6437       if (!IsFastCall)
6438         ArgOffset += 16;
6439       break;
6440     }
6441   }
6442 
6443   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6444          "mismatch in size of parameter area");
6445   (void)NumBytesActuallyUsed;
6446 
6447   if (!MemOpChains.empty())
6448     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6449 
6450   // Check if this is an indirect call (MTCTR/BCTRL).
6451   // See prepareDescriptorIndirectCall and buildCallOperands for more
6452   // information about calls through function pointers in the 64-bit SVR4 ABI.
6453   if (CFlags.IsIndirect) {
6454     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6455     // caller in the TOC save area.
6456     if (isTOCSaveRestoreRequired(Subtarget)) {
6457       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6458       // Load r2 into a virtual register and store it to the TOC save area.
6459       setUsesTOCBasePtr(DAG);
6460       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6461       // TOC save area offset.
6462       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6463       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6464       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6465       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6466                            MachinePointerInfo::getStack(
6467                                DAG.getMachineFunction(), TOCSaveOffset));
6468     }
6469     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6470     // This does not mean the MTCTR instruction must use R12; it's easier
6471     // to model this as an extra parameter, so do that.
6472     if (isELFv2ABI && !CFlags.IsPatchPoint)
6473       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6474   }
6475 
6476   // Build a sequence of copy-to-reg nodes chained together with token chain
6477   // and flag operands which copy the outgoing args into the appropriate regs.
6478   SDValue InFlag;
6479   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6480     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6481                              RegsToPass[i].second, InFlag);
6482     InFlag = Chain.getValue(1);
6483   }
6484 
6485   if (CFlags.IsTailCall && !IsSibCall)
6486     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6487                     TailCallArguments);
6488 
6489   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6490                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6491 }
6492 
6493 // Returns true when the shadow of a general purpose argument register
6494 // in the parameter save area is aligned to at least 'RequiredAlign'.
6495 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
6496   assert(RequiredAlign.value() <= 16 &&
6497          "Required alignment greater than stack alignment.");
6498   switch (Reg) {
6499   default:
6500     report_fatal_error("called on invalid register.");
6501   case PPC::R5:
6502   case PPC::R9:
6503   case PPC::X3:
6504   case PPC::X5:
6505   case PPC::X7:
6506   case PPC::X9:
6507     // These registers are 16 byte aligned which is the most strict aligment
6508     // we can support.
6509     return true;
6510   case PPC::R3:
6511   case PPC::R7:
6512   case PPC::X4:
6513   case PPC::X6:
6514   case PPC::X8:
6515   case PPC::X10:
6516     // The shadow of these registers in the PSA is 8 byte aligned.
6517     return RequiredAlign <= 8;
6518   case PPC::R4:
6519   case PPC::R6:
6520   case PPC::R8:
6521   case PPC::R10:
6522     return RequiredAlign <= 4;
6523   }
6524 }
6525 
6526 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6527                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6528                    CCState &S) {
6529   AIXCCState &State = static_cast<AIXCCState &>(S);
6530   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6531       State.getMachineFunction().getSubtarget());
6532   const bool IsPPC64 = Subtarget.isPPC64();
6533   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6534   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6535 
6536   if (ValVT == MVT::f128)
6537     report_fatal_error("f128 is unimplemented on AIX.");
6538 
6539   if (ArgFlags.isNest())
6540     report_fatal_error("Nest arguments are unimplemented.");
6541 
6542   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6543                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6544                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6545   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6546                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6547                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6548 
6549   static const MCPhysReg VR[] = {// Vector registers.
6550                                  PPC::V2,  PPC::V3,  PPC::V4,  PPC::V5,
6551                                  PPC::V6,  PPC::V7,  PPC::V8,  PPC::V9,
6552                                  PPC::V10, PPC::V11, PPC::V12, PPC::V13};
6553 
6554   if (ArgFlags.isByVal()) {
6555     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6556       report_fatal_error("Pass-by-value arguments with alignment greater than "
6557                          "register width are not supported.");
6558 
6559     const unsigned ByValSize = ArgFlags.getByValSize();
6560 
6561     // An empty aggregate parameter takes up no storage and no registers,
6562     // but needs a MemLoc for a stack slot for the formal arguments side.
6563     if (ByValSize == 0) {
6564       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6565                                        State.getNextStackOffset(), RegVT,
6566                                        LocInfo));
6567       return false;
6568     }
6569 
6570     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6571     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6572     for (const unsigned E = Offset + StackSize; Offset < E;
6573          Offset += PtrAlign.value()) {
6574       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6575         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6576       else {
6577         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6578                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6579                                          LocInfo));
6580         break;
6581       }
6582     }
6583     return false;
6584   }
6585 
6586   // Arguments always reserve parameter save area.
6587   switch (ValVT.SimpleTy) {
6588   default:
6589     report_fatal_error("Unhandled value type for argument.");
6590   case MVT::i64:
6591     // i64 arguments should have been split to i32 for PPC32.
6592     assert(IsPPC64 && "PPC32 should have split i64 values.");
6593     LLVM_FALLTHROUGH;
6594   case MVT::i1:
6595   case MVT::i32: {
6596     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6597     // AIX integer arguments are always passed in register width.
6598     if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6599       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6600                                   : CCValAssign::LocInfo::ZExt;
6601     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6602       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6603     else
6604       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6605 
6606     return false;
6607   }
6608   case MVT::f32:
6609   case MVT::f64: {
6610     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6611     const unsigned StoreSize = LocVT.getStoreSize();
6612     // Floats are always 4-byte aligned in the PSA on AIX.
6613     // This includes f64 in 64-bit mode for ABI compatibility.
6614     const unsigned Offset =
6615         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6616     unsigned FReg = State.AllocateReg(FPR);
6617     if (FReg)
6618       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6619 
6620     // Reserve and initialize GPRs or initialize the PSA as required.
6621     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6622       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6623         assert(FReg && "An FPR should be available when a GPR is reserved.");
6624         if (State.isVarArg()) {
6625           // Successfully reserved GPRs are only initialized for vararg calls.
6626           // Custom handling is required for:
6627           //   f64 in PPC32 needs to be split into 2 GPRs.
6628           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6629           State.addLoc(
6630               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6631         }
6632       } else {
6633         // If there are insufficient GPRs, the PSA needs to be initialized.
6634         // Initialization occurs even if an FPR was initialized for
6635         // compatibility with the AIX XL compiler. The full memory for the
6636         // argument will be initialized even if a prior word is saved in GPR.
6637         // A custom memLoc is used when the argument also passes in FPR so
6638         // that the callee handling can skip over it easily.
6639         State.addLoc(
6640             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6641                                              LocInfo)
6642                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6643         break;
6644       }
6645     }
6646 
6647     return false;
6648   }
6649   case MVT::v4f32:
6650   case MVT::v4i32:
6651   case MVT::v8i16:
6652   case MVT::v16i8:
6653   case MVT::v2i64:
6654   case MVT::v2f64:
6655   case MVT::v1i128: {
6656     const unsigned VecSize = 16;
6657     const Align VecAlign(VecSize);
6658 
6659     if (!State.isVarArg()) {
6660       // If there are vector registers remaining we don't consume any stack
6661       // space.
6662       if (unsigned VReg = State.AllocateReg(VR)) {
6663         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6664         return false;
6665       }
6666       // Vectors passed on the stack do not shadow GPRs or FPRs even though they
6667       // might be allocated in the portion of the PSA that is shadowed by the
6668       // GPRs.
6669       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6670       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6671       return false;
6672     }
6673 
6674     const unsigned PtrSize = IsPPC64 ? 8 : 4;
6675     ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
6676 
6677     unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
6678     // Burn any underaligned registers and their shadowed stack space until
6679     // we reach the required alignment.
6680     while (NextRegIndex != GPRs.size() &&
6681            !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
6682       // Shadow allocate register and its stack shadow.
6683       unsigned Reg = State.AllocateReg(GPRs);
6684       State.AllocateStack(PtrSize, PtrAlign);
6685       assert(Reg && "Allocating register unexpectedly failed.");
6686       (void)Reg;
6687       NextRegIndex = State.getFirstUnallocated(GPRs);
6688     }
6689 
6690     // Vectors that are passed as fixed arguments are handled differently.
6691     // They are passed in VRs if any are available (unlike arguments passed
6692     // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
6693     // functions)
6694     if (State.isFixed(ValNo)) {
6695       if (unsigned VReg = State.AllocateReg(VR)) {
6696         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6697         // Shadow allocate GPRs and stack space even though we pass in a VR.
6698         for (unsigned I = 0; I != VecSize; I += PtrSize)
6699           State.AllocateReg(GPRs);
6700         State.AllocateStack(VecSize, VecAlign);
6701         return false;
6702       }
6703       // No vector registers remain so pass on the stack.
6704       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6705       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6706       return false;
6707     }
6708 
6709     // If all GPRS are consumed then we pass the argument fully on the stack.
6710     if (NextRegIndex == GPRs.size()) {
6711       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6712       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6713       return false;
6714     }
6715 
6716     // Corner case for 32-bit codegen. We have 2 registers to pass the first
6717     // half of the argument, and then need to pass the remaining half on the
6718     // stack.
6719     if (GPRs[NextRegIndex] == PPC::R9) {
6720       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6721       State.addLoc(
6722           CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6723 
6724       const unsigned FirstReg = State.AllocateReg(PPC::R9);
6725       const unsigned SecondReg = State.AllocateReg(PPC::R10);
6726       assert(FirstReg && SecondReg &&
6727              "Allocating R9 or R10 unexpectedly failed.");
6728       State.addLoc(
6729           CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
6730       State.addLoc(
6731           CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
6732       return false;
6733     }
6734 
6735     // We have enough GPRs to fully pass the vector argument, and we have
6736     // already consumed any underaligned registers. Start with the custom
6737     // MemLoc and then the custom RegLocs.
6738     const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6739     State.addLoc(
6740         CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6741     for (unsigned I = 0; I != VecSize; I += PtrSize) {
6742       const unsigned Reg = State.AllocateReg(GPRs);
6743       assert(Reg && "Failed to allocated register for vararg vector argument");
6744       State.addLoc(
6745           CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6746     }
6747     return false;
6748   }
6749   }
6750   return true;
6751 }
6752 
6753 // So far, this function is only used by LowerFormalArguments_AIX()
6754 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6755                                                     bool IsPPC64,
6756                                                     bool HasP8Vector,
6757                                                     bool HasVSX) {
6758   assert((IsPPC64 || SVT != MVT::i64) &&
6759          "i64 should have been split for 32-bit codegen.");
6760 
6761   switch (SVT) {
6762   default:
6763     report_fatal_error("Unexpected value type for formal argument");
6764   case MVT::i1:
6765   case MVT::i32:
6766   case MVT::i64:
6767     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6768   case MVT::f32:
6769     return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass;
6770   case MVT::f64:
6771     return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass;
6772   case MVT::v4f32:
6773   case MVT::v4i32:
6774   case MVT::v8i16:
6775   case MVT::v16i8:
6776   case MVT::v2i64:
6777   case MVT::v2f64:
6778   case MVT::v1i128:
6779     return &PPC::VRRCRegClass;
6780   }
6781 }
6782 
6783 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6784                                         SelectionDAG &DAG, SDValue ArgValue,
6785                                         MVT LocVT, const SDLoc &dl) {
6786   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6787   assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
6788 
6789   if (Flags.isSExt())
6790     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6791                            DAG.getValueType(ValVT));
6792   else if (Flags.isZExt())
6793     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6794                            DAG.getValueType(ValVT));
6795 
6796   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6797 }
6798 
6799 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6800   const unsigned LASize = FL->getLinkageSize();
6801 
6802   if (PPC::GPRCRegClass.contains(Reg)) {
6803     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6804            "Reg must be a valid argument register!");
6805     return LASize + 4 * (Reg - PPC::R3);
6806   }
6807 
6808   if (PPC::G8RCRegClass.contains(Reg)) {
6809     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6810            "Reg must be a valid argument register!");
6811     return LASize + 8 * (Reg - PPC::X3);
6812   }
6813 
6814   llvm_unreachable("Only general purpose registers expected.");
6815 }
6816 
6817 //   AIX ABI Stack Frame Layout:
6818 //
6819 //   Low Memory +--------------------------------------------+
6820 //   SP   +---> | Back chain                                 | ---+
6821 //        |     +--------------------------------------------+    |
6822 //        |     | Saved Condition Register                   |    |
6823 //        |     +--------------------------------------------+    |
6824 //        |     | Saved Linkage Register                     |    |
6825 //        |     +--------------------------------------------+    | Linkage Area
6826 //        |     | Reserved for compilers                     |    |
6827 //        |     +--------------------------------------------+    |
6828 //        |     | Reserved for binders                       |    |
6829 //        |     +--------------------------------------------+    |
6830 //        |     | Saved TOC pointer                          | ---+
6831 //        |     +--------------------------------------------+
6832 //        |     | Parameter save area                        |
6833 //        |     +--------------------------------------------+
6834 //        |     | Alloca space                               |
6835 //        |     +--------------------------------------------+
6836 //        |     | Local variable space                       |
6837 //        |     +--------------------------------------------+
6838 //        |     | Float/int conversion temporary             |
6839 //        |     +--------------------------------------------+
6840 //        |     | Save area for AltiVec registers            |
6841 //        |     +--------------------------------------------+
6842 //        |     | AltiVec alignment padding                  |
6843 //        |     +--------------------------------------------+
6844 //        |     | Save area for VRSAVE register              |
6845 //        |     +--------------------------------------------+
6846 //        |     | Save area for General Purpose registers    |
6847 //        |     +--------------------------------------------+
6848 //        |     | Save area for Floating Point registers     |
6849 //        |     +--------------------------------------------+
6850 //        +---- | Back chain                                 |
6851 // High Memory  +--------------------------------------------+
6852 //
6853 //  Specifications:
6854 //  AIX 7.2 Assembler Language Reference
6855 //  Subroutine linkage convention
6856 
6857 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6858     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6859     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6860     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6861 
6862   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6863           CallConv == CallingConv::Fast) &&
6864          "Unexpected calling convention!");
6865 
6866   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6867     report_fatal_error("Tail call support is unimplemented on AIX.");
6868 
6869   if (useSoftFloat())
6870     report_fatal_error("Soft float support is unimplemented on AIX.");
6871 
6872   const PPCSubtarget &Subtarget =
6873       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6874 
6875   const bool IsPPC64 = Subtarget.isPPC64();
6876   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6877 
6878   // Assign locations to all of the incoming arguments.
6879   SmallVector<CCValAssign, 16> ArgLocs;
6880   MachineFunction &MF = DAG.getMachineFunction();
6881   MachineFrameInfo &MFI = MF.getFrameInfo();
6882   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6883   AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6884 
6885   const EVT PtrVT = getPointerTy(MF.getDataLayout());
6886   // Reserve space for the linkage area on the stack.
6887   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6888   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
6889   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6890 
6891   SmallVector<SDValue, 8> MemOps;
6892 
6893   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
6894     CCValAssign &VA = ArgLocs[I++];
6895     MVT LocVT = VA.getLocVT();
6896     MVT ValVT = VA.getValVT();
6897     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
6898     // For compatibility with the AIX XL compiler, the float args in the
6899     // parameter save area are initialized even if the argument is available
6900     // in register.  The caller is required to initialize both the register
6901     // and memory, however, the callee can choose to expect it in either.
6902     // The memloc is dismissed here because the argument is retrieved from
6903     // the register.
6904     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
6905       continue;
6906 
6907     auto HandleMemLoc = [&]() {
6908       const unsigned LocSize = LocVT.getStoreSize();
6909       const unsigned ValSize = ValVT.getStoreSize();
6910       assert((ValSize <= LocSize) &&
6911              "Object size is larger than size of MemLoc");
6912       int CurArgOffset = VA.getLocMemOffset();
6913       // Objects are right-justified because AIX is big-endian.
6914       if (LocSize > ValSize)
6915         CurArgOffset += LocSize - ValSize;
6916       // Potential tail calls could cause overwriting of argument stack slots.
6917       const bool IsImmutable =
6918           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
6919             (CallConv == CallingConv::Fast));
6920       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
6921       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6922       SDValue ArgValue =
6923           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
6924       InVals.push_back(ArgValue);
6925     };
6926 
6927     // Vector arguments to VaArg functions are passed both on the stack, and
6928     // in any available GPRs. Load the value from the stack and add the GPRs
6929     // as live ins.
6930     if (VA.isMemLoc() && VA.needsCustom()) {
6931       assert(ValVT.isVector() && "Unexpected Custom MemLoc type.");
6932       assert(isVarArg && "Only use custom memloc for vararg.");
6933       // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
6934       // matching custom RegLocs.
6935       const unsigned OriginalValNo = VA.getValNo();
6936       (void)OriginalValNo;
6937 
6938       auto HandleCustomVecRegLoc = [&]() {
6939         assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
6940                "Missing custom RegLoc.");
6941         VA = ArgLocs[I++];
6942         assert(VA.getValVT().isVector() &&
6943                "Unexpected Val type for custom RegLoc.");
6944         assert(VA.getValNo() == OriginalValNo &&
6945                "ValNo mismatch between custom MemLoc and RegLoc.");
6946         MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy;
6947         MF.addLiveIn(VA.getLocReg(),
6948                      getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
6949                                        Subtarget.hasVSX()));
6950       };
6951 
6952       HandleMemLoc();
6953       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
6954       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
6955       // R10.
6956       HandleCustomVecRegLoc();
6957       HandleCustomVecRegLoc();
6958 
6959       // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
6960       // we passed the vector in R5, R6, R7 and R8.
6961       if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
6962         assert(!IsPPC64 &&
6963                "Only 2 custom RegLocs expected for 64-bit codegen.");
6964         HandleCustomVecRegLoc();
6965         HandleCustomVecRegLoc();
6966       }
6967 
6968       continue;
6969     }
6970 
6971     if (VA.isRegLoc()) {
6972       if (VA.getValVT().isScalarInteger())
6973         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
6974       else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) {
6975         switch (VA.getValVT().SimpleTy) {
6976         default:
6977           report_fatal_error("Unhandled value type for argument.");
6978         case MVT::f32:
6979           FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint);
6980           break;
6981         case MVT::f64:
6982           FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint);
6983           break;
6984         }
6985       } else if (VA.getValVT().isVector()) {
6986         switch (VA.getValVT().SimpleTy) {
6987         default:
6988           report_fatal_error("Unhandled value type for argument.");
6989         case MVT::v16i8:
6990           FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar);
6991           break;
6992         case MVT::v8i16:
6993           FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort);
6994           break;
6995         case MVT::v4i32:
6996         case MVT::v2i64:
6997         case MVT::v1i128:
6998           FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt);
6999           break;
7000         case MVT::v4f32:
7001         case MVT::v2f64:
7002           FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat);
7003           break;
7004         }
7005       }
7006     }
7007 
7008     if (Flags.isByVal() && VA.isMemLoc()) {
7009       const unsigned Size =
7010           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7011                   PtrByteSize);
7012       const int FI = MF.getFrameInfo().CreateFixedObject(
7013           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7014           /* IsAliased */ true);
7015       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7016       InVals.push_back(FIN);
7017 
7018       continue;
7019     }
7020 
7021     if (Flags.isByVal()) {
7022       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7023 
7024       const MCPhysReg ArgReg = VA.getLocReg();
7025       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7026 
7027       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7028         report_fatal_error("Over aligned byvals not supported yet.");
7029 
7030       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7031       const int FI = MF.getFrameInfo().CreateFixedObject(
7032           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7033           /* IsAliased */ true);
7034       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7035       InVals.push_back(FIN);
7036 
7037       // Add live ins for all the RegLocs for the same ByVal.
7038       const TargetRegisterClass *RegClass =
7039           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7040 
7041       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7042                                                unsigned Offset) {
7043         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7044         // Since the callers side has left justified the aggregate in the
7045         // register, we can simply store the entire register into the stack
7046         // slot.
7047         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7048         // The store to the fixedstack object is needed becuase accessing a
7049         // field of the ByVal will use a gep and load. Ideally we will optimize
7050         // to extracting the value from the register directly, and elide the
7051         // stores when the arguments address is not taken, but that will need to
7052         // be future work.
7053         SDValue Store = DAG.getStore(
7054             CopyFrom.getValue(1), dl, CopyFrom,
7055             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7056             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7057 
7058         MemOps.push_back(Store);
7059       };
7060 
7061       unsigned Offset = 0;
7062       HandleRegLoc(VA.getLocReg(), Offset);
7063       Offset += PtrByteSize;
7064       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7065            Offset += PtrByteSize) {
7066         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7067                "RegLocs should be for ByVal argument.");
7068 
7069         const CCValAssign RL = ArgLocs[I++];
7070         HandleRegLoc(RL.getLocReg(), Offset);
7071         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7072       }
7073 
7074       if (Offset != StackSize) {
7075         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7076                "Expected MemLoc for remaining bytes.");
7077         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7078         // Consume the MemLoc.The InVal has already been emitted, so nothing
7079         // more needs to be done.
7080         ++I;
7081       }
7082 
7083       continue;
7084     }
7085 
7086     if (VA.isRegLoc() && !VA.needsCustom()) {
7087       MVT::SimpleValueType SVT = ValVT.SimpleTy;
7088       Register VReg =
7089           MF.addLiveIn(VA.getLocReg(),
7090                        getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7091                                          Subtarget.hasVSX()));
7092       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7093       if (ValVT.isScalarInteger() &&
7094           (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7095         ArgValue =
7096             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7097       }
7098       InVals.push_back(ArgValue);
7099       continue;
7100     }
7101     if (VA.isMemLoc()) {
7102       HandleMemLoc();
7103       continue;
7104     }
7105   }
7106 
7107   // On AIX a minimum of 8 words is saved to the parameter save area.
7108   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7109   // Area that is at least reserved in the caller of this function.
7110   unsigned CallerReservedArea =
7111       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7112 
7113   // Set the size that is at least reserved in caller of this function. Tail
7114   // call optimized function's reserved stack space needs to be aligned so
7115   // that taking the difference between two stack areas will result in an
7116   // aligned stack.
7117   CallerReservedArea =
7118       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7119   FuncInfo->setMinReservedArea(CallerReservedArea);
7120 
7121   if (isVarArg) {
7122     FuncInfo->setVarArgsFrameIndex(
7123         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7124     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7125 
7126     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7127                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7128 
7129     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7130                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7131     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7132 
7133     // The fixed integer arguments of a variadic function are stored to the
7134     // VarArgsFrameIndex on the stack so that they may be loaded by
7135     // dereferencing the result of va_next.
7136     for (unsigned GPRIndex =
7137              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7138          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7139 
7140       const unsigned VReg =
7141           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7142                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7143 
7144       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7145       SDValue Store =
7146           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7147       MemOps.push_back(Store);
7148       // Increment the address for the next argument to store.
7149       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7150       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7151     }
7152   }
7153 
7154   if (!MemOps.empty())
7155     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7156 
7157   return Chain;
7158 }
7159 
7160 SDValue PPCTargetLowering::LowerCall_AIX(
7161     SDValue Chain, SDValue Callee, CallFlags CFlags,
7162     const SmallVectorImpl<ISD::OutputArg> &Outs,
7163     const SmallVectorImpl<SDValue> &OutVals,
7164     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7165     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7166     const CallBase *CB) const {
7167   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7168   // AIX ABI stack frame layout.
7169 
7170   assert((CFlags.CallConv == CallingConv::C ||
7171           CFlags.CallConv == CallingConv::Cold ||
7172           CFlags.CallConv == CallingConv::Fast) &&
7173          "Unexpected calling convention!");
7174 
7175   if (CFlags.IsPatchPoint)
7176     report_fatal_error("This call type is unimplemented on AIX.");
7177 
7178   const PPCSubtarget& Subtarget =
7179       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7180 
7181   MachineFunction &MF = DAG.getMachineFunction();
7182   SmallVector<CCValAssign, 16> ArgLocs;
7183   AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7184                     *DAG.getContext());
7185 
7186   // Reserve space for the linkage save area (LSA) on the stack.
7187   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7188   //   [SP][CR][LR][2 x reserved][TOC].
7189   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7190   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7191   const bool IsPPC64 = Subtarget.isPPC64();
7192   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7193   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7194   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7195   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7196 
7197   // The prolog code of the callee may store up to 8 GPR argument registers to
7198   // the stack, allowing va_start to index over them in memory if the callee
7199   // is variadic.
7200   // Because we cannot tell if this is needed on the caller side, we have to
7201   // conservatively assume that it is needed.  As such, make sure we have at
7202   // least enough stack space for the caller to store the 8 GPRs.
7203   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7204   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7205                                      CCInfo.getNextStackOffset());
7206 
7207   // Adjust the stack pointer for the new arguments...
7208   // These operations are automatically eliminated by the prolog/epilog pass.
7209   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7210   SDValue CallSeqStart = Chain;
7211 
7212   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7213   SmallVector<SDValue, 8> MemOpChains;
7214 
7215   // Set up a copy of the stack pointer for loading and storing any
7216   // arguments that may not fit in the registers available for argument
7217   // passing.
7218   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7219                                    : DAG.getRegister(PPC::R1, MVT::i32);
7220 
7221   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7222     const unsigned ValNo = ArgLocs[I].getValNo();
7223     SDValue Arg = OutVals[ValNo];
7224     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7225 
7226     if (Flags.isByVal()) {
7227       const unsigned ByValSize = Flags.getByValSize();
7228 
7229       // Nothing to do for zero-sized ByVals on the caller side.
7230       if (!ByValSize) {
7231         ++I;
7232         continue;
7233       }
7234 
7235       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7236         return DAG.getExtLoad(
7237             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7238             (LoadOffset != 0)
7239                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7240                 : Arg,
7241             MachinePointerInfo(), VT);
7242       };
7243 
7244       unsigned LoadOffset = 0;
7245 
7246       // Initialize registers, which are fully occupied by the by-val argument.
7247       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7248         SDValue Load = GetLoad(PtrVT, LoadOffset);
7249         MemOpChains.push_back(Load.getValue(1));
7250         LoadOffset += PtrByteSize;
7251         const CCValAssign &ByValVA = ArgLocs[I++];
7252         assert(ByValVA.getValNo() == ValNo &&
7253                "Unexpected location for pass-by-value argument.");
7254         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7255       }
7256 
7257       if (LoadOffset == ByValSize)
7258         continue;
7259 
7260       // There must be one more loc to handle the remainder.
7261       assert(ArgLocs[I].getValNo() == ValNo &&
7262              "Expected additional location for by-value argument.");
7263 
7264       if (ArgLocs[I].isMemLoc()) {
7265         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7266         const CCValAssign &ByValVA = ArgLocs[I++];
7267         ISD::ArgFlagsTy MemcpyFlags = Flags;
7268         // Only memcpy the bytes that don't pass in register.
7269         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7270         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7271             (LoadOffset != 0)
7272                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7273                 : Arg,
7274             DAG.getObjectPtrOffset(dl, StackPtr,
7275                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7276             CallSeqStart, MemcpyFlags, DAG, dl);
7277         continue;
7278       }
7279 
7280       // Initialize the final register residue.
7281       // Any residue that occupies the final by-val arg register must be
7282       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7283       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7284       // 2 and 1 byte loads.
7285       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7286       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7287              "Unexpected register residue for by-value argument.");
7288       SDValue ResidueVal;
7289       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7290         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7291         const MVT VT =
7292             N == 1 ? MVT::i8
7293                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7294         SDValue Load = GetLoad(VT, LoadOffset);
7295         MemOpChains.push_back(Load.getValue(1));
7296         LoadOffset += N;
7297         Bytes += N;
7298 
7299         // By-val arguments are passed left-justfied in register.
7300         // Every load here needs to be shifted, otherwise a full register load
7301         // should have been used.
7302         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7303                "Unexpected load emitted during handling of pass-by-value "
7304                "argument.");
7305         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7306         EVT ShiftAmountTy =
7307             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7308         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7309         SDValue ShiftedLoad =
7310             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7311         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7312                                               ShiftedLoad)
7313                                 : ShiftedLoad;
7314       }
7315 
7316       const CCValAssign &ByValVA = ArgLocs[I++];
7317       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7318       continue;
7319     }
7320 
7321     CCValAssign &VA = ArgLocs[I++];
7322     const MVT LocVT = VA.getLocVT();
7323     const MVT ValVT = VA.getValVT();
7324 
7325     switch (VA.getLocInfo()) {
7326     default:
7327       report_fatal_error("Unexpected argument extension type.");
7328     case CCValAssign::Full:
7329       break;
7330     case CCValAssign::ZExt:
7331       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7332       break;
7333     case CCValAssign::SExt:
7334       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7335       break;
7336     }
7337 
7338     if (VA.isRegLoc() && !VA.needsCustom()) {
7339       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7340       continue;
7341     }
7342 
7343     // Vector arguments passed to VarArg functions need custom handling when
7344     // they are passed (at least partially) in GPRs.
7345     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
7346       assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.");
7347       // Store value to its stack slot.
7348       SDValue PtrOff =
7349           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7350       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7351       SDValue Store =
7352           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
7353       MemOpChains.push_back(Store);
7354       const unsigned OriginalValNo = VA.getValNo();
7355       // Then load the GPRs from the stack
7356       unsigned LoadOffset = 0;
7357       auto HandleCustomVecRegLoc = [&]() {
7358         assert(I != E && "Unexpected end of CCvalAssigns.");
7359         assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7360                "Expected custom RegLoc.");
7361         CCValAssign RegVA = ArgLocs[I++];
7362         assert(RegVA.getValNo() == OriginalValNo &&
7363                "Custom MemLoc ValNo and custom RegLoc ValNo must match.");
7364         SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
7365                                   DAG.getConstant(LoadOffset, dl, PtrVT));
7366         SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
7367         MemOpChains.push_back(Load.getValue(1));
7368         RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
7369         LoadOffset += PtrByteSize;
7370       };
7371 
7372       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7373       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7374       // R10.
7375       HandleCustomVecRegLoc();
7376       HandleCustomVecRegLoc();
7377 
7378       if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7379           ArgLocs[I].getValNo() == OriginalValNo) {
7380         assert(!IsPPC64 &&
7381                "Only 2 custom RegLocs expected for 64-bit codegen.");
7382         HandleCustomVecRegLoc();
7383         HandleCustomVecRegLoc();
7384       }
7385 
7386       continue;
7387     }
7388 
7389     if (VA.isMemLoc()) {
7390       SDValue PtrOff =
7391           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7392       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7393       MemOpChains.push_back(
7394           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7395 
7396       continue;
7397     }
7398 
7399     if (!ValVT.isFloatingPoint())
7400       report_fatal_error(
7401           "Unexpected register handling for calling convention.");
7402 
7403     // Custom handling is used for GPR initializations for vararg float
7404     // arguments.
7405     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7406            LocVT.isInteger() &&
7407            "Custom register handling only expected for VarArg.");
7408 
7409     SDValue ArgAsInt =
7410         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7411 
7412     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7413       // f32 in 32-bit GPR
7414       // f64 in 64-bit GPR
7415       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7416     else if (Arg.getValueType().getFixedSizeInBits() <
7417              LocVT.getFixedSizeInBits())
7418       // f32 in 64-bit GPR.
7419       RegsToPass.push_back(std::make_pair(
7420           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7421     else {
7422       // f64 in two 32-bit GPRs
7423       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7424       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7425              "Unexpected custom register for argument!");
7426       CCValAssign &GPR1 = VA;
7427       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7428                                      DAG.getConstant(32, dl, MVT::i8));
7429       RegsToPass.push_back(std::make_pair(
7430           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7431 
7432       if (I != E) {
7433         // If only 1 GPR was available, there will only be one custom GPR and
7434         // the argument will also pass in memory.
7435         CCValAssign &PeekArg = ArgLocs[I];
7436         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7437           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7438           CCValAssign &GPR2 = ArgLocs[I++];
7439           RegsToPass.push_back(std::make_pair(
7440               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7441         }
7442       }
7443     }
7444   }
7445 
7446   if (!MemOpChains.empty())
7447     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7448 
7449   // For indirect calls, we need to save the TOC base to the stack for
7450   // restoration after the call.
7451   if (CFlags.IsIndirect) {
7452     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7453     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7454     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7455     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7456     const unsigned TOCSaveOffset =
7457         Subtarget.getFrameLowering()->getTOCSaveOffset();
7458 
7459     setUsesTOCBasePtr(DAG);
7460     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7461     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7462     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7463     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7464     Chain = DAG.getStore(
7465         Val.getValue(1), dl, Val, AddPtr,
7466         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7467   }
7468 
7469   // Build a sequence of copy-to-reg nodes chained together with token chain
7470   // and flag operands which copy the outgoing args into the appropriate regs.
7471   SDValue InFlag;
7472   for (auto Reg : RegsToPass) {
7473     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7474     InFlag = Chain.getValue(1);
7475   }
7476 
7477   const int SPDiff = 0;
7478   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7479                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7480 }
7481 
7482 bool
7483 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7484                                   MachineFunction &MF, bool isVarArg,
7485                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7486                                   LLVMContext &Context) const {
7487   SmallVector<CCValAssign, 16> RVLocs;
7488   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7489   return CCInfo.CheckReturn(
7490       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7491                 ? RetCC_PPC_Cold
7492                 : RetCC_PPC);
7493 }
7494 
7495 SDValue
7496 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7497                                bool isVarArg,
7498                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7499                                const SmallVectorImpl<SDValue> &OutVals,
7500                                const SDLoc &dl, SelectionDAG &DAG) const {
7501   SmallVector<CCValAssign, 16> RVLocs;
7502   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7503                  *DAG.getContext());
7504   CCInfo.AnalyzeReturn(Outs,
7505                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7506                            ? RetCC_PPC_Cold
7507                            : RetCC_PPC);
7508 
7509   SDValue Flag;
7510   SmallVector<SDValue, 4> RetOps(1, Chain);
7511 
7512   // Copy the result values into the output registers.
7513   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7514     CCValAssign &VA = RVLocs[i];
7515     assert(VA.isRegLoc() && "Can only return in registers!");
7516 
7517     SDValue Arg = OutVals[RealResIdx];
7518 
7519     switch (VA.getLocInfo()) {
7520     default: llvm_unreachable("Unknown loc info!");
7521     case CCValAssign::Full: break;
7522     case CCValAssign::AExt:
7523       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7524       break;
7525     case CCValAssign::ZExt:
7526       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7527       break;
7528     case CCValAssign::SExt:
7529       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7530       break;
7531     }
7532     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7533       bool isLittleEndian = Subtarget.isLittleEndian();
7534       // Legalize ret f64 -> ret 2 x i32.
7535       SDValue SVal =
7536           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7537                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7538       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7539       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7540       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7541                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7542       Flag = Chain.getValue(1);
7543       VA = RVLocs[++i]; // skip ahead to next loc
7544       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7545     } else
7546       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7547     Flag = Chain.getValue(1);
7548     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7549   }
7550 
7551   RetOps[0] = Chain;  // Update chain.
7552 
7553   // Add the flag if we have it.
7554   if (Flag.getNode())
7555     RetOps.push_back(Flag);
7556 
7557   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7558 }
7559 
7560 SDValue
7561 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7562                                                 SelectionDAG &DAG) const {
7563   SDLoc dl(Op);
7564 
7565   // Get the correct type for integers.
7566   EVT IntVT = Op.getValueType();
7567 
7568   // Get the inputs.
7569   SDValue Chain = Op.getOperand(0);
7570   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7571   // Build a DYNAREAOFFSET node.
7572   SDValue Ops[2] = {Chain, FPSIdx};
7573   SDVTList VTs = DAG.getVTList(IntVT);
7574   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7575 }
7576 
7577 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7578                                              SelectionDAG &DAG) const {
7579   // When we pop the dynamic allocation we need to restore the SP link.
7580   SDLoc dl(Op);
7581 
7582   // Get the correct type for pointers.
7583   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7584 
7585   // Construct the stack pointer operand.
7586   bool isPPC64 = Subtarget.isPPC64();
7587   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7588   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7589 
7590   // Get the operands for the STACKRESTORE.
7591   SDValue Chain = Op.getOperand(0);
7592   SDValue SaveSP = Op.getOperand(1);
7593 
7594   // Load the old link SP.
7595   SDValue LoadLinkSP =
7596       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7597 
7598   // Restore the stack pointer.
7599   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7600 
7601   // Store the old link SP.
7602   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7603 }
7604 
7605 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7606   MachineFunction &MF = DAG.getMachineFunction();
7607   bool isPPC64 = Subtarget.isPPC64();
7608   EVT PtrVT = getPointerTy(MF.getDataLayout());
7609 
7610   // Get current frame pointer save index.  The users of this index will be
7611   // primarily DYNALLOC instructions.
7612   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7613   int RASI = FI->getReturnAddrSaveIndex();
7614 
7615   // If the frame pointer save index hasn't been defined yet.
7616   if (!RASI) {
7617     // Find out what the fix offset of the frame pointer save area.
7618     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7619     // Allocate the frame index for frame pointer save area.
7620     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7621     // Save the result.
7622     FI->setReturnAddrSaveIndex(RASI);
7623   }
7624   return DAG.getFrameIndex(RASI, PtrVT);
7625 }
7626 
7627 SDValue
7628 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7629   MachineFunction &MF = DAG.getMachineFunction();
7630   bool isPPC64 = Subtarget.isPPC64();
7631   EVT PtrVT = getPointerTy(MF.getDataLayout());
7632 
7633   // Get current frame pointer save index.  The users of this index will be
7634   // primarily DYNALLOC instructions.
7635   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7636   int FPSI = FI->getFramePointerSaveIndex();
7637 
7638   // If the frame pointer save index hasn't been defined yet.
7639   if (!FPSI) {
7640     // Find out what the fix offset of the frame pointer save area.
7641     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7642     // Allocate the frame index for frame pointer save area.
7643     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7644     // Save the result.
7645     FI->setFramePointerSaveIndex(FPSI);
7646   }
7647   return DAG.getFrameIndex(FPSI, PtrVT);
7648 }
7649 
7650 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7651                                                    SelectionDAG &DAG) const {
7652   MachineFunction &MF = DAG.getMachineFunction();
7653   // Get the inputs.
7654   SDValue Chain = Op.getOperand(0);
7655   SDValue Size  = Op.getOperand(1);
7656   SDLoc dl(Op);
7657 
7658   // Get the correct type for pointers.
7659   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7660   // Negate the size.
7661   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7662                                 DAG.getConstant(0, dl, PtrVT), Size);
7663   // Construct a node for the frame pointer save index.
7664   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7665   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7666   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7667   if (hasInlineStackProbe(MF))
7668     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7669   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7670 }
7671 
7672 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7673                                                      SelectionDAG &DAG) const {
7674   MachineFunction &MF = DAG.getMachineFunction();
7675 
7676   bool isPPC64 = Subtarget.isPPC64();
7677   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7678 
7679   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7680   return DAG.getFrameIndex(FI, PtrVT);
7681 }
7682 
7683 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7684                                                SelectionDAG &DAG) const {
7685   SDLoc DL(Op);
7686   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7687                      DAG.getVTList(MVT::i32, MVT::Other),
7688                      Op.getOperand(0), Op.getOperand(1));
7689 }
7690 
7691 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7692                                                 SelectionDAG &DAG) const {
7693   SDLoc DL(Op);
7694   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7695                      Op.getOperand(0), Op.getOperand(1));
7696 }
7697 
7698 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7699   if (Op.getValueType().isVector())
7700     return LowerVectorLoad(Op, DAG);
7701 
7702   assert(Op.getValueType() == MVT::i1 &&
7703          "Custom lowering only for i1 loads");
7704 
7705   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7706 
7707   SDLoc dl(Op);
7708   LoadSDNode *LD = cast<LoadSDNode>(Op);
7709 
7710   SDValue Chain = LD->getChain();
7711   SDValue BasePtr = LD->getBasePtr();
7712   MachineMemOperand *MMO = LD->getMemOperand();
7713 
7714   SDValue NewLD =
7715       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7716                      BasePtr, MVT::i8, MMO);
7717   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7718 
7719   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7720   return DAG.getMergeValues(Ops, dl);
7721 }
7722 
7723 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7724   if (Op.getOperand(1).getValueType().isVector())
7725     return LowerVectorStore(Op, DAG);
7726 
7727   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7728          "Custom lowering only for i1 stores");
7729 
7730   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7731 
7732   SDLoc dl(Op);
7733   StoreSDNode *ST = cast<StoreSDNode>(Op);
7734 
7735   SDValue Chain = ST->getChain();
7736   SDValue BasePtr = ST->getBasePtr();
7737   SDValue Value = ST->getValue();
7738   MachineMemOperand *MMO = ST->getMemOperand();
7739 
7740   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7741                       Value);
7742   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7743 }
7744 
7745 // FIXME: Remove this once the ANDI glue bug is fixed:
7746 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7747   assert(Op.getValueType() == MVT::i1 &&
7748          "Custom lowering only for i1 results");
7749 
7750   SDLoc DL(Op);
7751   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7752 }
7753 
7754 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7755                                                SelectionDAG &DAG) const {
7756 
7757   // Implements a vector truncate that fits in a vector register as a shuffle.
7758   // We want to legalize vector truncates down to where the source fits in
7759   // a vector register (and target is therefore smaller than vector register
7760   // size).  At that point legalization will try to custom lower the sub-legal
7761   // result and get here - where we can contain the truncate as a single target
7762   // operation.
7763 
7764   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7765   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7766   //
7767   // We will implement it for big-endian ordering as this (where x denotes
7768   // undefined):
7769   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7770   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7771   //
7772   // The same operation in little-endian ordering will be:
7773   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7774   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7775 
7776   EVT TrgVT = Op.getValueType();
7777   assert(TrgVT.isVector() && "Vector type expected.");
7778   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7779   EVT EltVT = TrgVT.getVectorElementType();
7780   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
7781       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
7782       !isPowerOf2_32(EltVT.getSizeInBits()))
7783     return SDValue();
7784 
7785   SDValue N1 = Op.getOperand(0);
7786   EVT SrcVT = N1.getValueType();
7787   unsigned SrcSize = SrcVT.getSizeInBits();
7788   if (SrcSize > 256 ||
7789       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
7790       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
7791     return SDValue();
7792   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
7793     return SDValue();
7794 
7795   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7796   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7797 
7798   SDLoc DL(Op);
7799   SDValue Op1, Op2;
7800   if (SrcSize == 256) {
7801     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
7802     EVT SplitVT =
7803         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
7804     unsigned SplitNumElts = SplitVT.getVectorNumElements();
7805     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7806                       DAG.getConstant(0, DL, VecIdxTy));
7807     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7808                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
7809   }
7810   else {
7811     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7812     Op2 = DAG.getUNDEF(WideVT);
7813   }
7814 
7815   // First list the elements we want to keep.
7816   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7817   SmallVector<int, 16> ShuffV;
7818   if (Subtarget.isLittleEndian())
7819     for (unsigned i = 0; i < TrgNumElts; ++i)
7820       ShuffV.push_back(i * SizeMult);
7821   else
7822     for (unsigned i = 1; i <= TrgNumElts; ++i)
7823       ShuffV.push_back(i * SizeMult - 1);
7824 
7825   // Populate the remaining elements with undefs.
7826   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7827     // ShuffV.push_back(i + WideNumElts);
7828     ShuffV.push_back(WideNumElts + 1);
7829 
7830   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
7831   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
7832   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
7833 }
7834 
7835 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7836 /// possible.
7837 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7838   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7839   EVT ResVT = Op.getValueType();
7840   EVT CmpVT = Op.getOperand(0).getValueType();
7841   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7842   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7843   SDLoc dl(Op);
7844 
7845   // Without power9-vector, we don't have native instruction for f128 comparison.
7846   // Following transformation to libcall is needed for setcc:
7847   // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE
7848   if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) {
7849     SDValue Z = DAG.getSetCC(
7850         dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT),
7851         LHS, RHS, CC);
7852     SDValue Zero = DAG.getConstant(0, dl, Z.getValueType());
7853     return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE);
7854   }
7855 
7856   // Not FP, or using SPE? Not a fsel.
7857   if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() ||
7858       Subtarget.hasSPE())
7859     return Op;
7860 
7861   SDNodeFlags Flags = Op.getNode()->getFlags();
7862 
7863   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7864   // presence of infinities.
7865   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7866     switch (CC) {
7867     default:
7868       break;
7869     case ISD::SETOGT:
7870     case ISD::SETGT:
7871       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7872     case ISD::SETOLT:
7873     case ISD::SETLT:
7874       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7875     }
7876   }
7877 
7878   // We might be able to do better than this under some circumstances, but in
7879   // general, fsel-based lowering of select is a finite-math-only optimization.
7880   // For more information, see section F.3 of the 2.06 ISA specification.
7881   // With ISA 3.0
7882   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7883       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7884     return Op;
7885 
7886   // If the RHS of the comparison is a 0.0, we don't need to do the
7887   // subtraction at all.
7888   SDValue Sel1;
7889   if (isFloatingPointZero(RHS))
7890     switch (CC) {
7891     default: break;       // SETUO etc aren't handled by fsel.
7892     case ISD::SETNE:
7893       std::swap(TV, FV);
7894       LLVM_FALLTHROUGH;
7895     case ISD::SETEQ:
7896       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7897         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7898       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7899       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7900         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7901       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7902                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7903     case ISD::SETULT:
7904     case ISD::SETLT:
7905       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7906       LLVM_FALLTHROUGH;
7907     case ISD::SETOGE:
7908     case ISD::SETGE:
7909       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7910         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7911       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7912     case ISD::SETUGT:
7913     case ISD::SETGT:
7914       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7915       LLVM_FALLTHROUGH;
7916     case ISD::SETOLE:
7917     case ISD::SETLE:
7918       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7919         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7920       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7921                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7922     }
7923 
7924   SDValue Cmp;
7925   switch (CC) {
7926   default: break;       // SETUO etc aren't handled by fsel.
7927   case ISD::SETNE:
7928     std::swap(TV, FV);
7929     LLVM_FALLTHROUGH;
7930   case ISD::SETEQ:
7931     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7932     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7933       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7934     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7935     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7936       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7937     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7938                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7939   case ISD::SETULT:
7940   case ISD::SETLT:
7941     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7942     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7943       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7944     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7945   case ISD::SETOGE:
7946   case ISD::SETGE:
7947     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7948     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7949       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7950     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7951   case ISD::SETUGT:
7952   case ISD::SETGT:
7953     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7954     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7955       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7956     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7957   case ISD::SETOLE:
7958   case ISD::SETLE:
7959     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7960     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7961       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7962     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7963   }
7964   return Op;
7965 }
7966 
7967 static unsigned getPPCStrictOpcode(unsigned Opc) {
7968   switch (Opc) {
7969   default:
7970     llvm_unreachable("No strict version of this opcode!");
7971   case PPCISD::FCTIDZ:
7972     return PPCISD::STRICT_FCTIDZ;
7973   case PPCISD::FCTIWZ:
7974     return PPCISD::STRICT_FCTIWZ;
7975   case PPCISD::FCTIDUZ:
7976     return PPCISD::STRICT_FCTIDUZ;
7977   case PPCISD::FCTIWUZ:
7978     return PPCISD::STRICT_FCTIWUZ;
7979   case PPCISD::FCFID:
7980     return PPCISD::STRICT_FCFID;
7981   case PPCISD::FCFIDU:
7982     return PPCISD::STRICT_FCFIDU;
7983   case PPCISD::FCFIDS:
7984     return PPCISD::STRICT_FCFIDS;
7985   case PPCISD::FCFIDUS:
7986     return PPCISD::STRICT_FCFIDUS;
7987   }
7988 }
7989 
7990 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
7991                               const PPCSubtarget &Subtarget) {
7992   SDLoc dl(Op);
7993   bool IsStrict = Op->isStrictFPOpcode();
7994   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
7995                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
7996 
7997   // TODO: Any other flags to propagate?
7998   SDNodeFlags Flags;
7999   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8000 
8001   // For strict nodes, source is the second operand.
8002   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8003   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8004   assert(Src.getValueType().isFloatingPoint());
8005   if (Src.getValueType() == MVT::f32) {
8006     if (IsStrict) {
8007       Src =
8008           DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
8009                       DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
8010       Chain = Src.getValue(1);
8011     } else
8012       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8013   }
8014   SDValue Conv;
8015   unsigned Opc = ISD::DELETED_NODE;
8016   switch (Op.getSimpleValueType().SimpleTy) {
8017   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8018   case MVT::i32:
8019     Opc = IsSigned ? PPCISD::FCTIWZ
8020                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8021     break;
8022   case MVT::i64:
8023     assert((IsSigned || Subtarget.hasFPCVT()) &&
8024            "i64 FP_TO_UINT is supported only with FPCVT");
8025     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8026   }
8027   if (IsStrict) {
8028     Opc = getPPCStrictOpcode(Opc);
8029     Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
8030                        {Chain, Src}, Flags);
8031   } else {
8032     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8033   }
8034   return Conv;
8035 }
8036 
8037 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8038                                                SelectionDAG &DAG,
8039                                                const SDLoc &dl) const {
8040   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8041   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8042                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8043   bool IsStrict = Op->isStrictFPOpcode();
8044 
8045   // Convert the FP value to an int value through memory.
8046   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8047                   (IsSigned || Subtarget.hasFPCVT());
8048   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8049   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8050   MachinePointerInfo MPI =
8051       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8052 
8053   // Emit a store to the stack slot.
8054   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8055   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8056   if (i32Stack) {
8057     MachineFunction &MF = DAG.getMachineFunction();
8058     Alignment = Align(4);
8059     MachineMemOperand *MMO =
8060         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8061     SDValue Ops[] = { Chain, Tmp, FIPtr };
8062     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8063               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8064   } else
8065     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8066 
8067   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8068   // add in a bias on big endian.
8069   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8070     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8071                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8072     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8073   }
8074 
8075   RLI.Chain = Chain;
8076   RLI.Ptr = FIPtr;
8077   RLI.MPI = MPI;
8078   RLI.Alignment = Alignment;
8079 }
8080 
8081 /// Custom lowers floating point to integer conversions to use
8082 /// the direct move instructions available in ISA 2.07 to avoid the
8083 /// need for load/store combinations.
8084 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8085                                                     SelectionDAG &DAG,
8086                                                     const SDLoc &dl) const {
8087   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8088   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8089   if (Op->isStrictFPOpcode())
8090     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8091   else
8092     return Mov;
8093 }
8094 
8095 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8096                                           const SDLoc &dl) const {
8097   bool IsStrict = Op->isStrictFPOpcode();
8098   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8099                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8100   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8101   EVT SrcVT = Src.getValueType();
8102   EVT DstVT = Op.getValueType();
8103 
8104   // FP to INT conversions are legal for f128.
8105   if (SrcVT == MVT::f128)
8106     return Subtarget.hasP9Vector() ? Op : SDValue();
8107 
8108   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8109   // PPC (the libcall is not available).
8110   if (SrcVT == MVT::ppcf128) {
8111     if (DstVT == MVT::i32) {
8112       // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8113       // set other fast-math flags to FP operations in both strict and
8114       // non-strict cases. (FP_TO_SINT, FSUB)
8115       SDNodeFlags Flags;
8116       Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8117 
8118       if (IsSigned) {
8119         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8120                                  DAG.getIntPtrConstant(0, dl));
8121         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8122                                  DAG.getIntPtrConstant(1, dl));
8123 
8124         // Add the two halves of the long double in round-to-zero mode, and use
8125         // a smaller FP_TO_SINT.
8126         if (IsStrict) {
8127           SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8128                                     DAG.getVTList(MVT::f64, MVT::Other),
8129                                     {Op.getOperand(0), Lo, Hi}, Flags);
8130           return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8131                              DAG.getVTList(MVT::i32, MVT::Other),
8132                              {Res.getValue(1), Res}, Flags);
8133         } else {
8134           SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8135           return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8136         }
8137       } else {
8138         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8139         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8140         SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8141         SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8142         if (IsStrict) {
8143           // Sel = Src < 0x80000000
8144           // FltOfs = select Sel, 0.0, 0x80000000
8145           // IntOfs = select Sel, 0, 0x80000000
8146           // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8147           SDValue Chain = Op.getOperand(0);
8148           EVT SetCCVT =
8149               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8150           EVT DstSetCCVT =
8151               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8152           SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8153                                      Chain, true);
8154           Chain = Sel.getValue(1);
8155 
8156           SDValue FltOfs = DAG.getSelect(
8157               dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8158           Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8159 
8160           SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8161                                     DAG.getVTList(SrcVT, MVT::Other),
8162                                     {Chain, Src, FltOfs}, Flags);
8163           Chain = Val.getValue(1);
8164           SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8165                                      DAG.getVTList(DstVT, MVT::Other),
8166                                      {Chain, Val}, Flags);
8167           Chain = SInt.getValue(1);
8168           SDValue IntOfs = DAG.getSelect(
8169               dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8170           SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8171           return DAG.getMergeValues({Result, Chain}, dl);
8172         } else {
8173           // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8174           // FIXME: generated code sucks.
8175           SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8176           True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8177           True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8178           SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8179           return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8180         }
8181       }
8182     }
8183 
8184     return SDValue();
8185   }
8186 
8187   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8188     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8189 
8190   ReuseLoadInfo RLI;
8191   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8192 
8193   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8194                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8195 }
8196 
8197 // We're trying to insert a regular store, S, and then a load, L. If the
8198 // incoming value, O, is a load, we might just be able to have our load use the
8199 // address used by O. However, we don't know if anything else will store to
8200 // that address before we can load from it. To prevent this situation, we need
8201 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8202 // the same chain operand as O, we create a token factor from the chain results
8203 // of O and L, and we replace all uses of O's chain result with that token
8204 // factor (see spliceIntoChain below for this last part).
8205 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8206                                             ReuseLoadInfo &RLI,
8207                                             SelectionDAG &DAG,
8208                                             ISD::LoadExtType ET) const {
8209   // Conservatively skip reusing for constrained FP nodes.
8210   if (Op->isStrictFPOpcode())
8211     return false;
8212 
8213   SDLoc dl(Op);
8214   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8215                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8216   if (ET == ISD::NON_EXTLOAD &&
8217       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8218       isOperationLegalOrCustom(Op.getOpcode(),
8219                                Op.getOperand(0).getValueType())) {
8220 
8221     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8222     return true;
8223   }
8224 
8225   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8226   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8227       LD->isNonTemporal())
8228     return false;
8229   if (LD->getMemoryVT() != MemVT)
8230     return false;
8231 
8232   // If the result of the load is an illegal type, then we can't build a
8233   // valid chain for reuse since the legalised loads and token factor node that
8234   // ties the legalised loads together uses a different output chain then the
8235   // illegal load.
8236   if (!isTypeLegal(LD->getValueType(0)))
8237     return false;
8238 
8239   RLI.Ptr = LD->getBasePtr();
8240   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8241     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8242            "Non-pre-inc AM on PPC?");
8243     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8244                           LD->getOffset());
8245   }
8246 
8247   RLI.Chain = LD->getChain();
8248   RLI.MPI = LD->getPointerInfo();
8249   RLI.IsDereferenceable = LD->isDereferenceable();
8250   RLI.IsInvariant = LD->isInvariant();
8251   RLI.Alignment = LD->getAlign();
8252   RLI.AAInfo = LD->getAAInfo();
8253   RLI.Ranges = LD->getRanges();
8254 
8255   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8256   return true;
8257 }
8258 
8259 // Given the head of the old chain, ResChain, insert a token factor containing
8260 // it and NewResChain, and make users of ResChain now be users of that token
8261 // factor.
8262 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8263 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8264                                         SDValue NewResChain,
8265                                         SelectionDAG &DAG) const {
8266   if (!ResChain)
8267     return;
8268 
8269   SDLoc dl(NewResChain);
8270 
8271   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8272                            NewResChain, DAG.getUNDEF(MVT::Other));
8273   assert(TF.getNode() != NewResChain.getNode() &&
8274          "A new TF really is required here");
8275 
8276   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8277   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8278 }
8279 
8280 /// Analyze profitability of direct move
8281 /// prefer float load to int load plus direct move
8282 /// when there is no integer use of int load
8283 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8284   SDNode *Origin = Op.getOperand(0).getNode();
8285   if (Origin->getOpcode() != ISD::LOAD)
8286     return true;
8287 
8288   // If there is no LXSIBZX/LXSIHZX, like Power8,
8289   // prefer direct move if the memory size is 1 or 2 bytes.
8290   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8291   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8292     return true;
8293 
8294   for (SDNode::use_iterator UI = Origin->use_begin(),
8295                             UE = Origin->use_end();
8296        UI != UE; ++UI) {
8297 
8298     // Only look at the users of the loaded value.
8299     if (UI.getUse().get().getResNo() != 0)
8300       continue;
8301 
8302     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8303         UI->getOpcode() != ISD::UINT_TO_FP &&
8304         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8305         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8306       return true;
8307   }
8308 
8309   return false;
8310 }
8311 
8312 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8313                               const PPCSubtarget &Subtarget,
8314                               SDValue Chain = SDValue()) {
8315   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8316                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8317   SDLoc dl(Op);
8318 
8319   // TODO: Any other flags to propagate?
8320   SDNodeFlags Flags;
8321   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8322 
8323   // If we have FCFIDS, then use it when converting to single-precision.
8324   // Otherwise, convert to double-precision and then round.
8325   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8326   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8327                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8328   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8329   if (Op->isStrictFPOpcode()) {
8330     if (!Chain)
8331       Chain = Op.getOperand(0);
8332     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8333                        DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8334   } else
8335     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8336 }
8337 
8338 /// Custom lowers integer to floating point conversions to use
8339 /// the direct move instructions available in ISA 2.07 to avoid the
8340 /// need for load/store combinations.
8341 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8342                                                     SelectionDAG &DAG,
8343                                                     const SDLoc &dl) const {
8344   assert((Op.getValueType() == MVT::f32 ||
8345           Op.getValueType() == MVT::f64) &&
8346          "Invalid floating point type as target of conversion");
8347   assert(Subtarget.hasFPCVT() &&
8348          "Int to FP conversions with direct moves require FPCVT");
8349   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8350   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8351   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8352                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8353   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8354   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8355   return convertIntToFP(Op, Mov, DAG, Subtarget);
8356 }
8357 
8358 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8359 
8360   EVT VecVT = Vec.getValueType();
8361   assert(VecVT.isVector() && "Expected a vector type.");
8362   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8363 
8364   EVT EltVT = VecVT.getVectorElementType();
8365   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8366   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8367 
8368   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8369   SmallVector<SDValue, 16> Ops(NumConcat);
8370   Ops[0] = Vec;
8371   SDValue UndefVec = DAG.getUNDEF(VecVT);
8372   for (unsigned i = 1; i < NumConcat; ++i)
8373     Ops[i] = UndefVec;
8374 
8375   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8376 }
8377 
8378 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8379                                                 const SDLoc &dl) const {
8380   bool IsStrict = Op->isStrictFPOpcode();
8381   unsigned Opc = Op.getOpcode();
8382   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8383   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8384           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8385          "Unexpected conversion type");
8386   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8387          "Supports conversions to v2f64/v4f32 only.");
8388 
8389   // TODO: Any other flags to propagate?
8390   SDNodeFlags Flags;
8391   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8392 
8393   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8394   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8395 
8396   SDValue Wide = widenVec(DAG, Src, dl);
8397   EVT WideVT = Wide.getValueType();
8398   unsigned WideNumElts = WideVT.getVectorNumElements();
8399   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8400 
8401   SmallVector<int, 16> ShuffV;
8402   for (unsigned i = 0; i < WideNumElts; ++i)
8403     ShuffV.push_back(i + WideNumElts);
8404 
8405   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8406   int SaveElts = FourEltRes ? 4 : 2;
8407   if (Subtarget.isLittleEndian())
8408     for (int i = 0; i < SaveElts; i++)
8409       ShuffV[i * Stride] = i;
8410   else
8411     for (int i = 1; i <= SaveElts; i++)
8412       ShuffV[i * Stride - 1] = i - 1;
8413 
8414   SDValue ShuffleSrc2 =
8415       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8416   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8417 
8418   SDValue Extend;
8419   if (SignedConv) {
8420     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8421     EVT ExtVT = Src.getValueType();
8422     if (Subtarget.hasP9Altivec())
8423       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8424                                IntermediateVT.getVectorNumElements());
8425 
8426     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8427                          DAG.getValueType(ExtVT));
8428   } else
8429     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8430 
8431   if (IsStrict)
8432     return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8433                        {Op.getOperand(0), Extend}, Flags);
8434 
8435   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8436 }
8437 
8438 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8439                                           SelectionDAG &DAG) const {
8440   SDLoc dl(Op);
8441   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8442                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8443   bool IsStrict = Op->isStrictFPOpcode();
8444   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8445   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8446 
8447   // TODO: Any other flags to propagate?
8448   SDNodeFlags Flags;
8449   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8450 
8451   EVT InVT = Src.getValueType();
8452   EVT OutVT = Op.getValueType();
8453   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8454       isOperationCustom(Op.getOpcode(), InVT))
8455     return LowerINT_TO_FPVector(Op, DAG, dl);
8456 
8457   // Conversions to f128 are legal.
8458   if (Op.getValueType() == MVT::f128)
8459     return Subtarget.hasP9Vector() ? Op : SDValue();
8460 
8461   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8462   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8463     return SDValue();
8464 
8465   if (Src.getValueType() == MVT::i1) {
8466     SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8467                               DAG.getConstantFP(1.0, dl, Op.getValueType()),
8468                               DAG.getConstantFP(0.0, dl, Op.getValueType()));
8469     if (IsStrict)
8470       return DAG.getMergeValues({Sel, Chain}, dl);
8471     else
8472       return Sel;
8473   }
8474 
8475   // If we have direct moves, we can do all the conversion, skip the store/load
8476   // however, without FPCVT we can't do most conversions.
8477   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8478       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8479     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8480 
8481   assert((IsSigned || Subtarget.hasFPCVT()) &&
8482          "UINT_TO_FP is supported only with FPCVT");
8483 
8484   if (Src.getValueType() == MVT::i64) {
8485     SDValue SINT = Src;
8486     // When converting to single-precision, we actually need to convert
8487     // to double-precision first and then round to single-precision.
8488     // To avoid double-rounding effects during that operation, we have
8489     // to prepare the input operand.  Bits that might be truncated when
8490     // converting to double-precision are replaced by a bit that won't
8491     // be lost at this stage, but is below the single-precision rounding
8492     // position.
8493     //
8494     // However, if -enable-unsafe-fp-math is in effect, accept double
8495     // rounding to avoid the extra overhead.
8496     if (Op.getValueType() == MVT::f32 &&
8497         !Subtarget.hasFPCVT() &&
8498         !DAG.getTarget().Options.UnsafeFPMath) {
8499 
8500       // Twiddle input to make sure the low 11 bits are zero.  (If this
8501       // is the case, we are guaranteed the value will fit into the 53 bit
8502       // mantissa of an IEEE double-precision value without rounding.)
8503       // If any of those low 11 bits were not zero originally, make sure
8504       // bit 12 (value 2048) is set instead, so that the final rounding
8505       // to single-precision gets the correct result.
8506       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8507                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8508       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8509                           Round, DAG.getConstant(2047, dl, MVT::i64));
8510       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8511       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8512                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8513 
8514       // However, we cannot use that value unconditionally: if the magnitude
8515       // of the input value is small, the bit-twiddling we did above might
8516       // end up visibly changing the output.  Fortunately, in that case, we
8517       // don't need to twiddle bits since the original input will convert
8518       // exactly to double-precision floating-point already.  Therefore,
8519       // construct a conditional to use the original value if the top 11
8520       // bits are all sign-bit copies, and use the rounded value computed
8521       // above otherwise.
8522       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8523                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8524       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8525                          Cond, DAG.getConstant(1, dl, MVT::i64));
8526       Cond = DAG.getSetCC(
8527           dl,
8528           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8529           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8530 
8531       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8532     }
8533 
8534     ReuseLoadInfo RLI;
8535     SDValue Bits;
8536 
8537     MachineFunction &MF = DAG.getMachineFunction();
8538     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8539       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8540                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8541       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8542     } else if (Subtarget.hasLFIWAX() &&
8543                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8544       MachineMemOperand *MMO =
8545         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8546                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8547       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8548       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8549                                      DAG.getVTList(MVT::f64, MVT::Other),
8550                                      Ops, MVT::i32, MMO);
8551       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8552     } else if (Subtarget.hasFPCVT() &&
8553                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8554       MachineMemOperand *MMO =
8555         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8556                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8557       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8558       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8559                                      DAG.getVTList(MVT::f64, MVT::Other),
8560                                      Ops, MVT::i32, MMO);
8561       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8562     } else if (((Subtarget.hasLFIWAX() &&
8563                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8564                 (Subtarget.hasFPCVT() &&
8565                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8566                SINT.getOperand(0).getValueType() == MVT::i32) {
8567       MachineFrameInfo &MFI = MF.getFrameInfo();
8568       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8569 
8570       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8571       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8572 
8573       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8574                                    MachinePointerInfo::getFixedStack(
8575                                        DAG.getMachineFunction(), FrameIdx));
8576       Chain = Store;
8577 
8578       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8579              "Expected an i32 store");
8580 
8581       RLI.Ptr = FIdx;
8582       RLI.Chain = Chain;
8583       RLI.MPI =
8584           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8585       RLI.Alignment = Align(4);
8586 
8587       MachineMemOperand *MMO =
8588         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8589                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8590       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8591       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8592                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8593                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8594                                      Ops, MVT::i32, MMO);
8595       Chain = Bits.getValue(1);
8596     } else
8597       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8598 
8599     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8600     if (IsStrict)
8601       Chain = FP.getValue(1);
8602 
8603     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8604       if (IsStrict)
8605         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8606                          DAG.getVTList(MVT::f32, MVT::Other),
8607                          {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8608       else
8609         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8610                          DAG.getIntPtrConstant(0, dl));
8611     }
8612     return FP;
8613   }
8614 
8615   assert(Src.getValueType() == MVT::i32 &&
8616          "Unhandled INT_TO_FP type in custom expander!");
8617   // Since we only generate this in 64-bit mode, we can take advantage of
8618   // 64-bit registers.  In particular, sign extend the input value into the
8619   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8620   // then lfd it and fcfid it.
8621   MachineFunction &MF = DAG.getMachineFunction();
8622   MachineFrameInfo &MFI = MF.getFrameInfo();
8623   EVT PtrVT = getPointerTy(MF.getDataLayout());
8624 
8625   SDValue Ld;
8626   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8627     ReuseLoadInfo RLI;
8628     bool ReusingLoad;
8629     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8630       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8631       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8632 
8633       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8634                                    MachinePointerInfo::getFixedStack(
8635                                        DAG.getMachineFunction(), FrameIdx));
8636       Chain = Store;
8637 
8638       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8639              "Expected an i32 store");
8640 
8641       RLI.Ptr = FIdx;
8642       RLI.Chain = Chain;
8643       RLI.MPI =
8644           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8645       RLI.Alignment = Align(4);
8646     }
8647 
8648     MachineMemOperand *MMO =
8649       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8650                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8651     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8652     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8653                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8654                                  MVT::i32, MMO);
8655     Chain = Ld.getValue(1);
8656     if (ReusingLoad)
8657       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8658   } else {
8659     assert(Subtarget.isPPC64() &&
8660            "i32->FP without LFIWAX supported only on PPC64");
8661 
8662     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8663     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8664 
8665     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8666 
8667     // STD the extended value into the stack slot.
8668     SDValue Store = DAG.getStore(
8669         Chain, dl, Ext64, FIdx,
8670         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8671     Chain = Store;
8672 
8673     // Load the value as a double.
8674     Ld = DAG.getLoad(
8675         MVT::f64, dl, Chain, FIdx,
8676         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8677     Chain = Ld.getValue(1);
8678   }
8679 
8680   // FCFID it and return it.
8681   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8682   if (IsStrict)
8683     Chain = FP.getValue(1);
8684   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8685     if (IsStrict)
8686       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8687                        DAG.getVTList(MVT::f32, MVT::Other),
8688                        {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8689     else
8690       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8691                        DAG.getIntPtrConstant(0, dl));
8692   }
8693   return FP;
8694 }
8695 
8696 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8697                                             SelectionDAG &DAG) const {
8698   SDLoc dl(Op);
8699   /*
8700    The rounding mode is in bits 30:31 of FPSR, and has the following
8701    settings:
8702      00 Round to nearest
8703      01 Round to 0
8704      10 Round to +inf
8705      11 Round to -inf
8706 
8707   FLT_ROUNDS, on the other hand, expects the following:
8708     -1 Undefined
8709      0 Round to 0
8710      1 Round to nearest
8711      2 Round to +inf
8712      3 Round to -inf
8713 
8714   To perform the conversion, we do:
8715     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8716   */
8717 
8718   MachineFunction &MF = DAG.getMachineFunction();
8719   EVT VT = Op.getValueType();
8720   EVT PtrVT = getPointerTy(MF.getDataLayout());
8721 
8722   // Save FP Control Word to register
8723   SDValue Chain = Op.getOperand(0);
8724   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8725   Chain = MFFS.getValue(1);
8726 
8727   SDValue CWD;
8728   if (isTypeLegal(MVT::i64)) {
8729     CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
8730                       DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
8731   } else {
8732     // Save FP register to stack slot
8733     int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8734     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8735     Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8736 
8737     // Load FP Control Word from low 32 bits of stack slot.
8738     assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) &&
8739            "Stack slot adjustment is valid only on big endian subtargets!");
8740     SDValue Four = DAG.getConstant(4, dl, PtrVT);
8741     SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8742     CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8743     Chain = CWD.getValue(1);
8744   }
8745 
8746   // Transform as necessary
8747   SDValue CWD1 =
8748     DAG.getNode(ISD::AND, dl, MVT::i32,
8749                 CWD, DAG.getConstant(3, dl, MVT::i32));
8750   SDValue CWD2 =
8751     DAG.getNode(ISD::SRL, dl, MVT::i32,
8752                 DAG.getNode(ISD::AND, dl, MVT::i32,
8753                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8754                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8755                             DAG.getConstant(3, dl, MVT::i32)),
8756                 DAG.getConstant(1, dl, MVT::i32));
8757 
8758   SDValue RetVal =
8759     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8760 
8761   RetVal =
8762       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8763                   dl, VT, RetVal);
8764 
8765   return DAG.getMergeValues({RetVal, Chain}, dl);
8766 }
8767 
8768 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8769   EVT VT = Op.getValueType();
8770   unsigned BitWidth = VT.getSizeInBits();
8771   SDLoc dl(Op);
8772   assert(Op.getNumOperands() == 3 &&
8773          VT == Op.getOperand(1).getValueType() &&
8774          "Unexpected SHL!");
8775 
8776   // Expand into a bunch of logical ops.  Note that these ops
8777   // depend on the PPC behavior for oversized shift amounts.
8778   SDValue Lo = Op.getOperand(0);
8779   SDValue Hi = Op.getOperand(1);
8780   SDValue Amt = Op.getOperand(2);
8781   EVT AmtVT = Amt.getValueType();
8782 
8783   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8784                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8785   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8786   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8787   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8788   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8789                              DAG.getConstant(-BitWidth, dl, AmtVT));
8790   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8791   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8792   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8793   SDValue OutOps[] = { OutLo, OutHi };
8794   return DAG.getMergeValues(OutOps, dl);
8795 }
8796 
8797 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8798   EVT VT = Op.getValueType();
8799   SDLoc dl(Op);
8800   unsigned BitWidth = VT.getSizeInBits();
8801   assert(Op.getNumOperands() == 3 &&
8802          VT == Op.getOperand(1).getValueType() &&
8803          "Unexpected SRL!");
8804 
8805   // Expand into a bunch of logical ops.  Note that these ops
8806   // depend on the PPC behavior for oversized shift amounts.
8807   SDValue Lo = Op.getOperand(0);
8808   SDValue Hi = Op.getOperand(1);
8809   SDValue Amt = Op.getOperand(2);
8810   EVT AmtVT = Amt.getValueType();
8811 
8812   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8813                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8814   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8815   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8816   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8817   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8818                              DAG.getConstant(-BitWidth, dl, AmtVT));
8819   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8820   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8821   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8822   SDValue OutOps[] = { OutLo, OutHi };
8823   return DAG.getMergeValues(OutOps, dl);
8824 }
8825 
8826 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8827   SDLoc dl(Op);
8828   EVT VT = Op.getValueType();
8829   unsigned BitWidth = VT.getSizeInBits();
8830   assert(Op.getNumOperands() == 3 &&
8831          VT == Op.getOperand(1).getValueType() &&
8832          "Unexpected SRA!");
8833 
8834   // Expand into a bunch of logical ops, followed by a select_cc.
8835   SDValue Lo = Op.getOperand(0);
8836   SDValue Hi = Op.getOperand(1);
8837   SDValue Amt = Op.getOperand(2);
8838   EVT AmtVT = Amt.getValueType();
8839 
8840   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8841                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8842   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8843   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8844   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8845   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8846                              DAG.getConstant(-BitWidth, dl, AmtVT));
8847   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8848   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8849   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8850                                   Tmp4, Tmp6, ISD::SETLE);
8851   SDValue OutOps[] = { OutLo, OutHi };
8852   return DAG.getMergeValues(OutOps, dl);
8853 }
8854 
8855 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8856                                             SelectionDAG &DAG) const {
8857   SDLoc dl(Op);
8858   EVT VT = Op.getValueType();
8859   unsigned BitWidth = VT.getSizeInBits();
8860 
8861   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8862   SDValue X = Op.getOperand(0);
8863   SDValue Y = Op.getOperand(1);
8864   SDValue Z = Op.getOperand(2);
8865   EVT AmtVT = Z.getValueType();
8866 
8867   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8868   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8869   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8870   // on PowerPC shift by BW being well defined.
8871   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8872                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8873   SDValue SubZ =
8874       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8875   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8876   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8877   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8878 }
8879 
8880 //===----------------------------------------------------------------------===//
8881 // Vector related lowering.
8882 //
8883 
8884 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8885 /// element size of SplatSize. Cast the result to VT.
8886 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8887                                       SelectionDAG &DAG, const SDLoc &dl) {
8888   static const MVT VTys[] = { // canonical VT to use for each size.
8889     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8890   };
8891 
8892   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8893 
8894   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8895   if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
8896     SplatSize = 1;
8897     Val = 0xFF;
8898   }
8899 
8900   EVT CanonicalVT = VTys[SplatSize-1];
8901 
8902   // Build a canonical splat for this value.
8903   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8904 }
8905 
8906 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8907 /// specified intrinsic ID.
8908 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8909                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8910   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8911   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8912                      DAG.getConstant(IID, dl, MVT::i32), Op);
8913 }
8914 
8915 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8916 /// specified intrinsic ID.
8917 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8918                                 SelectionDAG &DAG, const SDLoc &dl,
8919                                 EVT DestVT = MVT::Other) {
8920   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8921   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8922                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8923 }
8924 
8925 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8926 /// specified intrinsic ID.
8927 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8928                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8929                                 EVT DestVT = MVT::Other) {
8930   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8931   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8932                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8933 }
8934 
8935 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8936 /// amount.  The result has the specified value type.
8937 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8938                            SelectionDAG &DAG, const SDLoc &dl) {
8939   // Force LHS/RHS to be the right type.
8940   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8941   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8942 
8943   int Ops[16];
8944   for (unsigned i = 0; i != 16; ++i)
8945     Ops[i] = i + Amt;
8946   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8947   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8948 }
8949 
8950 /// Do we have an efficient pattern in a .td file for this node?
8951 ///
8952 /// \param V - pointer to the BuildVectorSDNode being matched
8953 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8954 ///
8955 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8956 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8957 /// the opposite is true (expansion is beneficial) are:
8958 /// - The node builds a vector out of integers that are not 32 or 64-bits
8959 /// - The node builds a vector out of constants
8960 /// - The node is a "load-and-splat"
8961 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8962 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8963                                             bool HasDirectMove,
8964                                             bool HasP8Vector) {
8965   EVT VecVT = V->getValueType(0);
8966   bool RightType = VecVT == MVT::v2f64 ||
8967     (HasP8Vector && VecVT == MVT::v4f32) ||
8968     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8969   if (!RightType)
8970     return false;
8971 
8972   bool IsSplat = true;
8973   bool IsLoad = false;
8974   SDValue Op0 = V->getOperand(0);
8975 
8976   // This function is called in a block that confirms the node is not a constant
8977   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8978   // different constants.
8979   if (V->isConstant())
8980     return false;
8981   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8982     if (V->getOperand(i).isUndef())
8983       return false;
8984     // We want to expand nodes that represent load-and-splat even if the
8985     // loaded value is a floating point truncation or conversion to int.
8986     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8987         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8988          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8989         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8990          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8991         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8992          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8993       IsLoad = true;
8994     // If the operands are different or the input is not a load and has more
8995     // uses than just this BV node, then it isn't a splat.
8996     if (V->getOperand(i) != Op0 ||
8997         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8998       IsSplat = false;
8999   }
9000   return !(IsSplat && IsLoad);
9001 }
9002 
9003 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9004 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9005 
9006   SDLoc dl(Op);
9007   SDValue Op0 = Op->getOperand(0);
9008 
9009   if ((Op.getValueType() != MVT::f128) ||
9010       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9011       (Op0.getOperand(0).getValueType() != MVT::i64) ||
9012       (Op0.getOperand(1).getValueType() != MVT::i64))
9013     return SDValue();
9014 
9015   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9016                      Op0.getOperand(1));
9017 }
9018 
9019 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9020   const SDValue *InputLoad = &Op;
9021   if (InputLoad->getOpcode() == ISD::BITCAST)
9022     InputLoad = &InputLoad->getOperand(0);
9023   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9024       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9025     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9026     InputLoad = &InputLoad->getOperand(0);
9027   }
9028   if (InputLoad->getOpcode() != ISD::LOAD)
9029     return nullptr;
9030   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9031   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9032 }
9033 
9034 // Convert the argument APFloat to a single precision APFloat if there is no
9035 // loss in information during the conversion to single precision APFloat and the
9036 // resulting number is not a denormal number. Return true if successful.
9037 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9038   APFloat APFloatToConvert = ArgAPFloat;
9039   bool LosesInfo = true;
9040   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9041                            &LosesInfo);
9042   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9043   if (Success)
9044     ArgAPFloat = APFloatToConvert;
9045   return Success;
9046 }
9047 
9048 // Bitcast the argument APInt to a double and convert it to a single precision
9049 // APFloat, bitcast the APFloat to an APInt and assign it to the original
9050 // argument if there is no loss in information during the conversion from
9051 // double to single precision APFloat and the resulting number is not a denormal
9052 // number. Return true if successful.
9053 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9054   double DpValue = ArgAPInt.bitsToDouble();
9055   APFloat APFloatDp(DpValue);
9056   bool Success = convertToNonDenormSingle(APFloatDp);
9057   if (Success)
9058     ArgAPInt = APFloatDp.bitcastToAPInt();
9059   return Success;
9060 }
9061 
9062 // Nondestructive check for convertTonNonDenormSingle.
9063 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) {
9064   // Only convert if it loses info, since XXSPLTIDP should
9065   // handle the other case.
9066   APFloat APFloatToConvert = ArgAPFloat;
9067   bool LosesInfo = true;
9068   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9069                            &LosesInfo);
9070 
9071   return (!LosesInfo && !APFloatToConvert.isDenormal());
9072 }
9073 
9074 // If this is a case we can't handle, return null and let the default
9075 // expansion code take care of it.  If we CAN select this case, and if it
9076 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9077 // this case more efficiently than a constant pool load, lower it to the
9078 // sequence of ops that should be used.
9079 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9080                                              SelectionDAG &DAG) const {
9081   SDLoc dl(Op);
9082   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9083   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9084 
9085   // Check if this is a splat of a constant value.
9086   APInt APSplatBits, APSplatUndef;
9087   unsigned SplatBitSize;
9088   bool HasAnyUndefs;
9089   bool BVNIsConstantSplat =
9090       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9091                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9092 
9093   // If it is a splat of a double, check if we can shrink it to a 32 bit
9094   // non-denormal float which when converted back to double gives us the same
9095   // double. This is to exploit the XXSPLTIDP instruction.
9096   // If we lose precision, we use XXSPLTI32DX.
9097   if (BVNIsConstantSplat && (SplatBitSize == 64) &&
9098       Subtarget.hasPrefixInstrs()) {
9099     // Check the type first to short-circuit so we don't modify APSplatBits if
9100     // this block isn't executed.
9101     if ((Op->getValueType(0) == MVT::v2f64) &&
9102         convertToNonDenormSingle(APSplatBits)) {
9103       SDValue SplatNode = DAG.getNode(
9104           PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9105           DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9106       return DAG.getBitcast(Op.getValueType(), SplatNode);
9107     } else {
9108       // We may lose precision, so we have to use XXSPLTI32DX.
9109 
9110       uint32_t Hi =
9111           (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32);
9112       uint32_t Lo =
9113           (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF);
9114       SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
9115 
9116       if (!Hi || !Lo)
9117         // If either load is 0, then we should generate XXLXOR to set to 0.
9118         SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
9119 
9120       if (Hi)
9121         SplatNode = DAG.getNode(
9122             PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9123             DAG.getTargetConstant(0, dl, MVT::i32),
9124             DAG.getTargetConstant(Hi, dl, MVT::i32));
9125 
9126       if (Lo)
9127         SplatNode =
9128             DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9129                         DAG.getTargetConstant(1, dl, MVT::i32),
9130                         DAG.getTargetConstant(Lo, dl, MVT::i32));
9131 
9132       return DAG.getBitcast(Op.getValueType(), SplatNode);
9133     }
9134   }
9135 
9136   if (!BVNIsConstantSplat || SplatBitSize > 32) {
9137 
9138     bool IsPermutedLoad = false;
9139     const SDValue *InputLoad =
9140         getNormalLoadInput(Op.getOperand(0), IsPermutedLoad);
9141     // Handle load-and-splat patterns as we have instructions that will do this
9142     // in one go.
9143     if (InputLoad && DAG.isSplatValue(Op, true)) {
9144       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9145 
9146       // We have handling for 4 and 8 byte elements.
9147       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9148 
9149       // Checking for a single use of this load, we have to check for vector
9150       // width (128 bits) / ElementSize uses (since each operand of the
9151       // BUILD_VECTOR is a separate use of the value.
9152       unsigned NumUsesOfInputLD = 128 / ElementSize;
9153       for (SDValue BVInOp : Op->ops())
9154         if (BVInOp.isUndef())
9155           NumUsesOfInputLD--;
9156       assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
9157       if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
9158           ((Subtarget.hasVSX() && ElementSize == 64) ||
9159            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9160         SDValue Ops[] = {
9161           LD->getChain(),    // Chain
9162           LD->getBasePtr(),  // Ptr
9163           DAG.getValueType(Op.getValueType()) // VT
9164         };
9165         SDValue LdSplt = DAG.getMemIntrinsicNode(
9166             PPCISD::LD_SPLAT, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
9167             Ops, LD->getMemoryVT(), LD->getMemOperand());
9168         // Replace all uses of the output chain of the original load with the
9169         // output chain of the new load.
9170         DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
9171                                       LdSplt.getValue(1));
9172         return LdSplt;
9173       }
9174     }
9175 
9176     // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
9177     // 32-bits can be lowered to VSX instructions under certain conditions.
9178     // Without VSX, there is no pattern more efficient than expanding the node.
9179     if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
9180         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9181                                         Subtarget.hasP8Vector()))
9182       return Op;
9183     return SDValue();
9184   }
9185 
9186   uint64_t SplatBits = APSplatBits.getZExtValue();
9187   uint64_t SplatUndef = APSplatUndef.getZExtValue();
9188   unsigned SplatSize = SplatBitSize / 8;
9189 
9190   // First, handle single instruction cases.
9191 
9192   // All zeros?
9193   if (SplatBits == 0) {
9194     // Canonicalize all zero vectors to be v4i32.
9195     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9196       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9197       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9198     }
9199     return Op;
9200   }
9201 
9202   // We have XXSPLTIW for constant splats four bytes wide.
9203   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9204   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9205   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9206   // turned into a 4-byte splat of 0xABABABAB.
9207   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9208     return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
9209                                   Op.getValueType(), DAG, dl);
9210 
9211   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9212     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9213                                   dl);
9214 
9215   // We have XXSPLTIB for constant splats one byte wide.
9216   if (Subtarget.hasP9Vector() && SplatSize == 1)
9217     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9218                                   dl);
9219 
9220   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9221   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9222                     (32-SplatBitSize));
9223   if (SextVal >= -16 && SextVal <= 15)
9224     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9225                                   dl);
9226 
9227   // Two instruction sequences.
9228 
9229   // If this value is in the range [-32,30] and is even, use:
9230   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9231   // If this value is in the range [17,31] and is odd, use:
9232   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9233   // If this value is in the range [-31,-17] and is odd, use:
9234   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9235   // Note the last two are three-instruction sequences.
9236   if (SextVal >= -32 && SextVal <= 31) {
9237     // To avoid having these optimizations undone by constant folding,
9238     // we convert to a pseudo that will be expanded later into one of
9239     // the above forms.
9240     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9241     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9242               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9243     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9244     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9245     if (VT == Op.getValueType())
9246       return RetVal;
9247     else
9248       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9249   }
9250 
9251   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9252   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9253   // for fneg/fabs.
9254   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9255     // Make -1 and vspltisw -1:
9256     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9257 
9258     // Make the VSLW intrinsic, computing 0x8000_0000.
9259     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9260                                    OnesV, DAG, dl);
9261 
9262     // xor by OnesV to invert it.
9263     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9264     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9265   }
9266 
9267   // Check to see if this is a wide variety of vsplti*, binop self cases.
9268   static const signed char SplatCsts[] = {
9269     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9270     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9271   };
9272 
9273   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9274     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9275     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9276     int i = SplatCsts[idx];
9277 
9278     // Figure out what shift amount will be used by altivec if shifted by i in
9279     // this splat size.
9280     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9281 
9282     // vsplti + shl self.
9283     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9284       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9285       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9286         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9287         Intrinsic::ppc_altivec_vslw
9288       };
9289       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9290       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9291     }
9292 
9293     // vsplti + srl self.
9294     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9295       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9296       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9297         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9298         Intrinsic::ppc_altivec_vsrw
9299       };
9300       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9301       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9302     }
9303 
9304     // vsplti + rol self.
9305     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9306                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9307       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9308       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9309         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9310         Intrinsic::ppc_altivec_vrlw
9311       };
9312       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9313       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9314     }
9315 
9316     // t = vsplti c, result = vsldoi t, t, 1
9317     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9318       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9319       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9320       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9321     }
9322     // t = vsplti c, result = vsldoi t, t, 2
9323     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9324       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9325       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9326       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9327     }
9328     // t = vsplti c, result = vsldoi t, t, 3
9329     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9330       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9331       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9332       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9333     }
9334   }
9335 
9336   return SDValue();
9337 }
9338 
9339 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9340 /// the specified operations to build the shuffle.
9341 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9342                                       SDValue RHS, SelectionDAG &DAG,
9343                                       const SDLoc &dl) {
9344   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9345   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9346   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9347 
9348   enum {
9349     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9350     OP_VMRGHW,
9351     OP_VMRGLW,
9352     OP_VSPLTISW0,
9353     OP_VSPLTISW1,
9354     OP_VSPLTISW2,
9355     OP_VSPLTISW3,
9356     OP_VSLDOI4,
9357     OP_VSLDOI8,
9358     OP_VSLDOI12
9359   };
9360 
9361   if (OpNum == OP_COPY) {
9362     if (LHSID == (1*9+2)*9+3) return LHS;
9363     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9364     return RHS;
9365   }
9366 
9367   SDValue OpLHS, OpRHS;
9368   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9369   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9370 
9371   int ShufIdxs[16];
9372   switch (OpNum) {
9373   default: llvm_unreachable("Unknown i32 permute!");
9374   case OP_VMRGHW:
9375     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9376     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9377     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9378     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9379     break;
9380   case OP_VMRGLW:
9381     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9382     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9383     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9384     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9385     break;
9386   case OP_VSPLTISW0:
9387     for (unsigned i = 0; i != 16; ++i)
9388       ShufIdxs[i] = (i&3)+0;
9389     break;
9390   case OP_VSPLTISW1:
9391     for (unsigned i = 0; i != 16; ++i)
9392       ShufIdxs[i] = (i&3)+4;
9393     break;
9394   case OP_VSPLTISW2:
9395     for (unsigned i = 0; i != 16; ++i)
9396       ShufIdxs[i] = (i&3)+8;
9397     break;
9398   case OP_VSPLTISW3:
9399     for (unsigned i = 0; i != 16; ++i)
9400       ShufIdxs[i] = (i&3)+12;
9401     break;
9402   case OP_VSLDOI4:
9403     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9404   case OP_VSLDOI8:
9405     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9406   case OP_VSLDOI12:
9407     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9408   }
9409   EVT VT = OpLHS.getValueType();
9410   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9411   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9412   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9413   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9414 }
9415 
9416 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9417 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9418 /// SDValue.
9419 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9420                                            SelectionDAG &DAG) const {
9421   const unsigned BytesInVector = 16;
9422   bool IsLE = Subtarget.isLittleEndian();
9423   SDLoc dl(N);
9424   SDValue V1 = N->getOperand(0);
9425   SDValue V2 = N->getOperand(1);
9426   unsigned ShiftElts = 0, InsertAtByte = 0;
9427   bool Swap = false;
9428 
9429   // Shifts required to get the byte we want at element 7.
9430   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9431                                    0, 15, 14, 13, 12, 11, 10, 9};
9432   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9433                                 1, 2,  3,  4,  5,  6,  7,  8};
9434 
9435   ArrayRef<int> Mask = N->getMask();
9436   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9437 
9438   // For each mask element, find out if we're just inserting something
9439   // from V2 into V1 or vice versa.
9440   // Possible permutations inserting an element from V2 into V1:
9441   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9442   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9443   //   ...
9444   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9445   // Inserting from V1 into V2 will be similar, except mask range will be
9446   // [16,31].
9447 
9448   bool FoundCandidate = false;
9449   // If both vector operands for the shuffle are the same vector, the mask
9450   // will contain only elements from the first one and the second one will be
9451   // undef.
9452   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9453   // Go through the mask of half-words to find an element that's being moved
9454   // from one vector to the other.
9455   for (unsigned i = 0; i < BytesInVector; ++i) {
9456     unsigned CurrentElement = Mask[i];
9457     // If 2nd operand is undefined, we should only look for element 7 in the
9458     // Mask.
9459     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9460       continue;
9461 
9462     bool OtherElementsInOrder = true;
9463     // Examine the other elements in the Mask to see if they're in original
9464     // order.
9465     for (unsigned j = 0; j < BytesInVector; ++j) {
9466       if (j == i)
9467         continue;
9468       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9469       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9470       // in which we always assume we're always picking from the 1st operand.
9471       int MaskOffset =
9472           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9473       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9474         OtherElementsInOrder = false;
9475         break;
9476       }
9477     }
9478     // If other elements are in original order, we record the number of shifts
9479     // we need to get the element we want into element 7. Also record which byte
9480     // in the vector we should insert into.
9481     if (OtherElementsInOrder) {
9482       // If 2nd operand is undefined, we assume no shifts and no swapping.
9483       if (V2.isUndef()) {
9484         ShiftElts = 0;
9485         Swap = false;
9486       } else {
9487         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9488         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9489                          : BigEndianShifts[CurrentElement & 0xF];
9490         Swap = CurrentElement < BytesInVector;
9491       }
9492       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9493       FoundCandidate = true;
9494       break;
9495     }
9496   }
9497 
9498   if (!FoundCandidate)
9499     return SDValue();
9500 
9501   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9502   // optionally with VECSHL if shift is required.
9503   if (Swap)
9504     std::swap(V1, V2);
9505   if (V2.isUndef())
9506     V2 = V1;
9507   if (ShiftElts) {
9508     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9509                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9510     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9511                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9512   }
9513   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9514                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9515 }
9516 
9517 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9518 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9519 /// SDValue.
9520 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9521                                            SelectionDAG &DAG) const {
9522   const unsigned NumHalfWords = 8;
9523   const unsigned BytesInVector = NumHalfWords * 2;
9524   // Check that the shuffle is on half-words.
9525   if (!isNByteElemShuffleMask(N, 2, 1))
9526     return SDValue();
9527 
9528   bool IsLE = Subtarget.isLittleEndian();
9529   SDLoc dl(N);
9530   SDValue V1 = N->getOperand(0);
9531   SDValue V2 = N->getOperand(1);
9532   unsigned ShiftElts = 0, InsertAtByte = 0;
9533   bool Swap = false;
9534 
9535   // Shifts required to get the half-word we want at element 3.
9536   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9537   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9538 
9539   uint32_t Mask = 0;
9540   uint32_t OriginalOrderLow = 0x1234567;
9541   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9542   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9543   // 32-bit space, only need 4-bit nibbles per element.
9544   for (unsigned i = 0; i < NumHalfWords; ++i) {
9545     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9546     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9547   }
9548 
9549   // For each mask element, find out if we're just inserting something
9550   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9551   // from V2 into V1:
9552   //   X, 1, 2, 3, 4, 5, 6, 7
9553   //   0, X, 2, 3, 4, 5, 6, 7
9554   //   0, 1, X, 3, 4, 5, 6, 7
9555   //   0, 1, 2, X, 4, 5, 6, 7
9556   //   0, 1, 2, 3, X, 5, 6, 7
9557   //   0, 1, 2, 3, 4, X, 6, 7
9558   //   0, 1, 2, 3, 4, 5, X, 7
9559   //   0, 1, 2, 3, 4, 5, 6, X
9560   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9561 
9562   bool FoundCandidate = false;
9563   // Go through the mask of half-words to find an element that's being moved
9564   // from one vector to the other.
9565   for (unsigned i = 0; i < NumHalfWords; ++i) {
9566     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9567     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9568     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9569     uint32_t TargetOrder = 0x0;
9570 
9571     // If both vector operands for the shuffle are the same vector, the mask
9572     // will contain only elements from the first one and the second one will be
9573     // undef.
9574     if (V2.isUndef()) {
9575       ShiftElts = 0;
9576       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9577       TargetOrder = OriginalOrderLow;
9578       Swap = false;
9579       // Skip if not the correct element or mask of other elements don't equal
9580       // to our expected order.
9581       if (MaskOneElt == VINSERTHSrcElem &&
9582           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9583         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9584         FoundCandidate = true;
9585         break;
9586       }
9587     } else { // If both operands are defined.
9588       // Target order is [8,15] if the current mask is between [0,7].
9589       TargetOrder =
9590           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9591       // Skip if mask of other elements don't equal our expected order.
9592       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9593         // We only need the last 3 bits for the number of shifts.
9594         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9595                          : BigEndianShifts[MaskOneElt & 0x7];
9596         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9597         Swap = MaskOneElt < NumHalfWords;
9598         FoundCandidate = true;
9599         break;
9600       }
9601     }
9602   }
9603 
9604   if (!FoundCandidate)
9605     return SDValue();
9606 
9607   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9608   // optionally with VECSHL if shift is required.
9609   if (Swap)
9610     std::swap(V1, V2);
9611   if (V2.isUndef())
9612     V2 = V1;
9613   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9614   if (ShiftElts) {
9615     // Double ShiftElts because we're left shifting on v16i8 type.
9616     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9617                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9618     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9619     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9620                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9621     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9622   }
9623   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9624   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9625                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9626   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9627 }
9628 
9629 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9630 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9631 /// return the default SDValue.
9632 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9633                                               SelectionDAG &DAG) const {
9634   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9635   // to v16i8. Peek through the bitcasts to get the actual operands.
9636   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9637   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9638 
9639   auto ShuffleMask = SVN->getMask();
9640   SDValue VecShuffle(SVN, 0);
9641   SDLoc DL(SVN);
9642 
9643   // Check that we have a four byte shuffle.
9644   if (!isNByteElemShuffleMask(SVN, 4, 1))
9645     return SDValue();
9646 
9647   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9648   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9649     std::swap(LHS, RHS);
9650     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9651     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9652   }
9653 
9654   // Ensure that the RHS is a vector of constants.
9655   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9656   if (!BVN)
9657     return SDValue();
9658 
9659   // Check if RHS is a splat of 4-bytes (or smaller).
9660   APInt APSplatValue, APSplatUndef;
9661   unsigned SplatBitSize;
9662   bool HasAnyUndefs;
9663   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9664                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9665       SplatBitSize > 32)
9666     return SDValue();
9667 
9668   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9669   // The instruction splats a constant C into two words of the source vector
9670   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9671   // Thus we check that the shuffle mask is the equivalent  of
9672   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9673   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9674   // within each word are consecutive, so we only need to check the first byte.
9675   SDValue Index;
9676   bool IsLE = Subtarget.isLittleEndian();
9677   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9678       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9679        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9680     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9681   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9682            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9683             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9684     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9685   else
9686     return SDValue();
9687 
9688   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9689   // for XXSPLTI32DX.
9690   unsigned SplatVal = APSplatValue.getZExtValue();
9691   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9692     SplatVal |= (SplatVal << SplatBitSize);
9693 
9694   SDValue SplatNode = DAG.getNode(
9695       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9696       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9697   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9698 }
9699 
9700 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9701 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9702 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9703 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9704 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9705   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9706   assert(Op.getValueType() == MVT::v1i128 &&
9707          "Only set v1i128 as custom, other type shouldn't reach here!");
9708   SDLoc dl(Op);
9709   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9710   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9711   unsigned SHLAmt = N1.getConstantOperandVal(0);
9712   if (SHLAmt % 8 == 0) {
9713     SmallVector<int, 16> Mask(16, 0);
9714     std::iota(Mask.begin(), Mask.end(), 0);
9715     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9716     if (SDValue Shuffle =
9717             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9718                                  DAG.getUNDEF(MVT::v16i8), Mask))
9719       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9720   }
9721   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9722   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9723                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9724   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9725                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9726   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9727   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9728 }
9729 
9730 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9731 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9732 /// return the code it can be lowered into.  Worst case, it can always be
9733 /// lowered into a vperm.
9734 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9735                                                SelectionDAG &DAG) const {
9736   SDLoc dl(Op);
9737   SDValue V1 = Op.getOperand(0);
9738   SDValue V2 = Op.getOperand(1);
9739   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9740 
9741   // Any nodes that were combined in the target-independent combiner prior
9742   // to vector legalization will not be sent to the target combine. Try to
9743   // combine it here.
9744   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9745     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9746       return NewShuffle;
9747     Op = NewShuffle;
9748     SVOp = cast<ShuffleVectorSDNode>(Op);
9749     V1 = Op.getOperand(0);
9750     V2 = Op.getOperand(1);
9751   }
9752   EVT VT = Op.getValueType();
9753   bool isLittleEndian = Subtarget.isLittleEndian();
9754 
9755   unsigned ShiftElts, InsertAtByte;
9756   bool Swap = false;
9757 
9758   // If this is a load-and-splat, we can do that with a single instruction
9759   // in some cases. However if the load has multiple uses, we don't want to
9760   // combine it because that will just produce multiple loads.
9761   bool IsPermutedLoad = false;
9762   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9763   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9764       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9765       InputLoad->hasOneUse()) {
9766     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9767     int SplatIdx =
9768       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9769 
9770     // The splat index for permuted loads will be in the left half of the vector
9771     // which is strictly wider than the loaded value by 8 bytes. So we need to
9772     // adjust the splat index to point to the correct address in memory.
9773     if (IsPermutedLoad) {
9774       assert((isLittleEndian || IsFourByte) &&
9775              "Unexpected size for permuted load on big endian target");
9776       SplatIdx += IsFourByte ? 2 : 1;
9777       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9778              "Splat of a value outside of the loaded memory");
9779     }
9780 
9781     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9782     // For 4-byte load-and-splat, we need Power9.
9783     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9784       uint64_t Offset = 0;
9785       if (IsFourByte)
9786         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9787       else
9788         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9789 
9790       // If the width of the load is the same as the width of the splat,
9791       // loading with an offset would load the wrong memory.
9792       if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64))
9793         Offset = 0;
9794 
9795       SDValue BasePtr = LD->getBasePtr();
9796       if (Offset != 0)
9797         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9798                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9799       SDValue Ops[] = {
9800         LD->getChain(),    // Chain
9801         BasePtr,           // BasePtr
9802         DAG.getValueType(Op.getValueType()) // VT
9803       };
9804       SDVTList VTL =
9805         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9806       SDValue LdSplt =
9807         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9808                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9809       DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
9810       if (LdSplt.getValueType() != SVOp->getValueType(0))
9811         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9812       return LdSplt;
9813     }
9814   }
9815   if (Subtarget.hasP9Vector() &&
9816       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9817                            isLittleEndian)) {
9818     if (Swap)
9819       std::swap(V1, V2);
9820     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9821     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9822     if (ShiftElts) {
9823       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9824                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9825       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9826                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9827       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9828     }
9829     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9830                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9831     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9832   }
9833 
9834   if (Subtarget.hasPrefixInstrs()) {
9835     SDValue SplatInsertNode;
9836     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9837       return SplatInsertNode;
9838   }
9839 
9840   if (Subtarget.hasP9Altivec()) {
9841     SDValue NewISDNode;
9842     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9843       return NewISDNode;
9844 
9845     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9846       return NewISDNode;
9847   }
9848 
9849   if (Subtarget.hasVSX() &&
9850       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9851     if (Swap)
9852       std::swap(V1, V2);
9853     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9854     SDValue Conv2 =
9855         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9856 
9857     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9858                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9859     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9860   }
9861 
9862   if (Subtarget.hasVSX() &&
9863     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9864     if (Swap)
9865       std::swap(V1, V2);
9866     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9867     SDValue Conv2 =
9868         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9869 
9870     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9871                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9872     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9873   }
9874 
9875   if (Subtarget.hasP9Vector()) {
9876      if (PPC::isXXBRHShuffleMask(SVOp)) {
9877       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9878       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9879       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9880     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9881       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9882       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9883       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9884     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9885       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9886       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9887       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9888     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9889       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9890       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9891       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9892     }
9893   }
9894 
9895   if (Subtarget.hasVSX()) {
9896     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9897       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9898 
9899       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9900       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9901                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9902       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9903     }
9904 
9905     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9906     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9907       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9908       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9909       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9910     }
9911   }
9912 
9913   // Cases that are handled by instructions that take permute immediates
9914   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9915   // selected by the instruction selector.
9916   if (V2.isUndef()) {
9917     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9918         PPC::isSplatShuffleMask(SVOp, 2) ||
9919         PPC::isSplatShuffleMask(SVOp, 4) ||
9920         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9921         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9922         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9923         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9924         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9925         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9926         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9927         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9928         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9929         (Subtarget.hasP8Altivec() && (
9930          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9931          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9932          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9933       return Op;
9934     }
9935   }
9936 
9937   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9938   // and produce a fixed permutation.  If any of these match, do not lower to
9939   // VPERM.
9940   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9941   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9942       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9943       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9944       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9945       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9946       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9947       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9948       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9949       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9950       (Subtarget.hasP8Altivec() && (
9951        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9952        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9953        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9954     return Op;
9955 
9956   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9957   // perfect shuffle table to emit an optimal matching sequence.
9958   ArrayRef<int> PermMask = SVOp->getMask();
9959 
9960   unsigned PFIndexes[4];
9961   bool isFourElementShuffle = true;
9962   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9963     unsigned EltNo = 8;   // Start out undef.
9964     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9965       if (PermMask[i*4+j] < 0)
9966         continue;   // Undef, ignore it.
9967 
9968       unsigned ByteSource = PermMask[i*4+j];
9969       if ((ByteSource & 3) != j) {
9970         isFourElementShuffle = false;
9971         break;
9972       }
9973 
9974       if (EltNo == 8) {
9975         EltNo = ByteSource/4;
9976       } else if (EltNo != ByteSource/4) {
9977         isFourElementShuffle = false;
9978         break;
9979       }
9980     }
9981     PFIndexes[i] = EltNo;
9982   }
9983 
9984   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9985   // perfect shuffle vector to determine if it is cost effective to do this as
9986   // discrete instructions, or whether we should use a vperm.
9987   // For now, we skip this for little endian until such time as we have a
9988   // little-endian perfect shuffle table.
9989   if (isFourElementShuffle && !isLittleEndian) {
9990     // Compute the index in the perfect shuffle table.
9991     unsigned PFTableIndex =
9992       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9993 
9994     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9995     unsigned Cost  = (PFEntry >> 30);
9996 
9997     // Determining when to avoid vperm is tricky.  Many things affect the cost
9998     // of vperm, particularly how many times the perm mask needs to be computed.
9999     // For example, if the perm mask can be hoisted out of a loop or is already
10000     // used (perhaps because there are multiple permutes with the same shuffle
10001     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
10002     // the loop requires an extra register.
10003     //
10004     // As a compromise, we only emit discrete instructions if the shuffle can be
10005     // generated in 3 or fewer operations.  When we have loop information
10006     // available, if this block is within a loop, we should avoid using vperm
10007     // for 3-operation perms and use a constant pool load instead.
10008     if (Cost < 3)
10009       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10010   }
10011 
10012   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10013   // vector that will get spilled to the constant pool.
10014   if (V2.isUndef()) V2 = V1;
10015 
10016   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10017   // that it is in input element units, not in bytes.  Convert now.
10018 
10019   // For little endian, the order of the input vectors is reversed, and
10020   // the permutation mask is complemented with respect to 31.  This is
10021   // necessary to produce proper semantics with the big-endian-biased vperm
10022   // instruction.
10023   EVT EltVT = V1.getValueType().getVectorElementType();
10024   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
10025 
10026   SmallVector<SDValue, 16> ResultMask;
10027   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10028     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10029 
10030     for (unsigned j = 0; j != BytesPerElement; ++j)
10031       if (isLittleEndian)
10032         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
10033                                              dl, MVT::i32));
10034       else
10035         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
10036                                              MVT::i32));
10037   }
10038 
10039   ShufflesHandledWithVPERM++;
10040   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10041   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
10042   LLVM_DEBUG(SVOp->dump());
10043   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
10044   LLVM_DEBUG(VPermMask.dump());
10045 
10046   if (isLittleEndian)
10047     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10048                        V2, V1, VPermMask);
10049   else
10050     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10051                        V1, V2, VPermMask);
10052 }
10053 
10054 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10055 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10056 /// information about the intrinsic.
10057 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10058                                  bool &isDot, const PPCSubtarget &Subtarget) {
10059   unsigned IntrinsicID =
10060       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10061   CompareOpc = -1;
10062   isDot = false;
10063   switch (IntrinsicID) {
10064   default:
10065     return false;
10066   // Comparison predicates.
10067   case Intrinsic::ppc_altivec_vcmpbfp_p:
10068     CompareOpc = 966;
10069     isDot = true;
10070     break;
10071   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10072     CompareOpc = 198;
10073     isDot = true;
10074     break;
10075   case Intrinsic::ppc_altivec_vcmpequb_p:
10076     CompareOpc = 6;
10077     isDot = true;
10078     break;
10079   case Intrinsic::ppc_altivec_vcmpequh_p:
10080     CompareOpc = 70;
10081     isDot = true;
10082     break;
10083   case Intrinsic::ppc_altivec_vcmpequw_p:
10084     CompareOpc = 134;
10085     isDot = true;
10086     break;
10087   case Intrinsic::ppc_altivec_vcmpequd_p:
10088     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10089       CompareOpc = 199;
10090       isDot = true;
10091     } else
10092       return false;
10093     break;
10094   case Intrinsic::ppc_altivec_vcmpneb_p:
10095   case Intrinsic::ppc_altivec_vcmpneh_p:
10096   case Intrinsic::ppc_altivec_vcmpnew_p:
10097   case Intrinsic::ppc_altivec_vcmpnezb_p:
10098   case Intrinsic::ppc_altivec_vcmpnezh_p:
10099   case Intrinsic::ppc_altivec_vcmpnezw_p:
10100     if (Subtarget.hasP9Altivec()) {
10101       switch (IntrinsicID) {
10102       default:
10103         llvm_unreachable("Unknown comparison intrinsic.");
10104       case Intrinsic::ppc_altivec_vcmpneb_p:
10105         CompareOpc = 7;
10106         break;
10107       case Intrinsic::ppc_altivec_vcmpneh_p:
10108         CompareOpc = 71;
10109         break;
10110       case Intrinsic::ppc_altivec_vcmpnew_p:
10111         CompareOpc = 135;
10112         break;
10113       case Intrinsic::ppc_altivec_vcmpnezb_p:
10114         CompareOpc = 263;
10115         break;
10116       case Intrinsic::ppc_altivec_vcmpnezh_p:
10117         CompareOpc = 327;
10118         break;
10119       case Intrinsic::ppc_altivec_vcmpnezw_p:
10120         CompareOpc = 391;
10121         break;
10122       }
10123       isDot = true;
10124     } else
10125       return false;
10126     break;
10127   case Intrinsic::ppc_altivec_vcmpgefp_p:
10128     CompareOpc = 454;
10129     isDot = true;
10130     break;
10131   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10132     CompareOpc = 710;
10133     isDot = true;
10134     break;
10135   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10136     CompareOpc = 774;
10137     isDot = true;
10138     break;
10139   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10140     CompareOpc = 838;
10141     isDot = true;
10142     break;
10143   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10144     CompareOpc = 902;
10145     isDot = true;
10146     break;
10147   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10148     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10149       CompareOpc = 967;
10150       isDot = true;
10151     } else
10152       return false;
10153     break;
10154   case Intrinsic::ppc_altivec_vcmpgtub_p:
10155     CompareOpc = 518;
10156     isDot = true;
10157     break;
10158   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10159     CompareOpc = 582;
10160     isDot = true;
10161     break;
10162   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10163     CompareOpc = 646;
10164     isDot = true;
10165     break;
10166   case Intrinsic::ppc_altivec_vcmpgtud_p:
10167     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10168       CompareOpc = 711;
10169       isDot = true;
10170     } else
10171       return false;
10172     break;
10173 
10174   case Intrinsic::ppc_altivec_vcmpequq:
10175   case Intrinsic::ppc_altivec_vcmpgtsq:
10176   case Intrinsic::ppc_altivec_vcmpgtuq:
10177     if (!Subtarget.isISA3_1())
10178       return false;
10179     switch (IntrinsicID) {
10180     default:
10181       llvm_unreachable("Unknown comparison intrinsic.");
10182     case Intrinsic::ppc_altivec_vcmpequq:
10183       CompareOpc = 455;
10184       break;
10185     case Intrinsic::ppc_altivec_vcmpgtsq:
10186       CompareOpc = 903;
10187       break;
10188     case Intrinsic::ppc_altivec_vcmpgtuq:
10189       CompareOpc = 647;
10190       break;
10191     }
10192     break;
10193 
10194   // VSX predicate comparisons use the same infrastructure
10195   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10196   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10197   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10198   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10199   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10200   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10201     if (Subtarget.hasVSX()) {
10202       switch (IntrinsicID) {
10203       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10204         CompareOpc = 99;
10205         break;
10206       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10207         CompareOpc = 115;
10208         break;
10209       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10210         CompareOpc = 107;
10211         break;
10212       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10213         CompareOpc = 67;
10214         break;
10215       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10216         CompareOpc = 83;
10217         break;
10218       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10219         CompareOpc = 75;
10220         break;
10221       }
10222       isDot = true;
10223     } else
10224       return false;
10225     break;
10226 
10227   // Normal Comparisons.
10228   case Intrinsic::ppc_altivec_vcmpbfp:
10229     CompareOpc = 966;
10230     break;
10231   case Intrinsic::ppc_altivec_vcmpeqfp:
10232     CompareOpc = 198;
10233     break;
10234   case Intrinsic::ppc_altivec_vcmpequb:
10235     CompareOpc = 6;
10236     break;
10237   case Intrinsic::ppc_altivec_vcmpequh:
10238     CompareOpc = 70;
10239     break;
10240   case Intrinsic::ppc_altivec_vcmpequw:
10241     CompareOpc = 134;
10242     break;
10243   case Intrinsic::ppc_altivec_vcmpequd:
10244     if (Subtarget.hasP8Altivec())
10245       CompareOpc = 199;
10246     else
10247       return false;
10248     break;
10249   case Intrinsic::ppc_altivec_vcmpneb:
10250   case Intrinsic::ppc_altivec_vcmpneh:
10251   case Intrinsic::ppc_altivec_vcmpnew:
10252   case Intrinsic::ppc_altivec_vcmpnezb:
10253   case Intrinsic::ppc_altivec_vcmpnezh:
10254   case Intrinsic::ppc_altivec_vcmpnezw:
10255     if (Subtarget.hasP9Altivec())
10256       switch (IntrinsicID) {
10257       default:
10258         llvm_unreachable("Unknown comparison intrinsic.");
10259       case Intrinsic::ppc_altivec_vcmpneb:
10260         CompareOpc = 7;
10261         break;
10262       case Intrinsic::ppc_altivec_vcmpneh:
10263         CompareOpc = 71;
10264         break;
10265       case Intrinsic::ppc_altivec_vcmpnew:
10266         CompareOpc = 135;
10267         break;
10268       case Intrinsic::ppc_altivec_vcmpnezb:
10269         CompareOpc = 263;
10270         break;
10271       case Intrinsic::ppc_altivec_vcmpnezh:
10272         CompareOpc = 327;
10273         break;
10274       case Intrinsic::ppc_altivec_vcmpnezw:
10275         CompareOpc = 391;
10276         break;
10277       }
10278     else
10279       return false;
10280     break;
10281   case Intrinsic::ppc_altivec_vcmpgefp:
10282     CompareOpc = 454;
10283     break;
10284   case Intrinsic::ppc_altivec_vcmpgtfp:
10285     CompareOpc = 710;
10286     break;
10287   case Intrinsic::ppc_altivec_vcmpgtsb:
10288     CompareOpc = 774;
10289     break;
10290   case Intrinsic::ppc_altivec_vcmpgtsh:
10291     CompareOpc = 838;
10292     break;
10293   case Intrinsic::ppc_altivec_vcmpgtsw:
10294     CompareOpc = 902;
10295     break;
10296   case Intrinsic::ppc_altivec_vcmpgtsd:
10297     if (Subtarget.hasP8Altivec())
10298       CompareOpc = 967;
10299     else
10300       return false;
10301     break;
10302   case Intrinsic::ppc_altivec_vcmpgtub:
10303     CompareOpc = 518;
10304     break;
10305   case Intrinsic::ppc_altivec_vcmpgtuh:
10306     CompareOpc = 582;
10307     break;
10308   case Intrinsic::ppc_altivec_vcmpgtuw:
10309     CompareOpc = 646;
10310     break;
10311   case Intrinsic::ppc_altivec_vcmpgtud:
10312     if (Subtarget.hasP8Altivec())
10313       CompareOpc = 711;
10314     else
10315       return false;
10316     break;
10317   case Intrinsic::ppc_altivec_vcmpequq_p:
10318   case Intrinsic::ppc_altivec_vcmpgtsq_p:
10319   case Intrinsic::ppc_altivec_vcmpgtuq_p:
10320     if (!Subtarget.isISA3_1())
10321       return false;
10322     switch (IntrinsicID) {
10323     default:
10324       llvm_unreachable("Unknown comparison intrinsic.");
10325     case Intrinsic::ppc_altivec_vcmpequq_p:
10326       CompareOpc = 455;
10327       break;
10328     case Intrinsic::ppc_altivec_vcmpgtsq_p:
10329       CompareOpc = 903;
10330       break;
10331     case Intrinsic::ppc_altivec_vcmpgtuq_p:
10332       CompareOpc = 647;
10333       break;
10334     }
10335     isDot = true;
10336     break;
10337   }
10338   return true;
10339 }
10340 
10341 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10342 /// lower, do it, otherwise return null.
10343 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10344                                                    SelectionDAG &DAG) const {
10345   unsigned IntrinsicID =
10346     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10347 
10348   SDLoc dl(Op);
10349 
10350   switch (IntrinsicID) {
10351   case Intrinsic::thread_pointer:
10352     // Reads the thread pointer register, used for __builtin_thread_pointer.
10353     if (Subtarget.isPPC64())
10354       return DAG.getRegister(PPC::X13, MVT::i64);
10355     return DAG.getRegister(PPC::R2, MVT::i32);
10356 
10357   case Intrinsic::ppc_mma_disassemble_acc:
10358   case Intrinsic::ppc_vsx_disassemble_pair: {
10359     int NumVecs = 2;
10360     SDValue WideVec = Op.getOperand(1);
10361     if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
10362       NumVecs = 4;
10363       WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
10364     }
10365     SmallVector<SDValue, 4> RetOps;
10366     for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
10367       SDValue Extract = DAG.getNode(
10368           PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
10369           DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
10370                                                      : VecNo,
10371                           dl, getPointerTy(DAG.getDataLayout())));
10372       RetOps.push_back(Extract);
10373     }
10374     return DAG.getMergeValues(RetOps, dl);
10375   }
10376   case Intrinsic::ppc_compare_exp_lt:
10377   case Intrinsic::ppc_compare_exp_gt:
10378   case Intrinsic::ppc_compare_exp_eq:
10379   case Intrinsic::ppc_compare_exp_uo: {
10380     unsigned Pred;
10381     switch (IntrinsicID) {
10382     case Intrinsic::ppc_compare_exp_lt:
10383       Pred = PPC::PRED_LT;
10384       break;
10385     case Intrinsic::ppc_compare_exp_gt:
10386       Pred = PPC::PRED_GT;
10387       break;
10388     case Intrinsic::ppc_compare_exp_eq:
10389       Pred = PPC::PRED_EQ;
10390       break;
10391     case Intrinsic::ppc_compare_exp_uo:
10392       Pred = PPC::PRED_UN;
10393       break;
10394     }
10395     return SDValue(
10396         DAG.getMachineNode(
10397             PPC::SELECT_CC_I4, dl, MVT::i32,
10398             {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32,
10399                                         Op.getOperand(1), Op.getOperand(2)),
10400                      0),
10401              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10402              DAG.getTargetConstant(Pred, dl, MVT::i32)}),
10403         0);
10404   }
10405   case Intrinsic::ppc_test_data_class_d:
10406   case Intrinsic::ppc_test_data_class_f: {
10407     unsigned CmprOpc = PPC::XSTSTDCDP;
10408     if (IntrinsicID == Intrinsic::ppc_test_data_class_f)
10409       CmprOpc = PPC::XSTSTDCSP;
10410     return SDValue(
10411         DAG.getMachineNode(
10412             PPC::SELECT_CC_I4, dl, MVT::i32,
10413             {SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32, Op.getOperand(2),
10414                                         Op.getOperand(1)),
10415                      0),
10416              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10417              DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}),
10418         0);
10419   }
10420   }
10421 
10422   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10423   // opcode number of the comparison.
10424   int CompareOpc;
10425   bool isDot;
10426   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10427     return SDValue();    // Don't custom lower most intrinsics.
10428 
10429   // If this is a non-dot comparison, make the VCMP node and we are done.
10430   if (!isDot) {
10431     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10432                               Op.getOperand(1), Op.getOperand(2),
10433                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10434     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10435   }
10436 
10437   // Create the PPCISD altivec 'dot' comparison node.
10438   SDValue Ops[] = {
10439     Op.getOperand(2),  // LHS
10440     Op.getOperand(3),  // RHS
10441     DAG.getConstant(CompareOpc, dl, MVT::i32)
10442   };
10443   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10444   SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
10445 
10446   // Now that we have the comparison, emit a copy from the CR to a GPR.
10447   // This is flagged to the above dot comparison.
10448   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10449                                 DAG.getRegister(PPC::CR6, MVT::i32),
10450                                 CompNode.getValue(1));
10451 
10452   // Unpack the result based on how the target uses it.
10453   unsigned BitNo;   // Bit # of CR6.
10454   bool InvertBit;   // Invert result?
10455   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10456   default:  // Can't happen, don't crash on invalid number though.
10457   case 0:   // Return the value of the EQ bit of CR6.
10458     BitNo = 0; InvertBit = false;
10459     break;
10460   case 1:   // Return the inverted value of the EQ bit of CR6.
10461     BitNo = 0; InvertBit = true;
10462     break;
10463   case 2:   // Return the value of the LT bit of CR6.
10464     BitNo = 2; InvertBit = false;
10465     break;
10466   case 3:   // Return the inverted value of the LT bit of CR6.
10467     BitNo = 2; InvertBit = true;
10468     break;
10469   }
10470 
10471   // Shift the bit into the low position.
10472   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10473                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10474   // Isolate the bit.
10475   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10476                       DAG.getConstant(1, dl, MVT::i32));
10477 
10478   // If we are supposed to, toggle the bit.
10479   if (InvertBit)
10480     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10481                         DAG.getConstant(1, dl, MVT::i32));
10482   return Flags;
10483 }
10484 
10485 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10486                                                SelectionDAG &DAG) const {
10487   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10488   // the beginning of the argument list.
10489   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10490   SDLoc DL(Op);
10491   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10492   case Intrinsic::ppc_cfence: {
10493     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10494     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10495     SDValue Val = Op.getOperand(ArgStart + 1);
10496     EVT Ty = Val.getValueType();
10497     if (Ty == MVT::i128) {
10498       // FIXME: Testing one of two paired registers is sufficient to guarantee
10499       // ordering?
10500       Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val);
10501     }
10502     return SDValue(
10503         DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10504                            DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Val),
10505                            Op.getOperand(0)),
10506         0);
10507   }
10508   default:
10509     break;
10510   }
10511   return SDValue();
10512 }
10513 
10514 // Lower scalar BSWAP64 to xxbrd.
10515 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10516   SDLoc dl(Op);
10517   if (!Subtarget.isPPC64())
10518     return Op;
10519   // MTVSRDD
10520   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10521                    Op.getOperand(0));
10522   // XXBRD
10523   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10524   // MFVSRD
10525   int VectorIndex = 0;
10526   if (Subtarget.isLittleEndian())
10527     VectorIndex = 1;
10528   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10529                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10530   return Op;
10531 }
10532 
10533 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10534 // compared to a value that is atomically loaded (atomic loads zero-extend).
10535 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10536                                                 SelectionDAG &DAG) const {
10537   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10538          "Expecting an atomic compare-and-swap here.");
10539   SDLoc dl(Op);
10540   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10541   EVT MemVT = AtomicNode->getMemoryVT();
10542   if (MemVT.getSizeInBits() >= 32)
10543     return Op;
10544 
10545   SDValue CmpOp = Op.getOperand(2);
10546   // If this is already correctly zero-extended, leave it alone.
10547   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10548   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10549     return Op;
10550 
10551   // Clear the high bits of the compare operand.
10552   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10553   SDValue NewCmpOp =
10554     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10555                 DAG.getConstant(MaskVal, dl, MVT::i32));
10556 
10557   // Replace the existing compare operand with the properly zero-extended one.
10558   SmallVector<SDValue, 4> Ops;
10559   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10560     Ops.push_back(AtomicNode->getOperand(i));
10561   Ops[2] = NewCmpOp;
10562   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10563   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10564   auto NodeTy =
10565     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10566   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10567 }
10568 
10569 SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op,
10570                                                   SelectionDAG &DAG) const {
10571   AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode());
10572   EVT MemVT = N->getMemoryVT();
10573   assert(MemVT.getSimpleVT() == MVT::i128 &&
10574          "Expect quadword atomic operations");
10575   SDLoc dl(N);
10576   unsigned Opc = N->getOpcode();
10577   switch (Opc) {
10578   case ISD::ATOMIC_LOAD: {
10579     // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be
10580     // lowered to ppc instructions by pattern matching instruction selector.
10581     SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
10582     SmallVector<SDValue, 4> Ops{
10583         N->getOperand(0),
10584         DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)};
10585     for (int I = 1, E = N->getNumOperands(); I < E; ++I)
10586       Ops.push_back(N->getOperand(I));
10587     SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys,
10588                                                 Ops, MemVT, N->getMemOperand());
10589     SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal);
10590     SDValue ValHi =
10591         DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1));
10592     ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi,
10593                         DAG.getConstant(64, dl, MVT::i32));
10594     SDValue Val =
10595         DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi});
10596     return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other},
10597                        {Val, LoadedVal.getValue(2)});
10598   }
10599   case ISD::ATOMIC_STORE: {
10600     // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be
10601     // lowered to ppc instructions by pattern matching instruction selector.
10602     SDVTList Tys = DAG.getVTList(MVT::Other);
10603     SmallVector<SDValue, 4> Ops{
10604         N->getOperand(0),
10605         DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)};
10606     SDValue Val = N->getOperand(2);
10607     SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val);
10608     SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val,
10609                                 DAG.getConstant(64, dl, MVT::i32));
10610     ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi);
10611     Ops.push_back(ValLo);
10612     Ops.push_back(ValHi);
10613     Ops.push_back(N->getOperand(1));
10614     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT,
10615                                    N->getMemOperand());
10616   }
10617   default:
10618     llvm_unreachable("Unexpected atomic opcode");
10619   }
10620 }
10621 
10622 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10623                                                  SelectionDAG &DAG) const {
10624   SDLoc dl(Op);
10625   // Create a stack slot that is 16-byte aligned.
10626   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10627   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10628   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10629   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10630 
10631   // Store the input value into Value#0 of the stack slot.
10632   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10633                                MachinePointerInfo());
10634   // Load it out.
10635   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10636 }
10637 
10638 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10639                                                   SelectionDAG &DAG) const {
10640   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10641          "Should only be called for ISD::INSERT_VECTOR_ELT");
10642 
10643   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10644 
10645   EVT VT = Op.getValueType();
10646   SDLoc dl(Op);
10647   SDValue V1 = Op.getOperand(0);
10648   SDValue V2 = Op.getOperand(1);
10649   SDValue V3 = Op.getOperand(2);
10650 
10651   if (VT == MVT::v2f64 && C)
10652     return Op;
10653 
10654   if (Subtarget.isISA3_1()) {
10655     if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64())
10656       return SDValue();
10657     // On P10, we have legal lowering for constant and variable indices for
10658     // integer vectors.
10659     if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
10660         VT == MVT::v2i64)
10661       return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3);
10662     // For f32 and f64 vectors, we have legal lowering for variable indices.
10663     // For f32 we also have legal lowering when the element is loaded from
10664     // memory.
10665     if (VT == MVT::v4f32 || VT == MVT::v2f64) {
10666       if (!C || (VT == MVT::v4f32 && dyn_cast<LoadSDNode>(V2)))
10667         return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3);
10668       return Op;
10669     }
10670   }
10671 
10672   // Before P10, we have legal lowering for constant indices but not for
10673   // variable ones.
10674   if (!C)
10675     return SDValue();
10676 
10677   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10678   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10679     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10680     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10681     unsigned InsertAtElement = C->getZExtValue();
10682     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10683     if (Subtarget.isLittleEndian()) {
10684       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10685     }
10686     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10687                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10688   }
10689   return Op;
10690 }
10691 
10692 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10693                                            SelectionDAG &DAG) const {
10694   SDLoc dl(Op);
10695   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10696   SDValue LoadChain = LN->getChain();
10697   SDValue BasePtr = LN->getBasePtr();
10698   EVT VT = Op.getValueType();
10699 
10700   if (VT != MVT::v256i1 && VT != MVT::v512i1)
10701     return Op;
10702 
10703   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10704   // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
10705   // 2 or 4 vsx registers.
10706   assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
10707          "Type unsupported without MMA");
10708   assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10709          "Type unsupported without paired vector support");
10710   Align Alignment = LN->getAlign();
10711   SmallVector<SDValue, 4> Loads;
10712   SmallVector<SDValue, 4> LoadChains;
10713   unsigned NumVecs = VT.getSizeInBits() / 128;
10714   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10715     SDValue Load =
10716         DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
10717                     LN->getPointerInfo().getWithOffset(Idx * 16),
10718                     commonAlignment(Alignment, Idx * 16),
10719                     LN->getMemOperand()->getFlags(), LN->getAAInfo());
10720     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10721                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10722     Loads.push_back(Load);
10723     LoadChains.push_back(Load.getValue(1));
10724   }
10725   if (Subtarget.isLittleEndian()) {
10726     std::reverse(Loads.begin(), Loads.end());
10727     std::reverse(LoadChains.begin(), LoadChains.end());
10728   }
10729   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10730   SDValue Value =
10731       DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
10732                   dl, VT, Loads);
10733   SDValue RetOps[] = {Value, TF};
10734   return DAG.getMergeValues(RetOps, dl);
10735 }
10736 
10737 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10738                                             SelectionDAG &DAG) const {
10739   SDLoc dl(Op);
10740   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10741   SDValue StoreChain = SN->getChain();
10742   SDValue BasePtr = SN->getBasePtr();
10743   SDValue Value = SN->getValue();
10744   EVT StoreVT = Value.getValueType();
10745 
10746   if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
10747     return Op;
10748 
10749   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10750   // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
10751   // underlying registers individually.
10752   assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
10753          "Type unsupported without MMA");
10754   assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10755          "Type unsupported without paired vector support");
10756   Align Alignment = SN->getAlign();
10757   SmallVector<SDValue, 4> Stores;
10758   unsigned NumVecs = 2;
10759   if (StoreVT == MVT::v512i1) {
10760     Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
10761     NumVecs = 4;
10762   }
10763   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10764     unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
10765     SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
10766                               DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
10767     SDValue Store =
10768         DAG.getStore(StoreChain, dl, Elt, BasePtr,
10769                      SN->getPointerInfo().getWithOffset(Idx * 16),
10770                      commonAlignment(Alignment, Idx * 16),
10771                      SN->getMemOperand()->getFlags(), SN->getAAInfo());
10772     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10773                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10774     Stores.push_back(Store);
10775   }
10776   SDValue TF = DAG.getTokenFactor(dl, Stores);
10777   return TF;
10778 }
10779 
10780 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10781   SDLoc dl(Op);
10782   if (Op.getValueType() == MVT::v4i32) {
10783     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10784 
10785     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10786     // +16 as shift amt.
10787     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10788     SDValue RHSSwap =   // = vrlw RHS, 16
10789       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10790 
10791     // Shrinkify inputs to v8i16.
10792     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10793     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10794     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10795 
10796     // Low parts multiplied together, generating 32-bit results (we ignore the
10797     // top parts).
10798     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10799                                         LHS, RHS, DAG, dl, MVT::v4i32);
10800 
10801     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10802                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10803     // Shift the high parts up 16 bits.
10804     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10805                               Neg16, DAG, dl);
10806     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10807   } else if (Op.getValueType() == MVT::v16i8) {
10808     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10809     bool isLittleEndian = Subtarget.isLittleEndian();
10810 
10811     // Multiply the even 8-bit parts, producing 16-bit sums.
10812     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10813                                            LHS, RHS, DAG, dl, MVT::v8i16);
10814     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10815 
10816     // Multiply the odd 8-bit parts, producing 16-bit sums.
10817     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10818                                           LHS, RHS, DAG, dl, MVT::v8i16);
10819     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10820 
10821     // Merge the results together.  Because vmuleub and vmuloub are
10822     // instructions with a big-endian bias, we must reverse the
10823     // element numbering and reverse the meaning of "odd" and "even"
10824     // when generating little endian code.
10825     int Ops[16];
10826     for (unsigned i = 0; i != 8; ++i) {
10827       if (isLittleEndian) {
10828         Ops[i*2  ] = 2*i;
10829         Ops[i*2+1] = 2*i+16;
10830       } else {
10831         Ops[i*2  ] = 2*i+1;
10832         Ops[i*2+1] = 2*i+1+16;
10833       }
10834     }
10835     if (isLittleEndian)
10836       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10837     else
10838       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10839   } else {
10840     llvm_unreachable("Unknown mul to lower!");
10841   }
10842 }
10843 
10844 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10845   bool IsStrict = Op->isStrictFPOpcode();
10846   if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
10847       !Subtarget.hasP9Vector())
10848     return SDValue();
10849 
10850   return Op;
10851 }
10852 
10853 // Custom lowering for fpext vf32 to v2f64
10854 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10855 
10856   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10857          "Should only be called for ISD::FP_EXTEND");
10858 
10859   // FIXME: handle extends from half precision float vectors on P9.
10860   // We only want to custom lower an extend from v2f32 to v2f64.
10861   if (Op.getValueType() != MVT::v2f64 ||
10862       Op.getOperand(0).getValueType() != MVT::v2f32)
10863     return SDValue();
10864 
10865   SDLoc dl(Op);
10866   SDValue Op0 = Op.getOperand(0);
10867 
10868   switch (Op0.getOpcode()) {
10869   default:
10870     return SDValue();
10871   case ISD::EXTRACT_SUBVECTOR: {
10872     assert(Op0.getNumOperands() == 2 &&
10873            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10874            "Node should have 2 operands with second one being a constant!");
10875 
10876     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10877       return SDValue();
10878 
10879     // Custom lower is only done for high or low doubleword.
10880     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10881     if (Idx % 2 != 0)
10882       return SDValue();
10883 
10884     // Since input is v4f32, at this point Idx is either 0 or 2.
10885     // Shift to get the doubleword position we want.
10886     int DWord = Idx >> 1;
10887 
10888     // High and low word positions are different on little endian.
10889     if (Subtarget.isLittleEndian())
10890       DWord ^= 0x1;
10891 
10892     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10893                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10894   }
10895   case ISD::FADD:
10896   case ISD::FMUL:
10897   case ISD::FSUB: {
10898     SDValue NewLoad[2];
10899     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10900       // Ensure both input are loads.
10901       SDValue LdOp = Op0.getOperand(i);
10902       if (LdOp.getOpcode() != ISD::LOAD)
10903         return SDValue();
10904       // Generate new load node.
10905       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10906       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10907       NewLoad[i] = DAG.getMemIntrinsicNode(
10908           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10909           LD->getMemoryVT(), LD->getMemOperand());
10910     }
10911     SDValue NewOp =
10912         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10913                     NewLoad[1], Op0.getNode()->getFlags());
10914     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10915                        DAG.getConstant(0, dl, MVT::i32));
10916   }
10917   case ISD::LOAD: {
10918     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10919     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10920     SDValue NewLd = DAG.getMemIntrinsicNode(
10921         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10922         LD->getMemoryVT(), LD->getMemOperand());
10923     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10924                        DAG.getConstant(0, dl, MVT::i32));
10925   }
10926   }
10927   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10928 }
10929 
10930 /// LowerOperation - Provide custom lowering hooks for some operations.
10931 ///
10932 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10933   switch (Op.getOpcode()) {
10934   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10935   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10936   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10937   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10938   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10939   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10940   case ISD::STRICT_FSETCC:
10941   case ISD::STRICT_FSETCCS:
10942   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10943   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10944   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10945 
10946   case ISD::INLINEASM:
10947   case ISD::INLINEASM_BR:       return LowerINLINEASM(Op, DAG);
10948   // Variable argument lowering.
10949   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10950   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10951   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10952 
10953   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10954   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10955   case ISD::GET_DYNAMIC_AREA_OFFSET:
10956     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10957 
10958   // Exception handling lowering.
10959   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10960   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10961   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10962 
10963   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10964   case ISD::STORE:              return LowerSTORE(Op, DAG);
10965   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10966   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10967   case ISD::STRICT_FP_TO_UINT:
10968   case ISD::STRICT_FP_TO_SINT:
10969   case ISD::FP_TO_UINT:
10970   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10971   case ISD::STRICT_UINT_TO_FP:
10972   case ISD::STRICT_SINT_TO_FP:
10973   case ISD::UINT_TO_FP:
10974   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10975   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10976 
10977   // Lower 64-bit shifts.
10978   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10979   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10980   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10981 
10982   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
10983   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
10984 
10985   // Vector-related lowering.
10986   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10987   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10988   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10989   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10990   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10991   case ISD::MUL:                return LowerMUL(Op, DAG);
10992   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10993   case ISD::STRICT_FP_ROUND:
10994   case ISD::FP_ROUND:
10995     return LowerFP_ROUND(Op, DAG);
10996   case ISD::ROTL:               return LowerROTL(Op, DAG);
10997 
10998   // For counter-based loop handling.
10999   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
11000 
11001   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11002 
11003   // Frame & Return address.
11004   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11005   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11006 
11007   case ISD::INTRINSIC_VOID:
11008     return LowerINTRINSIC_VOID(Op, DAG);
11009   case ISD::BSWAP:
11010     return LowerBSWAP(Op, DAG);
11011   case ISD::ATOMIC_CMP_SWAP:
11012     return LowerATOMIC_CMP_SWAP(Op, DAG);
11013   case ISD::ATOMIC_STORE:
11014     return LowerATOMIC_LOAD_STORE(Op, DAG);
11015   }
11016 }
11017 
11018 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
11019                                            SmallVectorImpl<SDValue>&Results,
11020                                            SelectionDAG &DAG) const {
11021   SDLoc dl(N);
11022   switch (N->getOpcode()) {
11023   default:
11024     llvm_unreachable("Do not know how to custom type legalize this operation!");
11025   case ISD::ATOMIC_LOAD: {
11026     SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG);
11027     Results.push_back(Res);
11028     Results.push_back(Res.getValue(1));
11029     break;
11030   }
11031   case ISD::READCYCLECOUNTER: {
11032     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11033     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
11034 
11035     Results.push_back(
11036         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
11037     Results.push_back(RTB.getValue(2));
11038     break;
11039   }
11040   case ISD::INTRINSIC_W_CHAIN: {
11041     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
11042         Intrinsic::loop_decrement)
11043       break;
11044 
11045     assert(N->getValueType(0) == MVT::i1 &&
11046            "Unexpected result type for CTR decrement intrinsic");
11047     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11048                                  N->getValueType(0));
11049     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
11050     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
11051                                  N->getOperand(1));
11052 
11053     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
11054     Results.push_back(NewInt.getValue(1));
11055     break;
11056   }
11057   case ISD::VAARG: {
11058     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
11059       return;
11060 
11061     EVT VT = N->getValueType(0);
11062 
11063     if (VT == MVT::i64) {
11064       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
11065 
11066       Results.push_back(NewNode);
11067       Results.push_back(NewNode.getValue(1));
11068     }
11069     return;
11070   }
11071   case ISD::STRICT_FP_TO_SINT:
11072   case ISD::STRICT_FP_TO_UINT:
11073   case ISD::FP_TO_SINT:
11074   case ISD::FP_TO_UINT:
11075     // LowerFP_TO_INT() can only handle f32 and f64.
11076     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
11077         MVT::ppcf128)
11078       return;
11079     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
11080     return;
11081   case ISD::TRUNCATE: {
11082     if (!N->getValueType(0).isVector())
11083       return;
11084     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
11085     if (Lowered)
11086       Results.push_back(Lowered);
11087     return;
11088   }
11089   case ISD::FSHL:
11090   case ISD::FSHR:
11091     // Don't handle funnel shifts here.
11092     return;
11093   case ISD::BITCAST:
11094     // Don't handle bitcast here.
11095     return;
11096   case ISD::FP_EXTEND:
11097     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
11098     if (Lowered)
11099       Results.push_back(Lowered);
11100     return;
11101   }
11102 }
11103 
11104 //===----------------------------------------------------------------------===//
11105 //  Other Lowering Code
11106 //===----------------------------------------------------------------------===//
11107 
11108 static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) {
11109   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11110   Function *Func = Intrinsic::getDeclaration(M, Id);
11111   return Builder.CreateCall(Func, {});
11112 }
11113 
11114 // The mappings for emitLeading/TrailingFence is taken from
11115 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11116 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11117                                                  Instruction *Inst,
11118                                                  AtomicOrdering Ord) const {
11119   if (Ord == AtomicOrdering::SequentiallyConsistent)
11120     return callIntrinsic(Builder, Intrinsic::ppc_sync);
11121   if (isReleaseOrStronger(Ord))
11122     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11123   return nullptr;
11124 }
11125 
11126 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11127                                                   Instruction *Inst,
11128                                                   AtomicOrdering Ord) const {
11129   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11130     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11131     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11132     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11133     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11134       return Builder.CreateCall(
11135           Intrinsic::getDeclaration(
11136               Builder.GetInsertBlock()->getParent()->getParent(),
11137               Intrinsic::ppc_cfence, {Inst->getType()}),
11138           {Inst});
11139     // FIXME: Can use isync for rmw operation.
11140     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11141   }
11142   return nullptr;
11143 }
11144 
11145 MachineBasicBlock *
11146 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11147                                     unsigned AtomicSize,
11148                                     unsigned BinOpcode,
11149                                     unsigned CmpOpcode,
11150                                     unsigned CmpPred) const {
11151   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11152   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11153 
11154   auto LoadMnemonic = PPC::LDARX;
11155   auto StoreMnemonic = PPC::STDCX;
11156   switch (AtomicSize) {
11157   default:
11158     llvm_unreachable("Unexpected size of atomic entity");
11159   case 1:
11160     LoadMnemonic = PPC::LBARX;
11161     StoreMnemonic = PPC::STBCX;
11162     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11163     break;
11164   case 2:
11165     LoadMnemonic = PPC::LHARX;
11166     StoreMnemonic = PPC::STHCX;
11167     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11168     break;
11169   case 4:
11170     LoadMnemonic = PPC::LWARX;
11171     StoreMnemonic = PPC::STWCX;
11172     break;
11173   case 8:
11174     LoadMnemonic = PPC::LDARX;
11175     StoreMnemonic = PPC::STDCX;
11176     break;
11177   }
11178 
11179   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11180   MachineFunction *F = BB->getParent();
11181   MachineFunction::iterator It = ++BB->getIterator();
11182 
11183   Register dest = MI.getOperand(0).getReg();
11184   Register ptrA = MI.getOperand(1).getReg();
11185   Register ptrB = MI.getOperand(2).getReg();
11186   Register incr = MI.getOperand(3).getReg();
11187   DebugLoc dl = MI.getDebugLoc();
11188 
11189   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11190   MachineBasicBlock *loop2MBB =
11191     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11192   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11193   F->insert(It, loopMBB);
11194   if (CmpOpcode)
11195     F->insert(It, loop2MBB);
11196   F->insert(It, exitMBB);
11197   exitMBB->splice(exitMBB->begin(), BB,
11198                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11199   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11200 
11201   MachineRegisterInfo &RegInfo = F->getRegInfo();
11202   Register TmpReg = (!BinOpcode) ? incr :
11203     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11204                                            : &PPC::GPRCRegClass);
11205 
11206   //  thisMBB:
11207   //   ...
11208   //   fallthrough --> loopMBB
11209   BB->addSuccessor(loopMBB);
11210 
11211   //  loopMBB:
11212   //   l[wd]arx dest, ptr
11213   //   add r0, dest, incr
11214   //   st[wd]cx. r0, ptr
11215   //   bne- loopMBB
11216   //   fallthrough --> exitMBB
11217 
11218   // For max/min...
11219   //  loopMBB:
11220   //   l[wd]arx dest, ptr
11221   //   cmpl?[wd] incr, dest
11222   //   bgt exitMBB
11223   //  loop2MBB:
11224   //   st[wd]cx. dest, ptr
11225   //   bne- loopMBB
11226   //   fallthrough --> exitMBB
11227 
11228   BB = loopMBB;
11229   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11230     .addReg(ptrA).addReg(ptrB);
11231   if (BinOpcode)
11232     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11233   if (CmpOpcode) {
11234     // Signed comparisons of byte or halfword values must be sign-extended.
11235     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11236       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11237       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11238               ExtReg).addReg(dest);
11239       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11240         .addReg(incr).addReg(ExtReg);
11241     } else
11242       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11243         .addReg(incr).addReg(dest);
11244 
11245     BuildMI(BB, dl, TII->get(PPC::BCC))
11246       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11247     BB->addSuccessor(loop2MBB);
11248     BB->addSuccessor(exitMBB);
11249     BB = loop2MBB;
11250   }
11251   BuildMI(BB, dl, TII->get(StoreMnemonic))
11252     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11253   BuildMI(BB, dl, TII->get(PPC::BCC))
11254     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11255   BB->addSuccessor(loopMBB);
11256   BB->addSuccessor(exitMBB);
11257 
11258   //  exitMBB:
11259   //   ...
11260   BB = exitMBB;
11261   return BB;
11262 }
11263 
11264 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) {
11265   switch(MI.getOpcode()) {
11266   default:
11267     return false;
11268   case PPC::COPY:
11269     return TII->isSignExtended(MI);
11270   case PPC::LHA:
11271   case PPC::LHA8:
11272   case PPC::LHAU:
11273   case PPC::LHAU8:
11274   case PPC::LHAUX:
11275   case PPC::LHAUX8:
11276   case PPC::LHAX:
11277   case PPC::LHAX8:
11278   case PPC::LWA:
11279   case PPC::LWAUX:
11280   case PPC::LWAX:
11281   case PPC::LWAX_32:
11282   case PPC::LWA_32:
11283   case PPC::PLHA:
11284   case PPC::PLHA8:
11285   case PPC::PLHA8pc:
11286   case PPC::PLHApc:
11287   case PPC::PLWA:
11288   case PPC::PLWA8:
11289   case PPC::PLWA8pc:
11290   case PPC::PLWApc:
11291   case PPC::EXTSB:
11292   case PPC::EXTSB8:
11293   case PPC::EXTSB8_32_64:
11294   case PPC::EXTSB8_rec:
11295   case PPC::EXTSB_rec:
11296   case PPC::EXTSH:
11297   case PPC::EXTSH8:
11298   case PPC::EXTSH8_32_64:
11299   case PPC::EXTSH8_rec:
11300   case PPC::EXTSH_rec:
11301   case PPC::EXTSW:
11302   case PPC::EXTSWSLI:
11303   case PPC::EXTSWSLI_32_64:
11304   case PPC::EXTSWSLI_32_64_rec:
11305   case PPC::EXTSWSLI_rec:
11306   case PPC::EXTSW_32:
11307   case PPC::EXTSW_32_64:
11308   case PPC::EXTSW_32_64_rec:
11309   case PPC::EXTSW_rec:
11310   case PPC::SRAW:
11311   case PPC::SRAWI:
11312   case PPC::SRAWI_rec:
11313   case PPC::SRAW_rec:
11314     return true;
11315   }
11316   return false;
11317 }
11318 
11319 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11320     MachineInstr &MI, MachineBasicBlock *BB,
11321     bool is8bit, // operation
11322     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11323   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11324   const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11325 
11326   // If this is a signed comparison and the value being compared is not known
11327   // to be sign extended, sign extend it here.
11328   DebugLoc dl = MI.getDebugLoc();
11329   MachineFunction *F = BB->getParent();
11330   MachineRegisterInfo &RegInfo = F->getRegInfo();
11331   Register incr = MI.getOperand(3).getReg();
11332   bool IsSignExtended = Register::isVirtualRegister(incr) &&
11333     isSignExtended(*RegInfo.getVRegDef(incr), TII);
11334 
11335   if (CmpOpcode == PPC::CMPW && !IsSignExtended) {
11336     Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11337     BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg)
11338         .addReg(MI.getOperand(3).getReg());
11339     MI.getOperand(3).setReg(ValueReg);
11340   }
11341   // If we support part-word atomic mnemonics, just use them
11342   if (Subtarget.hasPartwordAtomics())
11343     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11344                             CmpPred);
11345 
11346   // In 64 bit mode we have to use 64 bits for addresses, even though the
11347   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11348   // registers without caring whether they're 32 or 64, but here we're
11349   // doing actual arithmetic on the addresses.
11350   bool is64bit = Subtarget.isPPC64();
11351   bool isLittleEndian = Subtarget.isLittleEndian();
11352   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11353 
11354   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11355   MachineFunction::iterator It = ++BB->getIterator();
11356 
11357   Register dest = MI.getOperand(0).getReg();
11358   Register ptrA = MI.getOperand(1).getReg();
11359   Register ptrB = MI.getOperand(2).getReg();
11360 
11361   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11362   MachineBasicBlock *loop2MBB =
11363       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11364   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11365   F->insert(It, loopMBB);
11366   if (CmpOpcode)
11367     F->insert(It, loop2MBB);
11368   F->insert(It, exitMBB);
11369   exitMBB->splice(exitMBB->begin(), BB,
11370                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11371   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11372 
11373   const TargetRegisterClass *RC =
11374       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11375   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11376 
11377   Register PtrReg = RegInfo.createVirtualRegister(RC);
11378   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11379   Register ShiftReg =
11380       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11381   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11382   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11383   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11384   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11385   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11386   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11387   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11388   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11389   Register SrwDestReg = RegInfo.createVirtualRegister(GPRC);
11390   Register Ptr1Reg;
11391   Register TmpReg =
11392       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11393 
11394   //  thisMBB:
11395   //   ...
11396   //   fallthrough --> loopMBB
11397   BB->addSuccessor(loopMBB);
11398 
11399   // The 4-byte load must be aligned, while a char or short may be
11400   // anywhere in the word.  Hence all this nasty bookkeeping code.
11401   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11402   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11403   //   xori shift, shift1, 24 [16]
11404   //   rlwinm ptr, ptr1, 0, 0, 29
11405   //   slw incr2, incr, shift
11406   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11407   //   slw mask, mask2, shift
11408   //  loopMBB:
11409   //   lwarx tmpDest, ptr
11410   //   add tmp, tmpDest, incr2
11411   //   andc tmp2, tmpDest, mask
11412   //   and tmp3, tmp, mask
11413   //   or tmp4, tmp3, tmp2
11414   //   stwcx. tmp4, ptr
11415   //   bne- loopMBB
11416   //   fallthrough --> exitMBB
11417   //   srw SrwDest, tmpDest, shift
11418   //   rlwinm SrwDest, SrwDest, 0, 24 [16], 31
11419   if (ptrA != ZeroReg) {
11420     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11421     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11422         .addReg(ptrA)
11423         .addReg(ptrB);
11424   } else {
11425     Ptr1Reg = ptrB;
11426   }
11427   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11428   // mode.
11429   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11430       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11431       .addImm(3)
11432       .addImm(27)
11433       .addImm(is8bit ? 28 : 27);
11434   if (!isLittleEndian)
11435     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11436         .addReg(Shift1Reg)
11437         .addImm(is8bit ? 24 : 16);
11438   if (is64bit)
11439     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11440         .addReg(Ptr1Reg)
11441         .addImm(0)
11442         .addImm(61);
11443   else
11444     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11445         .addReg(Ptr1Reg)
11446         .addImm(0)
11447         .addImm(0)
11448         .addImm(29);
11449   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11450   if (is8bit)
11451     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11452   else {
11453     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11454     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11455         .addReg(Mask3Reg)
11456         .addImm(65535);
11457   }
11458   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11459       .addReg(Mask2Reg)
11460       .addReg(ShiftReg);
11461 
11462   BB = loopMBB;
11463   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11464       .addReg(ZeroReg)
11465       .addReg(PtrReg);
11466   if (BinOpcode)
11467     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11468         .addReg(Incr2Reg)
11469         .addReg(TmpDestReg);
11470   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11471       .addReg(TmpDestReg)
11472       .addReg(MaskReg);
11473   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11474   if (CmpOpcode) {
11475     // For unsigned comparisons, we can directly compare the shifted values.
11476     // For signed comparisons we shift and sign extend.
11477     Register SReg = RegInfo.createVirtualRegister(GPRC);
11478     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11479         .addReg(TmpDestReg)
11480         .addReg(MaskReg);
11481     unsigned ValueReg = SReg;
11482     unsigned CmpReg = Incr2Reg;
11483     if (CmpOpcode == PPC::CMPW) {
11484       ValueReg = RegInfo.createVirtualRegister(GPRC);
11485       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11486           .addReg(SReg)
11487           .addReg(ShiftReg);
11488       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11489       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11490           .addReg(ValueReg);
11491       ValueReg = ValueSReg;
11492       CmpReg = incr;
11493     }
11494     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11495         .addReg(CmpReg)
11496         .addReg(ValueReg);
11497     BuildMI(BB, dl, TII->get(PPC::BCC))
11498         .addImm(CmpPred)
11499         .addReg(PPC::CR0)
11500         .addMBB(exitMBB);
11501     BB->addSuccessor(loop2MBB);
11502     BB->addSuccessor(exitMBB);
11503     BB = loop2MBB;
11504   }
11505   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11506   BuildMI(BB, dl, TII->get(PPC::STWCX))
11507       .addReg(Tmp4Reg)
11508       .addReg(ZeroReg)
11509       .addReg(PtrReg);
11510   BuildMI(BB, dl, TII->get(PPC::BCC))
11511       .addImm(PPC::PRED_NE)
11512       .addReg(PPC::CR0)
11513       .addMBB(loopMBB);
11514   BB->addSuccessor(loopMBB);
11515   BB->addSuccessor(exitMBB);
11516 
11517   //  exitMBB:
11518   //   ...
11519   BB = exitMBB;
11520   // Since the shift amount is not a constant, we need to clear
11521   // the upper bits with a separate RLWINM.
11522   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest)
11523       .addReg(SrwDestReg)
11524       .addImm(0)
11525       .addImm(is8bit ? 24 : 16)
11526       .addImm(31);
11527   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg)
11528       .addReg(TmpDestReg)
11529       .addReg(ShiftReg);
11530   return BB;
11531 }
11532 
11533 llvm::MachineBasicBlock *
11534 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11535                                     MachineBasicBlock *MBB) const {
11536   DebugLoc DL = MI.getDebugLoc();
11537   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11538   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11539 
11540   MachineFunction *MF = MBB->getParent();
11541   MachineRegisterInfo &MRI = MF->getRegInfo();
11542 
11543   const BasicBlock *BB = MBB->getBasicBlock();
11544   MachineFunction::iterator I = ++MBB->getIterator();
11545 
11546   Register DstReg = MI.getOperand(0).getReg();
11547   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11548   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11549   Register mainDstReg = MRI.createVirtualRegister(RC);
11550   Register restoreDstReg = MRI.createVirtualRegister(RC);
11551 
11552   MVT PVT = getPointerTy(MF->getDataLayout());
11553   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11554          "Invalid Pointer Size!");
11555   // For v = setjmp(buf), we generate
11556   //
11557   // thisMBB:
11558   //  SjLjSetup mainMBB
11559   //  bl mainMBB
11560   //  v_restore = 1
11561   //  b sinkMBB
11562   //
11563   // mainMBB:
11564   //  buf[LabelOffset] = LR
11565   //  v_main = 0
11566   //
11567   // sinkMBB:
11568   //  v = phi(main, restore)
11569   //
11570 
11571   MachineBasicBlock *thisMBB = MBB;
11572   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11573   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11574   MF->insert(I, mainMBB);
11575   MF->insert(I, sinkMBB);
11576 
11577   MachineInstrBuilder MIB;
11578 
11579   // Transfer the remainder of BB and its successor edges to sinkMBB.
11580   sinkMBB->splice(sinkMBB->begin(), MBB,
11581                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11582   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11583 
11584   // Note that the structure of the jmp_buf used here is not compatible
11585   // with that used by libc, and is not designed to be. Specifically, it
11586   // stores only those 'reserved' registers that LLVM does not otherwise
11587   // understand how to spill. Also, by convention, by the time this
11588   // intrinsic is called, Clang has already stored the frame address in the
11589   // first slot of the buffer and stack address in the third. Following the
11590   // X86 target code, we'll store the jump address in the second slot. We also
11591   // need to save the TOC pointer (R2) to handle jumps between shared
11592   // libraries, and that will be stored in the fourth slot. The thread
11593   // identifier (R13) is not affected.
11594 
11595   // thisMBB:
11596   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11597   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11598   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11599 
11600   // Prepare IP either in reg.
11601   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11602   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11603   Register BufReg = MI.getOperand(1).getReg();
11604 
11605   if (Subtarget.is64BitELFABI()) {
11606     setUsesTOCBasePtr(*MBB->getParent());
11607     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11608               .addReg(PPC::X2)
11609               .addImm(TOCOffset)
11610               .addReg(BufReg)
11611               .cloneMemRefs(MI);
11612   }
11613 
11614   // Naked functions never have a base pointer, and so we use r1. For all
11615   // other functions, this decision must be delayed until during PEI.
11616   unsigned BaseReg;
11617   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11618     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11619   else
11620     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11621 
11622   MIB = BuildMI(*thisMBB, MI, DL,
11623                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11624             .addReg(BaseReg)
11625             .addImm(BPOffset)
11626             .addReg(BufReg)
11627             .cloneMemRefs(MI);
11628 
11629   // Setup
11630   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11631   MIB.addRegMask(TRI->getNoPreservedMask());
11632 
11633   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11634 
11635   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11636           .addMBB(mainMBB);
11637   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11638 
11639   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11640   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11641 
11642   // mainMBB:
11643   //  mainDstReg = 0
11644   MIB =
11645       BuildMI(mainMBB, DL,
11646               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11647 
11648   // Store IP
11649   if (Subtarget.isPPC64()) {
11650     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11651             .addReg(LabelReg)
11652             .addImm(LabelOffset)
11653             .addReg(BufReg);
11654   } else {
11655     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11656             .addReg(LabelReg)
11657             .addImm(LabelOffset)
11658             .addReg(BufReg);
11659   }
11660   MIB.cloneMemRefs(MI);
11661 
11662   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11663   mainMBB->addSuccessor(sinkMBB);
11664 
11665   // sinkMBB:
11666   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11667           TII->get(PPC::PHI), DstReg)
11668     .addReg(mainDstReg).addMBB(mainMBB)
11669     .addReg(restoreDstReg).addMBB(thisMBB);
11670 
11671   MI.eraseFromParent();
11672   return sinkMBB;
11673 }
11674 
11675 MachineBasicBlock *
11676 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11677                                      MachineBasicBlock *MBB) const {
11678   DebugLoc DL = MI.getDebugLoc();
11679   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11680 
11681   MachineFunction *MF = MBB->getParent();
11682   MachineRegisterInfo &MRI = MF->getRegInfo();
11683 
11684   MVT PVT = getPointerTy(MF->getDataLayout());
11685   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11686          "Invalid Pointer Size!");
11687 
11688   const TargetRegisterClass *RC =
11689     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11690   Register Tmp = MRI.createVirtualRegister(RC);
11691   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11692   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11693   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11694   unsigned BP =
11695       (PVT == MVT::i64)
11696           ? PPC::X30
11697           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11698                                                               : PPC::R30);
11699 
11700   MachineInstrBuilder MIB;
11701 
11702   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11703   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11704   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11705   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11706 
11707   Register BufReg = MI.getOperand(0).getReg();
11708 
11709   // Reload FP (the jumped-to function may not have had a
11710   // frame pointer, and if so, then its r31 will be restored
11711   // as necessary).
11712   if (PVT == MVT::i64) {
11713     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11714             .addImm(0)
11715             .addReg(BufReg);
11716   } else {
11717     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11718             .addImm(0)
11719             .addReg(BufReg);
11720   }
11721   MIB.cloneMemRefs(MI);
11722 
11723   // Reload IP
11724   if (PVT == MVT::i64) {
11725     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11726             .addImm(LabelOffset)
11727             .addReg(BufReg);
11728   } else {
11729     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11730             .addImm(LabelOffset)
11731             .addReg(BufReg);
11732   }
11733   MIB.cloneMemRefs(MI);
11734 
11735   // Reload SP
11736   if (PVT == MVT::i64) {
11737     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11738             .addImm(SPOffset)
11739             .addReg(BufReg);
11740   } else {
11741     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11742             .addImm(SPOffset)
11743             .addReg(BufReg);
11744   }
11745   MIB.cloneMemRefs(MI);
11746 
11747   // Reload BP
11748   if (PVT == MVT::i64) {
11749     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11750             .addImm(BPOffset)
11751             .addReg(BufReg);
11752   } else {
11753     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11754             .addImm(BPOffset)
11755             .addReg(BufReg);
11756   }
11757   MIB.cloneMemRefs(MI);
11758 
11759   // Reload TOC
11760   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11761     setUsesTOCBasePtr(*MBB->getParent());
11762     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11763               .addImm(TOCOffset)
11764               .addReg(BufReg)
11765               .cloneMemRefs(MI);
11766   }
11767 
11768   // Jump
11769   BuildMI(*MBB, MI, DL,
11770           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11771   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11772 
11773   MI.eraseFromParent();
11774   return MBB;
11775 }
11776 
11777 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11778   // If the function specifically requests inline stack probes, emit them.
11779   if (MF.getFunction().hasFnAttribute("probe-stack"))
11780     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11781            "inline-asm";
11782   return false;
11783 }
11784 
11785 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11786   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11787   unsigned StackAlign = TFI->getStackAlignment();
11788   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11789          "Unexpected stack alignment");
11790   // The default stack probe size is 4096 if the function has no
11791   // stack-probe-size attribute.
11792   unsigned StackProbeSize = 4096;
11793   const Function &Fn = MF.getFunction();
11794   if (Fn.hasFnAttribute("stack-probe-size"))
11795     Fn.getFnAttribute("stack-probe-size")
11796         .getValueAsString()
11797         .getAsInteger(0, StackProbeSize);
11798   // Round down to the stack alignment.
11799   StackProbeSize &= ~(StackAlign - 1);
11800   return StackProbeSize ? StackProbeSize : StackAlign;
11801 }
11802 
11803 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11804 // into three phases. In the first phase, it uses pseudo instruction
11805 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11806 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11807 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11808 // MaxCallFrameSize so that it can calculate correct data area pointer.
11809 MachineBasicBlock *
11810 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11811                                     MachineBasicBlock *MBB) const {
11812   const bool isPPC64 = Subtarget.isPPC64();
11813   MachineFunction *MF = MBB->getParent();
11814   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11815   DebugLoc DL = MI.getDebugLoc();
11816   const unsigned ProbeSize = getStackProbeSize(*MF);
11817   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11818   MachineRegisterInfo &MRI = MF->getRegInfo();
11819   // The CFG of probing stack looks as
11820   //         +-----+
11821   //         | MBB |
11822   //         +--+--+
11823   //            |
11824   //       +----v----+
11825   //  +--->+ TestMBB +---+
11826   //  |    +----+----+   |
11827   //  |         |        |
11828   //  |   +-----v----+   |
11829   //  +---+ BlockMBB |   |
11830   //      +----------+   |
11831   //                     |
11832   //       +---------+   |
11833   //       | TailMBB +<--+
11834   //       +---------+
11835   // In MBB, calculate previous frame pointer and final stack pointer.
11836   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11837   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11838   // TailMBB is spliced via \p MI.
11839   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11840   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11841   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11842 
11843   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11844   MF->insert(MBBIter, TestMBB);
11845   MF->insert(MBBIter, BlockMBB);
11846   MF->insert(MBBIter, TailMBB);
11847 
11848   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11849   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11850 
11851   Register DstReg = MI.getOperand(0).getReg();
11852   Register NegSizeReg = MI.getOperand(1).getReg();
11853   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11854   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11855   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11856   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11857 
11858   // Since value of NegSizeReg might be realigned in prologepilog, insert a
11859   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
11860   // NegSize.
11861   unsigned ProbeOpc;
11862   if (!MRI.hasOneNonDBGUse(NegSizeReg))
11863     ProbeOpc =
11864         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
11865   else
11866     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
11867     // and NegSizeReg will be allocated in the same phyreg to avoid
11868     // redundant copy when NegSizeReg has only one use which is current MI and
11869     // will be replaced by PREPARE_PROBED_ALLOCA then.
11870     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
11871                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
11872   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
11873       .addDef(ActualNegSizeReg)
11874       .addReg(NegSizeReg)
11875       .add(MI.getOperand(2))
11876       .add(MI.getOperand(3));
11877 
11878   // Calculate final stack pointer, which equals to SP + ActualNegSize.
11879   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
11880           FinalStackPtr)
11881       .addReg(SPReg)
11882       .addReg(ActualNegSizeReg);
11883 
11884   // Materialize a scratch register for update.
11885   int64_t NegProbeSize = -(int64_t)ProbeSize;
11886   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
11887   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11888   if (!isInt<16>(NegProbeSize)) {
11889     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11890     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
11891         .addImm(NegProbeSize >> 16);
11892     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
11893             ScratchReg)
11894         .addReg(TempReg)
11895         .addImm(NegProbeSize & 0xFFFF);
11896   } else
11897     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
11898         .addImm(NegProbeSize);
11899 
11900   {
11901     // Probing leading residual part.
11902     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11903     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
11904         .addReg(ActualNegSizeReg)
11905         .addReg(ScratchReg);
11906     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11907     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
11908         .addReg(Div)
11909         .addReg(ScratchReg);
11910     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11911     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
11912         .addReg(Mul)
11913         .addReg(ActualNegSizeReg);
11914     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11915         .addReg(FramePointer)
11916         .addReg(SPReg)
11917         .addReg(NegMod);
11918   }
11919 
11920   {
11921     // Remaining part should be multiple of ProbeSize.
11922     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
11923     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
11924         .addReg(SPReg)
11925         .addReg(FinalStackPtr);
11926     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
11927         .addImm(PPC::PRED_EQ)
11928         .addReg(CmpResult)
11929         .addMBB(TailMBB);
11930     TestMBB->addSuccessor(BlockMBB);
11931     TestMBB->addSuccessor(TailMBB);
11932   }
11933 
11934   {
11935     // Touch the block.
11936     // |P...|P...|P...
11937     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11938         .addReg(FramePointer)
11939         .addReg(SPReg)
11940         .addReg(ScratchReg);
11941     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
11942     BlockMBB->addSuccessor(TestMBB);
11943   }
11944 
11945   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
11946   // DYNAREAOFFSET pseudo instruction to get the future result.
11947   Register MaxCallFrameSizeReg =
11948       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11949   BuildMI(TailMBB, DL,
11950           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
11951           MaxCallFrameSizeReg)
11952       .add(MI.getOperand(2))
11953       .add(MI.getOperand(3));
11954   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
11955       .addReg(SPReg)
11956       .addReg(MaxCallFrameSizeReg);
11957 
11958   // Splice instructions after MI to TailMBB.
11959   TailMBB->splice(TailMBB->end(), MBB,
11960                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11961   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
11962   MBB->addSuccessor(TestMBB);
11963 
11964   // Delete the pseudo instruction.
11965   MI.eraseFromParent();
11966 
11967   ++NumDynamicAllocaProbed;
11968   return TailMBB;
11969 }
11970 
11971 MachineBasicBlock *
11972 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11973                                                MachineBasicBlock *BB) const {
11974   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11975       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11976     if (Subtarget.is64BitELFABI() &&
11977         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11978         !Subtarget.isUsingPCRelativeCalls()) {
11979       // Call lowering should have added an r2 operand to indicate a dependence
11980       // on the TOC base pointer value. It can't however, because there is no
11981       // way to mark the dependence as implicit there, and so the stackmap code
11982       // will confuse it with a regular operand. Instead, add the dependence
11983       // here.
11984       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11985     }
11986 
11987     return emitPatchPoint(MI, BB);
11988   }
11989 
11990   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11991       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11992     return emitEHSjLjSetJmp(MI, BB);
11993   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11994              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11995     return emitEHSjLjLongJmp(MI, BB);
11996   }
11997 
11998   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11999 
12000   // To "insert" these instructions we actually have to insert their
12001   // control-flow patterns.
12002   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12003   MachineFunction::iterator It = ++BB->getIterator();
12004 
12005   MachineFunction *F = BB->getParent();
12006 
12007   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12008       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
12009       MI.getOpcode() == PPC::SELECT_I8) {
12010     SmallVector<MachineOperand, 2> Cond;
12011     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12012         MI.getOpcode() == PPC::SELECT_CC_I8)
12013       Cond.push_back(MI.getOperand(4));
12014     else
12015       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
12016     Cond.push_back(MI.getOperand(1));
12017 
12018     DebugLoc dl = MI.getDebugLoc();
12019     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
12020                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
12021   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
12022              MI.getOpcode() == PPC::SELECT_CC_F8 ||
12023              MI.getOpcode() == PPC::SELECT_CC_F16 ||
12024              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
12025              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
12026              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
12027              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
12028              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
12029              MI.getOpcode() == PPC::SELECT_CC_SPE ||
12030              MI.getOpcode() == PPC::SELECT_F4 ||
12031              MI.getOpcode() == PPC::SELECT_F8 ||
12032              MI.getOpcode() == PPC::SELECT_F16 ||
12033              MI.getOpcode() == PPC::SELECT_SPE ||
12034              MI.getOpcode() == PPC::SELECT_SPE4 ||
12035              MI.getOpcode() == PPC::SELECT_VRRC ||
12036              MI.getOpcode() == PPC::SELECT_VSFRC ||
12037              MI.getOpcode() == PPC::SELECT_VSSRC ||
12038              MI.getOpcode() == PPC::SELECT_VSRC) {
12039     // The incoming instruction knows the destination vreg to set, the
12040     // condition code register to branch on, the true/false values to
12041     // select between, and a branch opcode to use.
12042 
12043     //  thisMBB:
12044     //  ...
12045     //   TrueVal = ...
12046     //   cmpTY ccX, r1, r2
12047     //   bCC copy1MBB
12048     //   fallthrough --> copy0MBB
12049     MachineBasicBlock *thisMBB = BB;
12050     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12051     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12052     DebugLoc dl = MI.getDebugLoc();
12053     F->insert(It, copy0MBB);
12054     F->insert(It, sinkMBB);
12055 
12056     // Transfer the remainder of BB and its successor edges to sinkMBB.
12057     sinkMBB->splice(sinkMBB->begin(), BB,
12058                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12059     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12060 
12061     // Next, add the true and fallthrough blocks as its successors.
12062     BB->addSuccessor(copy0MBB);
12063     BB->addSuccessor(sinkMBB);
12064 
12065     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
12066         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
12067         MI.getOpcode() == PPC::SELECT_F16 ||
12068         MI.getOpcode() == PPC::SELECT_SPE4 ||
12069         MI.getOpcode() == PPC::SELECT_SPE ||
12070         MI.getOpcode() == PPC::SELECT_VRRC ||
12071         MI.getOpcode() == PPC::SELECT_VSFRC ||
12072         MI.getOpcode() == PPC::SELECT_VSSRC ||
12073         MI.getOpcode() == PPC::SELECT_VSRC) {
12074       BuildMI(BB, dl, TII->get(PPC::BC))
12075           .addReg(MI.getOperand(1).getReg())
12076           .addMBB(sinkMBB);
12077     } else {
12078       unsigned SelectPred = MI.getOperand(4).getImm();
12079       BuildMI(BB, dl, TII->get(PPC::BCC))
12080           .addImm(SelectPred)
12081           .addReg(MI.getOperand(1).getReg())
12082           .addMBB(sinkMBB);
12083     }
12084 
12085     //  copy0MBB:
12086     //   %FalseValue = ...
12087     //   # fallthrough to sinkMBB
12088     BB = copy0MBB;
12089 
12090     // Update machine-CFG edges
12091     BB->addSuccessor(sinkMBB);
12092 
12093     //  sinkMBB:
12094     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12095     //  ...
12096     BB = sinkMBB;
12097     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
12098         .addReg(MI.getOperand(3).getReg())
12099         .addMBB(copy0MBB)
12100         .addReg(MI.getOperand(2).getReg())
12101         .addMBB(thisMBB);
12102   } else if (MI.getOpcode() == PPC::ReadTB) {
12103     // To read the 64-bit time-base register on a 32-bit target, we read the
12104     // two halves. Should the counter have wrapped while it was being read, we
12105     // need to try again.
12106     // ...
12107     // readLoop:
12108     // mfspr Rx,TBU # load from TBU
12109     // mfspr Ry,TB  # load from TB
12110     // mfspr Rz,TBU # load from TBU
12111     // cmpw crX,Rx,Rz # check if 'old'='new'
12112     // bne readLoop   # branch if they're not equal
12113     // ...
12114 
12115     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
12116     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12117     DebugLoc dl = MI.getDebugLoc();
12118     F->insert(It, readMBB);
12119     F->insert(It, sinkMBB);
12120 
12121     // Transfer the remainder of BB and its successor edges to sinkMBB.
12122     sinkMBB->splice(sinkMBB->begin(), BB,
12123                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12124     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12125 
12126     BB->addSuccessor(readMBB);
12127     BB = readMBB;
12128 
12129     MachineRegisterInfo &RegInfo = F->getRegInfo();
12130     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
12131     Register LoReg = MI.getOperand(0).getReg();
12132     Register HiReg = MI.getOperand(1).getReg();
12133 
12134     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
12135     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
12136     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
12137 
12138     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12139 
12140     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
12141         .addReg(HiReg)
12142         .addReg(ReadAgainReg);
12143     BuildMI(BB, dl, TII->get(PPC::BCC))
12144         .addImm(PPC::PRED_NE)
12145         .addReg(CmpReg)
12146         .addMBB(readMBB);
12147 
12148     BB->addSuccessor(readMBB);
12149     BB->addSuccessor(sinkMBB);
12150   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
12151     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
12152   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
12153     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
12154   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
12155     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
12156   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
12157     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
12158 
12159   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
12160     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
12161   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
12162     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
12163   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
12164     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
12165   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
12166     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
12167 
12168   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
12169     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
12170   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
12171     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
12172   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
12173     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
12174   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
12175     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
12176 
12177   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
12178     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
12179   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
12180     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
12181   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
12182     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
12183   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
12184     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
12185 
12186   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
12187     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
12188   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
12189     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
12190   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
12191     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
12192   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
12193     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
12194 
12195   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
12196     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
12197   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
12198     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
12199   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
12200     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
12201   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
12202     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
12203 
12204   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
12205     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
12206   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
12207     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
12208   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
12209     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
12210   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
12211     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
12212 
12213   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
12214     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
12215   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
12216     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
12217   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
12218     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
12219   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
12220     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
12221 
12222   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
12223     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
12224   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
12225     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
12226   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
12227     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
12228   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
12229     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
12230 
12231   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
12232     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
12233   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
12234     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
12235   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
12236     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
12237   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
12238     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
12239 
12240   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
12241     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
12242   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
12243     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
12244   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
12245     BB = EmitAtomicBinary(MI, BB, 4, 0);
12246   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
12247     BB = EmitAtomicBinary(MI, BB, 8, 0);
12248   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
12249            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
12250            (Subtarget.hasPartwordAtomics() &&
12251             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
12252            (Subtarget.hasPartwordAtomics() &&
12253             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
12254     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
12255 
12256     auto LoadMnemonic = PPC::LDARX;
12257     auto StoreMnemonic = PPC::STDCX;
12258     switch (MI.getOpcode()) {
12259     default:
12260       llvm_unreachable("Compare and swap of unknown size");
12261     case PPC::ATOMIC_CMP_SWAP_I8:
12262       LoadMnemonic = PPC::LBARX;
12263       StoreMnemonic = PPC::STBCX;
12264       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12265       break;
12266     case PPC::ATOMIC_CMP_SWAP_I16:
12267       LoadMnemonic = PPC::LHARX;
12268       StoreMnemonic = PPC::STHCX;
12269       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12270       break;
12271     case PPC::ATOMIC_CMP_SWAP_I32:
12272       LoadMnemonic = PPC::LWARX;
12273       StoreMnemonic = PPC::STWCX;
12274       break;
12275     case PPC::ATOMIC_CMP_SWAP_I64:
12276       LoadMnemonic = PPC::LDARX;
12277       StoreMnemonic = PPC::STDCX;
12278       break;
12279     }
12280     Register dest = MI.getOperand(0).getReg();
12281     Register ptrA = MI.getOperand(1).getReg();
12282     Register ptrB = MI.getOperand(2).getReg();
12283     Register oldval = MI.getOperand(3).getReg();
12284     Register newval = MI.getOperand(4).getReg();
12285     DebugLoc dl = MI.getDebugLoc();
12286 
12287     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12288     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12289     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12290     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12291     F->insert(It, loop1MBB);
12292     F->insert(It, loop2MBB);
12293     F->insert(It, midMBB);
12294     F->insert(It, exitMBB);
12295     exitMBB->splice(exitMBB->begin(), BB,
12296                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12297     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12298 
12299     //  thisMBB:
12300     //   ...
12301     //   fallthrough --> loopMBB
12302     BB->addSuccessor(loop1MBB);
12303 
12304     // loop1MBB:
12305     //   l[bhwd]arx dest, ptr
12306     //   cmp[wd] dest, oldval
12307     //   bne- midMBB
12308     // loop2MBB:
12309     //   st[bhwd]cx. newval, ptr
12310     //   bne- loopMBB
12311     //   b exitBB
12312     // midMBB:
12313     //   st[bhwd]cx. dest, ptr
12314     // exitBB:
12315     BB = loop1MBB;
12316     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12317     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12318         .addReg(oldval)
12319         .addReg(dest);
12320     BuildMI(BB, dl, TII->get(PPC::BCC))
12321         .addImm(PPC::PRED_NE)
12322         .addReg(PPC::CR0)
12323         .addMBB(midMBB);
12324     BB->addSuccessor(loop2MBB);
12325     BB->addSuccessor(midMBB);
12326 
12327     BB = loop2MBB;
12328     BuildMI(BB, dl, TII->get(StoreMnemonic))
12329         .addReg(newval)
12330         .addReg(ptrA)
12331         .addReg(ptrB);
12332     BuildMI(BB, dl, TII->get(PPC::BCC))
12333         .addImm(PPC::PRED_NE)
12334         .addReg(PPC::CR0)
12335         .addMBB(loop1MBB);
12336     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12337     BB->addSuccessor(loop1MBB);
12338     BB->addSuccessor(exitMBB);
12339 
12340     BB = midMBB;
12341     BuildMI(BB, dl, TII->get(StoreMnemonic))
12342         .addReg(dest)
12343         .addReg(ptrA)
12344         .addReg(ptrB);
12345     BB->addSuccessor(exitMBB);
12346 
12347     //  exitMBB:
12348     //   ...
12349     BB = exitMBB;
12350   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12351              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12352     // We must use 64-bit registers for addresses when targeting 64-bit,
12353     // since we're actually doing arithmetic on them.  Other registers
12354     // can be 32-bit.
12355     bool is64bit = Subtarget.isPPC64();
12356     bool isLittleEndian = Subtarget.isLittleEndian();
12357     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12358 
12359     Register dest = MI.getOperand(0).getReg();
12360     Register ptrA = MI.getOperand(1).getReg();
12361     Register ptrB = MI.getOperand(2).getReg();
12362     Register oldval = MI.getOperand(3).getReg();
12363     Register newval = MI.getOperand(4).getReg();
12364     DebugLoc dl = MI.getDebugLoc();
12365 
12366     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12367     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12368     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12369     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12370     F->insert(It, loop1MBB);
12371     F->insert(It, loop2MBB);
12372     F->insert(It, midMBB);
12373     F->insert(It, exitMBB);
12374     exitMBB->splice(exitMBB->begin(), BB,
12375                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12376     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12377 
12378     MachineRegisterInfo &RegInfo = F->getRegInfo();
12379     const TargetRegisterClass *RC =
12380         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12381     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12382 
12383     Register PtrReg = RegInfo.createVirtualRegister(RC);
12384     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12385     Register ShiftReg =
12386         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12387     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12388     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12389     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12390     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12391     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12392     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12393     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12394     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12395     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12396     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12397     Register Ptr1Reg;
12398     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12399     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12400     //  thisMBB:
12401     //   ...
12402     //   fallthrough --> loopMBB
12403     BB->addSuccessor(loop1MBB);
12404 
12405     // The 4-byte load must be aligned, while a char or short may be
12406     // anywhere in the word.  Hence all this nasty bookkeeping code.
12407     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12408     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12409     //   xori shift, shift1, 24 [16]
12410     //   rlwinm ptr, ptr1, 0, 0, 29
12411     //   slw newval2, newval, shift
12412     //   slw oldval2, oldval,shift
12413     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12414     //   slw mask, mask2, shift
12415     //   and newval3, newval2, mask
12416     //   and oldval3, oldval2, mask
12417     // loop1MBB:
12418     //   lwarx tmpDest, ptr
12419     //   and tmp, tmpDest, mask
12420     //   cmpw tmp, oldval3
12421     //   bne- midMBB
12422     // loop2MBB:
12423     //   andc tmp2, tmpDest, mask
12424     //   or tmp4, tmp2, newval3
12425     //   stwcx. tmp4, ptr
12426     //   bne- loop1MBB
12427     //   b exitBB
12428     // midMBB:
12429     //   stwcx. tmpDest, ptr
12430     // exitBB:
12431     //   srw dest, tmpDest, shift
12432     if (ptrA != ZeroReg) {
12433       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12434       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12435           .addReg(ptrA)
12436           .addReg(ptrB);
12437     } else {
12438       Ptr1Reg = ptrB;
12439     }
12440 
12441     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12442     // mode.
12443     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12444         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12445         .addImm(3)
12446         .addImm(27)
12447         .addImm(is8bit ? 28 : 27);
12448     if (!isLittleEndian)
12449       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12450           .addReg(Shift1Reg)
12451           .addImm(is8bit ? 24 : 16);
12452     if (is64bit)
12453       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12454           .addReg(Ptr1Reg)
12455           .addImm(0)
12456           .addImm(61);
12457     else
12458       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12459           .addReg(Ptr1Reg)
12460           .addImm(0)
12461           .addImm(0)
12462           .addImm(29);
12463     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12464         .addReg(newval)
12465         .addReg(ShiftReg);
12466     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12467         .addReg(oldval)
12468         .addReg(ShiftReg);
12469     if (is8bit)
12470       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12471     else {
12472       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12473       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12474           .addReg(Mask3Reg)
12475           .addImm(65535);
12476     }
12477     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12478         .addReg(Mask2Reg)
12479         .addReg(ShiftReg);
12480     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12481         .addReg(NewVal2Reg)
12482         .addReg(MaskReg);
12483     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12484         .addReg(OldVal2Reg)
12485         .addReg(MaskReg);
12486 
12487     BB = loop1MBB;
12488     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12489         .addReg(ZeroReg)
12490         .addReg(PtrReg);
12491     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12492         .addReg(TmpDestReg)
12493         .addReg(MaskReg);
12494     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12495         .addReg(TmpReg)
12496         .addReg(OldVal3Reg);
12497     BuildMI(BB, dl, TII->get(PPC::BCC))
12498         .addImm(PPC::PRED_NE)
12499         .addReg(PPC::CR0)
12500         .addMBB(midMBB);
12501     BB->addSuccessor(loop2MBB);
12502     BB->addSuccessor(midMBB);
12503 
12504     BB = loop2MBB;
12505     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12506         .addReg(TmpDestReg)
12507         .addReg(MaskReg);
12508     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12509         .addReg(Tmp2Reg)
12510         .addReg(NewVal3Reg);
12511     BuildMI(BB, dl, TII->get(PPC::STWCX))
12512         .addReg(Tmp4Reg)
12513         .addReg(ZeroReg)
12514         .addReg(PtrReg);
12515     BuildMI(BB, dl, TII->get(PPC::BCC))
12516         .addImm(PPC::PRED_NE)
12517         .addReg(PPC::CR0)
12518         .addMBB(loop1MBB);
12519     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12520     BB->addSuccessor(loop1MBB);
12521     BB->addSuccessor(exitMBB);
12522 
12523     BB = midMBB;
12524     BuildMI(BB, dl, TII->get(PPC::STWCX))
12525         .addReg(TmpDestReg)
12526         .addReg(ZeroReg)
12527         .addReg(PtrReg);
12528     BB->addSuccessor(exitMBB);
12529 
12530     //  exitMBB:
12531     //   ...
12532     BB = exitMBB;
12533     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12534         .addReg(TmpReg)
12535         .addReg(ShiftReg);
12536   } else if (MI.getOpcode() == PPC::FADDrtz) {
12537     // This pseudo performs an FADD with rounding mode temporarily forced
12538     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12539     // is not modeled at the SelectionDAG level.
12540     Register Dest = MI.getOperand(0).getReg();
12541     Register Src1 = MI.getOperand(1).getReg();
12542     Register Src2 = MI.getOperand(2).getReg();
12543     DebugLoc dl = MI.getDebugLoc();
12544 
12545     MachineRegisterInfo &RegInfo = F->getRegInfo();
12546     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12547 
12548     // Save FPSCR value.
12549     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12550 
12551     // Set rounding mode to round-to-zero.
12552     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12553         .addImm(31)
12554         .addReg(PPC::RM, RegState::ImplicitDefine);
12555 
12556     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12557         .addImm(30)
12558         .addReg(PPC::RM, RegState::ImplicitDefine);
12559 
12560     // Perform addition.
12561     auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
12562                    .addReg(Src1)
12563                    .addReg(Src2);
12564     if (MI.getFlag(MachineInstr::NoFPExcept))
12565       MIB.setMIFlag(MachineInstr::NoFPExcept);
12566 
12567     // Restore FPSCR value.
12568     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12569   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12570              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12571              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12572              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12573     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12574                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12575                           ? PPC::ANDI8_rec
12576                           : PPC::ANDI_rec;
12577     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12578                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12579 
12580     MachineRegisterInfo &RegInfo = F->getRegInfo();
12581     Register Dest = RegInfo.createVirtualRegister(
12582         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12583 
12584     DebugLoc Dl = MI.getDebugLoc();
12585     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12586         .addReg(MI.getOperand(1).getReg())
12587         .addImm(1);
12588     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12589             MI.getOperand(0).getReg())
12590         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12591   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12592     DebugLoc Dl = MI.getDebugLoc();
12593     MachineRegisterInfo &RegInfo = F->getRegInfo();
12594     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12595     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12596     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12597             MI.getOperand(0).getReg())
12598         .addReg(CRReg);
12599   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12600     DebugLoc Dl = MI.getDebugLoc();
12601     unsigned Imm = MI.getOperand(1).getImm();
12602     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12603     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12604             MI.getOperand(0).getReg())
12605         .addReg(PPC::CR0EQ);
12606   } else if (MI.getOpcode() == PPC::SETRNDi) {
12607     DebugLoc dl = MI.getDebugLoc();
12608     Register OldFPSCRReg = MI.getOperand(0).getReg();
12609 
12610     // Save FPSCR value.
12611     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12612 
12613     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12614     // the following settings:
12615     //   00 Round to nearest
12616     //   01 Round to 0
12617     //   10 Round to +inf
12618     //   11 Round to -inf
12619 
12620     // When the operand is immediate, using the two least significant bits of
12621     // the immediate to set the bits 62:63 of FPSCR.
12622     unsigned Mode = MI.getOperand(1).getImm();
12623     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12624         .addImm(31)
12625         .addReg(PPC::RM, RegState::ImplicitDefine);
12626 
12627     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12628         .addImm(30)
12629         .addReg(PPC::RM, RegState::ImplicitDefine);
12630   } else if (MI.getOpcode() == PPC::SETRND) {
12631     DebugLoc dl = MI.getDebugLoc();
12632 
12633     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12634     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12635     // If the target doesn't have DirectMove, we should use stack to do the
12636     // conversion, because the target doesn't have the instructions like mtvsrd
12637     // or mfvsrd to do this conversion directly.
12638     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12639       if (Subtarget.hasDirectMove()) {
12640         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12641           .addReg(SrcReg);
12642       } else {
12643         // Use stack to do the register copy.
12644         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12645         MachineRegisterInfo &RegInfo = F->getRegInfo();
12646         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12647         if (RC == &PPC::F8RCRegClass) {
12648           // Copy register from F8RCRegClass to G8RCRegclass.
12649           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12650                  "Unsupported RegClass.");
12651 
12652           StoreOp = PPC::STFD;
12653           LoadOp = PPC::LD;
12654         } else {
12655           // Copy register from G8RCRegClass to F8RCRegclass.
12656           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12657                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12658                  "Unsupported RegClass.");
12659         }
12660 
12661         MachineFrameInfo &MFI = F->getFrameInfo();
12662         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12663 
12664         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12665             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12666             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12667             MFI.getObjectAlign(FrameIdx));
12668 
12669         // Store the SrcReg into the stack.
12670         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12671           .addReg(SrcReg)
12672           .addImm(0)
12673           .addFrameIndex(FrameIdx)
12674           .addMemOperand(MMOStore);
12675 
12676         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12677             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12678             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12679             MFI.getObjectAlign(FrameIdx));
12680 
12681         // Load from the stack where SrcReg is stored, and save to DestReg,
12682         // so we have done the RegClass conversion from RegClass::SrcReg to
12683         // RegClass::DestReg.
12684         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12685           .addImm(0)
12686           .addFrameIndex(FrameIdx)
12687           .addMemOperand(MMOLoad);
12688       }
12689     };
12690 
12691     Register OldFPSCRReg = MI.getOperand(0).getReg();
12692 
12693     // Save FPSCR value.
12694     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12695 
12696     // When the operand is gprc register, use two least significant bits of the
12697     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12698     //
12699     // copy OldFPSCRTmpReg, OldFPSCRReg
12700     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12701     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12702     // copy NewFPSCRReg, NewFPSCRTmpReg
12703     // mtfsf 255, NewFPSCRReg
12704     MachineOperand SrcOp = MI.getOperand(1);
12705     MachineRegisterInfo &RegInfo = F->getRegInfo();
12706     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12707 
12708     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12709 
12710     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12711     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12712 
12713     // The first operand of INSERT_SUBREG should be a register which has
12714     // subregisters, we only care about its RegClass, so we should use an
12715     // IMPLICIT_DEF register.
12716     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12717     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12718       .addReg(ImDefReg)
12719       .add(SrcOp)
12720       .addImm(1);
12721 
12722     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12723     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12724       .addReg(OldFPSCRTmpReg)
12725       .addReg(ExtSrcReg)
12726       .addImm(0)
12727       .addImm(62);
12728 
12729     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12730     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12731 
12732     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12733     // bits of FPSCR.
12734     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12735       .addImm(255)
12736       .addReg(NewFPSCRReg)
12737       .addImm(0)
12738       .addImm(0);
12739   } else if (MI.getOpcode() == PPC::SETFLM) {
12740     DebugLoc Dl = MI.getDebugLoc();
12741 
12742     // Result of setflm is previous FPSCR content, so we need to save it first.
12743     Register OldFPSCRReg = MI.getOperand(0).getReg();
12744     BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12745 
12746     // Put bits in 32:63 to FPSCR.
12747     Register NewFPSCRReg = MI.getOperand(1).getReg();
12748     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12749         .addImm(255)
12750         .addReg(NewFPSCRReg)
12751         .addImm(0)
12752         .addImm(0);
12753   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12754              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12755     return emitProbedAlloca(MI, BB);
12756   } else if (MI.getOpcode() == PPC::SPLIT_QUADWORD) {
12757     DebugLoc DL = MI.getDebugLoc();
12758     Register Src = MI.getOperand(2).getReg();
12759     Register Lo = MI.getOperand(0).getReg();
12760     Register Hi = MI.getOperand(1).getReg();
12761     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12762         .addDef(Lo)
12763         .addUse(Src, 0, PPC::sub_gp8_x1);
12764     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12765         .addDef(Hi)
12766         .addUse(Src, 0, PPC::sub_gp8_x0);
12767   } else if (MI.getOpcode() == PPC::LQX_PSEUDO ||
12768              MI.getOpcode() == PPC::STQX_PSEUDO) {
12769     DebugLoc DL = MI.getDebugLoc();
12770     // Ptr is used as the ptr_rc_no_r0 part
12771     // of LQ/STQ's memory operand and adding result of RA and RB,
12772     // so it has to be g8rc_and_g8rc_nox0.
12773     Register Ptr =
12774         F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
12775     Register Val = MI.getOperand(0).getReg();
12776     Register RA = MI.getOperand(1).getReg();
12777     Register RB = MI.getOperand(2).getReg();
12778     BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB);
12779     BuildMI(*BB, MI, DL,
12780             MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ)
12781                                               : TII->get(PPC::STQ))
12782         .addReg(Val, MI.getOpcode() == PPC::LQX_PSEUDO ? RegState::Define : 0)
12783         .addImm(0)
12784         .addReg(Ptr);
12785   } else {
12786     llvm_unreachable("Unexpected instr type to insert");
12787   }
12788 
12789   MI.eraseFromParent(); // The pseudo instruction is gone now.
12790   return BB;
12791 }
12792 
12793 //===----------------------------------------------------------------------===//
12794 // Target Optimization Hooks
12795 //===----------------------------------------------------------------------===//
12796 
12797 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12798   // For the estimates, convergence is quadratic, so we essentially double the
12799   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12800   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12801   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12802   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12803   if (VT.getScalarType() == MVT::f64)
12804     RefinementSteps++;
12805   return RefinementSteps;
12806 }
12807 
12808 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
12809                                             const DenormalMode &Mode) const {
12810   // We only have VSX Vector Test for software Square Root.
12811   EVT VT = Op.getValueType();
12812   if (!isTypeLegal(MVT::i1) ||
12813       (VT != MVT::f64 &&
12814        ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
12815     return TargetLowering::getSqrtInputTest(Op, DAG, Mode);
12816 
12817   SDLoc DL(Op);
12818   // The output register of FTSQRT is CR field.
12819   SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
12820   // ftsqrt BF,FRB
12821   // Let e_b be the unbiased exponent of the double-precision
12822   // floating-point operand in register FRB.
12823   // fe_flag is set to 1 if either of the following conditions occurs.
12824   //   - The double-precision floating-point operand in register FRB is a zero,
12825   //     a NaN, or an infinity, or a negative value.
12826   //   - e_b is less than or equal to -970.
12827   // Otherwise fe_flag is set to 0.
12828   // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
12829   // not eligible for iteration. (zero/negative/infinity/nan or unbiased
12830   // exponent is less than -970)
12831   SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
12832   return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
12833                                     FTSQRT, SRIdxVal),
12834                  0);
12835 }
12836 
12837 SDValue
12838 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
12839                                                SelectionDAG &DAG) const {
12840   // We only have VSX Vector Square Root.
12841   EVT VT = Op.getValueType();
12842   if (VT != MVT::f64 &&
12843       ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
12844     return TargetLowering::getSqrtResultForDenormInput(Op, DAG);
12845 
12846   return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
12847 }
12848 
12849 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12850                                            int Enabled, int &RefinementSteps,
12851                                            bool &UseOneConstNR,
12852                                            bool Reciprocal) const {
12853   EVT VT = Operand.getValueType();
12854   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12855       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12856       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12857       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12858     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12859       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12860 
12861     // The Newton-Raphson computation with a single constant does not provide
12862     // enough accuracy on some CPUs.
12863     UseOneConstNR = !Subtarget.needsTwoConstNR();
12864     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12865   }
12866   return SDValue();
12867 }
12868 
12869 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12870                                             int Enabled,
12871                                             int &RefinementSteps) const {
12872   EVT VT = Operand.getValueType();
12873   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12874       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12875       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12876       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12877     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12878       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12879     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12880   }
12881   return SDValue();
12882 }
12883 
12884 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12885   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12886   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12887   // enabled for division), this functionality is redundant with the default
12888   // combiner logic (once the division -> reciprocal/multiply transformation
12889   // has taken place). As a result, this matters more for older cores than for
12890   // newer ones.
12891 
12892   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12893   // reciprocal if there are two or more FDIVs (for embedded cores with only
12894   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12895   switch (Subtarget.getCPUDirective()) {
12896   default:
12897     return 3;
12898   case PPC::DIR_440:
12899   case PPC::DIR_A2:
12900   case PPC::DIR_E500:
12901   case PPC::DIR_E500mc:
12902   case PPC::DIR_E5500:
12903     return 2;
12904   }
12905 }
12906 
12907 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12908 // collapsed, and so we need to look through chains of them.
12909 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12910                                      int64_t& Offset, SelectionDAG &DAG) {
12911   if (DAG.isBaseWithConstantOffset(Loc)) {
12912     Base = Loc.getOperand(0);
12913     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12914 
12915     // The base might itself be a base plus an offset, and if so, accumulate
12916     // that as well.
12917     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12918   }
12919 }
12920 
12921 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12922                             unsigned Bytes, int Dist,
12923                             SelectionDAG &DAG) {
12924   if (VT.getSizeInBits() / 8 != Bytes)
12925     return false;
12926 
12927   SDValue BaseLoc = Base->getBasePtr();
12928   if (Loc.getOpcode() == ISD::FrameIndex) {
12929     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12930       return false;
12931     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12932     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12933     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12934     int FS  = MFI.getObjectSize(FI);
12935     int BFS = MFI.getObjectSize(BFI);
12936     if (FS != BFS || FS != (int)Bytes) return false;
12937     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12938   }
12939 
12940   SDValue Base1 = Loc, Base2 = BaseLoc;
12941   int64_t Offset1 = 0, Offset2 = 0;
12942   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12943   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12944   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12945     return true;
12946 
12947   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12948   const GlobalValue *GV1 = nullptr;
12949   const GlobalValue *GV2 = nullptr;
12950   Offset1 = 0;
12951   Offset2 = 0;
12952   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12953   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12954   if (isGA1 && isGA2 && GV1 == GV2)
12955     return Offset1 == (Offset2 + Dist*Bytes);
12956   return false;
12957 }
12958 
12959 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12960 // not enforce equality of the chain operands.
12961 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12962                             unsigned Bytes, int Dist,
12963                             SelectionDAG &DAG) {
12964   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12965     EVT VT = LS->getMemoryVT();
12966     SDValue Loc = LS->getBasePtr();
12967     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12968   }
12969 
12970   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12971     EVT VT;
12972     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12973     default: return false;
12974     case Intrinsic::ppc_altivec_lvx:
12975     case Intrinsic::ppc_altivec_lvxl:
12976     case Intrinsic::ppc_vsx_lxvw4x:
12977     case Intrinsic::ppc_vsx_lxvw4x_be:
12978       VT = MVT::v4i32;
12979       break;
12980     case Intrinsic::ppc_vsx_lxvd2x:
12981     case Intrinsic::ppc_vsx_lxvd2x_be:
12982       VT = MVT::v2f64;
12983       break;
12984     case Intrinsic::ppc_altivec_lvebx:
12985       VT = MVT::i8;
12986       break;
12987     case Intrinsic::ppc_altivec_lvehx:
12988       VT = MVT::i16;
12989       break;
12990     case Intrinsic::ppc_altivec_lvewx:
12991       VT = MVT::i32;
12992       break;
12993     }
12994 
12995     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12996   }
12997 
12998   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12999     EVT VT;
13000     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13001     default: return false;
13002     case Intrinsic::ppc_altivec_stvx:
13003     case Intrinsic::ppc_altivec_stvxl:
13004     case Intrinsic::ppc_vsx_stxvw4x:
13005       VT = MVT::v4i32;
13006       break;
13007     case Intrinsic::ppc_vsx_stxvd2x:
13008       VT = MVT::v2f64;
13009       break;
13010     case Intrinsic::ppc_vsx_stxvw4x_be:
13011       VT = MVT::v4i32;
13012       break;
13013     case Intrinsic::ppc_vsx_stxvd2x_be:
13014       VT = MVT::v2f64;
13015       break;
13016     case Intrinsic::ppc_altivec_stvebx:
13017       VT = MVT::i8;
13018       break;
13019     case Intrinsic::ppc_altivec_stvehx:
13020       VT = MVT::i16;
13021       break;
13022     case Intrinsic::ppc_altivec_stvewx:
13023       VT = MVT::i32;
13024       break;
13025     }
13026 
13027     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
13028   }
13029 
13030   return false;
13031 }
13032 
13033 // Return true is there is a nearyby consecutive load to the one provided
13034 // (regardless of alignment). We search up and down the chain, looking though
13035 // token factors and other loads (but nothing else). As a result, a true result
13036 // indicates that it is safe to create a new consecutive load adjacent to the
13037 // load provided.
13038 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
13039   SDValue Chain = LD->getChain();
13040   EVT VT = LD->getMemoryVT();
13041 
13042   SmallSet<SDNode *, 16> LoadRoots;
13043   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
13044   SmallSet<SDNode *, 16> Visited;
13045 
13046   // First, search up the chain, branching to follow all token-factor operands.
13047   // If we find a consecutive load, then we're done, otherwise, record all
13048   // nodes just above the top-level loads and token factors.
13049   while (!Queue.empty()) {
13050     SDNode *ChainNext = Queue.pop_back_val();
13051     if (!Visited.insert(ChainNext).second)
13052       continue;
13053 
13054     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
13055       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13056         return true;
13057 
13058       if (!Visited.count(ChainLD->getChain().getNode()))
13059         Queue.push_back(ChainLD->getChain().getNode());
13060     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
13061       for (const SDUse &O : ChainNext->ops())
13062         if (!Visited.count(O.getNode()))
13063           Queue.push_back(O.getNode());
13064     } else
13065       LoadRoots.insert(ChainNext);
13066   }
13067 
13068   // Second, search down the chain, starting from the top-level nodes recorded
13069   // in the first phase. These top-level nodes are the nodes just above all
13070   // loads and token factors. Starting with their uses, recursively look though
13071   // all loads (just the chain uses) and token factors to find a consecutive
13072   // load.
13073   Visited.clear();
13074   Queue.clear();
13075 
13076   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
13077        IE = LoadRoots.end(); I != IE; ++I) {
13078     Queue.push_back(*I);
13079 
13080     while (!Queue.empty()) {
13081       SDNode *LoadRoot = Queue.pop_back_val();
13082       if (!Visited.insert(LoadRoot).second)
13083         continue;
13084 
13085       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
13086         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13087           return true;
13088 
13089       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
13090            UE = LoadRoot->use_end(); UI != UE; ++UI)
13091         if (((isa<MemSDNode>(*UI) &&
13092             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
13093             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
13094           Queue.push_back(*UI);
13095     }
13096   }
13097 
13098   return false;
13099 }
13100 
13101 /// This function is called when we have proved that a SETCC node can be replaced
13102 /// by subtraction (and other supporting instructions) so that the result of
13103 /// comparison is kept in a GPR instead of CR. This function is purely for
13104 /// codegen purposes and has some flags to guide the codegen process.
13105 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
13106                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
13107   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13108 
13109   // Zero extend the operands to the largest legal integer. Originally, they
13110   // must be of a strictly smaller size.
13111   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
13112                          DAG.getConstant(Size, DL, MVT::i32));
13113   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
13114                          DAG.getConstant(Size, DL, MVT::i32));
13115 
13116   // Swap if needed. Depends on the condition code.
13117   if (Swap)
13118     std::swap(Op0, Op1);
13119 
13120   // Subtract extended integers.
13121   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
13122 
13123   // Move the sign bit to the least significant position and zero out the rest.
13124   // Now the least significant bit carries the result of original comparison.
13125   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
13126                              DAG.getConstant(Size - 1, DL, MVT::i32));
13127   auto Final = Shifted;
13128 
13129   // Complement the result if needed. Based on the condition code.
13130   if (Complement)
13131     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
13132                         DAG.getConstant(1, DL, MVT::i64));
13133 
13134   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
13135 }
13136 
13137 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
13138                                                   DAGCombinerInfo &DCI) const {
13139   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13140 
13141   SelectionDAG &DAG = DCI.DAG;
13142   SDLoc DL(N);
13143 
13144   // Size of integers being compared has a critical role in the following
13145   // analysis, so we prefer to do this when all types are legal.
13146   if (!DCI.isAfterLegalizeDAG())
13147     return SDValue();
13148 
13149   // If all users of SETCC extend its value to a legal integer type
13150   // then we replace SETCC with a subtraction
13151   for (SDNode::use_iterator UI = N->use_begin(),
13152        UE = N->use_end(); UI != UE; ++UI) {
13153     if (UI->getOpcode() != ISD::ZERO_EXTEND)
13154       return SDValue();
13155   }
13156 
13157   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13158   auto OpSize = N->getOperand(0).getValueSizeInBits();
13159 
13160   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
13161 
13162   if (OpSize < Size) {
13163     switch (CC) {
13164     default: break;
13165     case ISD::SETULT:
13166       return generateEquivalentSub(N, Size, false, false, DL, DAG);
13167     case ISD::SETULE:
13168       return generateEquivalentSub(N, Size, true, true, DL, DAG);
13169     case ISD::SETUGT:
13170       return generateEquivalentSub(N, Size, false, true, DL, DAG);
13171     case ISD::SETUGE:
13172       return generateEquivalentSub(N, Size, true, false, DL, DAG);
13173     }
13174   }
13175 
13176   return SDValue();
13177 }
13178 
13179 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
13180                                                   DAGCombinerInfo &DCI) const {
13181   SelectionDAG &DAG = DCI.DAG;
13182   SDLoc dl(N);
13183 
13184   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
13185   // If we're tracking CR bits, we need to be careful that we don't have:
13186   //   trunc(binary-ops(zext(x), zext(y)))
13187   // or
13188   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
13189   // such that we're unnecessarily moving things into GPRs when it would be
13190   // better to keep them in CR bits.
13191 
13192   // Note that trunc here can be an actual i1 trunc, or can be the effective
13193   // truncation that comes from a setcc or select_cc.
13194   if (N->getOpcode() == ISD::TRUNCATE &&
13195       N->getValueType(0) != MVT::i1)
13196     return SDValue();
13197 
13198   if (N->getOperand(0).getValueType() != MVT::i32 &&
13199       N->getOperand(0).getValueType() != MVT::i64)
13200     return SDValue();
13201 
13202   if (N->getOpcode() == ISD::SETCC ||
13203       N->getOpcode() == ISD::SELECT_CC) {
13204     // If we're looking at a comparison, then we need to make sure that the
13205     // high bits (all except for the first) don't matter the result.
13206     ISD::CondCode CC =
13207       cast<CondCodeSDNode>(N->getOperand(
13208         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
13209     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
13210 
13211     if (ISD::isSignedIntSetCC(CC)) {
13212       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
13213           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
13214         return SDValue();
13215     } else if (ISD::isUnsignedIntSetCC(CC)) {
13216       if (!DAG.MaskedValueIsZero(N->getOperand(0),
13217                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
13218           !DAG.MaskedValueIsZero(N->getOperand(1),
13219                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
13220         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
13221                                              : SDValue());
13222     } else {
13223       // This is neither a signed nor an unsigned comparison, just make sure
13224       // that the high bits are equal.
13225       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
13226       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
13227 
13228       // We don't really care about what is known about the first bit (if
13229       // anything), so pretend that it is known zero for both to ensure they can
13230       // be compared as constants.
13231       Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
13232       Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
13233 
13234       if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
13235           Op1Known.getConstant() != Op2Known.getConstant())
13236         return SDValue();
13237     }
13238   }
13239 
13240   // We now know that the higher-order bits are irrelevant, we just need to
13241   // make sure that all of the intermediate operations are bit operations, and
13242   // all inputs are extensions.
13243   if (N->getOperand(0).getOpcode() != ISD::AND &&
13244       N->getOperand(0).getOpcode() != ISD::OR  &&
13245       N->getOperand(0).getOpcode() != ISD::XOR &&
13246       N->getOperand(0).getOpcode() != ISD::SELECT &&
13247       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
13248       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
13249       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
13250       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
13251       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
13252     return SDValue();
13253 
13254   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
13255       N->getOperand(1).getOpcode() != ISD::AND &&
13256       N->getOperand(1).getOpcode() != ISD::OR  &&
13257       N->getOperand(1).getOpcode() != ISD::XOR &&
13258       N->getOperand(1).getOpcode() != ISD::SELECT &&
13259       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
13260       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
13261       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
13262       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
13263       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
13264     return SDValue();
13265 
13266   SmallVector<SDValue, 4> Inputs;
13267   SmallVector<SDValue, 8> BinOps, PromOps;
13268   SmallPtrSet<SDNode *, 16> Visited;
13269 
13270   for (unsigned i = 0; i < 2; ++i) {
13271     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13272           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13273           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13274           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13275         isa<ConstantSDNode>(N->getOperand(i)))
13276       Inputs.push_back(N->getOperand(i));
13277     else
13278       BinOps.push_back(N->getOperand(i));
13279 
13280     if (N->getOpcode() == ISD::TRUNCATE)
13281       break;
13282   }
13283 
13284   // Visit all inputs, collect all binary operations (and, or, xor and
13285   // select) that are all fed by extensions.
13286   while (!BinOps.empty()) {
13287     SDValue BinOp = BinOps.pop_back_val();
13288 
13289     if (!Visited.insert(BinOp.getNode()).second)
13290       continue;
13291 
13292     PromOps.push_back(BinOp);
13293 
13294     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13295       // The condition of the select is not promoted.
13296       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13297         continue;
13298       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13299         continue;
13300 
13301       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13302             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13303             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13304            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13305           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13306         Inputs.push_back(BinOp.getOperand(i));
13307       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13308                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13309                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13310                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13311                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
13312                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13313                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13314                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13315                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
13316         BinOps.push_back(BinOp.getOperand(i));
13317       } else {
13318         // We have an input that is not an extension or another binary
13319         // operation; we'll abort this transformation.
13320         return SDValue();
13321       }
13322     }
13323   }
13324 
13325   // Make sure that this is a self-contained cluster of operations (which
13326   // is not quite the same thing as saying that everything has only one
13327   // use).
13328   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13329     if (isa<ConstantSDNode>(Inputs[i]))
13330       continue;
13331 
13332     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13333                               UE = Inputs[i].getNode()->use_end();
13334          UI != UE; ++UI) {
13335       SDNode *User = *UI;
13336       if (User != N && !Visited.count(User))
13337         return SDValue();
13338 
13339       // Make sure that we're not going to promote the non-output-value
13340       // operand(s) or SELECT or SELECT_CC.
13341       // FIXME: Although we could sometimes handle this, and it does occur in
13342       // practice that one of the condition inputs to the select is also one of
13343       // the outputs, we currently can't deal with this.
13344       if (User->getOpcode() == ISD::SELECT) {
13345         if (User->getOperand(0) == Inputs[i])
13346           return SDValue();
13347       } else if (User->getOpcode() == ISD::SELECT_CC) {
13348         if (User->getOperand(0) == Inputs[i] ||
13349             User->getOperand(1) == Inputs[i])
13350           return SDValue();
13351       }
13352     }
13353   }
13354 
13355   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13356     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13357                               UE = PromOps[i].getNode()->use_end();
13358          UI != UE; ++UI) {
13359       SDNode *User = *UI;
13360       if (User != N && !Visited.count(User))
13361         return SDValue();
13362 
13363       // Make sure that we're not going to promote the non-output-value
13364       // operand(s) or SELECT or SELECT_CC.
13365       // FIXME: Although we could sometimes handle this, and it does occur in
13366       // practice that one of the condition inputs to the select is also one of
13367       // the outputs, we currently can't deal with this.
13368       if (User->getOpcode() == ISD::SELECT) {
13369         if (User->getOperand(0) == PromOps[i])
13370           return SDValue();
13371       } else if (User->getOpcode() == ISD::SELECT_CC) {
13372         if (User->getOperand(0) == PromOps[i] ||
13373             User->getOperand(1) == PromOps[i])
13374           return SDValue();
13375       }
13376     }
13377   }
13378 
13379   // Replace all inputs with the extension operand.
13380   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13381     // Constants may have users outside the cluster of to-be-promoted nodes,
13382     // and so we need to replace those as we do the promotions.
13383     if (isa<ConstantSDNode>(Inputs[i]))
13384       continue;
13385     else
13386       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13387   }
13388 
13389   std::list<HandleSDNode> PromOpHandles;
13390   for (auto &PromOp : PromOps)
13391     PromOpHandles.emplace_back(PromOp);
13392 
13393   // Replace all operations (these are all the same, but have a different
13394   // (i1) return type). DAG.getNode will validate that the types of
13395   // a binary operator match, so go through the list in reverse so that
13396   // we've likely promoted both operands first. Any intermediate truncations or
13397   // extensions disappear.
13398   while (!PromOpHandles.empty()) {
13399     SDValue PromOp = PromOpHandles.back().getValue();
13400     PromOpHandles.pop_back();
13401 
13402     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13403         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13404         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13405         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13406       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13407           PromOp.getOperand(0).getValueType() != MVT::i1) {
13408         // The operand is not yet ready (see comment below).
13409         PromOpHandles.emplace_front(PromOp);
13410         continue;
13411       }
13412 
13413       SDValue RepValue = PromOp.getOperand(0);
13414       if (isa<ConstantSDNode>(RepValue))
13415         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13416 
13417       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13418       continue;
13419     }
13420 
13421     unsigned C;
13422     switch (PromOp.getOpcode()) {
13423     default:             C = 0; break;
13424     case ISD::SELECT:    C = 1; break;
13425     case ISD::SELECT_CC: C = 2; break;
13426     }
13427 
13428     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13429          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13430         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13431          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13432       // The to-be-promoted operands of this node have not yet been
13433       // promoted (this should be rare because we're going through the
13434       // list backward, but if one of the operands has several users in
13435       // this cluster of to-be-promoted nodes, it is possible).
13436       PromOpHandles.emplace_front(PromOp);
13437       continue;
13438     }
13439 
13440     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13441                                 PromOp.getNode()->op_end());
13442 
13443     // If there are any constant inputs, make sure they're replaced now.
13444     for (unsigned i = 0; i < 2; ++i)
13445       if (isa<ConstantSDNode>(Ops[C+i]))
13446         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13447 
13448     DAG.ReplaceAllUsesOfValueWith(PromOp,
13449       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13450   }
13451 
13452   // Now we're left with the initial truncation itself.
13453   if (N->getOpcode() == ISD::TRUNCATE)
13454     return N->getOperand(0);
13455 
13456   // Otherwise, this is a comparison. The operands to be compared have just
13457   // changed type (to i1), but everything else is the same.
13458   return SDValue(N, 0);
13459 }
13460 
13461 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13462                                                   DAGCombinerInfo &DCI) const {
13463   SelectionDAG &DAG = DCI.DAG;
13464   SDLoc dl(N);
13465 
13466   // If we're tracking CR bits, we need to be careful that we don't have:
13467   //   zext(binary-ops(trunc(x), trunc(y)))
13468   // or
13469   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13470   // such that we're unnecessarily moving things into CR bits that can more
13471   // efficiently stay in GPRs. Note that if we're not certain that the high
13472   // bits are set as required by the final extension, we still may need to do
13473   // some masking to get the proper behavior.
13474 
13475   // This same functionality is important on PPC64 when dealing with
13476   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13477   // the return values of functions. Because it is so similar, it is handled
13478   // here as well.
13479 
13480   if (N->getValueType(0) != MVT::i32 &&
13481       N->getValueType(0) != MVT::i64)
13482     return SDValue();
13483 
13484   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13485         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13486     return SDValue();
13487 
13488   if (N->getOperand(0).getOpcode() != ISD::AND &&
13489       N->getOperand(0).getOpcode() != ISD::OR  &&
13490       N->getOperand(0).getOpcode() != ISD::XOR &&
13491       N->getOperand(0).getOpcode() != ISD::SELECT &&
13492       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13493     return SDValue();
13494 
13495   SmallVector<SDValue, 4> Inputs;
13496   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13497   SmallPtrSet<SDNode *, 16> Visited;
13498 
13499   // Visit all inputs, collect all binary operations (and, or, xor and
13500   // select) that are all fed by truncations.
13501   while (!BinOps.empty()) {
13502     SDValue BinOp = BinOps.pop_back_val();
13503 
13504     if (!Visited.insert(BinOp.getNode()).second)
13505       continue;
13506 
13507     PromOps.push_back(BinOp);
13508 
13509     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13510       // The condition of the select is not promoted.
13511       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13512         continue;
13513       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13514         continue;
13515 
13516       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13517           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13518         Inputs.push_back(BinOp.getOperand(i));
13519       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13520                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13521                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13522                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13523                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13524         BinOps.push_back(BinOp.getOperand(i));
13525       } else {
13526         // We have an input that is not a truncation or another binary
13527         // operation; we'll abort this transformation.
13528         return SDValue();
13529       }
13530     }
13531   }
13532 
13533   // The operands of a select that must be truncated when the select is
13534   // promoted because the operand is actually part of the to-be-promoted set.
13535   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13536 
13537   // Make sure that this is a self-contained cluster of operations (which
13538   // is not quite the same thing as saying that everything has only one
13539   // use).
13540   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13541     if (isa<ConstantSDNode>(Inputs[i]))
13542       continue;
13543 
13544     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13545                               UE = Inputs[i].getNode()->use_end();
13546          UI != UE; ++UI) {
13547       SDNode *User = *UI;
13548       if (User != N && !Visited.count(User))
13549         return SDValue();
13550 
13551       // If we're going to promote the non-output-value operand(s) or SELECT or
13552       // SELECT_CC, record them for truncation.
13553       if (User->getOpcode() == ISD::SELECT) {
13554         if (User->getOperand(0) == Inputs[i])
13555           SelectTruncOp[0].insert(std::make_pair(User,
13556                                     User->getOperand(0).getValueType()));
13557       } else if (User->getOpcode() == ISD::SELECT_CC) {
13558         if (User->getOperand(0) == Inputs[i])
13559           SelectTruncOp[0].insert(std::make_pair(User,
13560                                     User->getOperand(0).getValueType()));
13561         if (User->getOperand(1) == Inputs[i])
13562           SelectTruncOp[1].insert(std::make_pair(User,
13563                                     User->getOperand(1).getValueType()));
13564       }
13565     }
13566   }
13567 
13568   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13569     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13570                               UE = PromOps[i].getNode()->use_end();
13571          UI != UE; ++UI) {
13572       SDNode *User = *UI;
13573       if (User != N && !Visited.count(User))
13574         return SDValue();
13575 
13576       // If we're going to promote the non-output-value operand(s) or SELECT or
13577       // SELECT_CC, record them for truncation.
13578       if (User->getOpcode() == ISD::SELECT) {
13579         if (User->getOperand(0) == PromOps[i])
13580           SelectTruncOp[0].insert(std::make_pair(User,
13581                                     User->getOperand(0).getValueType()));
13582       } else if (User->getOpcode() == ISD::SELECT_CC) {
13583         if (User->getOperand(0) == PromOps[i])
13584           SelectTruncOp[0].insert(std::make_pair(User,
13585                                     User->getOperand(0).getValueType()));
13586         if (User->getOperand(1) == PromOps[i])
13587           SelectTruncOp[1].insert(std::make_pair(User,
13588                                     User->getOperand(1).getValueType()));
13589       }
13590     }
13591   }
13592 
13593   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13594   bool ReallyNeedsExt = false;
13595   if (N->getOpcode() != ISD::ANY_EXTEND) {
13596     // If all of the inputs are not already sign/zero extended, then
13597     // we'll still need to do that at the end.
13598     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13599       if (isa<ConstantSDNode>(Inputs[i]))
13600         continue;
13601 
13602       unsigned OpBits =
13603         Inputs[i].getOperand(0).getValueSizeInBits();
13604       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13605 
13606       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13607            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13608                                   APInt::getHighBitsSet(OpBits,
13609                                                         OpBits-PromBits))) ||
13610           (N->getOpcode() == ISD::SIGN_EXTEND &&
13611            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13612              (OpBits-(PromBits-1)))) {
13613         ReallyNeedsExt = true;
13614         break;
13615       }
13616     }
13617   }
13618 
13619   // Replace all inputs, either with the truncation operand, or a
13620   // truncation or extension to the final output type.
13621   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13622     // Constant inputs need to be replaced with the to-be-promoted nodes that
13623     // use them because they might have users outside of the cluster of
13624     // promoted nodes.
13625     if (isa<ConstantSDNode>(Inputs[i]))
13626       continue;
13627 
13628     SDValue InSrc = Inputs[i].getOperand(0);
13629     if (Inputs[i].getValueType() == N->getValueType(0))
13630       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13631     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13632       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13633         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13634     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13635       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13636         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13637     else
13638       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13639         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13640   }
13641 
13642   std::list<HandleSDNode> PromOpHandles;
13643   for (auto &PromOp : PromOps)
13644     PromOpHandles.emplace_back(PromOp);
13645 
13646   // Replace all operations (these are all the same, but have a different
13647   // (promoted) return type). DAG.getNode will validate that the types of
13648   // a binary operator match, so go through the list in reverse so that
13649   // we've likely promoted both operands first.
13650   while (!PromOpHandles.empty()) {
13651     SDValue PromOp = PromOpHandles.back().getValue();
13652     PromOpHandles.pop_back();
13653 
13654     unsigned C;
13655     switch (PromOp.getOpcode()) {
13656     default:             C = 0; break;
13657     case ISD::SELECT:    C = 1; break;
13658     case ISD::SELECT_CC: C = 2; break;
13659     }
13660 
13661     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13662          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13663         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13664          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13665       // The to-be-promoted operands of this node have not yet been
13666       // promoted (this should be rare because we're going through the
13667       // list backward, but if one of the operands has several users in
13668       // this cluster of to-be-promoted nodes, it is possible).
13669       PromOpHandles.emplace_front(PromOp);
13670       continue;
13671     }
13672 
13673     // For SELECT and SELECT_CC nodes, we do a similar check for any
13674     // to-be-promoted comparison inputs.
13675     if (PromOp.getOpcode() == ISD::SELECT ||
13676         PromOp.getOpcode() == ISD::SELECT_CC) {
13677       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13678            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13679           (SelectTruncOp[1].count(PromOp.getNode()) &&
13680            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13681         PromOpHandles.emplace_front(PromOp);
13682         continue;
13683       }
13684     }
13685 
13686     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13687                                 PromOp.getNode()->op_end());
13688 
13689     // If this node has constant inputs, then they'll need to be promoted here.
13690     for (unsigned i = 0; i < 2; ++i) {
13691       if (!isa<ConstantSDNode>(Ops[C+i]))
13692         continue;
13693       if (Ops[C+i].getValueType() == N->getValueType(0))
13694         continue;
13695 
13696       if (N->getOpcode() == ISD::SIGN_EXTEND)
13697         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13698       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13699         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13700       else
13701         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13702     }
13703 
13704     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13705     // truncate them again to the original value type.
13706     if (PromOp.getOpcode() == ISD::SELECT ||
13707         PromOp.getOpcode() == ISD::SELECT_CC) {
13708       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13709       if (SI0 != SelectTruncOp[0].end())
13710         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13711       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13712       if (SI1 != SelectTruncOp[1].end())
13713         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13714     }
13715 
13716     DAG.ReplaceAllUsesOfValueWith(PromOp,
13717       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13718   }
13719 
13720   // Now we're left with the initial extension itself.
13721   if (!ReallyNeedsExt)
13722     return N->getOperand(0);
13723 
13724   // To zero extend, just mask off everything except for the first bit (in the
13725   // i1 case).
13726   if (N->getOpcode() == ISD::ZERO_EXTEND)
13727     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13728                        DAG.getConstant(APInt::getLowBitsSet(
13729                                          N->getValueSizeInBits(0), PromBits),
13730                                        dl, N->getValueType(0)));
13731 
13732   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13733          "Invalid extension type");
13734   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13735   SDValue ShiftCst =
13736       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13737   return DAG.getNode(
13738       ISD::SRA, dl, N->getValueType(0),
13739       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13740       ShiftCst);
13741 }
13742 
13743 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13744                                         DAGCombinerInfo &DCI) const {
13745   assert(N->getOpcode() == ISD::SETCC &&
13746          "Should be called with a SETCC node");
13747 
13748   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13749   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13750     SDValue LHS = N->getOperand(0);
13751     SDValue RHS = N->getOperand(1);
13752 
13753     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13754     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13755         LHS.hasOneUse())
13756       std::swap(LHS, RHS);
13757 
13758     // x == 0-y --> x+y == 0
13759     // x != 0-y --> x+y != 0
13760     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13761         RHS.hasOneUse()) {
13762       SDLoc DL(N);
13763       SelectionDAG &DAG = DCI.DAG;
13764       EVT VT = N->getValueType(0);
13765       EVT OpVT = LHS.getValueType();
13766       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13767       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13768     }
13769   }
13770 
13771   return DAGCombineTruncBoolExt(N, DCI);
13772 }
13773 
13774 // Is this an extending load from an f32 to an f64?
13775 static bool isFPExtLoad(SDValue Op) {
13776   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13777     return LD->getExtensionType() == ISD::EXTLOAD &&
13778       Op.getValueType() == MVT::f64;
13779   return false;
13780 }
13781 
13782 /// Reduces the number of fp-to-int conversion when building a vector.
13783 ///
13784 /// If this vector is built out of floating to integer conversions,
13785 /// transform it to a vector built out of floating point values followed by a
13786 /// single floating to integer conversion of the vector.
13787 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13788 /// becomes (fptosi (build_vector ($A, $B, ...)))
13789 SDValue PPCTargetLowering::
13790 combineElementTruncationToVectorTruncation(SDNode *N,
13791                                            DAGCombinerInfo &DCI) const {
13792   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13793          "Should be called with a BUILD_VECTOR node");
13794 
13795   SelectionDAG &DAG = DCI.DAG;
13796   SDLoc dl(N);
13797 
13798   SDValue FirstInput = N->getOperand(0);
13799   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13800          "The input operand must be an fp-to-int conversion.");
13801 
13802   // This combine happens after legalization so the fp_to_[su]i nodes are
13803   // already converted to PPCSISD nodes.
13804   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13805   if (FirstConversion == PPCISD::FCTIDZ ||
13806       FirstConversion == PPCISD::FCTIDUZ ||
13807       FirstConversion == PPCISD::FCTIWZ ||
13808       FirstConversion == PPCISD::FCTIWUZ) {
13809     bool IsSplat = true;
13810     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13811       FirstConversion == PPCISD::FCTIWUZ;
13812     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13813     SmallVector<SDValue, 4> Ops;
13814     EVT TargetVT = N->getValueType(0);
13815     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13816       SDValue NextOp = N->getOperand(i);
13817       if (NextOp.getOpcode() != PPCISD::MFVSR)
13818         return SDValue();
13819       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13820       if (NextConversion != FirstConversion)
13821         return SDValue();
13822       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13823       // This is not valid if the input was originally double precision. It is
13824       // also not profitable to do unless this is an extending load in which
13825       // case doing this combine will allow us to combine consecutive loads.
13826       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13827         return SDValue();
13828       if (N->getOperand(i) != FirstInput)
13829         IsSplat = false;
13830     }
13831 
13832     // If this is a splat, we leave it as-is since there will be only a single
13833     // fp-to-int conversion followed by a splat of the integer. This is better
13834     // for 32-bit and smaller ints and neutral for 64-bit ints.
13835     if (IsSplat)
13836       return SDValue();
13837 
13838     // Now that we know we have the right type of node, get its operands
13839     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13840       SDValue In = N->getOperand(i).getOperand(0);
13841       if (Is32Bit) {
13842         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13843         // here, we know that all inputs are extending loads so this is safe).
13844         if (In.isUndef())
13845           Ops.push_back(DAG.getUNDEF(SrcVT));
13846         else {
13847           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13848                                       MVT::f32, In.getOperand(0),
13849                                       DAG.getIntPtrConstant(1, dl));
13850           Ops.push_back(Trunc);
13851         }
13852       } else
13853         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13854     }
13855 
13856     unsigned Opcode;
13857     if (FirstConversion == PPCISD::FCTIDZ ||
13858         FirstConversion == PPCISD::FCTIWZ)
13859       Opcode = ISD::FP_TO_SINT;
13860     else
13861       Opcode = ISD::FP_TO_UINT;
13862 
13863     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13864     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13865     return DAG.getNode(Opcode, dl, TargetVT, BV);
13866   }
13867   return SDValue();
13868 }
13869 
13870 /// Reduce the number of loads when building a vector.
13871 ///
13872 /// Building a vector out of multiple loads can be converted to a load
13873 /// of the vector type if the loads are consecutive. If the loads are
13874 /// consecutive but in descending order, a shuffle is added at the end
13875 /// to reorder the vector.
13876 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13877   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13878          "Should be called with a BUILD_VECTOR node");
13879 
13880   SDLoc dl(N);
13881 
13882   // Return early for non byte-sized type, as they can't be consecutive.
13883   if (!N->getValueType(0).getVectorElementType().isByteSized())
13884     return SDValue();
13885 
13886   bool InputsAreConsecutiveLoads = true;
13887   bool InputsAreReverseConsecutive = true;
13888   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13889   SDValue FirstInput = N->getOperand(0);
13890   bool IsRoundOfExtLoad = false;
13891 
13892   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13893       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13894     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13895     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13896   }
13897   // Not a build vector of (possibly fp_rounded) loads.
13898   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13899       N->getNumOperands() == 1)
13900     return SDValue();
13901 
13902   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13903     // If any inputs are fp_round(extload), they all must be.
13904     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13905       return SDValue();
13906 
13907     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13908       N->getOperand(i);
13909     if (NextInput.getOpcode() != ISD::LOAD)
13910       return SDValue();
13911 
13912     SDValue PreviousInput =
13913       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13914     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13915     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13916 
13917     // If any inputs are fp_round(extload), they all must be.
13918     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13919       return SDValue();
13920 
13921     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13922       InputsAreConsecutiveLoads = false;
13923     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13924       InputsAreReverseConsecutive = false;
13925 
13926     // Exit early if the loads are neither consecutive nor reverse consecutive.
13927     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13928       return SDValue();
13929   }
13930 
13931   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13932          "The loads cannot be both consecutive and reverse consecutive.");
13933 
13934   SDValue FirstLoadOp =
13935     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13936   SDValue LastLoadOp =
13937     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13938                        N->getOperand(N->getNumOperands()-1);
13939 
13940   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13941   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13942   if (InputsAreConsecutiveLoads) {
13943     assert(LD1 && "Input needs to be a LoadSDNode.");
13944     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13945                        LD1->getBasePtr(), LD1->getPointerInfo(),
13946                        LD1->getAlignment());
13947   }
13948   if (InputsAreReverseConsecutive) {
13949     assert(LDL && "Input needs to be a LoadSDNode.");
13950     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13951                                LDL->getBasePtr(), LDL->getPointerInfo(),
13952                                LDL->getAlignment());
13953     SmallVector<int, 16> Ops;
13954     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13955       Ops.push_back(i);
13956 
13957     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13958                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13959   }
13960   return SDValue();
13961 }
13962 
13963 // This function adds the required vector_shuffle needed to get
13964 // the elements of the vector extract in the correct position
13965 // as specified by the CorrectElems encoding.
13966 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13967                                       SDValue Input, uint64_t Elems,
13968                                       uint64_t CorrectElems) {
13969   SDLoc dl(N);
13970 
13971   unsigned NumElems = Input.getValueType().getVectorNumElements();
13972   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13973 
13974   // Knowing the element indices being extracted from the original
13975   // vector and the order in which they're being inserted, just put
13976   // them at element indices required for the instruction.
13977   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13978     if (DAG.getDataLayout().isLittleEndian())
13979       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13980     else
13981       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13982     CorrectElems = CorrectElems >> 8;
13983     Elems = Elems >> 8;
13984   }
13985 
13986   SDValue Shuffle =
13987       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13988                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13989 
13990   EVT VT = N->getValueType(0);
13991   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13992 
13993   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13994                                Input.getValueType().getVectorElementType(),
13995                                VT.getVectorNumElements());
13996   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13997                      DAG.getValueType(ExtVT));
13998 }
13999 
14000 // Look for build vector patterns where input operands come from sign
14001 // extended vector_extract elements of specific indices. If the correct indices
14002 // aren't used, add a vector shuffle to fix up the indices and create
14003 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
14004 // during instruction selection.
14005 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
14006   // This array encodes the indices that the vector sign extend instructions
14007   // extract from when extending from one type to another for both BE and LE.
14008   // The right nibble of each byte corresponds to the LE incides.
14009   // and the left nibble of each byte corresponds to the BE incides.
14010   // For example: 0x3074B8FC  byte->word
14011   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
14012   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
14013   // For example: 0x000070F8  byte->double word
14014   // For LE: the allowed indices are: 0x0,0x8
14015   // For BE: the allowed indices are: 0x7,0xF
14016   uint64_t TargetElems[] = {
14017       0x3074B8FC, // b->w
14018       0x000070F8, // b->d
14019       0x10325476, // h->w
14020       0x00003074, // h->d
14021       0x00001032, // w->d
14022   };
14023 
14024   uint64_t Elems = 0;
14025   int Index;
14026   SDValue Input;
14027 
14028   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
14029     if (!Op)
14030       return false;
14031     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
14032         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
14033       return false;
14034 
14035     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
14036     // of the right width.
14037     SDValue Extract = Op.getOperand(0);
14038     if (Extract.getOpcode() == ISD::ANY_EXTEND)
14039       Extract = Extract.getOperand(0);
14040     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14041       return false;
14042 
14043     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
14044     if (!ExtOp)
14045       return false;
14046 
14047     Index = ExtOp->getZExtValue();
14048     if (Input && Input != Extract.getOperand(0))
14049       return false;
14050 
14051     if (!Input)
14052       Input = Extract.getOperand(0);
14053 
14054     Elems = Elems << 8;
14055     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
14056     Elems |= Index;
14057 
14058     return true;
14059   };
14060 
14061   // If the build vector operands aren't sign extended vector extracts,
14062   // of the same input vector, then return.
14063   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14064     if (!isSExtOfVecExtract(N->getOperand(i))) {
14065       return SDValue();
14066     }
14067   }
14068 
14069   // If the vector extract indicies are not correct, add the appropriate
14070   // vector_shuffle.
14071   int TgtElemArrayIdx;
14072   int InputSize = Input.getValueType().getScalarSizeInBits();
14073   int OutputSize = N->getValueType(0).getScalarSizeInBits();
14074   if (InputSize + OutputSize == 40)
14075     TgtElemArrayIdx = 0;
14076   else if (InputSize + OutputSize == 72)
14077     TgtElemArrayIdx = 1;
14078   else if (InputSize + OutputSize == 48)
14079     TgtElemArrayIdx = 2;
14080   else if (InputSize + OutputSize == 80)
14081     TgtElemArrayIdx = 3;
14082   else if (InputSize + OutputSize == 96)
14083     TgtElemArrayIdx = 4;
14084   else
14085     return SDValue();
14086 
14087   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
14088   CorrectElems = DAG.getDataLayout().isLittleEndian()
14089                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
14090                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
14091   if (Elems != CorrectElems) {
14092     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
14093   }
14094 
14095   // Regular lowering will catch cases where a shuffle is not needed.
14096   return SDValue();
14097 }
14098 
14099 // Look for the pattern of a load from a narrow width to i128, feeding
14100 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
14101 // (LXVRZX). This node represents a zero extending load that will be matched
14102 // to the Load VSX Vector Rightmost instructions.
14103 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
14104   SDLoc DL(N);
14105 
14106   // This combine is only eligible for a BUILD_VECTOR of v1i128.
14107   if (N->getValueType(0) != MVT::v1i128)
14108     return SDValue();
14109 
14110   SDValue Operand = N->getOperand(0);
14111   // Proceed with the transformation if the operand to the BUILD_VECTOR
14112   // is a load instruction.
14113   if (Operand.getOpcode() != ISD::LOAD)
14114     return SDValue();
14115 
14116   auto *LD = cast<LoadSDNode>(Operand);
14117   EVT MemoryType = LD->getMemoryVT();
14118 
14119   // This transformation is only valid if the we are loading either a byte,
14120   // halfword, word, or doubleword.
14121   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
14122                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
14123 
14124   // Ensure that the load from the narrow width is being zero extended to i128.
14125   if (!ValidLDType ||
14126       (LD->getExtensionType() != ISD::ZEXTLOAD &&
14127        LD->getExtensionType() != ISD::EXTLOAD))
14128     return SDValue();
14129 
14130   SDValue LoadOps[] = {
14131       LD->getChain(), LD->getBasePtr(),
14132       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
14133 
14134   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
14135                                  DAG.getVTList(MVT::v1i128, MVT::Other),
14136                                  LoadOps, MemoryType, LD->getMemOperand());
14137 }
14138 
14139 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
14140                                                  DAGCombinerInfo &DCI) const {
14141   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14142          "Should be called with a BUILD_VECTOR node");
14143 
14144   SelectionDAG &DAG = DCI.DAG;
14145   SDLoc dl(N);
14146 
14147   if (!Subtarget.hasVSX())
14148     return SDValue();
14149 
14150   // The target independent DAG combiner will leave a build_vector of
14151   // float-to-int conversions intact. We can generate MUCH better code for
14152   // a float-to-int conversion of a vector of floats.
14153   SDValue FirstInput = N->getOperand(0);
14154   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
14155     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
14156     if (Reduced)
14157       return Reduced;
14158   }
14159 
14160   // If we're building a vector out of consecutive loads, just load that
14161   // vector type.
14162   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
14163   if (Reduced)
14164     return Reduced;
14165 
14166   // If we're building a vector out of extended elements from another vector
14167   // we have P9 vector integer extend instructions. The code assumes legal
14168   // input types (i.e. it can't handle things like v4i16) so do not run before
14169   // legalization.
14170   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
14171     Reduced = combineBVOfVecSExt(N, DAG);
14172     if (Reduced)
14173       return Reduced;
14174   }
14175 
14176   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
14177   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
14178   // is a load from <valid narrow width> to i128.
14179   if (Subtarget.isISA3_1()) {
14180     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
14181     if (BVOfZLoad)
14182       return BVOfZLoad;
14183   }
14184 
14185   if (N->getValueType(0) != MVT::v2f64)
14186     return SDValue();
14187 
14188   // Looking for:
14189   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
14190   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
14191       FirstInput.getOpcode() != ISD::UINT_TO_FP)
14192     return SDValue();
14193   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
14194       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
14195     return SDValue();
14196   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
14197     return SDValue();
14198 
14199   SDValue Ext1 = FirstInput.getOperand(0);
14200   SDValue Ext2 = N->getOperand(1).getOperand(0);
14201   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14202      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14203     return SDValue();
14204 
14205   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
14206   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
14207   if (!Ext1Op || !Ext2Op)
14208     return SDValue();
14209   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
14210       Ext1.getOperand(0) != Ext2.getOperand(0))
14211     return SDValue();
14212 
14213   int FirstElem = Ext1Op->getZExtValue();
14214   int SecondElem = Ext2Op->getZExtValue();
14215   int SubvecIdx;
14216   if (FirstElem == 0 && SecondElem == 1)
14217     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
14218   else if (FirstElem == 2 && SecondElem == 3)
14219     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
14220   else
14221     return SDValue();
14222 
14223   SDValue SrcVec = Ext1.getOperand(0);
14224   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
14225     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
14226   return DAG.getNode(NodeType, dl, MVT::v2f64,
14227                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
14228 }
14229 
14230 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
14231                                               DAGCombinerInfo &DCI) const {
14232   assert((N->getOpcode() == ISD::SINT_TO_FP ||
14233           N->getOpcode() == ISD::UINT_TO_FP) &&
14234          "Need an int -> FP conversion node here");
14235 
14236   if (useSoftFloat() || !Subtarget.has64BitSupport())
14237     return SDValue();
14238 
14239   SelectionDAG &DAG = DCI.DAG;
14240   SDLoc dl(N);
14241   SDValue Op(N, 0);
14242 
14243   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
14244   // from the hardware.
14245   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
14246     return SDValue();
14247   if (!Op.getOperand(0).getValueType().isSimple())
14248     return SDValue();
14249   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
14250       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
14251     return SDValue();
14252 
14253   SDValue FirstOperand(Op.getOperand(0));
14254   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
14255     (FirstOperand.getValueType() == MVT::i8 ||
14256      FirstOperand.getValueType() == MVT::i16);
14257   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
14258     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
14259     bool DstDouble = Op.getValueType() == MVT::f64;
14260     unsigned ConvOp = Signed ?
14261       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
14262       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
14263     SDValue WidthConst =
14264       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
14265                             dl, false);
14266     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
14267     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
14268     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
14269                                          DAG.getVTList(MVT::f64, MVT::Other),
14270                                          Ops, MVT::i8, LDN->getMemOperand());
14271 
14272     // For signed conversion, we need to sign-extend the value in the VSR
14273     if (Signed) {
14274       SDValue ExtOps[] = { Ld, WidthConst };
14275       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
14276       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
14277     } else
14278       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
14279   }
14280 
14281 
14282   // For i32 intermediate values, unfortunately, the conversion functions
14283   // leave the upper 32 bits of the value are undefined. Within the set of
14284   // scalar instructions, we have no method for zero- or sign-extending the
14285   // value. Thus, we cannot handle i32 intermediate values here.
14286   if (Op.getOperand(0).getValueType() == MVT::i32)
14287     return SDValue();
14288 
14289   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
14290          "UINT_TO_FP is supported only with FPCVT");
14291 
14292   // If we have FCFIDS, then use it when converting to single-precision.
14293   // Otherwise, convert to double-precision and then round.
14294   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14295                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
14296                                                             : PPCISD::FCFIDS)
14297                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
14298                                                             : PPCISD::FCFID);
14299   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14300                   ? MVT::f32
14301                   : MVT::f64;
14302 
14303   // If we're converting from a float, to an int, and back to a float again,
14304   // then we don't need the store/load pair at all.
14305   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
14306        Subtarget.hasFPCVT()) ||
14307       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
14308     SDValue Src = Op.getOperand(0).getOperand(0);
14309     if (Src.getValueType() == MVT::f32) {
14310       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
14311       DCI.AddToWorklist(Src.getNode());
14312     } else if (Src.getValueType() != MVT::f64) {
14313       // Make sure that we don't pick up a ppc_fp128 source value.
14314       return SDValue();
14315     }
14316 
14317     unsigned FCTOp =
14318       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
14319                                                         PPCISD::FCTIDUZ;
14320 
14321     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
14322     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
14323 
14324     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
14325       FP = DAG.getNode(ISD::FP_ROUND, dl,
14326                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
14327       DCI.AddToWorklist(FP.getNode());
14328     }
14329 
14330     return FP;
14331   }
14332 
14333   return SDValue();
14334 }
14335 
14336 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
14337 // builtins) into loads with swaps.
14338 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
14339                                               DAGCombinerInfo &DCI) const {
14340   SelectionDAG &DAG = DCI.DAG;
14341   SDLoc dl(N);
14342   SDValue Chain;
14343   SDValue Base;
14344   MachineMemOperand *MMO;
14345 
14346   switch (N->getOpcode()) {
14347   default:
14348     llvm_unreachable("Unexpected opcode for little endian VSX load");
14349   case ISD::LOAD: {
14350     LoadSDNode *LD = cast<LoadSDNode>(N);
14351     Chain = LD->getChain();
14352     Base = LD->getBasePtr();
14353     MMO = LD->getMemOperand();
14354     // If the MMO suggests this isn't a load of a full vector, leave
14355     // things alone.  For a built-in, we have to make the change for
14356     // correctness, so if there is a size problem that will be a bug.
14357     if (MMO->getSize() < 16)
14358       return SDValue();
14359     break;
14360   }
14361   case ISD::INTRINSIC_W_CHAIN: {
14362     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14363     Chain = Intrin->getChain();
14364     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
14365     // us what we want. Get operand 2 instead.
14366     Base = Intrin->getOperand(2);
14367     MMO = Intrin->getMemOperand();
14368     break;
14369   }
14370   }
14371 
14372   MVT VecTy = N->getValueType(0).getSimpleVT();
14373 
14374   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
14375   // aligned and the type is a vector with elements up to 4 bytes
14376   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14377       VecTy.getScalarSizeInBits() <= 32) {
14378     return SDValue();
14379   }
14380 
14381   SDValue LoadOps[] = { Chain, Base };
14382   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14383                                          DAG.getVTList(MVT::v2f64, MVT::Other),
14384                                          LoadOps, MVT::v2f64, MMO);
14385 
14386   DCI.AddToWorklist(Load.getNode());
14387   Chain = Load.getValue(1);
14388   SDValue Swap = DAG.getNode(
14389       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14390   DCI.AddToWorklist(Swap.getNode());
14391 
14392   // Add a bitcast if the resulting load type doesn't match v2f64.
14393   if (VecTy != MVT::v2f64) {
14394     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14395     DCI.AddToWorklist(N.getNode());
14396     // Package {bitcast value, swap's chain} to match Load's shape.
14397     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14398                        N, Swap.getValue(1));
14399   }
14400 
14401   return Swap;
14402 }
14403 
14404 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14405 // builtins) into stores with swaps.
14406 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14407                                                DAGCombinerInfo &DCI) const {
14408   SelectionDAG &DAG = DCI.DAG;
14409   SDLoc dl(N);
14410   SDValue Chain;
14411   SDValue Base;
14412   unsigned SrcOpnd;
14413   MachineMemOperand *MMO;
14414 
14415   switch (N->getOpcode()) {
14416   default:
14417     llvm_unreachable("Unexpected opcode for little endian VSX store");
14418   case ISD::STORE: {
14419     StoreSDNode *ST = cast<StoreSDNode>(N);
14420     Chain = ST->getChain();
14421     Base = ST->getBasePtr();
14422     MMO = ST->getMemOperand();
14423     SrcOpnd = 1;
14424     // If the MMO suggests this isn't a store of a full vector, leave
14425     // things alone.  For a built-in, we have to make the change for
14426     // correctness, so if there is a size problem that will be a bug.
14427     if (MMO->getSize() < 16)
14428       return SDValue();
14429     break;
14430   }
14431   case ISD::INTRINSIC_VOID: {
14432     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14433     Chain = Intrin->getChain();
14434     // Intrin->getBasePtr() oddly does not get what we want.
14435     Base = Intrin->getOperand(3);
14436     MMO = Intrin->getMemOperand();
14437     SrcOpnd = 2;
14438     break;
14439   }
14440   }
14441 
14442   SDValue Src = N->getOperand(SrcOpnd);
14443   MVT VecTy = Src.getValueType().getSimpleVT();
14444 
14445   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14446   // aligned and the type is a vector with elements up to 4 bytes
14447   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14448       VecTy.getScalarSizeInBits() <= 32) {
14449     return SDValue();
14450   }
14451 
14452   // All stores are done as v2f64 and possible bit cast.
14453   if (VecTy != MVT::v2f64) {
14454     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14455     DCI.AddToWorklist(Src.getNode());
14456   }
14457 
14458   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14459                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14460   DCI.AddToWorklist(Swap.getNode());
14461   Chain = Swap.getValue(1);
14462   SDValue StoreOps[] = { Chain, Swap, Base };
14463   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14464                                           DAG.getVTList(MVT::Other),
14465                                           StoreOps, VecTy, MMO);
14466   DCI.AddToWorklist(Store.getNode());
14467   return Store;
14468 }
14469 
14470 // Handle DAG combine for STORE (FP_TO_INT F).
14471 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14472                                                DAGCombinerInfo &DCI) const {
14473 
14474   SelectionDAG &DAG = DCI.DAG;
14475   SDLoc dl(N);
14476   unsigned Opcode = N->getOperand(1).getOpcode();
14477 
14478   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14479          && "Not a FP_TO_INT Instruction!");
14480 
14481   SDValue Val = N->getOperand(1).getOperand(0);
14482   EVT Op1VT = N->getOperand(1).getValueType();
14483   EVT ResVT = Val.getValueType();
14484 
14485   if (!isTypeLegal(ResVT))
14486     return SDValue();
14487 
14488   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14489   bool ValidTypeForStoreFltAsInt =
14490         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14491          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14492 
14493   if (ResVT == MVT::f128 && !Subtarget.hasP9Vector())
14494     return SDValue();
14495 
14496   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14497       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14498     return SDValue();
14499 
14500   // Extend f32 values to f64
14501   if (ResVT.getScalarSizeInBits() == 32) {
14502     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14503     DCI.AddToWorklist(Val.getNode());
14504   }
14505 
14506   // Set signed or unsigned conversion opcode.
14507   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14508                           PPCISD::FP_TO_SINT_IN_VSR :
14509                           PPCISD::FP_TO_UINT_IN_VSR;
14510 
14511   Val = DAG.getNode(ConvOpcode,
14512                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14513   DCI.AddToWorklist(Val.getNode());
14514 
14515   // Set number of bytes being converted.
14516   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14517   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14518                     DAG.getIntPtrConstant(ByteSize, dl, false),
14519                     DAG.getValueType(Op1VT) };
14520 
14521   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14522           DAG.getVTList(MVT::Other), Ops,
14523           cast<StoreSDNode>(N)->getMemoryVT(),
14524           cast<StoreSDNode>(N)->getMemOperand());
14525 
14526   DCI.AddToWorklist(Val.getNode());
14527   return Val;
14528 }
14529 
14530 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14531   // Check that the source of the element keeps flipping
14532   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14533   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14534   for (int i = 1, e = Mask.size(); i < e; i++) {
14535     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14536       return false;
14537     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14538       return false;
14539     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14540   }
14541   return true;
14542 }
14543 
14544 static bool isSplatBV(SDValue Op) {
14545   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14546     return false;
14547   SDValue FirstOp;
14548 
14549   // Find first non-undef input.
14550   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14551     FirstOp = Op.getOperand(i);
14552     if (!FirstOp.isUndef())
14553       break;
14554   }
14555 
14556   // All inputs are undef or the same as the first non-undef input.
14557   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14558     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14559       return false;
14560   return true;
14561 }
14562 
14563 static SDValue isScalarToVec(SDValue Op) {
14564   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14565     return Op;
14566   if (Op.getOpcode() != ISD::BITCAST)
14567     return SDValue();
14568   Op = Op.getOperand(0);
14569   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14570     return Op;
14571   return SDValue();
14572 }
14573 
14574 // Fix up the shuffle mask to account for the fact that the result of
14575 // scalar_to_vector is not in lane zero. This just takes all values in
14576 // the ranges specified by the min/max indices and adds the number of
14577 // elements required to ensure each element comes from the respective
14578 // position in the valid lane.
14579 // On little endian, that's just the corresponding element in the other
14580 // half of the vector. On big endian, it is in the same half but right
14581 // justified rather than left justified in that half.
14582 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14583                                             int LHSMaxIdx, int RHSMinIdx,
14584                                             int RHSMaxIdx, int HalfVec,
14585                                             unsigned ValidLaneWidth,
14586                                             const PPCSubtarget &Subtarget) {
14587   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14588     int Idx = ShuffV[i];
14589     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14590       ShuffV[i] +=
14591           Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth;
14592   }
14593 }
14594 
14595 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14596 // the original is:
14597 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14598 // In such a case, just change the shuffle mask to extract the element
14599 // from the permuted index.
14600 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG,
14601                                const PPCSubtarget &Subtarget) {
14602   SDLoc dl(OrigSToV);
14603   EVT VT = OrigSToV.getValueType();
14604   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14605          "Expecting a SCALAR_TO_VECTOR here");
14606   SDValue Input = OrigSToV.getOperand(0);
14607 
14608   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14609     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14610     SDValue OrigVector = Input.getOperand(0);
14611 
14612     // Can't handle non-const element indices or different vector types
14613     // for the input to the extract and the output of the scalar_to_vector.
14614     if (Idx && VT == OrigVector.getValueType()) {
14615       unsigned NumElts = VT.getVectorNumElements();
14616       assert(
14617           NumElts > 1 &&
14618           "Cannot produce a permuted scalar_to_vector for one element vector");
14619       SmallVector<int, 16> NewMask(NumElts, -1);
14620       unsigned ResultInElt = NumElts / 2;
14621       ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1;
14622       NewMask[ResultInElt] = Idx->getZExtValue();
14623       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14624     }
14625   }
14626   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14627                      OrigSToV.getOperand(0));
14628 }
14629 
14630 // On little endian subtargets, combine shuffles such as:
14631 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14632 // into:
14633 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14634 // because the latter can be matched to a single instruction merge.
14635 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14636 // to put the value into element zero. Adjust the shuffle mask so that the
14637 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14638 // On big endian targets, this is still useful for SCALAR_TO_VECTOR
14639 // nodes with elements smaller than doubleword because all the ways
14640 // of getting scalar data into a vector register put the value in the
14641 // rightmost element of the left half of the vector.
14642 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14643                                                 SelectionDAG &DAG) const {
14644   SDValue LHS = SVN->getOperand(0);
14645   SDValue RHS = SVN->getOperand(1);
14646   auto Mask = SVN->getMask();
14647   int NumElts = LHS.getValueType().getVectorNumElements();
14648   SDValue Res(SVN, 0);
14649   SDLoc dl(SVN);
14650   bool IsLittleEndian = Subtarget.isLittleEndian();
14651 
14652   // On big endian targets this is only useful for subtargets with direct moves.
14653   // On little endian targets it would be useful for all subtargets with VSX.
14654   // However adding special handling for LE subtargets without direct moves
14655   // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8)
14656   // which includes direct moves.
14657   if (!Subtarget.hasDirectMove())
14658     return Res;
14659 
14660   // If this is not a shuffle of a shuffle and the first element comes from
14661   // the second vector, canonicalize to the commuted form. This will make it
14662   // more likely to match one of the single instruction patterns.
14663   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14664       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14665     std::swap(LHS, RHS);
14666     Res = DAG.getCommutedVectorShuffle(*SVN);
14667     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14668   }
14669 
14670   // Adjust the shuffle mask if either input vector comes from a
14671   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14672   // form (to prevent the need for a swap).
14673   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14674   SDValue SToVLHS = isScalarToVec(LHS);
14675   SDValue SToVRHS = isScalarToVec(RHS);
14676   if (SToVLHS || SToVRHS) {
14677     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14678                             : SToVRHS.getValueType().getVectorNumElements();
14679     int NumEltsOut = ShuffV.size();
14680     // The width of the "valid lane" (i.e. the lane that contains the value that
14681     // is vectorized) needs to be expressed in terms of the number of elements
14682     // of the shuffle. It is thereby the ratio of the values before and after
14683     // any bitcast.
14684     unsigned ValidLaneWidth =
14685         SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() /
14686                       LHS.getValueType().getScalarSizeInBits()
14687                 : SToVRHS.getValueType().getScalarSizeInBits() /
14688                       RHS.getValueType().getScalarSizeInBits();
14689 
14690     // Initially assume that neither input is permuted. These will be adjusted
14691     // accordingly if either input is.
14692     int LHSMaxIdx = -1;
14693     int RHSMinIdx = -1;
14694     int RHSMaxIdx = -1;
14695     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14696 
14697     // Get the permuted scalar to vector nodes for the source(s) that come from
14698     // ISD::SCALAR_TO_VECTOR.
14699     // On big endian systems, this only makes sense for element sizes smaller
14700     // than 64 bits since for 64-bit elements, all instructions already put
14701     // the value into element zero. Since scalar size of LHS and RHS may differ
14702     // after isScalarToVec, this should be checked using their own sizes.
14703     if (SToVLHS) {
14704       if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64)
14705         return Res;
14706       // Set up the values for the shuffle vector fixup.
14707       LHSMaxIdx = NumEltsOut / NumEltsIn;
14708       SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget);
14709       if (SToVLHS.getValueType() != LHS.getValueType())
14710         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14711       LHS = SToVLHS;
14712     }
14713     if (SToVRHS) {
14714       if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64)
14715         return Res;
14716       RHSMinIdx = NumEltsOut;
14717       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14718       SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget);
14719       if (SToVRHS.getValueType() != RHS.getValueType())
14720         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14721       RHS = SToVRHS;
14722     }
14723 
14724     // Fix up the shuffle mask to reflect where the desired element actually is.
14725     // The minimum and maximum indices that correspond to element zero for both
14726     // the LHS and RHS are computed and will control which shuffle mask entries
14727     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14728     // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted.
14729     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14730                                     HalfVec, ValidLaneWidth, Subtarget);
14731     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14732 
14733     // We may have simplified away the shuffle. We won't be able to do anything
14734     // further with it here.
14735     if (!isa<ShuffleVectorSDNode>(Res))
14736       return Res;
14737     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14738   }
14739 
14740   SDValue TheSplat = IsLittleEndian ? RHS : LHS;
14741   // The common case after we commuted the shuffle is that the RHS is a splat
14742   // and we have elements coming in from the splat at indices that are not
14743   // conducive to using a merge.
14744   // Example:
14745   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14746   if (!isSplatBV(TheSplat))
14747     return Res;
14748 
14749   // We are looking for a mask such that all even elements are from
14750   // one vector and all odd elements from the other.
14751   if (!isAlternatingShuffMask(Mask, NumElts))
14752     return Res;
14753 
14754   // Adjust the mask so we are pulling in the same index from the splat
14755   // as the index from the interesting vector in consecutive elements.
14756   if (IsLittleEndian) {
14757     // Example (even elements from first vector):
14758     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14759     if (Mask[0] < NumElts)
14760       for (int i = 1, e = Mask.size(); i < e; i += 2)
14761         ShuffV[i] = (ShuffV[i - 1] + NumElts);
14762     // Example (odd elements from first vector):
14763     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14764     else
14765       for (int i = 0, e = Mask.size(); i < e; i += 2)
14766         ShuffV[i] = (ShuffV[i + 1] + NumElts);
14767   } else {
14768     // Example (even elements from first vector):
14769     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1
14770     if (Mask[0] < NumElts)
14771       for (int i = 0, e = Mask.size(); i < e; i += 2)
14772         ShuffV[i] = ShuffV[i + 1] - NumElts;
14773     // Example (odd elements from first vector):
14774     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1
14775     else
14776       for (int i = 1, e = Mask.size(); i < e; i += 2)
14777         ShuffV[i] = ShuffV[i - 1] - NumElts;
14778   }
14779 
14780   // If the RHS has undefs, we need to remove them since we may have created
14781   // a shuffle that adds those instead of the splat value.
14782   SDValue SplatVal =
14783       cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue();
14784   TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal);
14785 
14786   if (IsLittleEndian)
14787     RHS = TheSplat;
14788   else
14789     LHS = TheSplat;
14790   return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14791 }
14792 
14793 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14794                                                 LSBaseSDNode *LSBase,
14795                                                 DAGCombinerInfo &DCI) const {
14796   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14797         "Not a reverse memop pattern!");
14798 
14799   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14800     auto Mask = SVN->getMask();
14801     int i = 0;
14802     auto I = Mask.rbegin();
14803     auto E = Mask.rend();
14804 
14805     for (; I != E; ++I) {
14806       if (*I != i)
14807         return false;
14808       i++;
14809     }
14810     return true;
14811   };
14812 
14813   SelectionDAG &DAG = DCI.DAG;
14814   EVT VT = SVN->getValueType(0);
14815 
14816   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14817     return SDValue();
14818 
14819   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14820   // See comment in PPCVSXSwapRemoval.cpp.
14821   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14822   if (!Subtarget.hasP9Vector())
14823     return SDValue();
14824 
14825   if(!IsElementReverse(SVN))
14826     return SDValue();
14827 
14828   if (LSBase->getOpcode() == ISD::LOAD) {
14829     // If the load return value 0 has more than one user except the
14830     // shufflevector instruction, it is not profitable to replace the
14831     // shufflevector with a reverse load.
14832     for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end();
14833          UI != UE; ++UI)
14834       if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE)
14835         return SDValue();
14836 
14837     SDLoc dl(LSBase);
14838     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14839     return DAG.getMemIntrinsicNode(
14840         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14841         LSBase->getMemoryVT(), LSBase->getMemOperand());
14842   }
14843 
14844   if (LSBase->getOpcode() == ISD::STORE) {
14845     // If there are other uses of the shuffle, the swap cannot be avoided.
14846     // Forcing the use of an X-Form (since swapped stores only have
14847     // X-Forms) without removing the swap is unprofitable.
14848     if (!SVN->hasOneUse())
14849       return SDValue();
14850 
14851     SDLoc dl(LSBase);
14852     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14853                           LSBase->getBasePtr()};
14854     return DAG.getMemIntrinsicNode(
14855         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14856         LSBase->getMemoryVT(), LSBase->getMemOperand());
14857   }
14858 
14859   llvm_unreachable("Expected a load or store node here");
14860 }
14861 
14862 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14863                                              DAGCombinerInfo &DCI) const {
14864   SelectionDAG &DAG = DCI.DAG;
14865   SDLoc dl(N);
14866   switch (N->getOpcode()) {
14867   default: break;
14868   case ISD::ADD:
14869     return combineADD(N, DCI);
14870   case ISD::SHL:
14871     return combineSHL(N, DCI);
14872   case ISD::SRA:
14873     return combineSRA(N, DCI);
14874   case ISD::SRL:
14875     return combineSRL(N, DCI);
14876   case ISD::MUL:
14877     return combineMUL(N, DCI);
14878   case ISD::FMA:
14879   case PPCISD::FNMSUB:
14880     return combineFMALike(N, DCI);
14881   case PPCISD::SHL:
14882     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14883         return N->getOperand(0);
14884     break;
14885   case PPCISD::SRL:
14886     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14887         return N->getOperand(0);
14888     break;
14889   case PPCISD::SRA:
14890     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14891       if (C->isZero() ||  //  0 >>s V -> 0.
14892           C->isAllOnes()) // -1 >>s V -> -1.
14893         return N->getOperand(0);
14894     }
14895     break;
14896   case ISD::SIGN_EXTEND:
14897   case ISD::ZERO_EXTEND:
14898   case ISD::ANY_EXTEND:
14899     return DAGCombineExtBoolTrunc(N, DCI);
14900   case ISD::TRUNCATE:
14901     return combineTRUNCATE(N, DCI);
14902   case ISD::SETCC:
14903     if (SDValue CSCC = combineSetCC(N, DCI))
14904       return CSCC;
14905     LLVM_FALLTHROUGH;
14906   case ISD::SELECT_CC:
14907     return DAGCombineTruncBoolExt(N, DCI);
14908   case ISD::SINT_TO_FP:
14909   case ISD::UINT_TO_FP:
14910     return combineFPToIntToFP(N, DCI);
14911   case ISD::VECTOR_SHUFFLE:
14912     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14913       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14914       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14915     }
14916     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14917   case ISD::STORE: {
14918 
14919     EVT Op1VT = N->getOperand(1).getValueType();
14920     unsigned Opcode = N->getOperand(1).getOpcode();
14921 
14922     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14923       SDValue Val= combineStoreFPToInt(N, DCI);
14924       if (Val)
14925         return Val;
14926     }
14927 
14928     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14929       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14930       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14931       if (Val)
14932         return Val;
14933     }
14934 
14935     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14936     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14937         N->getOperand(1).getNode()->hasOneUse() &&
14938         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14939          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14940 
14941       // STBRX can only handle simple types and it makes no sense to store less
14942       // two bytes in byte-reversed order.
14943       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14944       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14945         break;
14946 
14947       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14948       // Do an any-extend to 32-bits if this is a half-word input.
14949       if (BSwapOp.getValueType() == MVT::i16)
14950         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14951 
14952       // If the type of BSWAP operand is wider than stored memory width
14953       // it need to be shifted to the right side before STBRX.
14954       if (Op1VT.bitsGT(mVT)) {
14955         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14956         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14957                               DAG.getConstant(Shift, dl, MVT::i32));
14958         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14959         if (Op1VT == MVT::i64)
14960           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14961       }
14962 
14963       SDValue Ops[] = {
14964         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14965       };
14966       return
14967         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14968                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14969                                 cast<StoreSDNode>(N)->getMemOperand());
14970     }
14971 
14972     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14973     // So it can increase the chance of CSE constant construction.
14974     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14975         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14976       // Need to sign-extended to 64-bits to handle negative values.
14977       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14978       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14979                                     MemVT.getSizeInBits());
14980       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14981 
14982       // DAG.getTruncStore() can't be used here because it doesn't accept
14983       // the general (base + offset) addressing mode.
14984       // So we use UpdateNodeOperands and setTruncatingStore instead.
14985       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14986                              N->getOperand(3));
14987       cast<StoreSDNode>(N)->setTruncatingStore(true);
14988       return SDValue(N, 0);
14989     }
14990 
14991     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14992     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14993     if (Op1VT.isSimple()) {
14994       MVT StoreVT = Op1VT.getSimpleVT();
14995       if (Subtarget.needsSwapsForVSXMemOps() &&
14996           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14997            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14998         return expandVSXStoreForLE(N, DCI);
14999     }
15000     break;
15001   }
15002   case ISD::LOAD: {
15003     LoadSDNode *LD = cast<LoadSDNode>(N);
15004     EVT VT = LD->getValueType(0);
15005 
15006     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15007     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15008     if (VT.isSimple()) {
15009       MVT LoadVT = VT.getSimpleVT();
15010       if (Subtarget.needsSwapsForVSXMemOps() &&
15011           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
15012            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
15013         return expandVSXLoadForLE(N, DCI);
15014     }
15015 
15016     // We sometimes end up with a 64-bit integer load, from which we extract
15017     // two single-precision floating-point numbers. This happens with
15018     // std::complex<float>, and other similar structures, because of the way we
15019     // canonicalize structure copies. However, if we lack direct moves,
15020     // then the final bitcasts from the extracted integer values to the
15021     // floating-point numbers turn into store/load pairs. Even with direct moves,
15022     // just loading the two floating-point numbers is likely better.
15023     auto ReplaceTwoFloatLoad = [&]() {
15024       if (VT != MVT::i64)
15025         return false;
15026 
15027       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
15028           LD->isVolatile())
15029         return false;
15030 
15031       //  We're looking for a sequence like this:
15032       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
15033       //      t16: i64 = srl t13, Constant:i32<32>
15034       //    t17: i32 = truncate t16
15035       //  t18: f32 = bitcast t17
15036       //    t19: i32 = truncate t13
15037       //  t20: f32 = bitcast t19
15038 
15039       if (!LD->hasNUsesOfValue(2, 0))
15040         return false;
15041 
15042       auto UI = LD->use_begin();
15043       while (UI.getUse().getResNo() != 0) ++UI;
15044       SDNode *Trunc = *UI++;
15045       while (UI.getUse().getResNo() != 0) ++UI;
15046       SDNode *RightShift = *UI;
15047       if (Trunc->getOpcode() != ISD::TRUNCATE)
15048         std::swap(Trunc, RightShift);
15049 
15050       if (Trunc->getOpcode() != ISD::TRUNCATE ||
15051           Trunc->getValueType(0) != MVT::i32 ||
15052           !Trunc->hasOneUse())
15053         return false;
15054       if (RightShift->getOpcode() != ISD::SRL ||
15055           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
15056           RightShift->getConstantOperandVal(1) != 32 ||
15057           !RightShift->hasOneUse())
15058         return false;
15059 
15060       SDNode *Trunc2 = *RightShift->use_begin();
15061       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
15062           Trunc2->getValueType(0) != MVT::i32 ||
15063           !Trunc2->hasOneUse())
15064         return false;
15065 
15066       SDNode *Bitcast = *Trunc->use_begin();
15067       SDNode *Bitcast2 = *Trunc2->use_begin();
15068 
15069       if (Bitcast->getOpcode() != ISD::BITCAST ||
15070           Bitcast->getValueType(0) != MVT::f32)
15071         return false;
15072       if (Bitcast2->getOpcode() != ISD::BITCAST ||
15073           Bitcast2->getValueType(0) != MVT::f32)
15074         return false;
15075 
15076       if (Subtarget.isLittleEndian())
15077         std::swap(Bitcast, Bitcast2);
15078 
15079       // Bitcast has the second float (in memory-layout order) and Bitcast2
15080       // has the first one.
15081 
15082       SDValue BasePtr = LD->getBasePtr();
15083       if (LD->isIndexed()) {
15084         assert(LD->getAddressingMode() == ISD::PRE_INC &&
15085                "Non-pre-inc AM on PPC?");
15086         BasePtr =
15087           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15088                       LD->getOffset());
15089       }
15090 
15091       auto MMOFlags =
15092           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
15093       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
15094                                       LD->getPointerInfo(), LD->getAlignment(),
15095                                       MMOFlags, LD->getAAInfo());
15096       SDValue AddPtr =
15097         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
15098                     BasePtr, DAG.getIntPtrConstant(4, dl));
15099       SDValue FloatLoad2 = DAG.getLoad(
15100           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
15101           LD->getPointerInfo().getWithOffset(4),
15102           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
15103 
15104       if (LD->isIndexed()) {
15105         // Note that DAGCombine should re-form any pre-increment load(s) from
15106         // what is produced here if that makes sense.
15107         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
15108       }
15109 
15110       DCI.CombineTo(Bitcast2, FloatLoad);
15111       DCI.CombineTo(Bitcast, FloatLoad2);
15112 
15113       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
15114                                     SDValue(FloatLoad2.getNode(), 1));
15115       return true;
15116     };
15117 
15118     if (ReplaceTwoFloatLoad())
15119       return SDValue(N, 0);
15120 
15121     EVT MemVT = LD->getMemoryVT();
15122     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
15123     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
15124     if (LD->isUnindexed() && VT.isVector() &&
15125         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
15126           // P8 and later hardware should just use LOAD.
15127           !Subtarget.hasP8Vector() &&
15128           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
15129            VT == MVT::v4f32))) &&
15130         LD->getAlign() < ABIAlignment) {
15131       // This is a type-legal unaligned Altivec load.
15132       SDValue Chain = LD->getChain();
15133       SDValue Ptr = LD->getBasePtr();
15134       bool isLittleEndian = Subtarget.isLittleEndian();
15135 
15136       // This implements the loading of unaligned vectors as described in
15137       // the venerable Apple Velocity Engine overview. Specifically:
15138       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
15139       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
15140       //
15141       // The general idea is to expand a sequence of one or more unaligned
15142       // loads into an alignment-based permutation-control instruction (lvsl
15143       // or lvsr), a series of regular vector loads (which always truncate
15144       // their input address to an aligned address), and a series of
15145       // permutations.  The results of these permutations are the requested
15146       // loaded values.  The trick is that the last "extra" load is not taken
15147       // from the address you might suspect (sizeof(vector) bytes after the
15148       // last requested load), but rather sizeof(vector) - 1 bytes after the
15149       // last requested vector. The point of this is to avoid a page fault if
15150       // the base address happened to be aligned. This works because if the
15151       // base address is aligned, then adding less than a full vector length
15152       // will cause the last vector in the sequence to be (re)loaded.
15153       // Otherwise, the next vector will be fetched as you might suspect was
15154       // necessary.
15155 
15156       // We might be able to reuse the permutation generation from
15157       // a different base address offset from this one by an aligned amount.
15158       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
15159       // optimization later.
15160       Intrinsic::ID Intr, IntrLD, IntrPerm;
15161       MVT PermCntlTy, PermTy, LDTy;
15162       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15163                             : Intrinsic::ppc_altivec_lvsl;
15164       IntrLD = Intrinsic::ppc_altivec_lvx;
15165       IntrPerm = Intrinsic::ppc_altivec_vperm;
15166       PermCntlTy = MVT::v16i8;
15167       PermTy = MVT::v4i32;
15168       LDTy = MVT::v4i32;
15169 
15170       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
15171 
15172       // Create the new MMO for the new base load. It is like the original MMO,
15173       // but represents an area in memory almost twice the vector size centered
15174       // on the original address. If the address is unaligned, we might start
15175       // reading up to (sizeof(vector)-1) bytes below the address of the
15176       // original unaligned load.
15177       MachineFunction &MF = DAG.getMachineFunction();
15178       MachineMemOperand *BaseMMO =
15179         MF.getMachineMemOperand(LD->getMemOperand(),
15180                                 -(long)MemVT.getStoreSize()+1,
15181                                 2*MemVT.getStoreSize()-1);
15182 
15183       // Create the new base load.
15184       SDValue LDXIntID =
15185           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
15186       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
15187       SDValue BaseLoad =
15188         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15189                                 DAG.getVTList(PermTy, MVT::Other),
15190                                 BaseLoadOps, LDTy, BaseMMO);
15191 
15192       // Note that the value of IncOffset (which is provided to the next
15193       // load's pointer info offset value, and thus used to calculate the
15194       // alignment), and the value of IncValue (which is actually used to
15195       // increment the pointer value) are different! This is because we
15196       // require the next load to appear to be aligned, even though it
15197       // is actually offset from the base pointer by a lesser amount.
15198       int IncOffset = VT.getSizeInBits() / 8;
15199       int IncValue = IncOffset;
15200 
15201       // Walk (both up and down) the chain looking for another load at the real
15202       // (aligned) offset (the alignment of the other load does not matter in
15203       // this case). If found, then do not use the offset reduction trick, as
15204       // that will prevent the loads from being later combined (as they would
15205       // otherwise be duplicates).
15206       if (!findConsecutiveLoad(LD, DAG))
15207         --IncValue;
15208 
15209       SDValue Increment =
15210           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
15211       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15212 
15213       MachineMemOperand *ExtraMMO =
15214         MF.getMachineMemOperand(LD->getMemOperand(),
15215                                 1, 2*MemVT.getStoreSize()-1);
15216       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
15217       SDValue ExtraLoad =
15218         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15219                                 DAG.getVTList(PermTy, MVT::Other),
15220                                 ExtraLoadOps, LDTy, ExtraMMO);
15221 
15222       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15223         BaseLoad.getValue(1), ExtraLoad.getValue(1));
15224 
15225       // Because vperm has a big-endian bias, we must reverse the order
15226       // of the input vectors and complement the permute control vector
15227       // when generating little endian code.  We have already handled the
15228       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
15229       // and ExtraLoad here.
15230       SDValue Perm;
15231       if (isLittleEndian)
15232         Perm = BuildIntrinsicOp(IntrPerm,
15233                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
15234       else
15235         Perm = BuildIntrinsicOp(IntrPerm,
15236                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
15237 
15238       if (VT != PermTy)
15239         Perm = Subtarget.hasAltivec()
15240                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
15241                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
15242                                  DAG.getTargetConstant(1, dl, MVT::i64));
15243                                // second argument is 1 because this rounding
15244                                // is always exact.
15245 
15246       // The output of the permutation is our loaded result, the TokenFactor is
15247       // our new chain.
15248       DCI.CombineTo(N, Perm, TF);
15249       return SDValue(N, 0);
15250     }
15251     }
15252     break;
15253     case ISD::INTRINSIC_WO_CHAIN: {
15254       bool isLittleEndian = Subtarget.isLittleEndian();
15255       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15256       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15257                                            : Intrinsic::ppc_altivec_lvsl);
15258       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
15259         SDValue Add = N->getOperand(1);
15260 
15261         int Bits = 4 /* 16 byte alignment */;
15262 
15263         if (DAG.MaskedValueIsZero(Add->getOperand(1),
15264                                   APInt::getAllOnes(Bits /* alignment */)
15265                                       .zext(Add.getScalarValueSizeInBits()))) {
15266           SDNode *BasePtr = Add->getOperand(0).getNode();
15267           for (SDNode::use_iterator UI = BasePtr->use_begin(),
15268                                     UE = BasePtr->use_end();
15269                UI != UE; ++UI) {
15270             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15271                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
15272                     IID) {
15273               // We've found another LVSL/LVSR, and this address is an aligned
15274               // multiple of that one. The results will be the same, so use the
15275               // one we've just found instead.
15276 
15277               return SDValue(*UI, 0);
15278             }
15279           }
15280         }
15281 
15282         if (isa<ConstantSDNode>(Add->getOperand(1))) {
15283           SDNode *BasePtr = Add->getOperand(0).getNode();
15284           for (SDNode::use_iterator UI = BasePtr->use_begin(),
15285                UE = BasePtr->use_end(); UI != UE; ++UI) {
15286             if (UI->getOpcode() == ISD::ADD &&
15287                 isa<ConstantSDNode>(UI->getOperand(1)) &&
15288                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
15289                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
15290                 (1ULL << Bits) == 0) {
15291               SDNode *OtherAdd = *UI;
15292               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
15293                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
15294                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15295                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
15296                   return SDValue(*VI, 0);
15297                 }
15298               }
15299             }
15300           }
15301         }
15302       }
15303 
15304       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
15305       // Expose the vabsduw/h/b opportunity for down stream
15306       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
15307           (IID == Intrinsic::ppc_altivec_vmaxsw ||
15308            IID == Intrinsic::ppc_altivec_vmaxsh ||
15309            IID == Intrinsic::ppc_altivec_vmaxsb)) {
15310         SDValue V1 = N->getOperand(1);
15311         SDValue V2 = N->getOperand(2);
15312         if ((V1.getSimpleValueType() == MVT::v4i32 ||
15313              V1.getSimpleValueType() == MVT::v8i16 ||
15314              V1.getSimpleValueType() == MVT::v16i8) &&
15315             V1.getSimpleValueType() == V2.getSimpleValueType()) {
15316           // (0-a, a)
15317           if (V1.getOpcode() == ISD::SUB &&
15318               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
15319               V1.getOperand(1) == V2) {
15320             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
15321           }
15322           // (a, 0-a)
15323           if (V2.getOpcode() == ISD::SUB &&
15324               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
15325               V2.getOperand(1) == V1) {
15326             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15327           }
15328           // (x-y, y-x)
15329           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
15330               V1.getOperand(0) == V2.getOperand(1) &&
15331               V1.getOperand(1) == V2.getOperand(0)) {
15332             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15333           }
15334         }
15335       }
15336     }
15337 
15338     break;
15339   case ISD::INTRINSIC_W_CHAIN:
15340     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15341     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15342     if (Subtarget.needsSwapsForVSXMemOps()) {
15343       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15344       default:
15345         break;
15346       case Intrinsic::ppc_vsx_lxvw4x:
15347       case Intrinsic::ppc_vsx_lxvd2x:
15348         return expandVSXLoadForLE(N, DCI);
15349       }
15350     }
15351     break;
15352   case ISD::INTRINSIC_VOID:
15353     // For little endian, VSX stores require generating xxswapd/stxvd2x.
15354     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15355     if (Subtarget.needsSwapsForVSXMemOps()) {
15356       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15357       default:
15358         break;
15359       case Intrinsic::ppc_vsx_stxvw4x:
15360       case Intrinsic::ppc_vsx_stxvd2x:
15361         return expandVSXStoreForLE(N, DCI);
15362       }
15363     }
15364     break;
15365   case ISD::BSWAP: {
15366     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
15367     // For subtargets without LDBRX, we can still do better than the default
15368     // expansion even for 64-bit BSWAP (LOAD).
15369     bool Is64BitBswapOn64BitTgt =
15370         Subtarget.isPPC64() && N->getValueType(0) == MVT::i64;
15371     bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) &&
15372                                N->getOperand(0).hasOneUse();
15373     if (IsSingleUseNormalLd &&
15374         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
15375          (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) {
15376       SDValue Load = N->getOperand(0);
15377       LoadSDNode *LD = cast<LoadSDNode>(Load);
15378       // Create the byte-swapping load.
15379       SDValue Ops[] = {
15380         LD->getChain(),    // Chain
15381         LD->getBasePtr(),  // Ptr
15382         DAG.getValueType(N->getValueType(0)) // VT
15383       };
15384       SDValue BSLoad =
15385         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
15386                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
15387                                               MVT::i64 : MVT::i32, MVT::Other),
15388                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
15389 
15390       // If this is an i16 load, insert the truncate.
15391       SDValue ResVal = BSLoad;
15392       if (N->getValueType(0) == MVT::i16)
15393         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
15394 
15395       // First, combine the bswap away.  This makes the value produced by the
15396       // load dead.
15397       DCI.CombineTo(N, ResVal);
15398 
15399       // Next, combine the load away, we give it a bogus result value but a real
15400       // chain result.  The result value is dead because the bswap is dead.
15401       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
15402 
15403       // Return N so it doesn't get rechecked!
15404       return SDValue(N, 0);
15405     }
15406     // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only
15407     // before legalization so that the BUILD_PAIR is handled correctly.
15408     if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt ||
15409         !IsSingleUseNormalLd)
15410       return SDValue();
15411     LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0));
15412 
15413     // Can't split volatile or atomic loads.
15414     if (!LD->isSimple())
15415       return SDValue();
15416     SDValue BasePtr = LD->getBasePtr();
15417     SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr,
15418                              LD->getPointerInfo(), LD->getAlignment());
15419     Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo);
15420     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15421                           DAG.getIntPtrConstant(4, dl));
15422     MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand(
15423         LD->getMemOperand(), 4, 4);
15424     SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO);
15425     Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi);
15426     SDValue Res;
15427     if (Subtarget.isLittleEndian())
15428       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo);
15429     else
15430       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
15431     SDValue TF =
15432         DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15433                     Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1));
15434     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF);
15435     return Res;
15436   }
15437   case PPCISD::VCMP:
15438     // If a VCMP_rec node already exists with exactly the same operands as this
15439     // node, use its result instead of this node (VCMP_rec computes both a CR6
15440     // and a normal output).
15441     //
15442     if (!N->getOperand(0).hasOneUse() &&
15443         !N->getOperand(1).hasOneUse() &&
15444         !N->getOperand(2).hasOneUse()) {
15445 
15446       // Scan all of the users of the LHS, looking for VCMP_rec's that match.
15447       SDNode *VCMPrecNode = nullptr;
15448 
15449       SDNode *LHSN = N->getOperand(0).getNode();
15450       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
15451            UI != E; ++UI)
15452         if (UI->getOpcode() == PPCISD::VCMP_rec &&
15453             UI->getOperand(1) == N->getOperand(1) &&
15454             UI->getOperand(2) == N->getOperand(2) &&
15455             UI->getOperand(0) == N->getOperand(0)) {
15456           VCMPrecNode = *UI;
15457           break;
15458         }
15459 
15460       // If there is no VCMP_rec node, or if the flag value has a single use,
15461       // don't transform this.
15462       if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
15463         break;
15464 
15465       // Look at the (necessarily single) use of the flag value.  If it has a
15466       // chain, this transformation is more complex.  Note that multiple things
15467       // could use the value result, which we should ignore.
15468       SDNode *FlagUser = nullptr;
15469       for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
15470            FlagUser == nullptr; ++UI) {
15471         assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
15472         SDNode *User = *UI;
15473         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
15474           if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
15475             FlagUser = User;
15476             break;
15477           }
15478         }
15479       }
15480 
15481       // If the user is a MFOCRF instruction, we know this is safe.
15482       // Otherwise we give up for right now.
15483       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
15484         return SDValue(VCMPrecNode, 0);
15485     }
15486     break;
15487   case ISD::BRCOND: {
15488     SDValue Cond = N->getOperand(1);
15489     SDValue Target = N->getOperand(2);
15490 
15491     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15492         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15493           Intrinsic::loop_decrement) {
15494 
15495       // We now need to make the intrinsic dead (it cannot be instruction
15496       // selected).
15497       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15498       assert(Cond.getNode()->hasOneUse() &&
15499              "Counter decrement has more than one use");
15500 
15501       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15502                          N->getOperand(0), Target);
15503     }
15504   }
15505   break;
15506   case ISD::BR_CC: {
15507     // If this is a branch on an altivec predicate comparison, lower this so
15508     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15509     // lowering is done pre-legalize, because the legalizer lowers the predicate
15510     // compare down to code that is difficult to reassemble.
15511     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15512     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15513 
15514     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15515     // value. If so, pass-through the AND to get to the intrinsic.
15516     if (LHS.getOpcode() == ISD::AND &&
15517         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15518         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15519           Intrinsic::loop_decrement &&
15520         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15521         !isNullConstant(LHS.getOperand(1)))
15522       LHS = LHS.getOperand(0);
15523 
15524     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15525         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15526           Intrinsic::loop_decrement &&
15527         isa<ConstantSDNode>(RHS)) {
15528       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15529              "Counter decrement comparison is not EQ or NE");
15530 
15531       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15532       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15533                     (CC == ISD::SETNE && !Val);
15534 
15535       // We now need to make the intrinsic dead (it cannot be instruction
15536       // selected).
15537       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15538       assert(LHS.getNode()->hasOneUse() &&
15539              "Counter decrement has more than one use");
15540 
15541       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15542                          N->getOperand(0), N->getOperand(4));
15543     }
15544 
15545     int CompareOpc;
15546     bool isDot;
15547 
15548     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15549         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15550         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15551       assert(isDot && "Can't compare against a vector result!");
15552 
15553       // If this is a comparison against something other than 0/1, then we know
15554       // that the condition is never/always true.
15555       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15556       if (Val != 0 && Val != 1) {
15557         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15558           return N->getOperand(0);
15559         // Always !=, turn it into an unconditional branch.
15560         return DAG.getNode(ISD::BR, dl, MVT::Other,
15561                            N->getOperand(0), N->getOperand(4));
15562       }
15563 
15564       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15565 
15566       // Create the PPCISD altivec 'dot' comparison node.
15567       SDValue Ops[] = {
15568         LHS.getOperand(2),  // LHS of compare
15569         LHS.getOperand(3),  // RHS of compare
15570         DAG.getConstant(CompareOpc, dl, MVT::i32)
15571       };
15572       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15573       SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
15574 
15575       // Unpack the result based on how the target uses it.
15576       PPC::Predicate CompOpc;
15577       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15578       default:  // Can't happen, don't crash on invalid number though.
15579       case 0:   // Branch on the value of the EQ bit of CR6.
15580         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15581         break;
15582       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15583         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15584         break;
15585       case 2:   // Branch on the value of the LT bit of CR6.
15586         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15587         break;
15588       case 3:   // Branch on the inverted value of the LT bit of CR6.
15589         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15590         break;
15591       }
15592 
15593       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15594                          DAG.getConstant(CompOpc, dl, MVT::i32),
15595                          DAG.getRegister(PPC::CR6, MVT::i32),
15596                          N->getOperand(4), CompNode.getValue(1));
15597     }
15598     break;
15599   }
15600   case ISD::BUILD_VECTOR:
15601     return DAGCombineBuildVector(N, DCI);
15602   case ISD::ABS:
15603     return combineABS(N, DCI);
15604   case ISD::VSELECT:
15605     return combineVSelect(N, DCI);
15606   }
15607 
15608   return SDValue();
15609 }
15610 
15611 SDValue
15612 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15613                                  SelectionDAG &DAG,
15614                                  SmallVectorImpl<SDNode *> &Created) const {
15615   // fold (sdiv X, pow2)
15616   EVT VT = N->getValueType(0);
15617   if (VT == MVT::i64 && !Subtarget.isPPC64())
15618     return SDValue();
15619   if ((VT != MVT::i32 && VT != MVT::i64) ||
15620       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
15621     return SDValue();
15622 
15623   SDLoc DL(N);
15624   SDValue N0 = N->getOperand(0);
15625 
15626   bool IsNegPow2 = (-Divisor).isPowerOf2();
15627   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15628   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15629 
15630   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15631   Created.push_back(Op.getNode());
15632 
15633   if (IsNegPow2) {
15634     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15635     Created.push_back(Op.getNode());
15636   }
15637 
15638   return Op;
15639 }
15640 
15641 //===----------------------------------------------------------------------===//
15642 // Inline Assembly Support
15643 //===----------------------------------------------------------------------===//
15644 
15645 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15646                                                       KnownBits &Known,
15647                                                       const APInt &DemandedElts,
15648                                                       const SelectionDAG &DAG,
15649                                                       unsigned Depth) const {
15650   Known.resetAll();
15651   switch (Op.getOpcode()) {
15652   default: break;
15653   case PPCISD::LBRX: {
15654     // lhbrx is known to have the top bits cleared out.
15655     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15656       Known.Zero = 0xFFFF0000;
15657     break;
15658   }
15659   case ISD::INTRINSIC_WO_CHAIN: {
15660     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15661     default: break;
15662     case Intrinsic::ppc_altivec_vcmpbfp_p:
15663     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15664     case Intrinsic::ppc_altivec_vcmpequb_p:
15665     case Intrinsic::ppc_altivec_vcmpequh_p:
15666     case Intrinsic::ppc_altivec_vcmpequw_p:
15667     case Intrinsic::ppc_altivec_vcmpequd_p:
15668     case Intrinsic::ppc_altivec_vcmpequq_p:
15669     case Intrinsic::ppc_altivec_vcmpgefp_p:
15670     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15671     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15672     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15673     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15674     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15675     case Intrinsic::ppc_altivec_vcmpgtsq_p:
15676     case Intrinsic::ppc_altivec_vcmpgtub_p:
15677     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15678     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15679     case Intrinsic::ppc_altivec_vcmpgtud_p:
15680     case Intrinsic::ppc_altivec_vcmpgtuq_p:
15681       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15682       break;
15683     }
15684   }
15685   }
15686 }
15687 
15688 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15689   switch (Subtarget.getCPUDirective()) {
15690   default: break;
15691   case PPC::DIR_970:
15692   case PPC::DIR_PWR4:
15693   case PPC::DIR_PWR5:
15694   case PPC::DIR_PWR5X:
15695   case PPC::DIR_PWR6:
15696   case PPC::DIR_PWR6X:
15697   case PPC::DIR_PWR7:
15698   case PPC::DIR_PWR8:
15699   case PPC::DIR_PWR9:
15700   case PPC::DIR_PWR10:
15701   case PPC::DIR_PWR_FUTURE: {
15702     if (!ML)
15703       break;
15704 
15705     if (!DisableInnermostLoopAlign32) {
15706       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15707       // so that we can decrease cache misses and branch-prediction misses.
15708       // Actual alignment of the loop will depend on the hotness check and other
15709       // logic in alignBlocks.
15710       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15711         return Align(32);
15712     }
15713 
15714     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15715 
15716     // For small loops (between 5 and 8 instructions), align to a 32-byte
15717     // boundary so that the entire loop fits in one instruction-cache line.
15718     uint64_t LoopSize = 0;
15719     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15720       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15721         LoopSize += TII->getInstSizeInBytes(*J);
15722         if (LoopSize > 32)
15723           break;
15724       }
15725 
15726     if (LoopSize > 16 && LoopSize <= 32)
15727       return Align(32);
15728 
15729     break;
15730   }
15731   }
15732 
15733   return TargetLowering::getPrefLoopAlignment(ML);
15734 }
15735 
15736 /// getConstraintType - Given a constraint, return the type of
15737 /// constraint it is for this target.
15738 PPCTargetLowering::ConstraintType
15739 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15740   if (Constraint.size() == 1) {
15741     switch (Constraint[0]) {
15742     default: break;
15743     case 'b':
15744     case 'r':
15745     case 'f':
15746     case 'd':
15747     case 'v':
15748     case 'y':
15749       return C_RegisterClass;
15750     case 'Z':
15751       // FIXME: While Z does indicate a memory constraint, it specifically
15752       // indicates an r+r address (used in conjunction with the 'y' modifier
15753       // in the replacement string). Currently, we're forcing the base
15754       // register to be r0 in the asm printer (which is interpreted as zero)
15755       // and forming the complete address in the second register. This is
15756       // suboptimal.
15757       return C_Memory;
15758     }
15759   } else if (Constraint == "wc") { // individual CR bits.
15760     return C_RegisterClass;
15761   } else if (Constraint == "wa" || Constraint == "wd" ||
15762              Constraint == "wf" || Constraint == "ws" ||
15763              Constraint == "wi" || Constraint == "ww") {
15764     return C_RegisterClass; // VSX registers.
15765   }
15766   return TargetLowering::getConstraintType(Constraint);
15767 }
15768 
15769 /// Examine constraint type and operand type and determine a weight value.
15770 /// This object must already have been set up with the operand type
15771 /// and the current alternative constraint selected.
15772 TargetLowering::ConstraintWeight
15773 PPCTargetLowering::getSingleConstraintMatchWeight(
15774     AsmOperandInfo &info, const char *constraint) const {
15775   ConstraintWeight weight = CW_Invalid;
15776   Value *CallOperandVal = info.CallOperandVal;
15777     // If we don't have a value, we can't do a match,
15778     // but allow it at the lowest weight.
15779   if (!CallOperandVal)
15780     return CW_Default;
15781   Type *type = CallOperandVal->getType();
15782 
15783   // Look at the constraint type.
15784   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15785     return CW_Register; // an individual CR bit.
15786   else if ((StringRef(constraint) == "wa" ||
15787             StringRef(constraint) == "wd" ||
15788             StringRef(constraint) == "wf") &&
15789            type->isVectorTy())
15790     return CW_Register;
15791   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15792     return CW_Register; // just hold 64-bit integers data.
15793   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15794     return CW_Register;
15795   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15796     return CW_Register;
15797 
15798   switch (*constraint) {
15799   default:
15800     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15801     break;
15802   case 'b':
15803     if (type->isIntegerTy())
15804       weight = CW_Register;
15805     break;
15806   case 'f':
15807     if (type->isFloatTy())
15808       weight = CW_Register;
15809     break;
15810   case 'd':
15811     if (type->isDoubleTy())
15812       weight = CW_Register;
15813     break;
15814   case 'v':
15815     if (type->isVectorTy())
15816       weight = CW_Register;
15817     break;
15818   case 'y':
15819     weight = CW_Register;
15820     break;
15821   case 'Z':
15822     weight = CW_Memory;
15823     break;
15824   }
15825   return weight;
15826 }
15827 
15828 std::pair<unsigned, const TargetRegisterClass *>
15829 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15830                                                 StringRef Constraint,
15831                                                 MVT VT) const {
15832   if (Constraint.size() == 1) {
15833     // GCC RS6000 Constraint Letters
15834     switch (Constraint[0]) {
15835     case 'b':   // R1-R31
15836       if (VT == MVT::i64 && Subtarget.isPPC64())
15837         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15838       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15839     case 'r':   // R0-R31
15840       if (VT == MVT::i64 && Subtarget.isPPC64())
15841         return std::make_pair(0U, &PPC::G8RCRegClass);
15842       return std::make_pair(0U, &PPC::GPRCRegClass);
15843     // 'd' and 'f' constraints are both defined to be "the floating point
15844     // registers", where one is for 32-bit and the other for 64-bit. We don't
15845     // really care overly much here so just give them all the same reg classes.
15846     case 'd':
15847     case 'f':
15848       if (Subtarget.hasSPE()) {
15849         if (VT == MVT::f32 || VT == MVT::i32)
15850           return std::make_pair(0U, &PPC::GPRCRegClass);
15851         if (VT == MVT::f64 || VT == MVT::i64)
15852           return std::make_pair(0U, &PPC::SPERCRegClass);
15853       } else {
15854         if (VT == MVT::f32 || VT == MVT::i32)
15855           return std::make_pair(0U, &PPC::F4RCRegClass);
15856         if (VT == MVT::f64 || VT == MVT::i64)
15857           return std::make_pair(0U, &PPC::F8RCRegClass);
15858       }
15859       break;
15860     case 'v':
15861       if (Subtarget.hasAltivec())
15862         return std::make_pair(0U, &PPC::VRRCRegClass);
15863       break;
15864     case 'y':   // crrc
15865       return std::make_pair(0U, &PPC::CRRCRegClass);
15866     }
15867   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15868     // An individual CR bit.
15869     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15870   } else if ((Constraint == "wa" || Constraint == "wd" ||
15871              Constraint == "wf" || Constraint == "wi") &&
15872              Subtarget.hasVSX()) {
15873     // A VSX register for either a scalar (FP) or vector. There is no
15874     // support for single precision scalars on subtargets prior to Power8.
15875     if (VT.isVector())
15876       return std::make_pair(0U, &PPC::VSRCRegClass);
15877     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15878       return std::make_pair(0U, &PPC::VSSRCRegClass);
15879     return std::make_pair(0U, &PPC::VSFRCRegClass);
15880   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15881     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15882       return std::make_pair(0U, &PPC::VSSRCRegClass);
15883     else
15884       return std::make_pair(0U, &PPC::VSFRCRegClass);
15885   } else if (Constraint == "lr") {
15886     if (VT == MVT::i64)
15887       return std::make_pair(0U, &PPC::LR8RCRegClass);
15888     else
15889       return std::make_pair(0U, &PPC::LRRCRegClass);
15890   }
15891 
15892   // Handle special cases of physical registers that are not properly handled
15893   // by the base class.
15894   if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
15895     // If we name a VSX register, we can't defer to the base class because it
15896     // will not recognize the correct register (their names will be VSL{0-31}
15897     // and V{0-31} so they won't match). So we match them here.
15898     if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15899       int VSNum = atoi(Constraint.data() + 3);
15900       assert(VSNum >= 0 && VSNum <= 63 &&
15901              "Attempted to access a vsr out of range");
15902       if (VSNum < 32)
15903         return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15904       return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15905     }
15906 
15907     // For float registers, we can't defer to the base class as it will match
15908     // the SPILLTOVSRRC class.
15909     if (Constraint.size() > 3 && Constraint[1] == 'f') {
15910       int RegNum = atoi(Constraint.data() + 2);
15911       if (RegNum > 31 || RegNum < 0)
15912         report_fatal_error("Invalid floating point register number");
15913       if (VT == MVT::f32 || VT == MVT::i32)
15914         return Subtarget.hasSPE()
15915                    ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
15916                    : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
15917       if (VT == MVT::f64 || VT == MVT::i64)
15918         return Subtarget.hasSPE()
15919                    ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
15920                    : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
15921     }
15922   }
15923 
15924   std::pair<unsigned, const TargetRegisterClass *> R =
15925       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15926 
15927   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15928   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15929   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15930   // register.
15931   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15932   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15933   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15934       PPC::GPRCRegClass.contains(R.first))
15935     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15936                             PPC::sub_32, &PPC::G8RCRegClass),
15937                           &PPC::G8RCRegClass);
15938 
15939   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15940   if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) {
15941     R.first = PPC::CR0;
15942     R.second = &PPC::CRRCRegClass;
15943   }
15944   // FIXME: This warning should ideally be emitted in the front end.
15945   const auto &TM = getTargetMachine();
15946   if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) {
15947     if (((R.first >= PPC::V20 && R.first <= PPC::V31) ||
15948          (R.first >= PPC::VF20 && R.first <= PPC::VF31)) &&
15949         (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass))
15950       errs() << "warning: vector registers 20 to 32 are reserved in the "
15951                 "default AIX AltiVec ABI and cannot be used\n";
15952   }
15953 
15954   return R;
15955 }
15956 
15957 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15958 /// vector.  If it is invalid, don't add anything to Ops.
15959 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15960                                                      std::string &Constraint,
15961                                                      std::vector<SDValue>&Ops,
15962                                                      SelectionDAG &DAG) const {
15963   SDValue Result;
15964 
15965   // Only support length 1 constraints.
15966   if (Constraint.length() > 1) return;
15967 
15968   char Letter = Constraint[0];
15969   switch (Letter) {
15970   default: break;
15971   case 'I':
15972   case 'J':
15973   case 'K':
15974   case 'L':
15975   case 'M':
15976   case 'N':
15977   case 'O':
15978   case 'P': {
15979     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15980     if (!CST) return; // Must be an immediate to match.
15981     SDLoc dl(Op);
15982     int64_t Value = CST->getSExtValue();
15983     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15984                          // numbers are printed as such.
15985     switch (Letter) {
15986     default: llvm_unreachable("Unknown constraint letter!");
15987     case 'I':  // "I" is a signed 16-bit constant.
15988       if (isInt<16>(Value))
15989         Result = DAG.getTargetConstant(Value, dl, TCVT);
15990       break;
15991     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15992       if (isShiftedUInt<16, 16>(Value))
15993         Result = DAG.getTargetConstant(Value, dl, TCVT);
15994       break;
15995     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15996       if (isShiftedInt<16, 16>(Value))
15997         Result = DAG.getTargetConstant(Value, dl, TCVT);
15998       break;
15999     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
16000       if (isUInt<16>(Value))
16001         Result = DAG.getTargetConstant(Value, dl, TCVT);
16002       break;
16003     case 'M':  // "M" is a constant that is greater than 31.
16004       if (Value > 31)
16005         Result = DAG.getTargetConstant(Value, dl, TCVT);
16006       break;
16007     case 'N':  // "N" is a positive constant that is an exact power of two.
16008       if (Value > 0 && isPowerOf2_64(Value))
16009         Result = DAG.getTargetConstant(Value, dl, TCVT);
16010       break;
16011     case 'O':  // "O" is the constant zero.
16012       if (Value == 0)
16013         Result = DAG.getTargetConstant(Value, dl, TCVT);
16014       break;
16015     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
16016       if (isInt<16>(-Value))
16017         Result = DAG.getTargetConstant(Value, dl, TCVT);
16018       break;
16019     }
16020     break;
16021   }
16022   }
16023 
16024   if (Result.getNode()) {
16025     Ops.push_back(Result);
16026     return;
16027   }
16028 
16029   // Handle standard constraint letters.
16030   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16031 }
16032 
16033 // isLegalAddressingMode - Return true if the addressing mode represented
16034 // by AM is legal for this target, for a load/store of the specified type.
16035 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
16036                                               const AddrMode &AM, Type *Ty,
16037                                               unsigned AS,
16038                                               Instruction *I) const {
16039   // Vector type r+i form is supported since power9 as DQ form. We don't check
16040   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
16041   // imm form is preferred and the offset can be adjusted to use imm form later
16042   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
16043   // max offset to check legal addressing mode, we should be a little aggressive
16044   // to contain other offsets for that LSRUse.
16045   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
16046     return false;
16047 
16048   // PPC allows a sign-extended 16-bit immediate field.
16049   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
16050     return false;
16051 
16052   // No global is ever allowed as a base.
16053   if (AM.BaseGV)
16054     return false;
16055 
16056   // PPC only support r+r,
16057   switch (AM.Scale) {
16058   case 0:  // "r+i" or just "i", depending on HasBaseReg.
16059     break;
16060   case 1:
16061     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
16062       return false;
16063     // Otherwise we have r+r or r+i.
16064     break;
16065   case 2:
16066     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
16067       return false;
16068     // Allow 2*r as r+r.
16069     break;
16070   default:
16071     // No other scales are supported.
16072     return false;
16073   }
16074 
16075   return true;
16076 }
16077 
16078 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
16079                                            SelectionDAG &DAG) const {
16080   MachineFunction &MF = DAG.getMachineFunction();
16081   MachineFrameInfo &MFI = MF.getFrameInfo();
16082   MFI.setReturnAddressIsTaken(true);
16083 
16084   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16085     return SDValue();
16086 
16087   SDLoc dl(Op);
16088   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16089 
16090   // Make sure the function does not optimize away the store of the RA to
16091   // the stack.
16092   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
16093   FuncInfo->setLRStoreRequired();
16094   bool isPPC64 = Subtarget.isPPC64();
16095   auto PtrVT = getPointerTy(MF.getDataLayout());
16096 
16097   if (Depth > 0) {
16098     // The link register (return address) is saved in the caller's frame
16099     // not the callee's stack frame. So we must get the caller's frame
16100     // address and load the return address at the LR offset from there.
16101     SDValue FrameAddr =
16102         DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16103                     LowerFRAMEADDR(Op, DAG), MachinePointerInfo());
16104     SDValue Offset =
16105         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
16106                         isPPC64 ? MVT::i64 : MVT::i32);
16107     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16108                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
16109                        MachinePointerInfo());
16110   }
16111 
16112   // Just load the return address off the stack.
16113   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
16114   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
16115                      MachinePointerInfo());
16116 }
16117 
16118 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
16119                                           SelectionDAG &DAG) const {
16120   SDLoc dl(Op);
16121   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16122 
16123   MachineFunction &MF = DAG.getMachineFunction();
16124   MachineFrameInfo &MFI = MF.getFrameInfo();
16125   MFI.setFrameAddressIsTaken(true);
16126 
16127   EVT PtrVT = getPointerTy(MF.getDataLayout());
16128   bool isPPC64 = PtrVT == MVT::i64;
16129 
16130   // Naked functions never have a frame pointer, and so we use r1. For all
16131   // other functions, this decision must be delayed until during PEI.
16132   unsigned FrameReg;
16133   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
16134     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
16135   else
16136     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
16137 
16138   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
16139                                          PtrVT);
16140   while (Depth--)
16141     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16142                             FrameAddr, MachinePointerInfo());
16143   return FrameAddr;
16144 }
16145 
16146 // FIXME? Maybe this could be a TableGen attribute on some registers and
16147 // this table could be generated automatically from RegInfo.
16148 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
16149                                               const MachineFunction &MF) const {
16150   bool isPPC64 = Subtarget.isPPC64();
16151 
16152   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
16153   if (!is64Bit && VT != LLT::scalar(32))
16154     report_fatal_error("Invalid register global variable type");
16155 
16156   Register Reg = StringSwitch<Register>(RegName)
16157                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
16158                      .Case("r2", isPPC64 ? Register() : PPC::R2)
16159                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
16160                      .Default(Register());
16161 
16162   if (Reg)
16163     return Reg;
16164   report_fatal_error("Invalid register name global variable");
16165 }
16166 
16167 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
16168   // 32-bit SVR4 ABI access everything as got-indirect.
16169   if (Subtarget.is32BitELFABI())
16170     return true;
16171 
16172   // AIX accesses everything indirectly through the TOC, which is similar to
16173   // the GOT.
16174   if (Subtarget.isAIXABI())
16175     return true;
16176 
16177   CodeModel::Model CModel = getTargetMachine().getCodeModel();
16178   // If it is small or large code model, module locals are accessed
16179   // indirectly by loading their address from .toc/.got.
16180   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
16181     return true;
16182 
16183   // JumpTable and BlockAddress are accessed as got-indirect.
16184   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
16185     return true;
16186 
16187   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
16188     return Subtarget.isGVIndirectSymbol(G->getGlobal());
16189 
16190   return false;
16191 }
16192 
16193 bool
16194 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
16195   // The PowerPC target isn't yet aware of offsets.
16196   return false;
16197 }
16198 
16199 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
16200                                            const CallInst &I,
16201                                            MachineFunction &MF,
16202                                            unsigned Intrinsic) const {
16203   switch (Intrinsic) {
16204   case Intrinsic::ppc_atomicrmw_xchg_i128:
16205   case Intrinsic::ppc_atomicrmw_add_i128:
16206   case Intrinsic::ppc_atomicrmw_sub_i128:
16207   case Intrinsic::ppc_atomicrmw_nand_i128:
16208   case Intrinsic::ppc_atomicrmw_and_i128:
16209   case Intrinsic::ppc_atomicrmw_or_i128:
16210   case Intrinsic::ppc_atomicrmw_xor_i128:
16211   case Intrinsic::ppc_cmpxchg_i128:
16212     Info.opc = ISD::INTRINSIC_W_CHAIN;
16213     Info.memVT = MVT::i128;
16214     Info.ptrVal = I.getArgOperand(0);
16215     Info.offset = 0;
16216     Info.align = Align(16);
16217     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
16218                  MachineMemOperand::MOVolatile;
16219     return true;
16220   case Intrinsic::ppc_atomic_load_i128:
16221     Info.opc = ISD::INTRINSIC_W_CHAIN;
16222     Info.memVT = MVT::i128;
16223     Info.ptrVal = I.getArgOperand(0);
16224     Info.offset = 0;
16225     Info.align = Align(16);
16226     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16227     return true;
16228   case Intrinsic::ppc_atomic_store_i128:
16229     Info.opc = ISD::INTRINSIC_VOID;
16230     Info.memVT = MVT::i128;
16231     Info.ptrVal = I.getArgOperand(2);
16232     Info.offset = 0;
16233     Info.align = Align(16);
16234     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16235     return true;
16236   case Intrinsic::ppc_altivec_lvx:
16237   case Intrinsic::ppc_altivec_lvxl:
16238   case Intrinsic::ppc_altivec_lvebx:
16239   case Intrinsic::ppc_altivec_lvehx:
16240   case Intrinsic::ppc_altivec_lvewx:
16241   case Intrinsic::ppc_vsx_lxvd2x:
16242   case Intrinsic::ppc_vsx_lxvw4x:
16243   case Intrinsic::ppc_vsx_lxvd2x_be:
16244   case Intrinsic::ppc_vsx_lxvw4x_be:
16245   case Intrinsic::ppc_vsx_lxvl:
16246   case Intrinsic::ppc_vsx_lxvll: {
16247     EVT VT;
16248     switch (Intrinsic) {
16249     case Intrinsic::ppc_altivec_lvebx:
16250       VT = MVT::i8;
16251       break;
16252     case Intrinsic::ppc_altivec_lvehx:
16253       VT = MVT::i16;
16254       break;
16255     case Intrinsic::ppc_altivec_lvewx:
16256       VT = MVT::i32;
16257       break;
16258     case Intrinsic::ppc_vsx_lxvd2x:
16259     case Intrinsic::ppc_vsx_lxvd2x_be:
16260       VT = MVT::v2f64;
16261       break;
16262     default:
16263       VT = MVT::v4i32;
16264       break;
16265     }
16266 
16267     Info.opc = ISD::INTRINSIC_W_CHAIN;
16268     Info.memVT = VT;
16269     Info.ptrVal = I.getArgOperand(0);
16270     Info.offset = -VT.getStoreSize()+1;
16271     Info.size = 2*VT.getStoreSize()-1;
16272     Info.align = Align(1);
16273     Info.flags = MachineMemOperand::MOLoad;
16274     return true;
16275   }
16276   case Intrinsic::ppc_altivec_stvx:
16277   case Intrinsic::ppc_altivec_stvxl:
16278   case Intrinsic::ppc_altivec_stvebx:
16279   case Intrinsic::ppc_altivec_stvehx:
16280   case Intrinsic::ppc_altivec_stvewx:
16281   case Intrinsic::ppc_vsx_stxvd2x:
16282   case Intrinsic::ppc_vsx_stxvw4x:
16283   case Intrinsic::ppc_vsx_stxvd2x_be:
16284   case Intrinsic::ppc_vsx_stxvw4x_be:
16285   case Intrinsic::ppc_vsx_stxvl:
16286   case Intrinsic::ppc_vsx_stxvll: {
16287     EVT VT;
16288     switch (Intrinsic) {
16289     case Intrinsic::ppc_altivec_stvebx:
16290       VT = MVT::i8;
16291       break;
16292     case Intrinsic::ppc_altivec_stvehx:
16293       VT = MVT::i16;
16294       break;
16295     case Intrinsic::ppc_altivec_stvewx:
16296       VT = MVT::i32;
16297       break;
16298     case Intrinsic::ppc_vsx_stxvd2x:
16299     case Intrinsic::ppc_vsx_stxvd2x_be:
16300       VT = MVT::v2f64;
16301       break;
16302     default:
16303       VT = MVT::v4i32;
16304       break;
16305     }
16306 
16307     Info.opc = ISD::INTRINSIC_VOID;
16308     Info.memVT = VT;
16309     Info.ptrVal = I.getArgOperand(1);
16310     Info.offset = -VT.getStoreSize()+1;
16311     Info.size = 2*VT.getStoreSize()-1;
16312     Info.align = Align(1);
16313     Info.flags = MachineMemOperand::MOStore;
16314     return true;
16315   }
16316   default:
16317     break;
16318   }
16319 
16320   return false;
16321 }
16322 
16323 /// It returns EVT::Other if the type should be determined using generic
16324 /// target-independent logic.
16325 EVT PPCTargetLowering::getOptimalMemOpType(
16326     const MemOp &Op, const AttributeList &FuncAttributes) const {
16327   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
16328     // We should use Altivec/VSX loads and stores when available. For unaligned
16329     // addresses, unaligned VSX loads are only fast starting with the P8.
16330     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
16331         (Op.isAligned(Align(16)) ||
16332          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
16333       return MVT::v4i32;
16334   }
16335 
16336   if (Subtarget.isPPC64()) {
16337     return MVT::i64;
16338   }
16339 
16340   return MVT::i32;
16341 }
16342 
16343 /// Returns true if it is beneficial to convert a load of a constant
16344 /// to just the constant itself.
16345 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16346                                                           Type *Ty) const {
16347   assert(Ty->isIntegerTy());
16348 
16349   unsigned BitSize = Ty->getPrimitiveSizeInBits();
16350   return !(BitSize == 0 || BitSize > 64);
16351 }
16352 
16353 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16354   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16355     return false;
16356   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16357   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16358   return NumBits1 == 64 && NumBits2 == 32;
16359 }
16360 
16361 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16362   if (!VT1.isInteger() || !VT2.isInteger())
16363     return false;
16364   unsigned NumBits1 = VT1.getSizeInBits();
16365   unsigned NumBits2 = VT2.getSizeInBits();
16366   return NumBits1 == 64 && NumBits2 == 32;
16367 }
16368 
16369 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16370   // Generally speaking, zexts are not free, but they are free when they can be
16371   // folded with other operations.
16372   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
16373     EVT MemVT = LD->getMemoryVT();
16374     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
16375          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
16376         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
16377          LD->getExtensionType() == ISD::ZEXTLOAD))
16378       return true;
16379   }
16380 
16381   // FIXME: Add other cases...
16382   //  - 32-bit shifts with a zext to i64
16383   //  - zext after ctlz, bswap, etc.
16384   //  - zext after and by a constant mask
16385 
16386   return TargetLowering::isZExtFree(Val, VT2);
16387 }
16388 
16389 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
16390   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
16391          "invalid fpext types");
16392   // Extending to float128 is not free.
16393   if (DestVT == MVT::f128)
16394     return false;
16395   return true;
16396 }
16397 
16398 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16399   return isInt<16>(Imm) || isUInt<16>(Imm);
16400 }
16401 
16402 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16403   return isInt<16>(Imm) || isUInt<16>(Imm);
16404 }
16405 
16406 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align,
16407                                                        MachineMemOperand::Flags,
16408                                                        bool *Fast) const {
16409   if (DisablePPCUnaligned)
16410     return false;
16411 
16412   // PowerPC supports unaligned memory access for simple non-vector types.
16413   // Although accessing unaligned addresses is not as efficient as accessing
16414   // aligned addresses, it is generally more efficient than manual expansion,
16415   // and generally only traps for software emulation when crossing page
16416   // boundaries.
16417 
16418   if (!VT.isSimple())
16419     return false;
16420 
16421   if (VT.isFloatingPoint() && !VT.isVector() &&
16422       !Subtarget.allowsUnalignedFPAccess())
16423     return false;
16424 
16425   if (VT.getSimpleVT().isVector()) {
16426     if (Subtarget.hasVSX()) {
16427       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
16428           VT != MVT::v4f32 && VT != MVT::v4i32)
16429         return false;
16430     } else {
16431       return false;
16432     }
16433   }
16434 
16435   if (VT == MVT::ppcf128)
16436     return false;
16437 
16438   if (Fast)
16439     *Fast = true;
16440 
16441   return true;
16442 }
16443 
16444 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
16445                                                SDValue C) const {
16446   // Check integral scalar types.
16447   if (!VT.isScalarInteger())
16448     return false;
16449   if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
16450     if (!ConstNode->getAPIntValue().isSignedIntN(64))
16451       return false;
16452     // This transformation will generate >= 2 operations. But the following
16453     // cases will generate <= 2 instructions during ISEL. So exclude them.
16454     // 1. If the constant multiplier fits 16 bits, it can be handled by one
16455     // HW instruction, ie. MULLI
16456     // 2. If the multiplier after shifted fits 16 bits, an extra shift
16457     // instruction is needed than case 1, ie. MULLI and RLDICR
16458     int64_t Imm = ConstNode->getSExtValue();
16459     unsigned Shift = countTrailingZeros<uint64_t>(Imm);
16460     Imm >>= Shift;
16461     if (isInt<16>(Imm))
16462       return false;
16463     uint64_t UImm = static_cast<uint64_t>(Imm);
16464     if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
16465         isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
16466       return true;
16467   }
16468   return false;
16469 }
16470 
16471 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16472                                                    EVT VT) const {
16473   return isFMAFasterThanFMulAndFAdd(
16474       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
16475 }
16476 
16477 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
16478                                                    Type *Ty) const {
16479   switch (Ty->getScalarType()->getTypeID()) {
16480   case Type::FloatTyID:
16481   case Type::DoubleTyID:
16482     return true;
16483   case Type::FP128TyID:
16484     return Subtarget.hasP9Vector();
16485   default:
16486     return false;
16487   }
16488 }
16489 
16490 // FIXME: add more patterns which are not profitable to hoist.
16491 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
16492   if (!I->hasOneUse())
16493     return true;
16494 
16495   Instruction *User = I->user_back();
16496   assert(User && "A single use instruction with no uses.");
16497 
16498   switch (I->getOpcode()) {
16499   case Instruction::FMul: {
16500     // Don't break FMA, PowerPC prefers FMA.
16501     if (User->getOpcode() != Instruction::FSub &&
16502         User->getOpcode() != Instruction::FAdd)
16503       return true;
16504 
16505     const TargetOptions &Options = getTargetMachine().Options;
16506     const Function *F = I->getFunction();
16507     const DataLayout &DL = F->getParent()->getDataLayout();
16508     Type *Ty = User->getOperand(0)->getType();
16509 
16510     return !(
16511         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
16512         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
16513         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
16514   }
16515   case Instruction::Load: {
16516     // Don't break "store (load float*)" pattern, this pattern will be combined
16517     // to "store (load int32)" in later InstCombine pass. See function
16518     // combineLoadToOperationType. On PowerPC, loading a float point takes more
16519     // cycles than loading a 32 bit integer.
16520     LoadInst *LI = cast<LoadInst>(I);
16521     // For the loads that combineLoadToOperationType does nothing, like
16522     // ordered load, it should be profitable to hoist them.
16523     // For swifterror load, it can only be used for pointer to pointer type, so
16524     // later type check should get rid of this case.
16525     if (!LI->isUnordered())
16526       return true;
16527 
16528     if (User->getOpcode() != Instruction::Store)
16529       return true;
16530 
16531     if (I->getType()->getTypeID() != Type::FloatTyID)
16532       return true;
16533 
16534     return false;
16535   }
16536   default:
16537     return true;
16538   }
16539   return true;
16540 }
16541 
16542 const MCPhysReg *
16543 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
16544   // LR is a callee-save register, but we must treat it as clobbered by any call
16545   // site. Hence we include LR in the scratch registers, which are in turn added
16546   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
16547   // to CTR, which is used by any indirect call.
16548   static const MCPhysReg ScratchRegs[] = {
16549     PPC::X12, PPC::LR8, PPC::CTR8, 0
16550   };
16551 
16552   return ScratchRegs;
16553 }
16554 
16555 Register PPCTargetLowering::getExceptionPointerRegister(
16556     const Constant *PersonalityFn) const {
16557   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
16558 }
16559 
16560 Register PPCTargetLowering::getExceptionSelectorRegister(
16561     const Constant *PersonalityFn) const {
16562   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
16563 }
16564 
16565 bool
16566 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
16567                      EVT VT , unsigned DefinedValues) const {
16568   if (VT == MVT::v2i64)
16569     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
16570 
16571   if (Subtarget.hasVSX())
16572     return true;
16573 
16574   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
16575 }
16576 
16577 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16578   if (DisableILPPref || Subtarget.enableMachineScheduler())
16579     return TargetLowering::getSchedulingPreference(N);
16580 
16581   return Sched::ILP;
16582 }
16583 
16584 // Create a fast isel object.
16585 FastISel *
16586 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16587                                   const TargetLibraryInfo *LibInfo) const {
16588   return PPC::createFastISel(FuncInfo, LibInfo);
16589 }
16590 
16591 // 'Inverted' means the FMA opcode after negating one multiplicand.
16592 // For example, (fma -a b c) = (fnmsub a b c)
16593 static unsigned invertFMAOpcode(unsigned Opc) {
16594   switch (Opc) {
16595   default:
16596     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16597   case ISD::FMA:
16598     return PPCISD::FNMSUB;
16599   case PPCISD::FNMSUB:
16600     return ISD::FMA;
16601   }
16602 }
16603 
16604 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16605                                                 bool LegalOps, bool OptForSize,
16606                                                 NegatibleCost &Cost,
16607                                                 unsigned Depth) const {
16608   if (Depth > SelectionDAG::MaxRecursionDepth)
16609     return SDValue();
16610 
16611   unsigned Opc = Op.getOpcode();
16612   EVT VT = Op.getValueType();
16613   SDNodeFlags Flags = Op.getNode()->getFlags();
16614 
16615   switch (Opc) {
16616   case PPCISD::FNMSUB:
16617     if (!Op.hasOneUse() || !isTypeLegal(VT))
16618       break;
16619 
16620     const TargetOptions &Options = getTargetMachine().Options;
16621     SDValue N0 = Op.getOperand(0);
16622     SDValue N1 = Op.getOperand(1);
16623     SDValue N2 = Op.getOperand(2);
16624     SDLoc Loc(Op);
16625 
16626     NegatibleCost N2Cost = NegatibleCost::Expensive;
16627     SDValue NegN2 =
16628         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16629 
16630     if (!NegN2)
16631       return SDValue();
16632 
16633     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16634     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16635     // These transformations may change sign of zeroes. For example,
16636     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16637     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16638       // Try and choose the cheaper one to negate.
16639       NegatibleCost N0Cost = NegatibleCost::Expensive;
16640       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16641                                            N0Cost, Depth + 1);
16642 
16643       NegatibleCost N1Cost = NegatibleCost::Expensive;
16644       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16645                                            N1Cost, Depth + 1);
16646 
16647       if (NegN0 && N0Cost <= N1Cost) {
16648         Cost = std::min(N0Cost, N2Cost);
16649         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16650       } else if (NegN1) {
16651         Cost = std::min(N1Cost, N2Cost);
16652         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16653       }
16654     }
16655 
16656     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16657     if (isOperationLegal(ISD::FMA, VT)) {
16658       Cost = N2Cost;
16659       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16660     }
16661 
16662     break;
16663   }
16664 
16665   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16666                                               Cost, Depth);
16667 }
16668 
16669 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16670 bool PPCTargetLowering::useLoadStackGuardNode() const {
16671   if (!Subtarget.isTargetLinux())
16672     return TargetLowering::useLoadStackGuardNode();
16673   return true;
16674 }
16675 
16676 // Override to disable global variable loading on Linux and insert AIX canary
16677 // word declaration.
16678 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16679   if (Subtarget.isAIXABI()) {
16680     M.getOrInsertGlobal(AIXSSPCanaryWordName,
16681                         Type::getInt8PtrTy(M.getContext()));
16682     return;
16683   }
16684   if (!Subtarget.isTargetLinux())
16685     return TargetLowering::insertSSPDeclarations(M);
16686 }
16687 
16688 Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const {
16689   if (Subtarget.isAIXABI())
16690     return M.getGlobalVariable(AIXSSPCanaryWordName);
16691   return TargetLowering::getSDagStackGuard(M);
16692 }
16693 
16694 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16695                                      bool ForCodeSize) const {
16696   if (!VT.isSimple() || !Subtarget.hasVSX())
16697     return false;
16698 
16699   switch(VT.getSimpleVT().SimpleTy) {
16700   default:
16701     // For FP types that are currently not supported by PPC backend, return
16702     // false. Examples: f16, f80.
16703     return false;
16704   case MVT::f32:
16705   case MVT::f64:
16706     if (Subtarget.hasPrefixInstrs()) {
16707       // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP.
16708       return true;
16709     }
16710     LLVM_FALLTHROUGH;
16711   case MVT::ppcf128:
16712     return Imm.isPosZero();
16713   }
16714 }
16715 
16716 // For vector shift operation op, fold
16717 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16718 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16719                                   SelectionDAG &DAG) {
16720   SDValue N0 = N->getOperand(0);
16721   SDValue N1 = N->getOperand(1);
16722   EVT VT = N0.getValueType();
16723   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16724   unsigned Opcode = N->getOpcode();
16725   unsigned TargetOpcode;
16726 
16727   switch (Opcode) {
16728   default:
16729     llvm_unreachable("Unexpected shift operation");
16730   case ISD::SHL:
16731     TargetOpcode = PPCISD::SHL;
16732     break;
16733   case ISD::SRL:
16734     TargetOpcode = PPCISD::SRL;
16735     break;
16736   case ISD::SRA:
16737     TargetOpcode = PPCISD::SRA;
16738     break;
16739   }
16740 
16741   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16742       N1->getOpcode() == ISD::AND)
16743     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16744       if (Mask->getZExtValue() == OpSizeInBits - 1)
16745         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16746 
16747   return SDValue();
16748 }
16749 
16750 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16751   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16752     return Value;
16753 
16754   SDValue N0 = N->getOperand(0);
16755   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16756   if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
16757       N0.getOpcode() != ISD::SIGN_EXTEND ||
16758       N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
16759       N->getValueType(0) != MVT::i64)
16760     return SDValue();
16761 
16762   // We can't save an operation here if the value is already extended, and
16763   // the existing shift is easier to combine.
16764   SDValue ExtsSrc = N0.getOperand(0);
16765   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16766       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16767     return SDValue();
16768 
16769   SDLoc DL(N0);
16770   SDValue ShiftBy = SDValue(CN1, 0);
16771   // We want the shift amount to be i32 on the extswli, but the shift could
16772   // have an i64.
16773   if (ShiftBy.getValueType() == MVT::i64)
16774     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16775 
16776   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16777                          ShiftBy);
16778 }
16779 
16780 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16781   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16782     return Value;
16783 
16784   return SDValue();
16785 }
16786 
16787 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16788   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16789     return Value;
16790 
16791   return SDValue();
16792 }
16793 
16794 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16795 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16796 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16797 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16798 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16799                                  const PPCSubtarget &Subtarget) {
16800   if (!Subtarget.isPPC64())
16801     return SDValue();
16802 
16803   SDValue LHS = N->getOperand(0);
16804   SDValue RHS = N->getOperand(1);
16805 
16806   auto isZextOfCompareWithConstant = [](SDValue Op) {
16807     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16808         Op.getValueType() != MVT::i64)
16809       return false;
16810 
16811     SDValue Cmp = Op.getOperand(0);
16812     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16813         Cmp.getOperand(0).getValueType() != MVT::i64)
16814       return false;
16815 
16816     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
16817       int64_t NegConstant = 0 - Constant->getSExtValue();
16818       // Due to the limitations of the addi instruction,
16819       // -C is required to be [-32768, 32767].
16820       return isInt<16>(NegConstant);
16821     }
16822 
16823     return false;
16824   };
16825 
16826   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
16827   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16828 
16829   // If there is a pattern, canonicalize a zext operand to the RHS.
16830   if (LHSHasPattern && !RHSHasPattern)
16831     std::swap(LHS, RHS);
16832   else if (!LHSHasPattern && !RHSHasPattern)
16833     return SDValue();
16834 
16835   SDLoc DL(N);
16836   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16837   SDValue Cmp = RHS.getOperand(0);
16838   SDValue Z = Cmp.getOperand(0);
16839   auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1));
16840   int64_t NegConstant = 0 - Constant->getSExtValue();
16841 
16842   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16843   default: break;
16844   case ISD::SETNE: {
16845     //                                 when C == 0
16846     //                             --> addze X, (addic Z, -1).carry
16847     //                            /
16848     // add X, (zext(setne Z, C))--
16849     //                            \    when -32768 <= -C <= 32767 && C != 0
16850     //                             --> addze X, (addic (addi Z, -C), -1).carry
16851     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16852                               DAG.getConstant(NegConstant, DL, MVT::i64));
16853     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16854     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16855                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16856     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16857                        SDValue(Addc.getNode(), 1));
16858     }
16859   case ISD::SETEQ: {
16860     //                                 when C == 0
16861     //                             --> addze X, (subfic Z, 0).carry
16862     //                            /
16863     // add X, (zext(sete  Z, C))--
16864     //                            \    when -32768 <= -C <= 32767 && C != 0
16865     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16866     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16867                               DAG.getConstant(NegConstant, DL, MVT::i64));
16868     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16869     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16870                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16871     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16872                        SDValue(Subc.getNode(), 1));
16873     }
16874   }
16875 
16876   return SDValue();
16877 }
16878 
16879 // Transform
16880 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16881 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16882 // In this case both C1 and C2 must be known constants.
16883 // C1+C2 must fit into a 34 bit signed integer.
16884 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16885                                           const PPCSubtarget &Subtarget) {
16886   if (!Subtarget.isUsingPCRelativeCalls())
16887     return SDValue();
16888 
16889   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16890   // If we find that node try to cast the Global Address and the Constant.
16891   SDValue LHS = N->getOperand(0);
16892   SDValue RHS = N->getOperand(1);
16893 
16894   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16895     std::swap(LHS, RHS);
16896 
16897   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16898     return SDValue();
16899 
16900   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16901   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16902   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16903 
16904   // Check that both casts succeeded.
16905   if (!GSDN || !ConstNode)
16906     return SDValue();
16907 
16908   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16909   SDLoc DL(GSDN);
16910 
16911   // The signed int offset needs to fit in 34 bits.
16912   if (!isInt<34>(NewOffset))
16913     return SDValue();
16914 
16915   // The new global address is a copy of the old global address except
16916   // that it has the updated Offset.
16917   SDValue GA =
16918       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16919                                  NewOffset, GSDN->getTargetFlags());
16920   SDValue MatPCRel =
16921       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16922   return MatPCRel;
16923 }
16924 
16925 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16926   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16927     return Value;
16928 
16929   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16930     return Value;
16931 
16932   return SDValue();
16933 }
16934 
16935 // Detect TRUNCATE operations on bitcasts of float128 values.
16936 // What we are looking for here is the situtation where we extract a subset
16937 // of bits from a 128 bit float.
16938 // This can be of two forms:
16939 // 1) BITCAST of f128 feeding TRUNCATE
16940 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16941 // The reason this is required is because we do not have a legal i128 type
16942 // and so we want to prevent having to store the f128 and then reload part
16943 // of it.
16944 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16945                                            DAGCombinerInfo &DCI) const {
16946   // If we are using CRBits then try that first.
16947   if (Subtarget.useCRBits()) {
16948     // Check if CRBits did anything and return that if it did.
16949     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16950       return CRTruncValue;
16951   }
16952 
16953   SDLoc dl(N);
16954   SDValue Op0 = N->getOperand(0);
16955 
16956   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
16957   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
16958     EVT VT = N->getValueType(0);
16959     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16960       return SDValue();
16961     SDValue Sub = Op0.getOperand(0);
16962     if (Sub.getOpcode() == ISD::SUB) {
16963       SDValue SubOp0 = Sub.getOperand(0);
16964       SDValue SubOp1 = Sub.getOperand(1);
16965       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16966           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16967         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16968                                SubOp1.getOperand(0),
16969                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16970       }
16971     }
16972   }
16973 
16974   // Looking for a truncate of i128 to i64.
16975   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16976     return SDValue();
16977 
16978   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16979 
16980   // SRL feeding TRUNCATE.
16981   if (Op0.getOpcode() == ISD::SRL) {
16982     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16983     // The right shift has to be by 64 bits.
16984     if (!ConstNode || ConstNode->getZExtValue() != 64)
16985       return SDValue();
16986 
16987     // Switch the element number to extract.
16988     EltToExtract = EltToExtract ? 0 : 1;
16989     // Update Op0 past the SRL.
16990     Op0 = Op0.getOperand(0);
16991   }
16992 
16993   // BITCAST feeding a TRUNCATE possibly via SRL.
16994   if (Op0.getOpcode() == ISD::BITCAST &&
16995       Op0.getValueType() == MVT::i128 &&
16996       Op0.getOperand(0).getValueType() == MVT::f128) {
16997     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16998     return DCI.DAG.getNode(
16999         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
17000         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
17001   }
17002   return SDValue();
17003 }
17004 
17005 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
17006   SelectionDAG &DAG = DCI.DAG;
17007 
17008   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
17009   if (!ConstOpOrElement)
17010     return SDValue();
17011 
17012   // An imul is usually smaller than the alternative sequence for legal type.
17013   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
17014       isOperationLegal(ISD::MUL, N->getValueType(0)))
17015     return SDValue();
17016 
17017   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
17018     switch (this->Subtarget.getCPUDirective()) {
17019     default:
17020       // TODO: enhance the condition for subtarget before pwr8
17021       return false;
17022     case PPC::DIR_PWR8:
17023       //  type        mul     add    shl
17024       // scalar        4       1      1
17025       // vector        7       2      2
17026       return true;
17027     case PPC::DIR_PWR9:
17028     case PPC::DIR_PWR10:
17029     case PPC::DIR_PWR_FUTURE:
17030       //  type        mul     add    shl
17031       // scalar        5       2      2
17032       // vector        7       2      2
17033 
17034       // The cycle RATIO of related operations are showed as a table above.
17035       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
17036       // scalar and vector type. For 2 instrs patterns, add/sub + shl
17037       // are 4, it is always profitable; but for 3 instrs patterns
17038       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
17039       // So we should only do it for vector type.
17040       return IsAddOne && IsNeg ? VT.isVector() : true;
17041     }
17042   };
17043 
17044   EVT VT = N->getValueType(0);
17045   SDLoc DL(N);
17046 
17047   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
17048   bool IsNeg = MulAmt.isNegative();
17049   APInt MulAmtAbs = MulAmt.abs();
17050 
17051   if ((MulAmtAbs - 1).isPowerOf2()) {
17052     // (mul x, 2^N + 1) => (add (shl x, N), x)
17053     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
17054 
17055     if (!IsProfitable(IsNeg, true, VT))
17056       return SDValue();
17057 
17058     SDValue Op0 = N->getOperand(0);
17059     SDValue Op1 =
17060         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17061                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
17062     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
17063 
17064     if (!IsNeg)
17065       return Res;
17066 
17067     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
17068   } else if ((MulAmtAbs + 1).isPowerOf2()) {
17069     // (mul x, 2^N - 1) => (sub (shl x, N), x)
17070     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
17071 
17072     if (!IsProfitable(IsNeg, false, VT))
17073       return SDValue();
17074 
17075     SDValue Op0 = N->getOperand(0);
17076     SDValue Op1 =
17077         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17078                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
17079 
17080     if (!IsNeg)
17081       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
17082     else
17083       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
17084 
17085   } else {
17086     return SDValue();
17087   }
17088 }
17089 
17090 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
17091 // in combiner since we need to check SD flags and other subtarget features.
17092 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
17093                                           DAGCombinerInfo &DCI) const {
17094   SDValue N0 = N->getOperand(0);
17095   SDValue N1 = N->getOperand(1);
17096   SDValue N2 = N->getOperand(2);
17097   SDNodeFlags Flags = N->getFlags();
17098   EVT VT = N->getValueType(0);
17099   SelectionDAG &DAG = DCI.DAG;
17100   const TargetOptions &Options = getTargetMachine().Options;
17101   unsigned Opc = N->getOpcode();
17102   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
17103   bool LegalOps = !DCI.isBeforeLegalizeOps();
17104   SDLoc Loc(N);
17105 
17106   if (!isOperationLegal(ISD::FMA, VT))
17107     return SDValue();
17108 
17109   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
17110   // since (fnmsub a b c)=-0 while c-ab=+0.
17111   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
17112     return SDValue();
17113 
17114   // (fma (fneg a) b c) => (fnmsub a b c)
17115   // (fnmsub (fneg a) b c) => (fma a b c)
17116   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
17117     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
17118 
17119   // (fma a (fneg b) c) => (fnmsub a b c)
17120   // (fnmsub a (fneg b) c) => (fma a b c)
17121   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
17122     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
17123 
17124   return SDValue();
17125 }
17126 
17127 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
17128   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
17129   if (!Subtarget.is64BitELFABI())
17130     return false;
17131 
17132   // If not a tail call then no need to proceed.
17133   if (!CI->isTailCall())
17134     return false;
17135 
17136   // If sibling calls have been disabled and tail-calls aren't guaranteed
17137   // there is no reason to duplicate.
17138   auto &TM = getTargetMachine();
17139   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
17140     return false;
17141 
17142   // Can't tail call a function called indirectly, or if it has variadic args.
17143   const Function *Callee = CI->getCalledFunction();
17144   if (!Callee || Callee->isVarArg())
17145     return false;
17146 
17147   // Make sure the callee and caller calling conventions are eligible for tco.
17148   const Function *Caller = CI->getParent()->getParent();
17149   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
17150                                            CI->getCallingConv()))
17151       return false;
17152 
17153   // If the function is local then we have a good chance at tail-calling it
17154   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
17155 }
17156 
17157 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
17158   if (!Subtarget.hasVSX())
17159     return false;
17160   if (Subtarget.hasP9Vector() && VT == MVT::f128)
17161     return true;
17162   return VT == MVT::f32 || VT == MVT::f64 ||
17163     VT == MVT::v4f32 || VT == MVT::v2f64;
17164 }
17165 
17166 bool PPCTargetLowering::
17167 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
17168   const Value *Mask = AndI.getOperand(1);
17169   // If the mask is suitable for andi. or andis. we should sink the and.
17170   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
17171     // Can't handle constants wider than 64-bits.
17172     if (CI->getBitWidth() > 64)
17173       return false;
17174     int64_t ConstVal = CI->getZExtValue();
17175     return isUInt<16>(ConstVal) ||
17176       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
17177   }
17178 
17179   // For non-constant masks, we can always use the record-form and.
17180   return true;
17181 }
17182 
17183 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
17184 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
17185 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
17186 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
17187 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
17188 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
17189   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
17190   assert(Subtarget.hasP9Altivec() &&
17191          "Only combine this when P9 altivec supported!");
17192   EVT VT = N->getValueType(0);
17193   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17194     return SDValue();
17195 
17196   SelectionDAG &DAG = DCI.DAG;
17197   SDLoc dl(N);
17198   if (N->getOperand(0).getOpcode() == ISD::SUB) {
17199     // Even for signed integers, if it's known to be positive (as signed
17200     // integer) due to zero-extended inputs.
17201     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
17202     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
17203     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
17204          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
17205         (SubOpcd1 == ISD::ZERO_EXTEND ||
17206          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
17207       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17208                          N->getOperand(0)->getOperand(0),
17209                          N->getOperand(0)->getOperand(1),
17210                          DAG.getTargetConstant(0, dl, MVT::i32));
17211     }
17212 
17213     // For type v4i32, it can be optimized with xvnegsp + vabsduw
17214     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
17215         N->getOperand(0).hasOneUse()) {
17216       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17217                          N->getOperand(0)->getOperand(0),
17218                          N->getOperand(0)->getOperand(1),
17219                          DAG.getTargetConstant(1, dl, MVT::i32));
17220     }
17221   }
17222 
17223   return SDValue();
17224 }
17225 
17226 // For type v4i32/v8ii16/v16i8, transform
17227 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
17228 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
17229 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
17230 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
17231 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
17232                                           DAGCombinerInfo &DCI) const {
17233   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
17234   assert(Subtarget.hasP9Altivec() &&
17235          "Only combine this when P9 altivec supported!");
17236 
17237   SelectionDAG &DAG = DCI.DAG;
17238   SDLoc dl(N);
17239   SDValue Cond = N->getOperand(0);
17240   SDValue TrueOpnd = N->getOperand(1);
17241   SDValue FalseOpnd = N->getOperand(2);
17242   EVT VT = N->getOperand(1).getValueType();
17243 
17244   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
17245       FalseOpnd.getOpcode() != ISD::SUB)
17246     return SDValue();
17247 
17248   // ABSD only available for type v4i32/v8i16/v16i8
17249   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17250     return SDValue();
17251 
17252   // At least to save one more dependent computation
17253   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
17254     return SDValue();
17255 
17256   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17257 
17258   // Can only handle unsigned comparison here
17259   switch (CC) {
17260   default:
17261     return SDValue();
17262   case ISD::SETUGT:
17263   case ISD::SETUGE:
17264     break;
17265   case ISD::SETULT:
17266   case ISD::SETULE:
17267     std::swap(TrueOpnd, FalseOpnd);
17268     break;
17269   }
17270 
17271   SDValue CmpOpnd1 = Cond.getOperand(0);
17272   SDValue CmpOpnd2 = Cond.getOperand(1);
17273 
17274   // SETCC CmpOpnd1 CmpOpnd2 cond
17275   // TrueOpnd = CmpOpnd1 - CmpOpnd2
17276   // FalseOpnd = CmpOpnd2 - CmpOpnd1
17277   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
17278       TrueOpnd.getOperand(1) == CmpOpnd2 &&
17279       FalseOpnd.getOperand(0) == CmpOpnd2 &&
17280       FalseOpnd.getOperand(1) == CmpOpnd1) {
17281     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
17282                        CmpOpnd1, CmpOpnd2,
17283                        DAG.getTargetConstant(0, dl, MVT::i32));
17284   }
17285 
17286   return SDValue();
17287 }
17288 
17289 /// getAddrModeForFlags - Based on the set of address flags, select the most
17290 /// optimal instruction format to match by.
17291 PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const {
17292   // This is not a node we should be handling here.
17293   if (Flags == PPC::MOF_None)
17294     return PPC::AM_None;
17295   // Unaligned D-Forms are tried first, followed by the aligned D-Forms.
17296   for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm))
17297     if ((Flags & FlagSet) == FlagSet)
17298       return PPC::AM_DForm;
17299   for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm))
17300     if ((Flags & FlagSet) == FlagSet)
17301       return PPC::AM_DSForm;
17302   for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm))
17303     if ((Flags & FlagSet) == FlagSet)
17304       return PPC::AM_DQForm;
17305   for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm))
17306     if ((Flags & FlagSet) == FlagSet)
17307       return PPC::AM_PrefixDForm;
17308   // If no other forms are selected, return an X-Form as it is the most
17309   // general addressing mode.
17310   return PPC::AM_XForm;
17311 }
17312 
17313 /// Set alignment flags based on whether or not the Frame Index is aligned.
17314 /// Utilized when computing flags for address computation when selecting
17315 /// load and store instructions.
17316 static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet,
17317                                SelectionDAG &DAG) {
17318   bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR));
17319   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N);
17320   if (!FI)
17321     return;
17322   const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17323   unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value();
17324   // If this is (add $FI, $S16Imm), the alignment flags are already set
17325   // based on the immediate. We just need to clear the alignment flags
17326   // if the FI alignment is weaker.
17327   if ((FrameIndexAlign % 4) != 0)
17328     FlagSet &= ~PPC::MOF_RPlusSImm16Mult4;
17329   if ((FrameIndexAlign % 16) != 0)
17330     FlagSet &= ~PPC::MOF_RPlusSImm16Mult16;
17331   // If the address is a plain FrameIndex, set alignment flags based on
17332   // FI alignment.
17333   if (!IsAdd) {
17334     if ((FrameIndexAlign % 4) == 0)
17335       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17336     if ((FrameIndexAlign % 16) == 0)
17337       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17338   }
17339 }
17340 
17341 /// Given a node, compute flags that are used for address computation when
17342 /// selecting load and store instructions. The flags computed are stored in
17343 /// FlagSet. This function takes into account whether the node is a constant,
17344 /// an ADD, OR, or a constant, and computes the address flags accordingly.
17345 static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet,
17346                                               SelectionDAG &DAG) {
17347   // Set the alignment flags for the node depending on if the node is
17348   // 4-byte or 16-byte aligned.
17349   auto SetAlignFlagsForImm = [&](uint64_t Imm) {
17350     if ((Imm & 0x3) == 0)
17351       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17352     if ((Imm & 0xf) == 0)
17353       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17354   };
17355 
17356   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
17357     // All 32-bit constants can be computed as LIS + Disp.
17358     const APInt &ConstImm = CN->getAPIntValue();
17359     if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants.
17360       FlagSet |= PPC::MOF_AddrIsSImm32;
17361       SetAlignFlagsForImm(ConstImm.getZExtValue());
17362       setAlignFlagsForFI(N, FlagSet, DAG);
17363     }
17364     if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants.
17365       FlagSet |= PPC::MOF_RPlusSImm34;
17366     else // Let constant materialization handle large constants.
17367       FlagSet |= PPC::MOF_NotAddNorCst;
17368   } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) {
17369     // This address can be represented as an addition of:
17370     // - Register + Imm16 (possibly a multiple of 4/16)
17371     // - Register + Imm34
17372     // - Register + PPCISD::Lo
17373     // - Register + Register
17374     // In any case, we won't have to match this as Base + Zero.
17375     SDValue RHS = N.getOperand(1);
17376     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) {
17377       const APInt &ConstImm = CN->getAPIntValue();
17378       if (ConstImm.isSignedIntN(16)) {
17379         FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates.
17380         SetAlignFlagsForImm(ConstImm.getZExtValue());
17381         setAlignFlagsForFI(N, FlagSet, DAG);
17382       }
17383       if (ConstImm.isSignedIntN(34))
17384         FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates.
17385       else
17386         FlagSet |= PPC::MOF_RPlusR; // Register.
17387     } else if (RHS.getOpcode() == PPCISD::Lo &&
17388                !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue())
17389       FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo.
17390     else
17391       FlagSet |= PPC::MOF_RPlusR;
17392   } else { // The address computation is not a constant or an addition.
17393     setAlignFlagsForFI(N, FlagSet, DAG);
17394     FlagSet |= PPC::MOF_NotAddNorCst;
17395   }
17396 }
17397 
17398 static bool isPCRelNode(SDValue N) {
17399   return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR ||
17400       isValidPCRelNode<ConstantPoolSDNode>(N) ||
17401       isValidPCRelNode<GlobalAddressSDNode>(N) ||
17402       isValidPCRelNode<JumpTableSDNode>(N) ||
17403       isValidPCRelNode<BlockAddressSDNode>(N));
17404 }
17405 
17406 /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute
17407 /// the address flags of the load/store instruction that is to be matched.
17408 unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N,
17409                                            SelectionDAG &DAG) const {
17410   unsigned FlagSet = PPC::MOF_None;
17411 
17412   // Compute subtarget flags.
17413   if (!Subtarget.hasP9Vector())
17414     FlagSet |= PPC::MOF_SubtargetBeforeP9;
17415   else {
17416     FlagSet |= PPC::MOF_SubtargetP9;
17417     if (Subtarget.hasPrefixInstrs())
17418       FlagSet |= PPC::MOF_SubtargetP10;
17419   }
17420   if (Subtarget.hasSPE())
17421     FlagSet |= PPC::MOF_SubtargetSPE;
17422 
17423   // Check if we have a PCRel node and return early.
17424   if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N))
17425     return FlagSet;
17426 
17427   // If the node is the paired load/store intrinsics, compute flags for
17428   // address computation and return early.
17429   unsigned ParentOp = Parent->getOpcode();
17430   if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) ||
17431                                (ParentOp == ISD::INTRINSIC_VOID))) {
17432     unsigned ID = cast<ConstantSDNode>(Parent->getOperand(1))->getZExtValue();
17433     assert(
17434         ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) &&
17435         "Only the paired load and store (lxvp/stxvp) intrinsics are valid.");
17436     SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp) ? Parent->getOperand(2)
17437                                                        : Parent->getOperand(3);
17438     computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG);
17439     FlagSet |= PPC::MOF_Vector;
17440     return FlagSet;
17441   }
17442 
17443   // Mark this as something we don't want to handle here if it is atomic
17444   // or pre-increment instruction.
17445   if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent))
17446     if (LSB->isIndexed())
17447       return PPC::MOF_None;
17448 
17449   // Compute in-memory type flags. This is based on if there are scalars,
17450   // floats or vectors.
17451   const MemSDNode *MN = dyn_cast<MemSDNode>(Parent);
17452   assert(MN && "Parent should be a MemSDNode!");
17453   EVT MemVT = MN->getMemoryVT();
17454   unsigned Size = MemVT.getSizeInBits();
17455   if (MemVT.isScalarInteger()) {
17456     assert(Size <= 128 &&
17457            "Not expecting scalar integers larger than 16 bytes!");
17458     if (Size < 32)
17459       FlagSet |= PPC::MOF_SubWordInt;
17460     else if (Size == 32)
17461       FlagSet |= PPC::MOF_WordInt;
17462     else
17463       FlagSet |= PPC::MOF_DoubleWordInt;
17464   } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors.
17465     if (Size == 128)
17466       FlagSet |= PPC::MOF_Vector;
17467     else if (Size == 256) {
17468       assert(Subtarget.pairedVectorMemops() &&
17469              "256-bit vectors are only available when paired vector memops is "
17470              "enabled!");
17471       FlagSet |= PPC::MOF_Vector;
17472     } else
17473       llvm_unreachable("Not expecting illegal vectors!");
17474   } else { // Floating point type: can be scalar, f128 or vector types.
17475     if (Size == 32 || Size == 64)
17476       FlagSet |= PPC::MOF_ScalarFloat;
17477     else if (MemVT == MVT::f128 || MemVT.isVector())
17478       FlagSet |= PPC::MOF_Vector;
17479     else
17480       llvm_unreachable("Not expecting illegal scalar floats!");
17481   }
17482 
17483   // Compute flags for address computation.
17484   computeFlagsForAddressComputation(N, FlagSet, DAG);
17485 
17486   // Compute type extension flags.
17487   if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) {
17488     switch (LN->getExtensionType()) {
17489     case ISD::SEXTLOAD:
17490       FlagSet |= PPC::MOF_SExt;
17491       break;
17492     case ISD::EXTLOAD:
17493     case ISD::ZEXTLOAD:
17494       FlagSet |= PPC::MOF_ZExt;
17495       break;
17496     case ISD::NON_EXTLOAD:
17497       FlagSet |= PPC::MOF_NoExt;
17498       break;
17499     }
17500   } else
17501     FlagSet |= PPC::MOF_NoExt;
17502 
17503   // For integers, no extension is the same as zero extension.
17504   // We set the extension mode to zero extension so we don't have
17505   // to add separate entries in AddrModesMap for loads and stores.
17506   if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) {
17507     FlagSet |= PPC::MOF_ZExt;
17508     FlagSet &= ~PPC::MOF_NoExt;
17509   }
17510 
17511   // If we don't have prefixed instructions, 34-bit constants should be
17512   // treated as PPC::MOF_NotAddNorCst so they can match D-Forms.
17513   bool IsNonP1034BitConst =
17514       ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) &
17515        FlagSet) == PPC::MOF_RPlusSImm34;
17516   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR &&
17517       IsNonP1034BitConst)
17518     FlagSet |= PPC::MOF_NotAddNorCst;
17519 
17520   return FlagSet;
17521 }
17522 
17523 /// SelectForceXFormMode - Given the specified address, force it to be
17524 /// represented as an indexed [r+r] operation (an XForm instruction).
17525 PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp,
17526                                                       SDValue &Base,
17527                                                       SelectionDAG &DAG) const {
17528 
17529   PPC::AddrMode Mode = PPC::AM_XForm;
17530   int16_t ForceXFormImm = 0;
17531   if (provablyDisjointOr(DAG, N) &&
17532       !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) {
17533     Disp = N.getOperand(0);
17534     Base = N.getOperand(1);
17535     return Mode;
17536   }
17537 
17538   // If the address is the result of an add, we will utilize the fact that the
17539   // address calculation includes an implicit add.  However, we can reduce
17540   // register pressure if we do not materialize a constant just for use as the
17541   // index register.  We only get rid of the add if it is not an add of a
17542   // value and a 16-bit signed constant and both have a single use.
17543   if (N.getOpcode() == ISD::ADD &&
17544       (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) ||
17545        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
17546     Disp = N.getOperand(0);
17547     Base = N.getOperand(1);
17548     return Mode;
17549   }
17550 
17551   // Otherwise, use R0 as the base register.
17552   Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17553                          N.getValueType());
17554   Base = N;
17555 
17556   return Mode;
17557 }
17558 
17559 // If we happen to match to an aligned D-Form, check if the Frame Index is
17560 // adequately aligned. If it is not, reset the mode to match to X-Form.
17561 static void setXFormForUnalignedFI(SDValue N, unsigned Flags,
17562                                    PPC::AddrMode &Mode) {
17563   if (!isa<FrameIndexSDNode>(N))
17564     return;
17565   if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) ||
17566       (Mode == PPC::AM_DQForm && !(Flags & PPC::MOF_RPlusSImm16Mult16)))
17567     Mode = PPC::AM_XForm;
17568 }
17569 
17570 /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode),
17571 /// compute the address flags of the node, get the optimal address mode based
17572 /// on the flags, and set the Base and Disp based on the address mode.
17573 PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent,
17574                                                        SDValue N, SDValue &Disp,
17575                                                        SDValue &Base,
17576                                                        SelectionDAG &DAG,
17577                                                        MaybeAlign Align) const {
17578   SDLoc DL(Parent);
17579 
17580   // Compute the address flags.
17581   unsigned Flags = computeMOFlags(Parent, N, DAG);
17582 
17583   // Get the optimal address mode based on the Flags.
17584   PPC::AddrMode Mode = getAddrModeForFlags(Flags);
17585 
17586   // If the address mode is DS-Form or DQ-Form, check if the FI is aligned.
17587   // Select an X-Form load if it is not.
17588   setXFormForUnalignedFI(N, Flags, Mode);
17589 
17590   // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node.
17591   if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) {
17592     assert(Subtarget.isUsingPCRelativeCalls() &&
17593            "Must be using PC-Relative calls when a valid PC-Relative node is "
17594            "present!");
17595     Mode = PPC::AM_PCRel;
17596   }
17597 
17598   // Set Base and Disp accordingly depending on the address mode.
17599   switch (Mode) {
17600   case PPC::AM_DForm:
17601   case PPC::AM_DSForm:
17602   case PPC::AM_DQForm: {
17603     // This is a register plus a 16-bit immediate. The base will be the
17604     // register and the displacement will be the immediate unless it
17605     // isn't sufficiently aligned.
17606     if (Flags & PPC::MOF_RPlusSImm16) {
17607       SDValue Op0 = N.getOperand(0);
17608       SDValue Op1 = N.getOperand(1);
17609       int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue();
17610       if (!Align || isAligned(*Align, Imm)) {
17611         Disp = DAG.getTargetConstant(Imm, DL, N.getValueType());
17612         Base = Op0;
17613         if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) {
17614           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17615           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17616         }
17617         break;
17618       }
17619     }
17620     // This is a register plus the @lo relocation. The base is the register
17621     // and the displacement is the global address.
17622     else if (Flags & PPC::MOF_RPlusLo) {
17623       Disp = N.getOperand(1).getOperand(0); // The global address.
17624       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
17625              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
17626              Disp.getOpcode() == ISD::TargetConstantPool ||
17627              Disp.getOpcode() == ISD::TargetJumpTable);
17628       Base = N.getOperand(0);
17629       break;
17630     }
17631     // This is a constant address at most 32 bits. The base will be
17632     // zero or load-immediate-shifted and the displacement will be
17633     // the low 16 bits of the address.
17634     else if (Flags & PPC::MOF_AddrIsSImm32) {
17635       auto *CN = cast<ConstantSDNode>(N);
17636       EVT CNType = CN->getValueType(0);
17637       uint64_t CNImm = CN->getZExtValue();
17638       // If this address fits entirely in a 16-bit sext immediate field, codegen
17639       // this as "d, 0".
17640       int16_t Imm;
17641       if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) {
17642         Disp = DAG.getTargetConstant(Imm, DL, CNType);
17643         Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17644                                CNType);
17645         break;
17646       }
17647       // Handle 32-bit sext immediate with LIS + Addr mode.
17648       if ((CNType == MVT::i32 || isInt<32>(CNImm)) &&
17649           (!Align || isAligned(*Align, CNImm))) {
17650         int32_t Addr = (int32_t)CNImm;
17651         // Otherwise, break this down into LIS + Disp.
17652         Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32);
17653         Base =
17654             DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32);
17655         uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8;
17656         Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0);
17657         break;
17658       }
17659     }
17660     // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable.
17661     Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout()));
17662     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
17663       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17664       fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17665     } else
17666       Base = N;
17667     break;
17668   }
17669   case PPC::AM_PrefixDForm: {
17670     int64_t Imm34 = 0;
17671     unsigned Opcode = N.getOpcode();
17672     if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) &&
17673         (isIntS34Immediate(N.getOperand(1), Imm34))) {
17674       // N is an Add/OR Node, and it's operand is a 34-bit signed immediate.
17675       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
17676       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
17677         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17678       else
17679         Base = N.getOperand(0);
17680     } else if (isIntS34Immediate(N, Imm34)) {
17681       // The address is a 34-bit signed immediate.
17682       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
17683       Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
17684     }
17685     break;
17686   }
17687   case PPC::AM_PCRel: {
17688     // When selecting PC-Relative instructions, "Base" is not utilized as
17689     // we select the address as [PC+imm].
17690     Disp = N;
17691     break;
17692   }
17693   case PPC::AM_None:
17694     break;
17695   default: { // By default, X-Form is always available to be selected.
17696     // When a frame index is not aligned, we also match by XForm.
17697     FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N);
17698     Base = FI ? N : N.getOperand(1);
17699     Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17700                                 N.getValueType())
17701               : N.getOperand(0);
17702     break;
17703   }
17704   }
17705   return Mode;
17706 }
17707 
17708 CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC,
17709                                                  bool Return,
17710                                                  bool IsVarArg) const {
17711   switch (CC) {
17712   case CallingConv::Cold:
17713     return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS);
17714   default:
17715     return CC_PPC64_ELF_FIS;
17716   }
17717 }
17718 
17719 TargetLowering::AtomicExpansionKind
17720 PPCTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17721   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
17722   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
17723     return AtomicExpansionKind::MaskedIntrinsic;
17724   return TargetLowering::shouldExpandAtomicRMWInIR(AI);
17725 }
17726 
17727 TargetLowering::AtomicExpansionKind
17728 PPCTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
17729   unsigned Size = AI->getNewValOperand()->getType()->getPrimitiveSizeInBits();
17730   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
17731     return AtomicExpansionKind::MaskedIntrinsic;
17732   return TargetLowering::shouldExpandAtomicCmpXchgInIR(AI);
17733 }
17734 
17735 static Intrinsic::ID
17736 getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp) {
17737   switch (BinOp) {
17738   default:
17739     llvm_unreachable("Unexpected AtomicRMW BinOp");
17740   case AtomicRMWInst::Xchg:
17741     return Intrinsic::ppc_atomicrmw_xchg_i128;
17742   case AtomicRMWInst::Add:
17743     return Intrinsic::ppc_atomicrmw_add_i128;
17744   case AtomicRMWInst::Sub:
17745     return Intrinsic::ppc_atomicrmw_sub_i128;
17746   case AtomicRMWInst::And:
17747     return Intrinsic::ppc_atomicrmw_and_i128;
17748   case AtomicRMWInst::Or:
17749     return Intrinsic::ppc_atomicrmw_or_i128;
17750   case AtomicRMWInst::Xor:
17751     return Intrinsic::ppc_atomicrmw_xor_i128;
17752   case AtomicRMWInst::Nand:
17753     return Intrinsic::ppc_atomicrmw_nand_i128;
17754   }
17755 }
17756 
17757 Value *PPCTargetLowering::emitMaskedAtomicRMWIntrinsic(
17758     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
17759     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
17760   assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
17761          "Only support quadword now");
17762   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17763   Type *ValTy = cast<PointerType>(AlignedAddr->getType())->getElementType();
17764   assert(ValTy->getPrimitiveSizeInBits() == 128);
17765   Function *RMW = Intrinsic::getDeclaration(
17766       M, getIntrinsicForAtomicRMWBinOp128(AI->getOperation()));
17767   Type *Int64Ty = Type::getInt64Ty(M->getContext());
17768   Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo");
17769   Value *IncrHi =
17770       Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi");
17771   Value *Addr =
17772       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
17773   Value *LoHi = Builder.CreateCall(RMW, {Addr, IncrLo, IncrHi});
17774   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
17775   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
17776   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
17777   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
17778   return Builder.CreateOr(
17779       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
17780 }
17781 
17782 Value *PPCTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
17783     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
17784     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
17785   assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
17786          "Only support quadword now");
17787   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17788   Type *ValTy = cast<PointerType>(AlignedAddr->getType())->getElementType();
17789   assert(ValTy->getPrimitiveSizeInBits() == 128);
17790   Function *IntCmpXchg =
17791       Intrinsic::getDeclaration(M, Intrinsic::ppc_cmpxchg_i128);
17792   Type *Int64Ty = Type::getInt64Ty(M->getContext());
17793   Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo");
17794   Value *CmpHi =
17795       Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi");
17796   Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo");
17797   Value *NewHi =
17798       Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi");
17799   Value *Addr =
17800       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
17801   emitLeadingFence(Builder, CI, Ord);
17802   Value *LoHi =
17803       Builder.CreateCall(IntCmpXchg, {Addr, CmpLo, CmpHi, NewLo, NewHi});
17804   emitTrailingFence(Builder, CI, Ord);
17805   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
17806   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
17807   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
17808   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
17809   return Builder.CreateOr(
17810       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
17811 }
17812