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 uint64_t 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           EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8);
4373           SDValue Store =
4374               DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4375                                 MachinePointerInfo(&*FuncArg), ObjType);
4376           MemOps.push_back(Store);
4377         }
4378         // Whether we copied from a register or not, advance the offset
4379         // into the parameter save area by a full doubleword.
4380         ArgOffset += PtrByteSize;
4381         continue;
4382       }
4383 
4384       // The value of the object is its address, which is the address of
4385       // its first stack doubleword.
4386       InVals.push_back(FIN);
4387 
4388       // Store whatever pieces of the object are in registers to memory.
4389       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4390         if (GPR_idx == Num_GPR_Regs)
4391           break;
4392 
4393         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4394         FuncInfo->addLiveInAttr(VReg, Flags);
4395         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4396         SDValue Addr = FIN;
4397         if (j) {
4398           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4399           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4400         }
4401         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4402                                      MachinePointerInfo(&*FuncArg, j));
4403         MemOps.push_back(Store);
4404         ++GPR_idx;
4405       }
4406       ArgOffset += ArgSize;
4407       continue;
4408     }
4409 
4410     switch (ObjectVT.getSimpleVT().SimpleTy) {
4411     default: llvm_unreachable("Unhandled argument type!");
4412     case MVT::i1:
4413     case MVT::i32:
4414     case MVT::i64:
4415       if (Flags.isNest()) {
4416         // The 'nest' parameter, if any, is passed in R11.
4417         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4418         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4419 
4420         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4421           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4422 
4423         break;
4424       }
4425 
4426       // These can be scalar arguments or elements of an integer array type
4427       // passed directly.  Clang may use those instead of "byval" aggregate
4428       // types to avoid forcing arguments to memory unnecessarily.
4429       if (GPR_idx != Num_GPR_Regs) {
4430         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4431         FuncInfo->addLiveInAttr(VReg, Flags);
4432         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4433 
4434         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4435           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4436           // value to MVT::i64 and then truncate to the correct register size.
4437           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4438       } else {
4439         if (CallConv == CallingConv::Fast)
4440           ComputeArgOffset();
4441 
4442         needsLoad = true;
4443         ArgSize = PtrByteSize;
4444       }
4445       if (CallConv != CallingConv::Fast || needsLoad)
4446         ArgOffset += 8;
4447       break;
4448 
4449     case MVT::f32:
4450     case MVT::f64:
4451       // These can be scalar arguments or elements of a float array type
4452       // passed directly.  The latter are used to implement ELFv2 homogenous
4453       // float aggregates.
4454       if (FPR_idx != Num_FPR_Regs) {
4455         unsigned VReg;
4456 
4457         if (ObjectVT == MVT::f32)
4458           VReg = MF.addLiveIn(FPR[FPR_idx],
4459                               Subtarget.hasP8Vector()
4460                                   ? &PPC::VSSRCRegClass
4461                                   : &PPC::F4RCRegClass);
4462         else
4463           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4464                                                 ? &PPC::VSFRCRegClass
4465                                                 : &PPC::F8RCRegClass);
4466 
4467         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4468         ++FPR_idx;
4469       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4470         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4471         // once we support fp <-> gpr moves.
4472 
4473         // This can only ever happen in the presence of f32 array types,
4474         // since otherwise we never run out of FPRs before running out
4475         // of GPRs.
4476         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4477         FuncInfo->addLiveInAttr(VReg, Flags);
4478         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4479 
4480         if (ObjectVT == MVT::f32) {
4481           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4482             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4483                                  DAG.getConstant(32, dl, MVT::i32));
4484           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4485         }
4486 
4487         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4488       } else {
4489         if (CallConv == CallingConv::Fast)
4490           ComputeArgOffset();
4491 
4492         needsLoad = true;
4493       }
4494 
4495       // When passing an array of floats, the array occupies consecutive
4496       // space in the argument area; only round up to the next doubleword
4497       // at the end of the array.  Otherwise, each float takes 8 bytes.
4498       if (CallConv != CallingConv::Fast || needsLoad) {
4499         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4500         ArgOffset += ArgSize;
4501         if (Flags.isInConsecutiveRegsLast())
4502           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4503       }
4504       break;
4505     case MVT::v4f32:
4506     case MVT::v4i32:
4507     case MVT::v8i16:
4508     case MVT::v16i8:
4509     case MVT::v2f64:
4510     case MVT::v2i64:
4511     case MVT::v1i128:
4512     case MVT::f128:
4513       // These can be scalar arguments or elements of a vector array type
4514       // passed directly.  The latter are used to implement ELFv2 homogenous
4515       // vector aggregates.
4516       if (VR_idx != Num_VR_Regs) {
4517         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4518         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4519         ++VR_idx;
4520       } else {
4521         if (CallConv == CallingConv::Fast)
4522           ComputeArgOffset();
4523         needsLoad = true;
4524       }
4525       if (CallConv != CallingConv::Fast || needsLoad)
4526         ArgOffset += 16;
4527       break;
4528     }
4529 
4530     // We need to load the argument to a virtual register if we determined
4531     // above that we ran out of physical registers of the appropriate type.
4532     if (needsLoad) {
4533       if (ObjSize < ArgSize && !isLittleEndian)
4534         CurArgOffset += ArgSize - ObjSize;
4535       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4536       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4537       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4538     }
4539 
4540     InVals.push_back(ArgVal);
4541   }
4542 
4543   // Area that is at least reserved in the caller of this function.
4544   unsigned MinReservedArea;
4545   if (HasParameterArea)
4546     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4547   else
4548     MinReservedArea = LinkageSize;
4549 
4550   // Set the size that is at least reserved in caller of this function.  Tail
4551   // call optimized functions' reserved stack space needs to be aligned so that
4552   // taking the difference between two stack areas will result in an aligned
4553   // stack.
4554   MinReservedArea =
4555       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4556   FuncInfo->setMinReservedArea(MinReservedArea);
4557 
4558   // If the function takes variable number of arguments, make a frame index for
4559   // the start of the first vararg value... for expansion of llvm.va_start.
4560   // On ELFv2ABI spec, it writes:
4561   // C programs that are intended to be *portable* across different compilers
4562   // and architectures must use the header file <stdarg.h> to deal with variable
4563   // argument lists.
4564   if (isVarArg && MFI.hasVAStart()) {
4565     int Depth = ArgOffset;
4566 
4567     FuncInfo->setVarArgsFrameIndex(
4568       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4569     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4570 
4571     // If this function is vararg, store any remaining integer argument regs
4572     // to their spots on the stack so that they may be loaded by dereferencing
4573     // the result of va_next.
4574     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4575          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4576       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4577       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4578       SDValue Store =
4579           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4580       MemOps.push_back(Store);
4581       // Increment the address by four for the next argument to store
4582       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4583       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4584     }
4585   }
4586 
4587   if (!MemOps.empty())
4588     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4589 
4590   return Chain;
4591 }
4592 
4593 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4594 /// adjusted to accommodate the arguments for the tailcall.
4595 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4596                                    unsigned ParamSize) {
4597 
4598   if (!isTailCall) return 0;
4599 
4600   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4601   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4602   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4603   // Remember only if the new adjustment is bigger.
4604   if (SPDiff < FI->getTailCallSPDelta())
4605     FI->setTailCallSPDelta(SPDiff);
4606 
4607   return SPDiff;
4608 }
4609 
4610 static bool isFunctionGlobalAddress(SDValue Callee);
4611 
4612 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4613                               const TargetMachine &TM) {
4614   // It does not make sense to call callsShareTOCBase() with a caller that
4615   // is PC Relative since PC Relative callers do not have a TOC.
4616 #ifndef NDEBUG
4617   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4618   assert(!STICaller->isUsingPCRelativeCalls() &&
4619          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4620 #endif
4621 
4622   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4623   // don't have enough information to determine if the caller and callee share
4624   // the same  TOC base, so we have to pessimistically assume they don't for
4625   // correctness.
4626   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4627   if (!G)
4628     return false;
4629 
4630   const GlobalValue *GV = G->getGlobal();
4631 
4632   // If the callee is preemptable, then the static linker will use a plt-stub
4633   // which saves the toc to the stack, and needs a nop after the call
4634   // instruction to convert to a toc-restore.
4635   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4636     return false;
4637 
4638   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4639   // We may need a TOC restore in the situation where the caller requires a
4640   // valid TOC but the callee is PC Relative and does not.
4641   const Function *F = dyn_cast<Function>(GV);
4642   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4643 
4644   // If we have an Alias we can try to get the function from there.
4645   if (Alias) {
4646     const GlobalObject *GlobalObj = Alias->getAliaseeObject();
4647     F = dyn_cast<Function>(GlobalObj);
4648   }
4649 
4650   // If we still have no valid function pointer we do not have enough
4651   // information to determine if the callee uses PC Relative calls so we must
4652   // assume that it does.
4653   if (!F)
4654     return false;
4655 
4656   // If the callee uses PC Relative we cannot guarantee that the callee won't
4657   // clobber the TOC of the caller and so we must assume that the two
4658   // functions do not share a TOC base.
4659   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4660   if (STICallee->isUsingPCRelativeCalls())
4661     return false;
4662 
4663   // If the GV is not a strong definition then we need to assume it can be
4664   // replaced by another function at link time. The function that replaces
4665   // it may not share the same TOC as the caller since the callee may be
4666   // replaced by a PC Relative version of the same function.
4667   if (!GV->isStrongDefinitionForLinker())
4668     return false;
4669 
4670   // The medium and large code models are expected to provide a sufficiently
4671   // large TOC to provide all data addressing needs of a module with a
4672   // single TOC.
4673   if (CodeModel::Medium == TM.getCodeModel() ||
4674       CodeModel::Large == TM.getCodeModel())
4675     return true;
4676 
4677   // Any explicitly-specified sections and section prefixes must also match.
4678   // Also, if we're using -ffunction-sections, then each function is always in
4679   // a different section (the same is true for COMDAT functions).
4680   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4681       GV->getSection() != Caller->getSection())
4682     return false;
4683   if (const auto *F = dyn_cast<Function>(GV)) {
4684     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4685       return false;
4686   }
4687 
4688   return true;
4689 }
4690 
4691 static bool
4692 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4693                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4694   assert(Subtarget.is64BitELFABI());
4695 
4696   const unsigned PtrByteSize = 8;
4697   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4698 
4699   static const MCPhysReg GPR[] = {
4700     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4701     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4702   };
4703   static const MCPhysReg VR[] = {
4704     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4705     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4706   };
4707 
4708   const unsigned NumGPRs = array_lengthof(GPR);
4709   const unsigned NumFPRs = 13;
4710   const unsigned NumVRs = array_lengthof(VR);
4711   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4712 
4713   unsigned NumBytes = LinkageSize;
4714   unsigned AvailableFPRs = NumFPRs;
4715   unsigned AvailableVRs = NumVRs;
4716 
4717   for (const ISD::OutputArg& Param : Outs) {
4718     if (Param.Flags.isNest()) continue;
4719 
4720     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4721                                LinkageSize, ParamAreaSize, NumBytes,
4722                                AvailableFPRs, AvailableVRs))
4723       return true;
4724   }
4725   return false;
4726 }
4727 
4728 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4729   if (CB.arg_size() != CallerFn->arg_size())
4730     return false;
4731 
4732   auto CalleeArgIter = CB.arg_begin();
4733   auto CalleeArgEnd = CB.arg_end();
4734   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4735 
4736   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4737     const Value* CalleeArg = *CalleeArgIter;
4738     const Value* CallerArg = &(*CallerArgIter);
4739     if (CalleeArg == CallerArg)
4740       continue;
4741 
4742     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4743     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4744     //      }
4745     // 1st argument of callee is undef and has the same type as caller.
4746     if (CalleeArg->getType() == CallerArg->getType() &&
4747         isa<UndefValue>(CalleeArg))
4748       continue;
4749 
4750     return false;
4751   }
4752 
4753   return true;
4754 }
4755 
4756 // Returns true if TCO is possible between the callers and callees
4757 // calling conventions.
4758 static bool
4759 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4760                                     CallingConv::ID CalleeCC) {
4761   // Tail calls are possible with fastcc and ccc.
4762   auto isTailCallableCC  = [] (CallingConv::ID CC){
4763       return  CC == CallingConv::C || CC == CallingConv::Fast;
4764   };
4765   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4766     return false;
4767 
4768   // We can safely tail call both fastcc and ccc callees from a c calling
4769   // convention caller. If the caller is fastcc, we may have less stack space
4770   // than a non-fastcc caller with the same signature so disable tail-calls in
4771   // that case.
4772   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4773 }
4774 
4775 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4776     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4777     const SmallVectorImpl<ISD::OutputArg> &Outs,
4778     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4779   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4780 
4781   if (DisableSCO && !TailCallOpt) return false;
4782 
4783   // Variadic argument functions are not supported.
4784   if (isVarArg) return false;
4785 
4786   auto &Caller = DAG.getMachineFunction().getFunction();
4787   // Check that the calling conventions are compatible for tco.
4788   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4789     return false;
4790 
4791   // Caller contains any byval parameter is not supported.
4792   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4793     return false;
4794 
4795   // Callee contains any byval parameter is not supported, too.
4796   // Note: This is a quick work around, because in some cases, e.g.
4797   // caller's stack size > callee's stack size, we are still able to apply
4798   // sibling call optimization. For example, gcc is able to do SCO for caller1
4799   // in the following example, but not for caller2.
4800   //   struct test {
4801   //     long int a;
4802   //     char ary[56];
4803   //   } gTest;
4804   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4805   //     b->a = v.a;
4806   //     return 0;
4807   //   }
4808   //   void caller1(struct test a, struct test c, struct test *b) {
4809   //     callee(gTest, b); }
4810   //   void caller2(struct test *b) { callee(gTest, b); }
4811   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4812     return false;
4813 
4814   // If callee and caller use different calling conventions, we cannot pass
4815   // parameters on stack since offsets for the parameter area may be different.
4816   if (Caller.getCallingConv() != CalleeCC &&
4817       needStackSlotPassParameters(Subtarget, Outs))
4818     return false;
4819 
4820   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4821   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4822   // callee potentially have different TOC bases then we cannot tail call since
4823   // we need to restore the TOC pointer after the call.
4824   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4825   // We cannot guarantee this for indirect calls or calls to external functions.
4826   // When PC-Relative addressing is used, the concept of the TOC is no longer
4827   // applicable so this check is not required.
4828   // Check first for indirect calls.
4829   if (!Subtarget.isUsingPCRelativeCalls() &&
4830       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4831     return false;
4832 
4833   // Check if we share the TOC base.
4834   if (!Subtarget.isUsingPCRelativeCalls() &&
4835       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4836     return false;
4837 
4838   // TCO allows altering callee ABI, so we don't have to check further.
4839   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4840     return true;
4841 
4842   if (DisableSCO) return false;
4843 
4844   // If callee use the same argument list that caller is using, then we can
4845   // apply SCO on this case. If it is not, then we need to check if callee needs
4846   // stack for passing arguments.
4847   // PC Relative tail calls may not have a CallBase.
4848   // If there is no CallBase we cannot verify if we have the same argument
4849   // list so assume that we don't have the same argument list.
4850   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4851       needStackSlotPassParameters(Subtarget, Outs))
4852     return false;
4853   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4854     return false;
4855 
4856   return true;
4857 }
4858 
4859 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4860 /// for tail call optimization. Targets which want to do tail call
4861 /// optimization should implement this function.
4862 bool
4863 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4864                                                      CallingConv::ID CalleeCC,
4865                                                      bool isVarArg,
4866                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4867                                                      SelectionDAG& DAG) const {
4868   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4869     return false;
4870 
4871   // Variable argument functions are not supported.
4872   if (isVarArg)
4873     return false;
4874 
4875   MachineFunction &MF = DAG.getMachineFunction();
4876   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4877   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4878     // Functions containing by val parameters are not supported.
4879     for (unsigned i = 0; i != Ins.size(); i++) {
4880        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4881        if (Flags.isByVal()) return false;
4882     }
4883 
4884     // Non-PIC/GOT tail calls are supported.
4885     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4886       return true;
4887 
4888     // At the moment we can only do local tail calls (in same module, hidden
4889     // or protected) if we are generating PIC.
4890     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4891       return G->getGlobal()->hasHiddenVisibility()
4892           || G->getGlobal()->hasProtectedVisibility();
4893   }
4894 
4895   return false;
4896 }
4897 
4898 /// isCallCompatibleAddress - Return the immediate to use if the specified
4899 /// 32-bit value is representable in the immediate field of a BxA instruction.
4900 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4901   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4902   if (!C) return nullptr;
4903 
4904   int Addr = C->getZExtValue();
4905   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4906       SignExtend32<26>(Addr) != Addr)
4907     return nullptr;  // Top 6 bits have to be sext of immediate.
4908 
4909   return DAG
4910       .getConstant(
4911           (int)C->getZExtValue() >> 2, SDLoc(Op),
4912           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4913       .getNode();
4914 }
4915 
4916 namespace {
4917 
4918 struct TailCallArgumentInfo {
4919   SDValue Arg;
4920   SDValue FrameIdxOp;
4921   int FrameIdx = 0;
4922 
4923   TailCallArgumentInfo() = default;
4924 };
4925 
4926 } // end anonymous namespace
4927 
4928 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4929 static void StoreTailCallArgumentsToStackSlot(
4930     SelectionDAG &DAG, SDValue Chain,
4931     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4932     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4933   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4934     SDValue Arg = TailCallArgs[i].Arg;
4935     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4936     int FI = TailCallArgs[i].FrameIdx;
4937     // Store relative to framepointer.
4938     MemOpChains.push_back(DAG.getStore(
4939         Chain, dl, Arg, FIN,
4940         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4941   }
4942 }
4943 
4944 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4945 /// the appropriate stack slot for the tail call optimized function call.
4946 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4947                                              SDValue OldRetAddr, SDValue OldFP,
4948                                              int SPDiff, const SDLoc &dl) {
4949   if (SPDiff) {
4950     // Calculate the new stack slot for the return address.
4951     MachineFunction &MF = DAG.getMachineFunction();
4952     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4953     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4954     bool isPPC64 = Subtarget.isPPC64();
4955     int SlotSize = isPPC64 ? 8 : 4;
4956     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4957     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4958                                                          NewRetAddrLoc, true);
4959     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4960     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4961     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4962                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4963   }
4964   return Chain;
4965 }
4966 
4967 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4968 /// the position of the argument.
4969 static void
4970 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4971                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4972                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4973   int Offset = ArgOffset + SPDiff;
4974   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4975   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4976   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4977   SDValue FIN = DAG.getFrameIndex(FI, VT);
4978   TailCallArgumentInfo Info;
4979   Info.Arg = Arg;
4980   Info.FrameIdxOp = FIN;
4981   Info.FrameIdx = FI;
4982   TailCallArguments.push_back(Info);
4983 }
4984 
4985 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4986 /// stack slot. Returns the chain as result and the loaded frame pointers in
4987 /// LROpOut/FPOpout. Used when tail calling.
4988 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4989     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4990     SDValue &FPOpOut, const SDLoc &dl) const {
4991   if (SPDiff) {
4992     // Load the LR and FP stack slot for later adjusting.
4993     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4994     LROpOut = getReturnAddrFrameIndex(DAG);
4995     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4996     Chain = SDValue(LROpOut.getNode(), 1);
4997   }
4998   return Chain;
4999 }
5000 
5001 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5002 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5003 /// specified by the specific parameter attribute. The copy will be passed as
5004 /// a byval function parameter.
5005 /// Sometimes what we are copying is the end of a larger object, the part that
5006 /// does not fit in registers.
5007 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5008                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5009                                          SelectionDAG &DAG, const SDLoc &dl) {
5010   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5011   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5012                        Flags.getNonZeroByValAlign(), false, false, false,
5013                        MachinePointerInfo(), MachinePointerInfo());
5014 }
5015 
5016 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5017 /// tail calls.
5018 static void LowerMemOpCallTo(
5019     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5020     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5021     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5022     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5023   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5024   if (!isTailCall) {
5025     if (isVector) {
5026       SDValue StackPtr;
5027       if (isPPC64)
5028         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5029       else
5030         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5031       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5032                            DAG.getConstant(ArgOffset, dl, PtrVT));
5033     }
5034     MemOpChains.push_back(
5035         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5036     // Calculate and remember argument location.
5037   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5038                                   TailCallArguments);
5039 }
5040 
5041 static void
5042 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5043                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5044                 SDValue FPOp,
5045                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5046   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5047   // might overwrite each other in case of tail call optimization.
5048   SmallVector<SDValue, 8> MemOpChains2;
5049   // Do not flag preceding copytoreg stuff together with the following stuff.
5050   InFlag = SDValue();
5051   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5052                                     MemOpChains2, dl);
5053   if (!MemOpChains2.empty())
5054     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5055 
5056   // Store the return address to the appropriate stack slot.
5057   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5058 
5059   // Emit callseq_end just before tailcall node.
5060   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5061                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5062   InFlag = Chain.getValue(1);
5063 }
5064 
5065 // Is this global address that of a function that can be called by name? (as
5066 // opposed to something that must hold a descriptor for an indirect call).
5067 static bool isFunctionGlobalAddress(SDValue Callee) {
5068   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5069     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5070         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5071       return false;
5072 
5073     return G->getGlobal()->getValueType()->isFunctionTy();
5074   }
5075 
5076   return false;
5077 }
5078 
5079 SDValue PPCTargetLowering::LowerCallResult(
5080     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5081     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5082     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5083   SmallVector<CCValAssign, 16> RVLocs;
5084   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5085                     *DAG.getContext());
5086 
5087   CCRetInfo.AnalyzeCallResult(
5088       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5089                ? RetCC_PPC_Cold
5090                : RetCC_PPC);
5091 
5092   // Copy all of the result registers out of their specified physreg.
5093   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5094     CCValAssign &VA = RVLocs[i];
5095     assert(VA.isRegLoc() && "Can only return in registers!");
5096 
5097     SDValue Val;
5098 
5099     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5100       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5101                                       InFlag);
5102       Chain = Lo.getValue(1);
5103       InFlag = Lo.getValue(2);
5104       VA = RVLocs[++i]; // skip ahead to next loc
5105       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5106                                       InFlag);
5107       Chain = Hi.getValue(1);
5108       InFlag = Hi.getValue(2);
5109       if (!Subtarget.isLittleEndian())
5110         std::swap (Lo, Hi);
5111       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5112     } else {
5113       Val = DAG.getCopyFromReg(Chain, dl,
5114                                VA.getLocReg(), VA.getLocVT(), InFlag);
5115       Chain = Val.getValue(1);
5116       InFlag = Val.getValue(2);
5117     }
5118 
5119     switch (VA.getLocInfo()) {
5120     default: llvm_unreachable("Unknown loc info!");
5121     case CCValAssign::Full: break;
5122     case CCValAssign::AExt:
5123       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5124       break;
5125     case CCValAssign::ZExt:
5126       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5127                         DAG.getValueType(VA.getValVT()));
5128       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5129       break;
5130     case CCValAssign::SExt:
5131       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5132                         DAG.getValueType(VA.getValVT()));
5133       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5134       break;
5135     }
5136 
5137     InVals.push_back(Val);
5138   }
5139 
5140   return Chain;
5141 }
5142 
5143 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5144                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5145   // PatchPoint calls are not indirect.
5146   if (isPatchPoint)
5147     return false;
5148 
5149   if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee))
5150     return false;
5151 
5152   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5153   // becuase the immediate function pointer points to a descriptor instead of
5154   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5155   // pointer immediate points to the global entry point, while the BLA would
5156   // need to jump to the local entry point (see rL211174).
5157   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5158       isBLACompatibleAddress(Callee, DAG))
5159     return false;
5160 
5161   return true;
5162 }
5163 
5164 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5165 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5166   return Subtarget.isAIXABI() ||
5167          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5168 }
5169 
5170 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5171                               const Function &Caller,
5172                               const SDValue &Callee,
5173                               const PPCSubtarget &Subtarget,
5174                               const TargetMachine &TM) {
5175   if (CFlags.IsTailCall)
5176     return PPCISD::TC_RETURN;
5177 
5178   // This is a call through a function pointer.
5179   if (CFlags.IsIndirect) {
5180     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5181     // indirect calls. The save of the caller's TOC pointer to the stack will be
5182     // inserted into the DAG as part of call lowering. The restore of the TOC
5183     // pointer is modeled by using a pseudo instruction for the call opcode that
5184     // represents the 2 instruction sequence of an indirect branch and link,
5185     // immediately followed by a load of the TOC pointer from the the stack save
5186     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5187     // as it is not saved or used.
5188     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5189                                                : PPCISD::BCTRL;
5190   }
5191 
5192   if (Subtarget.isUsingPCRelativeCalls()) {
5193     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5194     return PPCISD::CALL_NOTOC;
5195   }
5196 
5197   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5198   // immediately following the call instruction if the caller and callee may
5199   // have different TOC bases. At link time if the linker determines the calls
5200   // may not share a TOC base, the call is redirected to a trampoline inserted
5201   // by the linker. The trampoline will (among other things) save the callers
5202   // TOC pointer at an ABI designated offset in the linkage area and the linker
5203   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5204   // into gpr2.
5205   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5206     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5207                                                   : PPCISD::CALL_NOP;
5208 
5209   return PPCISD::CALL;
5210 }
5211 
5212 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5213                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5214   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5215     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5216       return SDValue(Dest, 0);
5217 
5218   // Returns true if the callee is local, and false otherwise.
5219   auto isLocalCallee = [&]() {
5220     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5221     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5222     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5223 
5224     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5225            !dyn_cast_or_null<GlobalIFunc>(GV);
5226   };
5227 
5228   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5229   // a static relocation model causes some versions of GNU LD (2.17.50, at
5230   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5231   // built with secure-PLT.
5232   bool UsePlt =
5233       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5234       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5235 
5236   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5237     const TargetMachine &TM = Subtarget.getTargetMachine();
5238     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5239     MCSymbolXCOFF *S =
5240         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5241 
5242     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5243     return DAG.getMCSymbol(S, PtrVT);
5244   };
5245 
5246   if (isFunctionGlobalAddress(Callee)) {
5247     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5248 
5249     if (Subtarget.isAIXABI()) {
5250       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5251       return getAIXFuncEntryPointSymbolSDNode(GV);
5252     }
5253     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5254                                       UsePlt ? PPCII::MO_PLT : 0);
5255   }
5256 
5257   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5258     const char *SymName = S->getSymbol();
5259     if (Subtarget.isAIXABI()) {
5260       // If there exists a user-declared function whose name is the same as the
5261       // ExternalSymbol's, then we pick up the user-declared version.
5262       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5263       if (const Function *F =
5264               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5265         return getAIXFuncEntryPointSymbolSDNode(F);
5266 
5267       // On AIX, direct function calls reference the symbol for the function's
5268       // entry point, which is named by prepending a "." before the function's
5269       // C-linkage name. A Qualname is returned here because an external
5270       // function entry point is a csect with XTY_ER property.
5271       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5272         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5273         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5274             (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5275             XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER));
5276         return Sec->getQualNameSymbol();
5277       };
5278 
5279       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5280     }
5281     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5282                                        UsePlt ? PPCII::MO_PLT : 0);
5283   }
5284 
5285   // No transformation needed.
5286   assert(Callee.getNode() && "What no callee?");
5287   return Callee;
5288 }
5289 
5290 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5291   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5292          "Expected a CALLSEQ_STARTSDNode.");
5293 
5294   // The last operand is the chain, except when the node has glue. If the node
5295   // has glue, then the last operand is the glue, and the chain is the second
5296   // last operand.
5297   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5298   if (LastValue.getValueType() != MVT::Glue)
5299     return LastValue;
5300 
5301   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5302 }
5303 
5304 // Creates the node that moves a functions address into the count register
5305 // to prepare for an indirect call instruction.
5306 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5307                                 SDValue &Glue, SDValue &Chain,
5308                                 const SDLoc &dl) {
5309   SDValue MTCTROps[] = {Chain, Callee, Glue};
5310   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5311   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5312                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5313   // The glue is the second value produced.
5314   Glue = Chain.getValue(1);
5315 }
5316 
5317 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5318                                           SDValue &Glue, SDValue &Chain,
5319                                           SDValue CallSeqStart,
5320                                           const CallBase *CB, const SDLoc &dl,
5321                                           bool hasNest,
5322                                           const PPCSubtarget &Subtarget) {
5323   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5324   // entry point, but to the function descriptor (the function entry point
5325   // address is part of the function descriptor though).
5326   // The function descriptor is a three doubleword structure with the
5327   // following fields: function entry point, TOC base address and
5328   // environment pointer.
5329   // Thus for a call through a function pointer, the following actions need
5330   // to be performed:
5331   //   1. Save the TOC of the caller in the TOC save area of its stack
5332   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5333   //   2. Load the address of the function entry point from the function
5334   //      descriptor.
5335   //   3. Load the TOC of the callee from the function descriptor into r2.
5336   //   4. Load the environment pointer from the function descriptor into
5337   //      r11.
5338   //   5. Branch to the function entry point address.
5339   //   6. On return of the callee, the TOC of the caller needs to be
5340   //      restored (this is done in FinishCall()).
5341   //
5342   // The loads are scheduled at the beginning of the call sequence, and the
5343   // register copies are flagged together to ensure that no other
5344   // operations can be scheduled in between. E.g. without flagging the
5345   // copies together, a TOC access in the caller could be scheduled between
5346   // the assignment of the callee TOC and the branch to the callee, which leads
5347   // to incorrect code.
5348 
5349   // Start by loading the function address from the descriptor.
5350   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5351   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5352                       ? (MachineMemOperand::MODereferenceable |
5353                          MachineMemOperand::MOInvariant)
5354                       : MachineMemOperand::MONone;
5355 
5356   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5357 
5358   // Registers used in building the DAG.
5359   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5360   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5361 
5362   // Offsets of descriptor members.
5363   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5364   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5365 
5366   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5367   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5368 
5369   // One load for the functions entry point address.
5370   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5371                                     Alignment, MMOFlags);
5372 
5373   // One for loading the TOC anchor for the module that contains the called
5374   // function.
5375   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5376   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5377   SDValue TOCPtr =
5378       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5379                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5380 
5381   // One for loading the environment pointer.
5382   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5383   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5384   SDValue LoadEnvPtr =
5385       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5386                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5387 
5388 
5389   // Then copy the newly loaded TOC anchor to the TOC pointer.
5390   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5391   Chain = TOCVal.getValue(0);
5392   Glue = TOCVal.getValue(1);
5393 
5394   // If the function call has an explicit 'nest' parameter, it takes the
5395   // place of the environment pointer.
5396   assert((!hasNest || !Subtarget.isAIXABI()) &&
5397          "Nest parameter is not supported on AIX.");
5398   if (!hasNest) {
5399     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5400     Chain = EnvVal.getValue(0);
5401     Glue = EnvVal.getValue(1);
5402   }
5403 
5404   // The rest of the indirect call sequence is the same as the non-descriptor
5405   // DAG.
5406   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5407 }
5408 
5409 static void
5410 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5411                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5412                   SelectionDAG &DAG,
5413                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5414                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5415                   const PPCSubtarget &Subtarget) {
5416   const bool IsPPC64 = Subtarget.isPPC64();
5417   // MVT for a general purpose register.
5418   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5419 
5420   // First operand is always the chain.
5421   Ops.push_back(Chain);
5422 
5423   // If it's a direct call pass the callee as the second operand.
5424   if (!CFlags.IsIndirect)
5425     Ops.push_back(Callee);
5426   else {
5427     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5428 
5429     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5430     // on the stack (this would have been done in `LowerCall_64SVR4` or
5431     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5432     // represents both the indirect branch and a load that restores the TOC
5433     // pointer from the linkage area. The operand for the TOC restore is an add
5434     // of the TOC save offset to the stack pointer. This must be the second
5435     // operand: after the chain input but before any other variadic arguments.
5436     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5437     // saved or used.
5438     if (isTOCSaveRestoreRequired(Subtarget)) {
5439       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5440 
5441       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5442       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5443       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5444       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5445       Ops.push_back(AddTOC);
5446     }
5447 
5448     // Add the register used for the environment pointer.
5449     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5450       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5451                                     RegVT));
5452 
5453 
5454     // Add CTR register as callee so a bctr can be emitted later.
5455     if (CFlags.IsTailCall)
5456       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5457   }
5458 
5459   // If this is a tail call add stack pointer delta.
5460   if (CFlags.IsTailCall)
5461     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5462 
5463   // Add argument registers to the end of the list so that they are known live
5464   // into the call.
5465   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5466     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5467                                   RegsToPass[i].second.getValueType()));
5468 
5469   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5470   // no way to mark dependencies as implicit here.
5471   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5472   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5473        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5474     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5475 
5476   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5477   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5478     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5479 
5480   // Add a register mask operand representing the call-preserved registers.
5481   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5482   const uint32_t *Mask =
5483       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5484   assert(Mask && "Missing call preserved mask for calling convention");
5485   Ops.push_back(DAG.getRegisterMask(Mask));
5486 
5487   // If the glue is valid, it is the last operand.
5488   if (Glue.getNode())
5489     Ops.push_back(Glue);
5490 }
5491 
5492 SDValue PPCTargetLowering::FinishCall(
5493     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5494     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5495     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5496     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5497     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5498 
5499   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5500       Subtarget.isAIXABI())
5501     setUsesTOCBasePtr(DAG);
5502 
5503   unsigned CallOpc =
5504       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5505                     Subtarget, DAG.getTarget());
5506 
5507   if (!CFlags.IsIndirect)
5508     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5509   else if (Subtarget.usesFunctionDescriptors())
5510     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5511                                   dl, CFlags.HasNest, Subtarget);
5512   else
5513     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5514 
5515   // Build the operand list for the call instruction.
5516   SmallVector<SDValue, 8> Ops;
5517   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5518                     SPDiff, Subtarget);
5519 
5520   // Emit tail call.
5521   if (CFlags.IsTailCall) {
5522     // Indirect tail call when using PC Relative calls do not have the same
5523     // constraints.
5524     assert(((Callee.getOpcode() == ISD::Register &&
5525              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5526             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5527             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5528             isa<ConstantSDNode>(Callee) ||
5529             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5530            "Expecting a global address, external symbol, absolute value, "
5531            "register or an indirect tail call when PC Relative calls are "
5532            "used.");
5533     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5534     assert(CallOpc == PPCISD::TC_RETURN &&
5535            "Unexpected call opcode for a tail call.");
5536     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5537     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5538   }
5539 
5540   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5541   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5542   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5543   Glue = Chain.getValue(1);
5544 
5545   // When performing tail call optimization the callee pops its arguments off
5546   // the stack. Account for this here so these bytes can be pushed back on in
5547   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5548   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5549                          getTargetMachine().Options.GuaranteedTailCallOpt)
5550                             ? NumBytes
5551                             : 0;
5552 
5553   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5554                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5555                              Glue, dl);
5556   Glue = Chain.getValue(1);
5557 
5558   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5559                          DAG, InVals);
5560 }
5561 
5562 SDValue
5563 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5564                              SmallVectorImpl<SDValue> &InVals) const {
5565   SelectionDAG &DAG                     = CLI.DAG;
5566   SDLoc &dl                             = CLI.DL;
5567   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5568   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5569   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5570   SDValue Chain                         = CLI.Chain;
5571   SDValue Callee                        = CLI.Callee;
5572   bool &isTailCall                      = CLI.IsTailCall;
5573   CallingConv::ID CallConv              = CLI.CallConv;
5574   bool isVarArg                         = CLI.IsVarArg;
5575   bool isPatchPoint                     = CLI.IsPatchPoint;
5576   const CallBase *CB                    = CLI.CB;
5577 
5578   if (isTailCall) {
5579     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5580       isTailCall = false;
5581     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5582       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5583           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5584     else
5585       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5586                                                      Ins, DAG);
5587     if (isTailCall) {
5588       ++NumTailCalls;
5589       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5590         ++NumSiblingCalls;
5591 
5592       // PC Relative calls no longer guarantee that the callee is a Global
5593       // Address Node. The callee could be an indirect tail call in which
5594       // case the SDValue for the callee could be a load (to load the address
5595       // of a function pointer) or it may be a register copy (to move the
5596       // address of the callee from a function parameter into a virtual
5597       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5598       assert((Subtarget.isUsingPCRelativeCalls() ||
5599               isa<GlobalAddressSDNode>(Callee)) &&
5600              "Callee should be an llvm::Function object.");
5601 
5602       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5603                         << "\nTCO callee: ");
5604       LLVM_DEBUG(Callee.dump());
5605     }
5606   }
5607 
5608   if (!isTailCall && CB && CB->isMustTailCall())
5609     report_fatal_error("failed to perform tail call elimination on a call "
5610                        "site marked musttail");
5611 
5612   // When long calls (i.e. indirect calls) are always used, calls are always
5613   // made via function pointer. If we have a function name, first translate it
5614   // into a pointer.
5615   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5616       !isTailCall)
5617     Callee = LowerGlobalAddress(Callee, DAG);
5618 
5619   CallFlags CFlags(
5620       CallConv, isTailCall, isVarArg, isPatchPoint,
5621       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5622       // hasNest
5623       Subtarget.is64BitELFABI() &&
5624           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5625       CLI.NoMerge);
5626 
5627   if (Subtarget.isAIXABI())
5628     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5629                          InVals, CB);
5630 
5631   assert(Subtarget.isSVR4ABI());
5632   if (Subtarget.isPPC64())
5633     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5634                             InVals, CB);
5635   return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5636                           InVals, CB);
5637 }
5638 
5639 SDValue PPCTargetLowering::LowerCall_32SVR4(
5640     SDValue Chain, SDValue Callee, CallFlags CFlags,
5641     const SmallVectorImpl<ISD::OutputArg> &Outs,
5642     const SmallVectorImpl<SDValue> &OutVals,
5643     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5644     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5645     const CallBase *CB) const {
5646   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5647   // of the 32-bit SVR4 ABI stack frame layout.
5648 
5649   const CallingConv::ID CallConv = CFlags.CallConv;
5650   const bool IsVarArg = CFlags.IsVarArg;
5651   const bool IsTailCall = CFlags.IsTailCall;
5652 
5653   assert((CallConv == CallingConv::C ||
5654           CallConv == CallingConv::Cold ||
5655           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5656 
5657   const Align PtrAlign(4);
5658 
5659   MachineFunction &MF = DAG.getMachineFunction();
5660 
5661   // Mark this function as potentially containing a function that contains a
5662   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5663   // and restoring the callers stack pointer in this functions epilog. This is
5664   // done because by tail calling the called function might overwrite the value
5665   // in this function's (MF) stack pointer stack slot 0(SP).
5666   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5667       CallConv == CallingConv::Fast)
5668     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5669 
5670   // Count how many bytes are to be pushed on the stack, including the linkage
5671   // area, parameter list area and the part of the local variable space which
5672   // contains copies of aggregates which are passed by value.
5673 
5674   // Assign locations to all of the outgoing arguments.
5675   SmallVector<CCValAssign, 16> ArgLocs;
5676   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5677 
5678   // Reserve space for the linkage area on the stack.
5679   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5680                        PtrAlign);
5681   if (useSoftFloat())
5682     CCInfo.PreAnalyzeCallOperands(Outs);
5683 
5684   if (IsVarArg) {
5685     // Handle fixed and variable vector arguments differently.
5686     // Fixed vector arguments go into registers as long as registers are
5687     // available. Variable vector arguments always go into memory.
5688     unsigned NumArgs = Outs.size();
5689 
5690     for (unsigned i = 0; i != NumArgs; ++i) {
5691       MVT ArgVT = Outs[i].VT;
5692       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5693       bool Result;
5694 
5695       if (Outs[i].IsFixed) {
5696         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5697                                CCInfo);
5698       } else {
5699         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5700                                       ArgFlags, CCInfo);
5701       }
5702 
5703       if (Result) {
5704 #ifndef NDEBUG
5705         errs() << "Call operand #" << i << " has unhandled type "
5706              << EVT(ArgVT).getEVTString() << "\n";
5707 #endif
5708         llvm_unreachable(nullptr);
5709       }
5710     }
5711   } else {
5712     // All arguments are treated the same.
5713     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5714   }
5715   CCInfo.clearWasPPCF128();
5716 
5717   // Assign locations to all of the outgoing aggregate by value arguments.
5718   SmallVector<CCValAssign, 16> ByValArgLocs;
5719   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5720 
5721   // Reserve stack space for the allocations in CCInfo.
5722   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5723 
5724   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5725 
5726   // Size of the linkage area, parameter list area and the part of the local
5727   // space variable where copies of aggregates which are passed by value are
5728   // stored.
5729   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5730 
5731   // Calculate by how many bytes the stack has to be adjusted in case of tail
5732   // call optimization.
5733   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5734 
5735   // Adjust the stack pointer for the new arguments...
5736   // These operations are automatically eliminated by the prolog/epilog pass
5737   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5738   SDValue CallSeqStart = Chain;
5739 
5740   // Load the return address and frame pointer so it can be moved somewhere else
5741   // later.
5742   SDValue LROp, FPOp;
5743   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5744 
5745   // Set up a copy of the stack pointer for use loading and storing any
5746   // arguments that may not fit in the registers available for argument
5747   // passing.
5748   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5749 
5750   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5751   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5752   SmallVector<SDValue, 8> MemOpChains;
5753 
5754   bool seenFloatArg = false;
5755   // Walk the register/memloc assignments, inserting copies/loads.
5756   // i - Tracks the index into the list of registers allocated for the call
5757   // RealArgIdx - Tracks the index into the list of actual function arguments
5758   // j - Tracks the index into the list of byval arguments
5759   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5760        i != e;
5761        ++i, ++RealArgIdx) {
5762     CCValAssign &VA = ArgLocs[i];
5763     SDValue Arg = OutVals[RealArgIdx];
5764     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5765 
5766     if (Flags.isByVal()) {
5767       // Argument is an aggregate which is passed by value, thus we need to
5768       // create a copy of it in the local variable space of the current stack
5769       // frame (which is the stack frame of the caller) and pass the address of
5770       // this copy to the callee.
5771       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5772       CCValAssign &ByValVA = ByValArgLocs[j++];
5773       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5774 
5775       // Memory reserved in the local variable space of the callers stack frame.
5776       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5777 
5778       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5779       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5780                            StackPtr, PtrOff);
5781 
5782       // Create a copy of the argument in the local area of the current
5783       // stack frame.
5784       SDValue MemcpyCall =
5785         CreateCopyOfByValArgument(Arg, PtrOff,
5786                                   CallSeqStart.getNode()->getOperand(0),
5787                                   Flags, DAG, dl);
5788 
5789       // This must go outside the CALLSEQ_START..END.
5790       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5791                                                      SDLoc(MemcpyCall));
5792       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5793                              NewCallSeqStart.getNode());
5794       Chain = CallSeqStart = NewCallSeqStart;
5795 
5796       // Pass the address of the aggregate copy on the stack either in a
5797       // physical register or in the parameter list area of the current stack
5798       // frame to the callee.
5799       Arg = PtrOff;
5800     }
5801 
5802     // When useCRBits() is true, there can be i1 arguments.
5803     // It is because getRegisterType(MVT::i1) => MVT::i1,
5804     // and for other integer types getRegisterType() => MVT::i32.
5805     // Extend i1 and ensure callee will get i32.
5806     if (Arg.getValueType() == MVT::i1)
5807       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5808                         dl, MVT::i32, Arg);
5809 
5810     if (VA.isRegLoc()) {
5811       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5812       // Put argument in a physical register.
5813       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5814         bool IsLE = Subtarget.isLittleEndian();
5815         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5816                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5817         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5818         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5819                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5820         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5821                              SVal.getValue(0)));
5822       } else
5823         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5824     } else {
5825       // Put argument in the parameter list area of the current stack frame.
5826       assert(VA.isMemLoc());
5827       unsigned LocMemOffset = VA.getLocMemOffset();
5828 
5829       if (!IsTailCall) {
5830         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5831         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5832                              StackPtr, PtrOff);
5833 
5834         MemOpChains.push_back(
5835             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5836       } else {
5837         // Calculate and remember argument location.
5838         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5839                                  TailCallArguments);
5840       }
5841     }
5842   }
5843 
5844   if (!MemOpChains.empty())
5845     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5846 
5847   // Build a sequence of copy-to-reg nodes chained together with token chain
5848   // and flag operands which copy the outgoing args into the appropriate regs.
5849   SDValue InFlag;
5850   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5851     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5852                              RegsToPass[i].second, InFlag);
5853     InFlag = Chain.getValue(1);
5854   }
5855 
5856   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5857   // registers.
5858   if (IsVarArg) {
5859     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5860     SDValue Ops[] = { Chain, InFlag };
5861 
5862     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5863                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5864 
5865     InFlag = Chain.getValue(1);
5866   }
5867 
5868   if (IsTailCall)
5869     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5870                     TailCallArguments);
5871 
5872   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5873                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5874 }
5875 
5876 // Copy an argument into memory, being careful to do this outside the
5877 // call sequence for the call to which the argument belongs.
5878 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5879     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5880     SelectionDAG &DAG, const SDLoc &dl) const {
5881   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5882                         CallSeqStart.getNode()->getOperand(0),
5883                         Flags, DAG, dl);
5884   // The MEMCPY must go outside the CALLSEQ_START..END.
5885   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5886   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5887                                                  SDLoc(MemcpyCall));
5888   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5889                          NewCallSeqStart.getNode());
5890   return NewCallSeqStart;
5891 }
5892 
5893 SDValue PPCTargetLowering::LowerCall_64SVR4(
5894     SDValue Chain, SDValue Callee, CallFlags CFlags,
5895     const SmallVectorImpl<ISD::OutputArg> &Outs,
5896     const SmallVectorImpl<SDValue> &OutVals,
5897     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5898     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5899     const CallBase *CB) const {
5900   bool isELFv2ABI = Subtarget.isELFv2ABI();
5901   bool isLittleEndian = Subtarget.isLittleEndian();
5902   unsigned NumOps = Outs.size();
5903   bool IsSibCall = false;
5904   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5905 
5906   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5907   unsigned PtrByteSize = 8;
5908 
5909   MachineFunction &MF = DAG.getMachineFunction();
5910 
5911   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5912     IsSibCall = true;
5913 
5914   // Mark this function as potentially containing a function that contains a
5915   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5916   // and restoring the callers stack pointer in this functions epilog. This is
5917   // done because by tail calling the called function might overwrite the value
5918   // in this function's (MF) stack pointer stack slot 0(SP).
5919   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5920     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5921 
5922   assert(!(IsFastCall && CFlags.IsVarArg) &&
5923          "fastcc not supported on varargs functions");
5924 
5925   // Count how many bytes are to be pushed on the stack, including the linkage
5926   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5927   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5928   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5929   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5930   unsigned NumBytes = LinkageSize;
5931   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5932 
5933   static const MCPhysReg GPR[] = {
5934     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5935     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5936   };
5937   static const MCPhysReg VR[] = {
5938     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5939     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5940   };
5941 
5942   const unsigned NumGPRs = array_lengthof(GPR);
5943   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5944   const unsigned NumVRs  = array_lengthof(VR);
5945 
5946   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5947   // can be passed to the callee in registers.
5948   // For the fast calling convention, there is another check below.
5949   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5950   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5951   if (!HasParameterArea) {
5952     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5953     unsigned AvailableFPRs = NumFPRs;
5954     unsigned AvailableVRs = NumVRs;
5955     unsigned NumBytesTmp = NumBytes;
5956     for (unsigned i = 0; i != NumOps; ++i) {
5957       if (Outs[i].Flags.isNest()) continue;
5958       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5959                                  PtrByteSize, LinkageSize, ParamAreaSize,
5960                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
5961         HasParameterArea = true;
5962     }
5963   }
5964 
5965   // When using the fast calling convention, we don't provide backing for
5966   // arguments that will be in registers.
5967   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5968 
5969   // Avoid allocating parameter area for fastcc functions if all the arguments
5970   // can be passed in the registers.
5971   if (IsFastCall)
5972     HasParameterArea = false;
5973 
5974   // Add up all the space actually used.
5975   for (unsigned i = 0; i != NumOps; ++i) {
5976     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5977     EVT ArgVT = Outs[i].VT;
5978     EVT OrigVT = Outs[i].ArgVT;
5979 
5980     if (Flags.isNest())
5981       continue;
5982 
5983     if (IsFastCall) {
5984       if (Flags.isByVal()) {
5985         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5986         if (NumGPRsUsed > NumGPRs)
5987           HasParameterArea = true;
5988       } else {
5989         switch (ArgVT.getSimpleVT().SimpleTy) {
5990         default: llvm_unreachable("Unexpected ValueType for argument!");
5991         case MVT::i1:
5992         case MVT::i32:
5993         case MVT::i64:
5994           if (++NumGPRsUsed <= NumGPRs)
5995             continue;
5996           break;
5997         case MVT::v4i32:
5998         case MVT::v8i16:
5999         case MVT::v16i8:
6000         case MVT::v2f64:
6001         case MVT::v2i64:
6002         case MVT::v1i128:
6003         case MVT::f128:
6004           if (++NumVRsUsed <= NumVRs)
6005             continue;
6006           break;
6007         case MVT::v4f32:
6008           if (++NumVRsUsed <= NumVRs)
6009             continue;
6010           break;
6011         case MVT::f32:
6012         case MVT::f64:
6013           if (++NumFPRsUsed <= NumFPRs)
6014             continue;
6015           break;
6016         }
6017         HasParameterArea = true;
6018       }
6019     }
6020 
6021     /* Respect alignment of argument on the stack.  */
6022     auto Alignement =
6023         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6024     NumBytes = alignTo(NumBytes, Alignement);
6025 
6026     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6027     if (Flags.isInConsecutiveRegsLast())
6028       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6029   }
6030 
6031   unsigned NumBytesActuallyUsed = NumBytes;
6032 
6033   // In the old ELFv1 ABI,
6034   // the prolog code of the callee may store up to 8 GPR argument registers to
6035   // the stack, allowing va_start to index over them in memory if its varargs.
6036   // Because we cannot tell if this is needed on the caller side, we have to
6037   // conservatively assume that it is needed.  As such, make sure we have at
6038   // least enough stack space for the caller to store the 8 GPRs.
6039   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6040   // really requires memory operands, e.g. a vararg function.
6041   if (HasParameterArea)
6042     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6043   else
6044     NumBytes = LinkageSize;
6045 
6046   // Tail call needs the stack to be aligned.
6047   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6048     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6049 
6050   int SPDiff = 0;
6051 
6052   // Calculate by how many bytes the stack has to be adjusted in case of tail
6053   // call optimization.
6054   if (!IsSibCall)
6055     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6056 
6057   // To protect arguments on the stack from being clobbered in a tail call,
6058   // force all the loads to happen before doing any other lowering.
6059   if (CFlags.IsTailCall)
6060     Chain = DAG.getStackArgumentTokenFactor(Chain);
6061 
6062   // Adjust the stack pointer for the new arguments...
6063   // These operations are automatically eliminated by the prolog/epilog pass
6064   if (!IsSibCall)
6065     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6066   SDValue CallSeqStart = Chain;
6067 
6068   // Load the return address and frame pointer so it can be move somewhere else
6069   // later.
6070   SDValue LROp, FPOp;
6071   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6072 
6073   // Set up a copy of the stack pointer for use loading and storing any
6074   // arguments that may not fit in the registers available for argument
6075   // passing.
6076   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6077 
6078   // Figure out which arguments are going to go in registers, and which in
6079   // memory.  Also, if this is a vararg function, floating point operations
6080   // must be stored to our stack, and loaded into integer regs as well, if
6081   // any integer regs are available for argument passing.
6082   unsigned ArgOffset = LinkageSize;
6083 
6084   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6085   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6086 
6087   SmallVector<SDValue, 8> MemOpChains;
6088   for (unsigned i = 0; i != NumOps; ++i) {
6089     SDValue Arg = OutVals[i];
6090     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6091     EVT ArgVT = Outs[i].VT;
6092     EVT OrigVT = Outs[i].ArgVT;
6093 
6094     // PtrOff will be used to store the current argument to the stack if a
6095     // register cannot be found for it.
6096     SDValue PtrOff;
6097 
6098     // We re-align the argument offset for each argument, except when using the
6099     // fast calling convention, when we need to make sure we do that only when
6100     // we'll actually use a stack slot.
6101     auto ComputePtrOff = [&]() {
6102       /* Respect alignment of argument on the stack.  */
6103       auto Alignment =
6104           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6105       ArgOffset = alignTo(ArgOffset, Alignment);
6106 
6107       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6108 
6109       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6110     };
6111 
6112     if (!IsFastCall) {
6113       ComputePtrOff();
6114 
6115       /* Compute GPR index associated with argument offset.  */
6116       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6117       GPR_idx = std::min(GPR_idx, NumGPRs);
6118     }
6119 
6120     // Promote integers to 64-bit values.
6121     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6122       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6123       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6124       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6125     }
6126 
6127     // FIXME memcpy is used way more than necessary.  Correctness first.
6128     // Note: "by value" is code for passing a structure by value, not
6129     // basic types.
6130     if (Flags.isByVal()) {
6131       // Note: Size includes alignment padding, so
6132       //   struct x { short a; char b; }
6133       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6134       // These are the proper values we need for right-justifying the
6135       // aggregate in a parameter register.
6136       unsigned Size = Flags.getByValSize();
6137 
6138       // An empty aggregate parameter takes up no storage and no
6139       // registers.
6140       if (Size == 0)
6141         continue;
6142 
6143       if (IsFastCall)
6144         ComputePtrOff();
6145 
6146       // All aggregates smaller than 8 bytes must be passed right-justified.
6147       if (Size==1 || Size==2 || Size==4) {
6148         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6149         if (GPR_idx != NumGPRs) {
6150           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6151                                         MachinePointerInfo(), VT);
6152           MemOpChains.push_back(Load.getValue(1));
6153           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6154 
6155           ArgOffset += PtrByteSize;
6156           continue;
6157         }
6158       }
6159 
6160       if (GPR_idx == NumGPRs && Size < 8) {
6161         SDValue AddPtr = PtrOff;
6162         if (!isLittleEndian) {
6163           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6164                                           PtrOff.getValueType());
6165           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6166         }
6167         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6168                                                           CallSeqStart,
6169                                                           Flags, DAG, dl);
6170         ArgOffset += PtrByteSize;
6171         continue;
6172       }
6173       // Copy entire object into memory.  There are cases where gcc-generated
6174       // code assumes it is there, even if it could be put entirely into
6175       // registers.  (This is not what the doc says.)
6176 
6177       // FIXME: The above statement is likely due to a misunderstanding of the
6178       // documents.  All arguments must be copied into the parameter area BY
6179       // THE CALLEE in the event that the callee takes the address of any
6180       // formal argument.  That has not yet been implemented.  However, it is
6181       // reasonable to use the stack area as a staging area for the register
6182       // load.
6183 
6184       // Skip this for small aggregates, as we will use the same slot for a
6185       // right-justified copy, below.
6186       if (Size >= 8)
6187         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6188                                                           CallSeqStart,
6189                                                           Flags, DAG, dl);
6190 
6191       // When a register is available, pass a small aggregate right-justified.
6192       if (Size < 8 && GPR_idx != NumGPRs) {
6193         // The easiest way to get this right-justified in a register
6194         // is to copy the structure into the rightmost portion of a
6195         // local variable slot, then load the whole slot into the
6196         // register.
6197         // FIXME: The memcpy seems to produce pretty awful code for
6198         // small aggregates, particularly for packed ones.
6199         // FIXME: It would be preferable to use the slot in the
6200         // parameter save area instead of a new local variable.
6201         SDValue AddPtr = PtrOff;
6202         if (!isLittleEndian) {
6203           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6204           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6205         }
6206         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6207                                                           CallSeqStart,
6208                                                           Flags, DAG, dl);
6209 
6210         // Load the slot into the register.
6211         SDValue Load =
6212             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6213         MemOpChains.push_back(Load.getValue(1));
6214         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6215 
6216         // Done with this argument.
6217         ArgOffset += PtrByteSize;
6218         continue;
6219       }
6220 
6221       // For aggregates larger than PtrByteSize, copy the pieces of the
6222       // object that fit into registers from the parameter save area.
6223       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6224         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6225         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6226         if (GPR_idx != NumGPRs) {
6227           SDValue Load =
6228               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6229           MemOpChains.push_back(Load.getValue(1));
6230           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6231           ArgOffset += PtrByteSize;
6232         } else {
6233           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6234           break;
6235         }
6236       }
6237       continue;
6238     }
6239 
6240     switch (Arg.getSimpleValueType().SimpleTy) {
6241     default: llvm_unreachable("Unexpected ValueType for argument!");
6242     case MVT::i1:
6243     case MVT::i32:
6244     case MVT::i64:
6245       if (Flags.isNest()) {
6246         // The 'nest' parameter, if any, is passed in R11.
6247         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6248         break;
6249       }
6250 
6251       // These can be scalar arguments or elements of an integer array type
6252       // passed directly.  Clang may use those instead of "byval" aggregate
6253       // types to avoid forcing arguments to memory unnecessarily.
6254       if (GPR_idx != NumGPRs) {
6255         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6256       } else {
6257         if (IsFastCall)
6258           ComputePtrOff();
6259 
6260         assert(HasParameterArea &&
6261                "Parameter area must exist to pass an argument in memory.");
6262         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6263                          true, CFlags.IsTailCall, false, MemOpChains,
6264                          TailCallArguments, dl);
6265         if (IsFastCall)
6266           ArgOffset += PtrByteSize;
6267       }
6268       if (!IsFastCall)
6269         ArgOffset += PtrByteSize;
6270       break;
6271     case MVT::f32:
6272     case MVT::f64: {
6273       // These can be scalar arguments or elements of a float array type
6274       // passed directly.  The latter are used to implement ELFv2 homogenous
6275       // float aggregates.
6276 
6277       // Named arguments go into FPRs first, and once they overflow, the
6278       // remaining arguments go into GPRs and then the parameter save area.
6279       // Unnamed arguments for vararg functions always go to GPRs and
6280       // then the parameter save area.  For now, put all arguments to vararg
6281       // routines always in both locations (FPR *and* GPR or stack slot).
6282       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6283       bool NeededLoad = false;
6284 
6285       // First load the argument into the next available FPR.
6286       if (FPR_idx != NumFPRs)
6287         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6288 
6289       // Next, load the argument into GPR or stack slot if needed.
6290       if (!NeedGPROrStack)
6291         ;
6292       else if (GPR_idx != NumGPRs && !IsFastCall) {
6293         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6294         // once we support fp <-> gpr moves.
6295 
6296         // In the non-vararg case, this can only ever happen in the
6297         // presence of f32 array types, since otherwise we never run
6298         // out of FPRs before running out of GPRs.
6299         SDValue ArgVal;
6300 
6301         // Double values are always passed in a single GPR.
6302         if (Arg.getValueType() != MVT::f32) {
6303           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6304 
6305         // Non-array float values are extended and passed in a GPR.
6306         } else if (!Flags.isInConsecutiveRegs()) {
6307           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6308           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6309 
6310         // If we have an array of floats, we collect every odd element
6311         // together with its predecessor into one GPR.
6312         } else if (ArgOffset % PtrByteSize != 0) {
6313           SDValue Lo, Hi;
6314           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6315           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6316           if (!isLittleEndian)
6317             std::swap(Lo, Hi);
6318           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6319 
6320         // The final element, if even, goes into the first half of a GPR.
6321         } else if (Flags.isInConsecutiveRegsLast()) {
6322           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6323           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6324           if (!isLittleEndian)
6325             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6326                                  DAG.getConstant(32, dl, MVT::i32));
6327 
6328         // Non-final even elements are skipped; they will be handled
6329         // together the with subsequent argument on the next go-around.
6330         } else
6331           ArgVal = SDValue();
6332 
6333         if (ArgVal.getNode())
6334           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6335       } else {
6336         if (IsFastCall)
6337           ComputePtrOff();
6338 
6339         // Single-precision floating-point values are mapped to the
6340         // second (rightmost) word of the stack doubleword.
6341         if (Arg.getValueType() == MVT::f32 &&
6342             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6343           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6344           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6345         }
6346 
6347         assert(HasParameterArea &&
6348                "Parameter area must exist to pass an argument in memory.");
6349         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6350                          true, CFlags.IsTailCall, false, MemOpChains,
6351                          TailCallArguments, dl);
6352 
6353         NeededLoad = true;
6354       }
6355       // When passing an array of floats, the array occupies consecutive
6356       // space in the argument area; only round up to the next doubleword
6357       // at the end of the array.  Otherwise, each float takes 8 bytes.
6358       if (!IsFastCall || NeededLoad) {
6359         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6360                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6361         if (Flags.isInConsecutiveRegsLast())
6362           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6363       }
6364       break;
6365     }
6366     case MVT::v4f32:
6367     case MVT::v4i32:
6368     case MVT::v8i16:
6369     case MVT::v16i8:
6370     case MVT::v2f64:
6371     case MVT::v2i64:
6372     case MVT::v1i128:
6373     case MVT::f128:
6374       // These can be scalar arguments or elements of a vector array type
6375       // passed directly.  The latter are used to implement ELFv2 homogenous
6376       // vector aggregates.
6377 
6378       // For a varargs call, named arguments go into VRs or on the stack as
6379       // usual; unnamed arguments always go to the stack or the corresponding
6380       // GPRs when within range.  For now, we always put the value in both
6381       // locations (or even all three).
6382       if (CFlags.IsVarArg) {
6383         assert(HasParameterArea &&
6384                "Parameter area must exist if we have a varargs call.");
6385         // We could elide this store in the case where the object fits
6386         // entirely in R registers.  Maybe later.
6387         SDValue Store =
6388             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6389         MemOpChains.push_back(Store);
6390         if (VR_idx != NumVRs) {
6391           SDValue Load =
6392               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6393           MemOpChains.push_back(Load.getValue(1));
6394           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6395         }
6396         ArgOffset += 16;
6397         for (unsigned i=0; i<16; i+=PtrByteSize) {
6398           if (GPR_idx == NumGPRs)
6399             break;
6400           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6401                                    DAG.getConstant(i, dl, PtrVT));
6402           SDValue Load =
6403               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6404           MemOpChains.push_back(Load.getValue(1));
6405           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6406         }
6407         break;
6408       }
6409 
6410       // Non-varargs Altivec params go into VRs or on the stack.
6411       if (VR_idx != NumVRs) {
6412         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6413       } else {
6414         if (IsFastCall)
6415           ComputePtrOff();
6416 
6417         assert(HasParameterArea &&
6418                "Parameter area must exist to pass an argument in memory.");
6419         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6420                          true, CFlags.IsTailCall, true, MemOpChains,
6421                          TailCallArguments, dl);
6422         if (IsFastCall)
6423           ArgOffset += 16;
6424       }
6425 
6426       if (!IsFastCall)
6427         ArgOffset += 16;
6428       break;
6429     }
6430   }
6431 
6432   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6433          "mismatch in size of parameter area");
6434   (void)NumBytesActuallyUsed;
6435 
6436   if (!MemOpChains.empty())
6437     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6438 
6439   // Check if this is an indirect call (MTCTR/BCTRL).
6440   // See prepareDescriptorIndirectCall and buildCallOperands for more
6441   // information about calls through function pointers in the 64-bit SVR4 ABI.
6442   if (CFlags.IsIndirect) {
6443     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6444     // caller in the TOC save area.
6445     if (isTOCSaveRestoreRequired(Subtarget)) {
6446       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6447       // Load r2 into a virtual register and store it to the TOC save area.
6448       setUsesTOCBasePtr(DAG);
6449       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6450       // TOC save area offset.
6451       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6452       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6453       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6454       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6455                            MachinePointerInfo::getStack(
6456                                DAG.getMachineFunction(), TOCSaveOffset));
6457     }
6458     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6459     // This does not mean the MTCTR instruction must use R12; it's easier
6460     // to model this as an extra parameter, so do that.
6461     if (isELFv2ABI && !CFlags.IsPatchPoint)
6462       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6463   }
6464 
6465   // Build a sequence of copy-to-reg nodes chained together with token chain
6466   // and flag operands which copy the outgoing args into the appropriate regs.
6467   SDValue InFlag;
6468   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6469     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6470                              RegsToPass[i].second, InFlag);
6471     InFlag = Chain.getValue(1);
6472   }
6473 
6474   if (CFlags.IsTailCall && !IsSibCall)
6475     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6476                     TailCallArguments);
6477 
6478   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6479                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6480 }
6481 
6482 // Returns true when the shadow of a general purpose argument register
6483 // in the parameter save area is aligned to at least 'RequiredAlign'.
6484 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
6485   assert(RequiredAlign.value() <= 16 &&
6486          "Required alignment greater than stack alignment.");
6487   switch (Reg) {
6488   default:
6489     report_fatal_error("called on invalid register.");
6490   case PPC::R5:
6491   case PPC::R9:
6492   case PPC::X3:
6493   case PPC::X5:
6494   case PPC::X7:
6495   case PPC::X9:
6496     // These registers are 16 byte aligned which is the most strict aligment
6497     // we can support.
6498     return true;
6499   case PPC::R3:
6500   case PPC::R7:
6501   case PPC::X4:
6502   case PPC::X6:
6503   case PPC::X8:
6504   case PPC::X10:
6505     // The shadow of these registers in the PSA is 8 byte aligned.
6506     return RequiredAlign <= 8;
6507   case PPC::R4:
6508   case PPC::R6:
6509   case PPC::R8:
6510   case PPC::R10:
6511     return RequiredAlign <= 4;
6512   }
6513 }
6514 
6515 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6516                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6517                    CCState &S) {
6518   AIXCCState &State = static_cast<AIXCCState &>(S);
6519   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6520       State.getMachineFunction().getSubtarget());
6521   const bool IsPPC64 = Subtarget.isPPC64();
6522   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6523   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6524 
6525   if (ValVT == MVT::f128)
6526     report_fatal_error("f128 is unimplemented on AIX.");
6527 
6528   if (ArgFlags.isNest())
6529     report_fatal_error("Nest arguments are unimplemented.");
6530 
6531   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6532                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6533                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6534   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6535                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6536                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6537 
6538   static const MCPhysReg VR[] = {// Vector registers.
6539                                  PPC::V2,  PPC::V3,  PPC::V4,  PPC::V5,
6540                                  PPC::V6,  PPC::V7,  PPC::V8,  PPC::V9,
6541                                  PPC::V10, PPC::V11, PPC::V12, PPC::V13};
6542 
6543   if (ArgFlags.isByVal()) {
6544     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6545       report_fatal_error("Pass-by-value arguments with alignment greater than "
6546                          "register width are not supported.");
6547 
6548     const unsigned ByValSize = ArgFlags.getByValSize();
6549 
6550     // An empty aggregate parameter takes up no storage and no registers,
6551     // but needs a MemLoc for a stack slot for the formal arguments side.
6552     if (ByValSize == 0) {
6553       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6554                                        State.getNextStackOffset(), RegVT,
6555                                        LocInfo));
6556       return false;
6557     }
6558 
6559     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6560     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6561     for (const unsigned E = Offset + StackSize; Offset < E;
6562          Offset += PtrAlign.value()) {
6563       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6564         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6565       else {
6566         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6567                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6568                                          LocInfo));
6569         break;
6570       }
6571     }
6572     return false;
6573   }
6574 
6575   // Arguments always reserve parameter save area.
6576   switch (ValVT.SimpleTy) {
6577   default:
6578     report_fatal_error("Unhandled value type for argument.");
6579   case MVT::i64:
6580     // i64 arguments should have been split to i32 for PPC32.
6581     assert(IsPPC64 && "PPC32 should have split i64 values.");
6582     LLVM_FALLTHROUGH;
6583   case MVT::i1:
6584   case MVT::i32: {
6585     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6586     // AIX integer arguments are always passed in register width.
6587     if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6588       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6589                                   : CCValAssign::LocInfo::ZExt;
6590     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6591       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6592     else
6593       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6594 
6595     return false;
6596   }
6597   case MVT::f32:
6598   case MVT::f64: {
6599     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6600     const unsigned StoreSize = LocVT.getStoreSize();
6601     // Floats are always 4-byte aligned in the PSA on AIX.
6602     // This includes f64 in 64-bit mode for ABI compatibility.
6603     const unsigned Offset =
6604         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6605     unsigned FReg = State.AllocateReg(FPR);
6606     if (FReg)
6607       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6608 
6609     // Reserve and initialize GPRs or initialize the PSA as required.
6610     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6611       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6612         assert(FReg && "An FPR should be available when a GPR is reserved.");
6613         if (State.isVarArg()) {
6614           // Successfully reserved GPRs are only initialized for vararg calls.
6615           // Custom handling is required for:
6616           //   f64 in PPC32 needs to be split into 2 GPRs.
6617           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6618           State.addLoc(
6619               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6620         }
6621       } else {
6622         // If there are insufficient GPRs, the PSA needs to be initialized.
6623         // Initialization occurs even if an FPR was initialized for
6624         // compatibility with the AIX XL compiler. The full memory for the
6625         // argument will be initialized even if a prior word is saved in GPR.
6626         // A custom memLoc is used when the argument also passes in FPR so
6627         // that the callee handling can skip over it easily.
6628         State.addLoc(
6629             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6630                                              LocInfo)
6631                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6632         break;
6633       }
6634     }
6635 
6636     return false;
6637   }
6638   case MVT::v4f32:
6639   case MVT::v4i32:
6640   case MVT::v8i16:
6641   case MVT::v16i8:
6642   case MVT::v2i64:
6643   case MVT::v2f64:
6644   case MVT::v1i128: {
6645     const unsigned VecSize = 16;
6646     const Align VecAlign(VecSize);
6647 
6648     if (!State.isVarArg()) {
6649       // If there are vector registers remaining we don't consume any stack
6650       // space.
6651       if (unsigned VReg = State.AllocateReg(VR)) {
6652         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6653         return false;
6654       }
6655       // Vectors passed on the stack do not shadow GPRs or FPRs even though they
6656       // might be allocated in the portion of the PSA that is shadowed by the
6657       // GPRs.
6658       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6659       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6660       return false;
6661     }
6662 
6663     const unsigned PtrSize = IsPPC64 ? 8 : 4;
6664     ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
6665 
6666     unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
6667     // Burn any underaligned registers and their shadowed stack space until
6668     // we reach the required alignment.
6669     while (NextRegIndex != GPRs.size() &&
6670            !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
6671       // Shadow allocate register and its stack shadow.
6672       unsigned Reg = State.AllocateReg(GPRs);
6673       State.AllocateStack(PtrSize, PtrAlign);
6674       assert(Reg && "Allocating register unexpectedly failed.");
6675       (void)Reg;
6676       NextRegIndex = State.getFirstUnallocated(GPRs);
6677     }
6678 
6679     // Vectors that are passed as fixed arguments are handled differently.
6680     // They are passed in VRs if any are available (unlike arguments passed
6681     // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
6682     // functions)
6683     if (State.isFixed(ValNo)) {
6684       if (unsigned VReg = State.AllocateReg(VR)) {
6685         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6686         // Shadow allocate GPRs and stack space even though we pass in a VR.
6687         for (unsigned I = 0; I != VecSize; I += PtrSize)
6688           State.AllocateReg(GPRs);
6689         State.AllocateStack(VecSize, VecAlign);
6690         return false;
6691       }
6692       // No vector registers remain so pass on the stack.
6693       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6694       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6695       return false;
6696     }
6697 
6698     // If all GPRS are consumed then we pass the argument fully on the stack.
6699     if (NextRegIndex == GPRs.size()) {
6700       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6701       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6702       return false;
6703     }
6704 
6705     // Corner case for 32-bit codegen. We have 2 registers to pass the first
6706     // half of the argument, and then need to pass the remaining half on the
6707     // stack.
6708     if (GPRs[NextRegIndex] == PPC::R9) {
6709       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6710       State.addLoc(
6711           CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6712 
6713       const unsigned FirstReg = State.AllocateReg(PPC::R9);
6714       const unsigned SecondReg = State.AllocateReg(PPC::R10);
6715       assert(FirstReg && SecondReg &&
6716              "Allocating R9 or R10 unexpectedly failed.");
6717       State.addLoc(
6718           CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
6719       State.addLoc(
6720           CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
6721       return false;
6722     }
6723 
6724     // We have enough GPRs to fully pass the vector argument, and we have
6725     // already consumed any underaligned registers. Start with the custom
6726     // MemLoc and then the custom RegLocs.
6727     const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6728     State.addLoc(
6729         CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6730     for (unsigned I = 0; I != VecSize; I += PtrSize) {
6731       const unsigned Reg = State.AllocateReg(GPRs);
6732       assert(Reg && "Failed to allocated register for vararg vector argument");
6733       State.addLoc(
6734           CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6735     }
6736     return false;
6737   }
6738   }
6739   return true;
6740 }
6741 
6742 // So far, this function is only used by LowerFormalArguments_AIX()
6743 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6744                                                     bool IsPPC64,
6745                                                     bool HasP8Vector,
6746                                                     bool HasVSX) {
6747   assert((IsPPC64 || SVT != MVT::i64) &&
6748          "i64 should have been split for 32-bit codegen.");
6749 
6750   switch (SVT) {
6751   default:
6752     report_fatal_error("Unexpected value type for formal argument");
6753   case MVT::i1:
6754   case MVT::i32:
6755   case MVT::i64:
6756     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6757   case MVT::f32:
6758     return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass;
6759   case MVT::f64:
6760     return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass;
6761   case MVT::v4f32:
6762   case MVT::v4i32:
6763   case MVT::v8i16:
6764   case MVT::v16i8:
6765   case MVT::v2i64:
6766   case MVT::v2f64:
6767   case MVT::v1i128:
6768     return &PPC::VRRCRegClass;
6769   }
6770 }
6771 
6772 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6773                                         SelectionDAG &DAG, SDValue ArgValue,
6774                                         MVT LocVT, const SDLoc &dl) {
6775   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6776   assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
6777 
6778   if (Flags.isSExt())
6779     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6780                            DAG.getValueType(ValVT));
6781   else if (Flags.isZExt())
6782     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6783                            DAG.getValueType(ValVT));
6784 
6785   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6786 }
6787 
6788 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6789   const unsigned LASize = FL->getLinkageSize();
6790 
6791   if (PPC::GPRCRegClass.contains(Reg)) {
6792     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6793            "Reg must be a valid argument register!");
6794     return LASize + 4 * (Reg - PPC::R3);
6795   }
6796 
6797   if (PPC::G8RCRegClass.contains(Reg)) {
6798     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6799            "Reg must be a valid argument register!");
6800     return LASize + 8 * (Reg - PPC::X3);
6801   }
6802 
6803   llvm_unreachable("Only general purpose registers expected.");
6804 }
6805 
6806 //   AIX ABI Stack Frame Layout:
6807 //
6808 //   Low Memory +--------------------------------------------+
6809 //   SP   +---> | Back chain                                 | ---+
6810 //        |     +--------------------------------------------+    |
6811 //        |     | Saved Condition Register                   |    |
6812 //        |     +--------------------------------------------+    |
6813 //        |     | Saved Linkage Register                     |    |
6814 //        |     +--------------------------------------------+    | Linkage Area
6815 //        |     | Reserved for compilers                     |    |
6816 //        |     +--------------------------------------------+    |
6817 //        |     | Reserved for binders                       |    |
6818 //        |     +--------------------------------------------+    |
6819 //        |     | Saved TOC pointer                          | ---+
6820 //        |     +--------------------------------------------+
6821 //        |     | Parameter save area                        |
6822 //        |     +--------------------------------------------+
6823 //        |     | Alloca space                               |
6824 //        |     +--------------------------------------------+
6825 //        |     | Local variable space                       |
6826 //        |     +--------------------------------------------+
6827 //        |     | Float/int conversion temporary             |
6828 //        |     +--------------------------------------------+
6829 //        |     | Save area for AltiVec registers            |
6830 //        |     +--------------------------------------------+
6831 //        |     | AltiVec alignment padding                  |
6832 //        |     +--------------------------------------------+
6833 //        |     | Save area for VRSAVE register              |
6834 //        |     +--------------------------------------------+
6835 //        |     | Save area for General Purpose registers    |
6836 //        |     +--------------------------------------------+
6837 //        |     | Save area for Floating Point registers     |
6838 //        |     +--------------------------------------------+
6839 //        +---- | Back chain                                 |
6840 // High Memory  +--------------------------------------------+
6841 //
6842 //  Specifications:
6843 //  AIX 7.2 Assembler Language Reference
6844 //  Subroutine linkage convention
6845 
6846 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6847     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6848     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6849     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6850 
6851   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6852           CallConv == CallingConv::Fast) &&
6853          "Unexpected calling convention!");
6854 
6855   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6856     report_fatal_error("Tail call support is unimplemented on AIX.");
6857 
6858   if (useSoftFloat())
6859     report_fatal_error("Soft float support is unimplemented on AIX.");
6860 
6861   const PPCSubtarget &Subtarget =
6862       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6863 
6864   const bool IsPPC64 = Subtarget.isPPC64();
6865   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6866 
6867   // Assign locations to all of the incoming arguments.
6868   SmallVector<CCValAssign, 16> ArgLocs;
6869   MachineFunction &MF = DAG.getMachineFunction();
6870   MachineFrameInfo &MFI = MF.getFrameInfo();
6871   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6872   AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6873 
6874   const EVT PtrVT = getPointerTy(MF.getDataLayout());
6875   // Reserve space for the linkage area on the stack.
6876   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6877   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
6878   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6879 
6880   SmallVector<SDValue, 8> MemOps;
6881 
6882   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
6883     CCValAssign &VA = ArgLocs[I++];
6884     MVT LocVT = VA.getLocVT();
6885     MVT ValVT = VA.getValVT();
6886     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
6887     // For compatibility with the AIX XL compiler, the float args in the
6888     // parameter save area are initialized even if the argument is available
6889     // in register.  The caller is required to initialize both the register
6890     // and memory, however, the callee can choose to expect it in either.
6891     // The memloc is dismissed here because the argument is retrieved from
6892     // the register.
6893     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
6894       continue;
6895 
6896     auto HandleMemLoc = [&]() {
6897       const unsigned LocSize = LocVT.getStoreSize();
6898       const unsigned ValSize = ValVT.getStoreSize();
6899       assert((ValSize <= LocSize) &&
6900              "Object size is larger than size of MemLoc");
6901       int CurArgOffset = VA.getLocMemOffset();
6902       // Objects are right-justified because AIX is big-endian.
6903       if (LocSize > ValSize)
6904         CurArgOffset += LocSize - ValSize;
6905       // Potential tail calls could cause overwriting of argument stack slots.
6906       const bool IsImmutable =
6907           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
6908             (CallConv == CallingConv::Fast));
6909       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
6910       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6911       SDValue ArgValue =
6912           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
6913       InVals.push_back(ArgValue);
6914     };
6915 
6916     // Vector arguments to VaArg functions are passed both on the stack, and
6917     // in any available GPRs. Load the value from the stack and add the GPRs
6918     // as live ins.
6919     if (VA.isMemLoc() && VA.needsCustom()) {
6920       assert(ValVT.isVector() && "Unexpected Custom MemLoc type.");
6921       assert(isVarArg && "Only use custom memloc for vararg.");
6922       // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
6923       // matching custom RegLocs.
6924       const unsigned OriginalValNo = VA.getValNo();
6925       (void)OriginalValNo;
6926 
6927       auto HandleCustomVecRegLoc = [&]() {
6928         assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
6929                "Missing custom RegLoc.");
6930         VA = ArgLocs[I++];
6931         assert(VA.getValVT().isVector() &&
6932                "Unexpected Val type for custom RegLoc.");
6933         assert(VA.getValNo() == OriginalValNo &&
6934                "ValNo mismatch between custom MemLoc and RegLoc.");
6935         MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy;
6936         MF.addLiveIn(VA.getLocReg(),
6937                      getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
6938                                        Subtarget.hasVSX()));
6939       };
6940 
6941       HandleMemLoc();
6942       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
6943       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
6944       // R10.
6945       HandleCustomVecRegLoc();
6946       HandleCustomVecRegLoc();
6947 
6948       // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
6949       // we passed the vector in R5, R6, R7 and R8.
6950       if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
6951         assert(!IsPPC64 &&
6952                "Only 2 custom RegLocs expected for 64-bit codegen.");
6953         HandleCustomVecRegLoc();
6954         HandleCustomVecRegLoc();
6955       }
6956 
6957       continue;
6958     }
6959 
6960     if (VA.isRegLoc()) {
6961       if (VA.getValVT().isScalarInteger())
6962         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
6963       else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) {
6964         switch (VA.getValVT().SimpleTy) {
6965         default:
6966           report_fatal_error("Unhandled value type for argument.");
6967         case MVT::f32:
6968           FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint);
6969           break;
6970         case MVT::f64:
6971           FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint);
6972           break;
6973         }
6974       } else if (VA.getValVT().isVector()) {
6975         switch (VA.getValVT().SimpleTy) {
6976         default:
6977           report_fatal_error("Unhandled value type for argument.");
6978         case MVT::v16i8:
6979           FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar);
6980           break;
6981         case MVT::v8i16:
6982           FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort);
6983           break;
6984         case MVT::v4i32:
6985         case MVT::v2i64:
6986         case MVT::v1i128:
6987           FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt);
6988           break;
6989         case MVT::v4f32:
6990         case MVT::v2f64:
6991           FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat);
6992           break;
6993         }
6994       }
6995     }
6996 
6997     if (Flags.isByVal() && VA.isMemLoc()) {
6998       const unsigned Size =
6999           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7000                   PtrByteSize);
7001       const int FI = MF.getFrameInfo().CreateFixedObject(
7002           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7003           /* IsAliased */ true);
7004       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7005       InVals.push_back(FIN);
7006 
7007       continue;
7008     }
7009 
7010     if (Flags.isByVal()) {
7011       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7012 
7013       const MCPhysReg ArgReg = VA.getLocReg();
7014       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7015 
7016       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7017         report_fatal_error("Over aligned byvals not supported yet.");
7018 
7019       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7020       const int FI = MF.getFrameInfo().CreateFixedObject(
7021           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7022           /* IsAliased */ true);
7023       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7024       InVals.push_back(FIN);
7025 
7026       // Add live ins for all the RegLocs for the same ByVal.
7027       const TargetRegisterClass *RegClass =
7028           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7029 
7030       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7031                                                unsigned Offset) {
7032         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7033         // Since the callers side has left justified the aggregate in the
7034         // register, we can simply store the entire register into the stack
7035         // slot.
7036         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7037         // The store to the fixedstack object is needed becuase accessing a
7038         // field of the ByVal will use a gep and load. Ideally we will optimize
7039         // to extracting the value from the register directly, and elide the
7040         // stores when the arguments address is not taken, but that will need to
7041         // be future work.
7042         SDValue Store = DAG.getStore(
7043             CopyFrom.getValue(1), dl, CopyFrom,
7044             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7045             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7046 
7047         MemOps.push_back(Store);
7048       };
7049 
7050       unsigned Offset = 0;
7051       HandleRegLoc(VA.getLocReg(), Offset);
7052       Offset += PtrByteSize;
7053       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7054            Offset += PtrByteSize) {
7055         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7056                "RegLocs should be for ByVal argument.");
7057 
7058         const CCValAssign RL = ArgLocs[I++];
7059         HandleRegLoc(RL.getLocReg(), Offset);
7060         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7061       }
7062 
7063       if (Offset != StackSize) {
7064         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7065                "Expected MemLoc for remaining bytes.");
7066         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7067         // Consume the MemLoc.The InVal has already been emitted, so nothing
7068         // more needs to be done.
7069         ++I;
7070       }
7071 
7072       continue;
7073     }
7074 
7075     if (VA.isRegLoc() && !VA.needsCustom()) {
7076       MVT::SimpleValueType SVT = ValVT.SimpleTy;
7077       Register VReg =
7078           MF.addLiveIn(VA.getLocReg(),
7079                        getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7080                                          Subtarget.hasVSX()));
7081       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7082       if (ValVT.isScalarInteger() &&
7083           (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7084         ArgValue =
7085             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7086       }
7087       InVals.push_back(ArgValue);
7088       continue;
7089     }
7090     if (VA.isMemLoc()) {
7091       HandleMemLoc();
7092       continue;
7093     }
7094   }
7095 
7096   // On AIX a minimum of 8 words is saved to the parameter save area.
7097   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7098   // Area that is at least reserved in the caller of this function.
7099   unsigned CallerReservedArea =
7100       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7101 
7102   // Set the size that is at least reserved in caller of this function. Tail
7103   // call optimized function's reserved stack space needs to be aligned so
7104   // that taking the difference between two stack areas will result in an
7105   // aligned stack.
7106   CallerReservedArea =
7107       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7108   FuncInfo->setMinReservedArea(CallerReservedArea);
7109 
7110   if (isVarArg) {
7111     FuncInfo->setVarArgsFrameIndex(
7112         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7113     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7114 
7115     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7116                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7117 
7118     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7119                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7120     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7121 
7122     // The fixed integer arguments of a variadic function are stored to the
7123     // VarArgsFrameIndex on the stack so that they may be loaded by
7124     // dereferencing the result of va_next.
7125     for (unsigned GPRIndex =
7126              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7127          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7128 
7129       const unsigned VReg =
7130           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7131                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7132 
7133       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7134       SDValue Store =
7135           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7136       MemOps.push_back(Store);
7137       // Increment the address for the next argument to store.
7138       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7139       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7140     }
7141   }
7142 
7143   if (!MemOps.empty())
7144     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7145 
7146   return Chain;
7147 }
7148 
7149 SDValue PPCTargetLowering::LowerCall_AIX(
7150     SDValue Chain, SDValue Callee, CallFlags CFlags,
7151     const SmallVectorImpl<ISD::OutputArg> &Outs,
7152     const SmallVectorImpl<SDValue> &OutVals,
7153     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7154     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7155     const CallBase *CB) const {
7156   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7157   // AIX ABI stack frame layout.
7158 
7159   assert((CFlags.CallConv == CallingConv::C ||
7160           CFlags.CallConv == CallingConv::Cold ||
7161           CFlags.CallConv == CallingConv::Fast) &&
7162          "Unexpected calling convention!");
7163 
7164   if (CFlags.IsPatchPoint)
7165     report_fatal_error("This call type is unimplemented on AIX.");
7166 
7167   const PPCSubtarget& Subtarget =
7168       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7169 
7170   MachineFunction &MF = DAG.getMachineFunction();
7171   SmallVector<CCValAssign, 16> ArgLocs;
7172   AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7173                     *DAG.getContext());
7174 
7175   // Reserve space for the linkage save area (LSA) on the stack.
7176   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7177   //   [SP][CR][LR][2 x reserved][TOC].
7178   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7179   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7180   const bool IsPPC64 = Subtarget.isPPC64();
7181   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7182   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7183   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7184   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7185 
7186   // The prolog code of the callee may store up to 8 GPR argument registers to
7187   // the stack, allowing va_start to index over them in memory if the callee
7188   // is variadic.
7189   // Because we cannot tell if this is needed on the caller side, we have to
7190   // conservatively assume that it is needed.  As such, make sure we have at
7191   // least enough stack space for the caller to store the 8 GPRs.
7192   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7193   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7194                                      CCInfo.getNextStackOffset());
7195 
7196   // Adjust the stack pointer for the new arguments...
7197   // These operations are automatically eliminated by the prolog/epilog pass.
7198   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7199   SDValue CallSeqStart = Chain;
7200 
7201   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7202   SmallVector<SDValue, 8> MemOpChains;
7203 
7204   // Set up a copy of the stack pointer for loading and storing any
7205   // arguments that may not fit in the registers available for argument
7206   // passing.
7207   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7208                                    : DAG.getRegister(PPC::R1, MVT::i32);
7209 
7210   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7211     const unsigned ValNo = ArgLocs[I].getValNo();
7212     SDValue Arg = OutVals[ValNo];
7213     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7214 
7215     if (Flags.isByVal()) {
7216       const unsigned ByValSize = Flags.getByValSize();
7217 
7218       // Nothing to do for zero-sized ByVals on the caller side.
7219       if (!ByValSize) {
7220         ++I;
7221         continue;
7222       }
7223 
7224       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7225         return DAG.getExtLoad(
7226             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7227             (LoadOffset != 0)
7228                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7229                 : Arg,
7230             MachinePointerInfo(), VT);
7231       };
7232 
7233       unsigned LoadOffset = 0;
7234 
7235       // Initialize registers, which are fully occupied by the by-val argument.
7236       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7237         SDValue Load = GetLoad(PtrVT, LoadOffset);
7238         MemOpChains.push_back(Load.getValue(1));
7239         LoadOffset += PtrByteSize;
7240         const CCValAssign &ByValVA = ArgLocs[I++];
7241         assert(ByValVA.getValNo() == ValNo &&
7242                "Unexpected location for pass-by-value argument.");
7243         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7244       }
7245 
7246       if (LoadOffset == ByValSize)
7247         continue;
7248 
7249       // There must be one more loc to handle the remainder.
7250       assert(ArgLocs[I].getValNo() == ValNo &&
7251              "Expected additional location for by-value argument.");
7252 
7253       if (ArgLocs[I].isMemLoc()) {
7254         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7255         const CCValAssign &ByValVA = ArgLocs[I++];
7256         ISD::ArgFlagsTy MemcpyFlags = Flags;
7257         // Only memcpy the bytes that don't pass in register.
7258         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7259         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7260             (LoadOffset != 0)
7261                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7262                 : Arg,
7263             DAG.getObjectPtrOffset(dl, StackPtr,
7264                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7265             CallSeqStart, MemcpyFlags, DAG, dl);
7266         continue;
7267       }
7268 
7269       // Initialize the final register residue.
7270       // Any residue that occupies the final by-val arg register must be
7271       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7272       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7273       // 2 and 1 byte loads.
7274       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7275       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7276              "Unexpected register residue for by-value argument.");
7277       SDValue ResidueVal;
7278       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7279         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7280         const MVT VT =
7281             N == 1 ? MVT::i8
7282                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7283         SDValue Load = GetLoad(VT, LoadOffset);
7284         MemOpChains.push_back(Load.getValue(1));
7285         LoadOffset += N;
7286         Bytes += N;
7287 
7288         // By-val arguments are passed left-justfied in register.
7289         // Every load here needs to be shifted, otherwise a full register load
7290         // should have been used.
7291         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7292                "Unexpected load emitted during handling of pass-by-value "
7293                "argument.");
7294         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7295         EVT ShiftAmountTy =
7296             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7297         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7298         SDValue ShiftedLoad =
7299             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7300         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7301                                               ShiftedLoad)
7302                                 : ShiftedLoad;
7303       }
7304 
7305       const CCValAssign &ByValVA = ArgLocs[I++];
7306       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7307       continue;
7308     }
7309 
7310     CCValAssign &VA = ArgLocs[I++];
7311     const MVT LocVT = VA.getLocVT();
7312     const MVT ValVT = VA.getValVT();
7313 
7314     switch (VA.getLocInfo()) {
7315     default:
7316       report_fatal_error("Unexpected argument extension type.");
7317     case CCValAssign::Full:
7318       break;
7319     case CCValAssign::ZExt:
7320       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7321       break;
7322     case CCValAssign::SExt:
7323       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7324       break;
7325     }
7326 
7327     if (VA.isRegLoc() && !VA.needsCustom()) {
7328       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7329       continue;
7330     }
7331 
7332     // Vector arguments passed to VarArg functions need custom handling when
7333     // they are passed (at least partially) in GPRs.
7334     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
7335       assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.");
7336       // Store value to its stack slot.
7337       SDValue PtrOff =
7338           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7339       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7340       SDValue Store =
7341           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
7342       MemOpChains.push_back(Store);
7343       const unsigned OriginalValNo = VA.getValNo();
7344       // Then load the GPRs from the stack
7345       unsigned LoadOffset = 0;
7346       auto HandleCustomVecRegLoc = [&]() {
7347         assert(I != E && "Unexpected end of CCvalAssigns.");
7348         assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7349                "Expected custom RegLoc.");
7350         CCValAssign RegVA = ArgLocs[I++];
7351         assert(RegVA.getValNo() == OriginalValNo &&
7352                "Custom MemLoc ValNo and custom RegLoc ValNo must match.");
7353         SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
7354                                   DAG.getConstant(LoadOffset, dl, PtrVT));
7355         SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
7356         MemOpChains.push_back(Load.getValue(1));
7357         RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
7358         LoadOffset += PtrByteSize;
7359       };
7360 
7361       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7362       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7363       // R10.
7364       HandleCustomVecRegLoc();
7365       HandleCustomVecRegLoc();
7366 
7367       if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7368           ArgLocs[I].getValNo() == OriginalValNo) {
7369         assert(!IsPPC64 &&
7370                "Only 2 custom RegLocs expected for 64-bit codegen.");
7371         HandleCustomVecRegLoc();
7372         HandleCustomVecRegLoc();
7373       }
7374 
7375       continue;
7376     }
7377 
7378     if (VA.isMemLoc()) {
7379       SDValue PtrOff =
7380           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7381       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7382       MemOpChains.push_back(
7383           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7384 
7385       continue;
7386     }
7387 
7388     if (!ValVT.isFloatingPoint())
7389       report_fatal_error(
7390           "Unexpected register handling for calling convention.");
7391 
7392     // Custom handling is used for GPR initializations for vararg float
7393     // arguments.
7394     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7395            LocVT.isInteger() &&
7396            "Custom register handling only expected for VarArg.");
7397 
7398     SDValue ArgAsInt =
7399         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7400 
7401     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7402       // f32 in 32-bit GPR
7403       // f64 in 64-bit GPR
7404       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7405     else if (Arg.getValueType().getFixedSizeInBits() <
7406              LocVT.getFixedSizeInBits())
7407       // f32 in 64-bit GPR.
7408       RegsToPass.push_back(std::make_pair(
7409           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7410     else {
7411       // f64 in two 32-bit GPRs
7412       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7413       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7414              "Unexpected custom register for argument!");
7415       CCValAssign &GPR1 = VA;
7416       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7417                                      DAG.getConstant(32, dl, MVT::i8));
7418       RegsToPass.push_back(std::make_pair(
7419           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7420 
7421       if (I != E) {
7422         // If only 1 GPR was available, there will only be one custom GPR and
7423         // the argument will also pass in memory.
7424         CCValAssign &PeekArg = ArgLocs[I];
7425         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7426           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7427           CCValAssign &GPR2 = ArgLocs[I++];
7428           RegsToPass.push_back(std::make_pair(
7429               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7430         }
7431       }
7432     }
7433   }
7434 
7435   if (!MemOpChains.empty())
7436     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7437 
7438   // For indirect calls, we need to save the TOC base to the stack for
7439   // restoration after the call.
7440   if (CFlags.IsIndirect) {
7441     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7442     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7443     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7444     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7445     const unsigned TOCSaveOffset =
7446         Subtarget.getFrameLowering()->getTOCSaveOffset();
7447 
7448     setUsesTOCBasePtr(DAG);
7449     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7450     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7451     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7452     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7453     Chain = DAG.getStore(
7454         Val.getValue(1), dl, Val, AddPtr,
7455         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7456   }
7457 
7458   // Build a sequence of copy-to-reg nodes chained together with token chain
7459   // and flag operands which copy the outgoing args into the appropriate regs.
7460   SDValue InFlag;
7461   for (auto Reg : RegsToPass) {
7462     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7463     InFlag = Chain.getValue(1);
7464   }
7465 
7466   const int SPDiff = 0;
7467   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7468                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7469 }
7470 
7471 bool
7472 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7473                                   MachineFunction &MF, bool isVarArg,
7474                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7475                                   LLVMContext &Context) const {
7476   SmallVector<CCValAssign, 16> RVLocs;
7477   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7478   return CCInfo.CheckReturn(
7479       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7480                 ? RetCC_PPC_Cold
7481                 : RetCC_PPC);
7482 }
7483 
7484 SDValue
7485 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7486                                bool isVarArg,
7487                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7488                                const SmallVectorImpl<SDValue> &OutVals,
7489                                const SDLoc &dl, SelectionDAG &DAG) const {
7490   SmallVector<CCValAssign, 16> RVLocs;
7491   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7492                  *DAG.getContext());
7493   CCInfo.AnalyzeReturn(Outs,
7494                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7495                            ? RetCC_PPC_Cold
7496                            : RetCC_PPC);
7497 
7498   SDValue Flag;
7499   SmallVector<SDValue, 4> RetOps(1, Chain);
7500 
7501   // Copy the result values into the output registers.
7502   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7503     CCValAssign &VA = RVLocs[i];
7504     assert(VA.isRegLoc() && "Can only return in registers!");
7505 
7506     SDValue Arg = OutVals[RealResIdx];
7507 
7508     switch (VA.getLocInfo()) {
7509     default: llvm_unreachable("Unknown loc info!");
7510     case CCValAssign::Full: break;
7511     case CCValAssign::AExt:
7512       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7513       break;
7514     case CCValAssign::ZExt:
7515       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7516       break;
7517     case CCValAssign::SExt:
7518       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7519       break;
7520     }
7521     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7522       bool isLittleEndian = Subtarget.isLittleEndian();
7523       // Legalize ret f64 -> ret 2 x i32.
7524       SDValue SVal =
7525           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7526                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7527       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7528       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7529       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7530                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7531       Flag = Chain.getValue(1);
7532       VA = RVLocs[++i]; // skip ahead to next loc
7533       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7534     } else
7535       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7536     Flag = Chain.getValue(1);
7537     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7538   }
7539 
7540   RetOps[0] = Chain;  // Update chain.
7541 
7542   // Add the flag if we have it.
7543   if (Flag.getNode())
7544     RetOps.push_back(Flag);
7545 
7546   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7547 }
7548 
7549 SDValue
7550 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7551                                                 SelectionDAG &DAG) const {
7552   SDLoc dl(Op);
7553 
7554   // Get the correct type for integers.
7555   EVT IntVT = Op.getValueType();
7556 
7557   // Get the inputs.
7558   SDValue Chain = Op.getOperand(0);
7559   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7560   // Build a DYNAREAOFFSET node.
7561   SDValue Ops[2] = {Chain, FPSIdx};
7562   SDVTList VTs = DAG.getVTList(IntVT);
7563   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7564 }
7565 
7566 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7567                                              SelectionDAG &DAG) const {
7568   // When we pop the dynamic allocation we need to restore the SP link.
7569   SDLoc dl(Op);
7570 
7571   // Get the correct type for pointers.
7572   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7573 
7574   // Construct the stack pointer operand.
7575   bool isPPC64 = Subtarget.isPPC64();
7576   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7577   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7578 
7579   // Get the operands for the STACKRESTORE.
7580   SDValue Chain = Op.getOperand(0);
7581   SDValue SaveSP = Op.getOperand(1);
7582 
7583   // Load the old link SP.
7584   SDValue LoadLinkSP =
7585       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7586 
7587   // Restore the stack pointer.
7588   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7589 
7590   // Store the old link SP.
7591   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7592 }
7593 
7594 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7595   MachineFunction &MF = DAG.getMachineFunction();
7596   bool isPPC64 = Subtarget.isPPC64();
7597   EVT PtrVT = getPointerTy(MF.getDataLayout());
7598 
7599   // Get current frame pointer save index.  The users of this index will be
7600   // primarily DYNALLOC instructions.
7601   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7602   int RASI = FI->getReturnAddrSaveIndex();
7603 
7604   // If the frame pointer save index hasn't been defined yet.
7605   if (!RASI) {
7606     // Find out what the fix offset of the frame pointer save area.
7607     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7608     // Allocate the frame index for frame pointer save area.
7609     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7610     // Save the result.
7611     FI->setReturnAddrSaveIndex(RASI);
7612   }
7613   return DAG.getFrameIndex(RASI, PtrVT);
7614 }
7615 
7616 SDValue
7617 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7618   MachineFunction &MF = DAG.getMachineFunction();
7619   bool isPPC64 = Subtarget.isPPC64();
7620   EVT PtrVT = getPointerTy(MF.getDataLayout());
7621 
7622   // Get current frame pointer save index.  The users of this index will be
7623   // primarily DYNALLOC instructions.
7624   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7625   int FPSI = FI->getFramePointerSaveIndex();
7626 
7627   // If the frame pointer save index hasn't been defined yet.
7628   if (!FPSI) {
7629     // Find out what the fix offset of the frame pointer save area.
7630     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7631     // Allocate the frame index for frame pointer save area.
7632     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7633     // Save the result.
7634     FI->setFramePointerSaveIndex(FPSI);
7635   }
7636   return DAG.getFrameIndex(FPSI, PtrVT);
7637 }
7638 
7639 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7640                                                    SelectionDAG &DAG) const {
7641   MachineFunction &MF = DAG.getMachineFunction();
7642   // Get the inputs.
7643   SDValue Chain = Op.getOperand(0);
7644   SDValue Size  = Op.getOperand(1);
7645   SDLoc dl(Op);
7646 
7647   // Get the correct type for pointers.
7648   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7649   // Negate the size.
7650   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7651                                 DAG.getConstant(0, dl, PtrVT), Size);
7652   // Construct a node for the frame pointer save index.
7653   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7654   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7655   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7656   if (hasInlineStackProbe(MF))
7657     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7658   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7659 }
7660 
7661 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7662                                                      SelectionDAG &DAG) const {
7663   MachineFunction &MF = DAG.getMachineFunction();
7664 
7665   bool isPPC64 = Subtarget.isPPC64();
7666   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7667 
7668   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7669   return DAG.getFrameIndex(FI, PtrVT);
7670 }
7671 
7672 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7673                                                SelectionDAG &DAG) const {
7674   SDLoc DL(Op);
7675   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7676                      DAG.getVTList(MVT::i32, MVT::Other),
7677                      Op.getOperand(0), Op.getOperand(1));
7678 }
7679 
7680 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7681                                                 SelectionDAG &DAG) const {
7682   SDLoc DL(Op);
7683   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7684                      Op.getOperand(0), Op.getOperand(1));
7685 }
7686 
7687 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7688   if (Op.getValueType().isVector())
7689     return LowerVectorLoad(Op, DAG);
7690 
7691   assert(Op.getValueType() == MVT::i1 &&
7692          "Custom lowering only for i1 loads");
7693 
7694   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7695 
7696   SDLoc dl(Op);
7697   LoadSDNode *LD = cast<LoadSDNode>(Op);
7698 
7699   SDValue Chain = LD->getChain();
7700   SDValue BasePtr = LD->getBasePtr();
7701   MachineMemOperand *MMO = LD->getMemOperand();
7702 
7703   SDValue NewLD =
7704       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7705                      BasePtr, MVT::i8, MMO);
7706   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7707 
7708   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7709   return DAG.getMergeValues(Ops, dl);
7710 }
7711 
7712 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7713   if (Op.getOperand(1).getValueType().isVector())
7714     return LowerVectorStore(Op, DAG);
7715 
7716   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7717          "Custom lowering only for i1 stores");
7718 
7719   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7720 
7721   SDLoc dl(Op);
7722   StoreSDNode *ST = cast<StoreSDNode>(Op);
7723 
7724   SDValue Chain = ST->getChain();
7725   SDValue BasePtr = ST->getBasePtr();
7726   SDValue Value = ST->getValue();
7727   MachineMemOperand *MMO = ST->getMemOperand();
7728 
7729   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7730                       Value);
7731   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7732 }
7733 
7734 // FIXME: Remove this once the ANDI glue bug is fixed:
7735 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7736   assert(Op.getValueType() == MVT::i1 &&
7737          "Custom lowering only for i1 results");
7738 
7739   SDLoc DL(Op);
7740   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7741 }
7742 
7743 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7744                                                SelectionDAG &DAG) const {
7745 
7746   // Implements a vector truncate that fits in a vector register as a shuffle.
7747   // We want to legalize vector truncates down to where the source fits in
7748   // a vector register (and target is therefore smaller than vector register
7749   // size).  At that point legalization will try to custom lower the sub-legal
7750   // result and get here - where we can contain the truncate as a single target
7751   // operation.
7752 
7753   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7754   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7755   //
7756   // We will implement it for big-endian ordering as this (where x denotes
7757   // undefined):
7758   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7759   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7760   //
7761   // The same operation in little-endian ordering will be:
7762   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7763   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7764 
7765   EVT TrgVT = Op.getValueType();
7766   assert(TrgVT.isVector() && "Vector type expected.");
7767   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7768   EVT EltVT = TrgVT.getVectorElementType();
7769   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
7770       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
7771       !isPowerOf2_32(EltVT.getSizeInBits()))
7772     return SDValue();
7773 
7774   SDValue N1 = Op.getOperand(0);
7775   EVT SrcVT = N1.getValueType();
7776   unsigned SrcSize = SrcVT.getSizeInBits();
7777   if (SrcSize > 256 ||
7778       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
7779       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
7780     return SDValue();
7781   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
7782     return SDValue();
7783 
7784   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7785   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7786 
7787   SDLoc DL(Op);
7788   SDValue Op1, Op2;
7789   if (SrcSize == 256) {
7790     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
7791     EVT SplitVT =
7792         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
7793     unsigned SplitNumElts = SplitVT.getVectorNumElements();
7794     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7795                       DAG.getConstant(0, DL, VecIdxTy));
7796     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7797                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
7798   }
7799   else {
7800     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7801     Op2 = DAG.getUNDEF(WideVT);
7802   }
7803 
7804   // First list the elements we want to keep.
7805   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7806   SmallVector<int, 16> ShuffV;
7807   if (Subtarget.isLittleEndian())
7808     for (unsigned i = 0; i < TrgNumElts; ++i)
7809       ShuffV.push_back(i * SizeMult);
7810   else
7811     for (unsigned i = 1; i <= TrgNumElts; ++i)
7812       ShuffV.push_back(i * SizeMult - 1);
7813 
7814   // Populate the remaining elements with undefs.
7815   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7816     // ShuffV.push_back(i + WideNumElts);
7817     ShuffV.push_back(WideNumElts + 1);
7818 
7819   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
7820   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
7821   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
7822 }
7823 
7824 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7825 /// possible.
7826 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7827   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7828   EVT ResVT = Op.getValueType();
7829   EVT CmpVT = Op.getOperand(0).getValueType();
7830   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7831   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7832   SDLoc dl(Op);
7833 
7834   // Without power9-vector, we don't have native instruction for f128 comparison.
7835   // Following transformation to libcall is needed for setcc:
7836   // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE
7837   if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) {
7838     SDValue Z = DAG.getSetCC(
7839         dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT),
7840         LHS, RHS, CC);
7841     SDValue Zero = DAG.getConstant(0, dl, Z.getValueType());
7842     return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE);
7843   }
7844 
7845   // Not FP, or using SPE? Not a fsel.
7846   if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() ||
7847       Subtarget.hasSPE())
7848     return Op;
7849 
7850   SDNodeFlags Flags = Op.getNode()->getFlags();
7851 
7852   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7853   // presence of infinities.
7854   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7855     switch (CC) {
7856     default:
7857       break;
7858     case ISD::SETOGT:
7859     case ISD::SETGT:
7860       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7861     case ISD::SETOLT:
7862     case ISD::SETLT:
7863       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7864     }
7865   }
7866 
7867   // We might be able to do better than this under some circumstances, but in
7868   // general, fsel-based lowering of select is a finite-math-only optimization.
7869   // For more information, see section F.3 of the 2.06 ISA specification.
7870   // With ISA 3.0
7871   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7872       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7873     return Op;
7874 
7875   // If the RHS of the comparison is a 0.0, we don't need to do the
7876   // subtraction at all.
7877   SDValue Sel1;
7878   if (isFloatingPointZero(RHS))
7879     switch (CC) {
7880     default: break;       // SETUO etc aren't handled by fsel.
7881     case ISD::SETNE:
7882       std::swap(TV, FV);
7883       LLVM_FALLTHROUGH;
7884     case ISD::SETEQ:
7885       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7886         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7887       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7888       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7889         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7890       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7891                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7892     case ISD::SETULT:
7893     case ISD::SETLT:
7894       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7895       LLVM_FALLTHROUGH;
7896     case ISD::SETOGE:
7897     case ISD::SETGE:
7898       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7899         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7900       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7901     case ISD::SETUGT:
7902     case ISD::SETGT:
7903       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7904       LLVM_FALLTHROUGH;
7905     case ISD::SETOLE:
7906     case ISD::SETLE:
7907       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7908         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7909       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7910                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7911     }
7912 
7913   SDValue Cmp;
7914   switch (CC) {
7915   default: break;       // SETUO etc aren't handled by fsel.
7916   case ISD::SETNE:
7917     std::swap(TV, FV);
7918     LLVM_FALLTHROUGH;
7919   case ISD::SETEQ:
7920     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7921     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7922       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7923     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7924     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7925       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7926     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7927                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7928   case ISD::SETULT:
7929   case ISD::SETLT:
7930     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7931     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7932       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7933     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7934   case ISD::SETOGE:
7935   case ISD::SETGE:
7936     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7937     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7938       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7939     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7940   case ISD::SETUGT:
7941   case ISD::SETGT:
7942     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7943     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7944       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7945     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7946   case ISD::SETOLE:
7947   case ISD::SETLE:
7948     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7949     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7950       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7951     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7952   }
7953   return Op;
7954 }
7955 
7956 static unsigned getPPCStrictOpcode(unsigned Opc) {
7957   switch (Opc) {
7958   default:
7959     llvm_unreachable("No strict version of this opcode!");
7960   case PPCISD::FCTIDZ:
7961     return PPCISD::STRICT_FCTIDZ;
7962   case PPCISD::FCTIWZ:
7963     return PPCISD::STRICT_FCTIWZ;
7964   case PPCISD::FCTIDUZ:
7965     return PPCISD::STRICT_FCTIDUZ;
7966   case PPCISD::FCTIWUZ:
7967     return PPCISD::STRICT_FCTIWUZ;
7968   case PPCISD::FCFID:
7969     return PPCISD::STRICT_FCFID;
7970   case PPCISD::FCFIDU:
7971     return PPCISD::STRICT_FCFIDU;
7972   case PPCISD::FCFIDS:
7973     return PPCISD::STRICT_FCFIDS;
7974   case PPCISD::FCFIDUS:
7975     return PPCISD::STRICT_FCFIDUS;
7976   }
7977 }
7978 
7979 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
7980                               const PPCSubtarget &Subtarget) {
7981   SDLoc dl(Op);
7982   bool IsStrict = Op->isStrictFPOpcode();
7983   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
7984                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
7985 
7986   // TODO: Any other flags to propagate?
7987   SDNodeFlags Flags;
7988   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
7989 
7990   // For strict nodes, source is the second operand.
7991   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
7992   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
7993   assert(Src.getValueType().isFloatingPoint());
7994   if (Src.getValueType() == MVT::f32) {
7995     if (IsStrict) {
7996       Src =
7997           DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
7998                       DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
7999       Chain = Src.getValue(1);
8000     } else
8001       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8002   }
8003   SDValue Conv;
8004   unsigned Opc = ISD::DELETED_NODE;
8005   switch (Op.getSimpleValueType().SimpleTy) {
8006   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8007   case MVT::i32:
8008     Opc = IsSigned ? PPCISD::FCTIWZ
8009                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8010     break;
8011   case MVT::i64:
8012     assert((IsSigned || Subtarget.hasFPCVT()) &&
8013            "i64 FP_TO_UINT is supported only with FPCVT");
8014     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8015   }
8016   if (IsStrict) {
8017     Opc = getPPCStrictOpcode(Opc);
8018     Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
8019                        {Chain, Src}, Flags);
8020   } else {
8021     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8022   }
8023   return Conv;
8024 }
8025 
8026 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8027                                                SelectionDAG &DAG,
8028                                                const SDLoc &dl) const {
8029   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8030   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8031                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8032   bool IsStrict = Op->isStrictFPOpcode();
8033 
8034   // Convert the FP value to an int value through memory.
8035   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8036                   (IsSigned || Subtarget.hasFPCVT());
8037   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8038   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8039   MachinePointerInfo MPI =
8040       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8041 
8042   // Emit a store to the stack slot.
8043   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8044   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8045   if (i32Stack) {
8046     MachineFunction &MF = DAG.getMachineFunction();
8047     Alignment = Align(4);
8048     MachineMemOperand *MMO =
8049         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8050     SDValue Ops[] = { Chain, Tmp, FIPtr };
8051     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8052               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8053   } else
8054     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8055 
8056   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8057   // add in a bias on big endian.
8058   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8059     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8060                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8061     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8062   }
8063 
8064   RLI.Chain = Chain;
8065   RLI.Ptr = FIPtr;
8066   RLI.MPI = MPI;
8067   RLI.Alignment = Alignment;
8068 }
8069 
8070 /// Custom lowers floating point to integer conversions to use
8071 /// the direct move instructions available in ISA 2.07 to avoid the
8072 /// need for load/store combinations.
8073 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8074                                                     SelectionDAG &DAG,
8075                                                     const SDLoc &dl) const {
8076   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8077   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8078   if (Op->isStrictFPOpcode())
8079     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8080   else
8081     return Mov;
8082 }
8083 
8084 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8085                                           const SDLoc &dl) const {
8086   bool IsStrict = Op->isStrictFPOpcode();
8087   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8088                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8089   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8090   EVT SrcVT = Src.getValueType();
8091   EVT DstVT = Op.getValueType();
8092 
8093   // FP to INT conversions are legal for f128.
8094   if (SrcVT == MVT::f128)
8095     return Subtarget.hasP9Vector() ? Op : SDValue();
8096 
8097   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8098   // PPC (the libcall is not available).
8099   if (SrcVT == MVT::ppcf128) {
8100     if (DstVT == MVT::i32) {
8101       // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8102       // set other fast-math flags to FP operations in both strict and
8103       // non-strict cases. (FP_TO_SINT, FSUB)
8104       SDNodeFlags Flags;
8105       Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8106 
8107       if (IsSigned) {
8108         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8109                                  DAG.getIntPtrConstant(0, dl));
8110         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8111                                  DAG.getIntPtrConstant(1, dl));
8112 
8113         // Add the two halves of the long double in round-to-zero mode, and use
8114         // a smaller FP_TO_SINT.
8115         if (IsStrict) {
8116           SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8117                                     DAG.getVTList(MVT::f64, MVT::Other),
8118                                     {Op.getOperand(0), Lo, Hi}, Flags);
8119           return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8120                              DAG.getVTList(MVT::i32, MVT::Other),
8121                              {Res.getValue(1), Res}, Flags);
8122         } else {
8123           SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8124           return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8125         }
8126       } else {
8127         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8128         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8129         SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8130         SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8131         if (IsStrict) {
8132           // Sel = Src < 0x80000000
8133           // FltOfs = select Sel, 0.0, 0x80000000
8134           // IntOfs = select Sel, 0, 0x80000000
8135           // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8136           SDValue Chain = Op.getOperand(0);
8137           EVT SetCCVT =
8138               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8139           EVT DstSetCCVT =
8140               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8141           SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8142                                      Chain, true);
8143           Chain = Sel.getValue(1);
8144 
8145           SDValue FltOfs = DAG.getSelect(
8146               dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8147           Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8148 
8149           SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8150                                     DAG.getVTList(SrcVT, MVT::Other),
8151                                     {Chain, Src, FltOfs}, Flags);
8152           Chain = Val.getValue(1);
8153           SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8154                                      DAG.getVTList(DstVT, MVT::Other),
8155                                      {Chain, Val}, Flags);
8156           Chain = SInt.getValue(1);
8157           SDValue IntOfs = DAG.getSelect(
8158               dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8159           SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8160           return DAG.getMergeValues({Result, Chain}, dl);
8161         } else {
8162           // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8163           // FIXME: generated code sucks.
8164           SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8165           True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8166           True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8167           SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8168           return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8169         }
8170       }
8171     }
8172 
8173     return SDValue();
8174   }
8175 
8176   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8177     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8178 
8179   ReuseLoadInfo RLI;
8180   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8181 
8182   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8183                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8184 }
8185 
8186 // We're trying to insert a regular store, S, and then a load, L. If the
8187 // incoming value, O, is a load, we might just be able to have our load use the
8188 // address used by O. However, we don't know if anything else will store to
8189 // that address before we can load from it. To prevent this situation, we need
8190 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8191 // the same chain operand as O, we create a token factor from the chain results
8192 // of O and L, and we replace all uses of O's chain result with that token
8193 // factor (see spliceIntoChain below for this last part).
8194 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8195                                             ReuseLoadInfo &RLI,
8196                                             SelectionDAG &DAG,
8197                                             ISD::LoadExtType ET) const {
8198   // Conservatively skip reusing for constrained FP nodes.
8199   if (Op->isStrictFPOpcode())
8200     return false;
8201 
8202   SDLoc dl(Op);
8203   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8204                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8205   if (ET == ISD::NON_EXTLOAD &&
8206       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8207       isOperationLegalOrCustom(Op.getOpcode(),
8208                                Op.getOperand(0).getValueType())) {
8209 
8210     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8211     return true;
8212   }
8213 
8214   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8215   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8216       LD->isNonTemporal())
8217     return false;
8218   if (LD->getMemoryVT() != MemVT)
8219     return false;
8220 
8221   // If the result of the load is an illegal type, then we can't build a
8222   // valid chain for reuse since the legalised loads and token factor node that
8223   // ties the legalised loads together uses a different output chain then the
8224   // illegal load.
8225   if (!isTypeLegal(LD->getValueType(0)))
8226     return false;
8227 
8228   RLI.Ptr = LD->getBasePtr();
8229   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8230     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8231            "Non-pre-inc AM on PPC?");
8232     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8233                           LD->getOffset());
8234   }
8235 
8236   RLI.Chain = LD->getChain();
8237   RLI.MPI = LD->getPointerInfo();
8238   RLI.IsDereferenceable = LD->isDereferenceable();
8239   RLI.IsInvariant = LD->isInvariant();
8240   RLI.Alignment = LD->getAlign();
8241   RLI.AAInfo = LD->getAAInfo();
8242   RLI.Ranges = LD->getRanges();
8243 
8244   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8245   return true;
8246 }
8247 
8248 // Given the head of the old chain, ResChain, insert a token factor containing
8249 // it and NewResChain, and make users of ResChain now be users of that token
8250 // factor.
8251 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8252 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8253                                         SDValue NewResChain,
8254                                         SelectionDAG &DAG) const {
8255   if (!ResChain)
8256     return;
8257 
8258   SDLoc dl(NewResChain);
8259 
8260   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8261                            NewResChain, DAG.getUNDEF(MVT::Other));
8262   assert(TF.getNode() != NewResChain.getNode() &&
8263          "A new TF really is required here");
8264 
8265   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8266   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8267 }
8268 
8269 /// Analyze profitability of direct move
8270 /// prefer float load to int load plus direct move
8271 /// when there is no integer use of int load
8272 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8273   SDNode *Origin = Op.getOperand(0).getNode();
8274   if (Origin->getOpcode() != ISD::LOAD)
8275     return true;
8276 
8277   // If there is no LXSIBZX/LXSIHZX, like Power8,
8278   // prefer direct move if the memory size is 1 or 2 bytes.
8279   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8280   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8281     return true;
8282 
8283   for (SDNode::use_iterator UI = Origin->use_begin(),
8284                             UE = Origin->use_end();
8285        UI != UE; ++UI) {
8286 
8287     // Only look at the users of the loaded value.
8288     if (UI.getUse().get().getResNo() != 0)
8289       continue;
8290 
8291     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8292         UI->getOpcode() != ISD::UINT_TO_FP &&
8293         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8294         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8295       return true;
8296   }
8297 
8298   return false;
8299 }
8300 
8301 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8302                               const PPCSubtarget &Subtarget,
8303                               SDValue Chain = SDValue()) {
8304   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8305                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8306   SDLoc dl(Op);
8307 
8308   // TODO: Any other flags to propagate?
8309   SDNodeFlags Flags;
8310   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8311 
8312   // If we have FCFIDS, then use it when converting to single-precision.
8313   // Otherwise, convert to double-precision and then round.
8314   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8315   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8316                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8317   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8318   if (Op->isStrictFPOpcode()) {
8319     if (!Chain)
8320       Chain = Op.getOperand(0);
8321     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8322                        DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8323   } else
8324     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8325 }
8326 
8327 /// Custom lowers integer to floating point conversions to use
8328 /// the direct move instructions available in ISA 2.07 to avoid the
8329 /// need for load/store combinations.
8330 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8331                                                     SelectionDAG &DAG,
8332                                                     const SDLoc &dl) const {
8333   assert((Op.getValueType() == MVT::f32 ||
8334           Op.getValueType() == MVT::f64) &&
8335          "Invalid floating point type as target of conversion");
8336   assert(Subtarget.hasFPCVT() &&
8337          "Int to FP conversions with direct moves require FPCVT");
8338   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8339   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8340   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8341                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8342   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8343   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8344   return convertIntToFP(Op, Mov, DAG, Subtarget);
8345 }
8346 
8347 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8348 
8349   EVT VecVT = Vec.getValueType();
8350   assert(VecVT.isVector() && "Expected a vector type.");
8351   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8352 
8353   EVT EltVT = VecVT.getVectorElementType();
8354   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8355   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8356 
8357   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8358   SmallVector<SDValue, 16> Ops(NumConcat);
8359   Ops[0] = Vec;
8360   SDValue UndefVec = DAG.getUNDEF(VecVT);
8361   for (unsigned i = 1; i < NumConcat; ++i)
8362     Ops[i] = UndefVec;
8363 
8364   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8365 }
8366 
8367 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8368                                                 const SDLoc &dl) const {
8369   bool IsStrict = Op->isStrictFPOpcode();
8370   unsigned Opc = Op.getOpcode();
8371   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8372   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8373           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8374          "Unexpected conversion type");
8375   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8376          "Supports conversions to v2f64/v4f32 only.");
8377 
8378   // TODO: Any other flags to propagate?
8379   SDNodeFlags Flags;
8380   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8381 
8382   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8383   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8384 
8385   SDValue Wide = widenVec(DAG, Src, dl);
8386   EVT WideVT = Wide.getValueType();
8387   unsigned WideNumElts = WideVT.getVectorNumElements();
8388   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8389 
8390   SmallVector<int, 16> ShuffV;
8391   for (unsigned i = 0; i < WideNumElts; ++i)
8392     ShuffV.push_back(i + WideNumElts);
8393 
8394   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8395   int SaveElts = FourEltRes ? 4 : 2;
8396   if (Subtarget.isLittleEndian())
8397     for (int i = 0; i < SaveElts; i++)
8398       ShuffV[i * Stride] = i;
8399   else
8400     for (int i = 1; i <= SaveElts; i++)
8401       ShuffV[i * Stride - 1] = i - 1;
8402 
8403   SDValue ShuffleSrc2 =
8404       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8405   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8406 
8407   SDValue Extend;
8408   if (SignedConv) {
8409     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8410     EVT ExtVT = Src.getValueType();
8411     if (Subtarget.hasP9Altivec())
8412       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8413                                IntermediateVT.getVectorNumElements());
8414 
8415     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8416                          DAG.getValueType(ExtVT));
8417   } else
8418     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8419 
8420   if (IsStrict)
8421     return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8422                        {Op.getOperand(0), Extend}, Flags);
8423 
8424   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8425 }
8426 
8427 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8428                                           SelectionDAG &DAG) const {
8429   SDLoc dl(Op);
8430   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8431                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8432   bool IsStrict = Op->isStrictFPOpcode();
8433   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8434   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8435 
8436   // TODO: Any other flags to propagate?
8437   SDNodeFlags Flags;
8438   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8439 
8440   EVT InVT = Src.getValueType();
8441   EVT OutVT = Op.getValueType();
8442   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8443       isOperationCustom(Op.getOpcode(), InVT))
8444     return LowerINT_TO_FPVector(Op, DAG, dl);
8445 
8446   // Conversions to f128 are legal.
8447   if (Op.getValueType() == MVT::f128)
8448     return Subtarget.hasP9Vector() ? Op : SDValue();
8449 
8450   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8451   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8452     return SDValue();
8453 
8454   if (Src.getValueType() == MVT::i1) {
8455     SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8456                               DAG.getConstantFP(1.0, dl, Op.getValueType()),
8457                               DAG.getConstantFP(0.0, dl, Op.getValueType()));
8458     if (IsStrict)
8459       return DAG.getMergeValues({Sel, Chain}, dl);
8460     else
8461       return Sel;
8462   }
8463 
8464   // If we have direct moves, we can do all the conversion, skip the store/load
8465   // however, without FPCVT we can't do most conversions.
8466   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8467       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8468     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8469 
8470   assert((IsSigned || Subtarget.hasFPCVT()) &&
8471          "UINT_TO_FP is supported only with FPCVT");
8472 
8473   if (Src.getValueType() == MVT::i64) {
8474     SDValue SINT = Src;
8475     // When converting to single-precision, we actually need to convert
8476     // to double-precision first and then round to single-precision.
8477     // To avoid double-rounding effects during that operation, we have
8478     // to prepare the input operand.  Bits that might be truncated when
8479     // converting to double-precision are replaced by a bit that won't
8480     // be lost at this stage, but is below the single-precision rounding
8481     // position.
8482     //
8483     // However, if -enable-unsafe-fp-math is in effect, accept double
8484     // rounding to avoid the extra overhead.
8485     if (Op.getValueType() == MVT::f32 &&
8486         !Subtarget.hasFPCVT() &&
8487         !DAG.getTarget().Options.UnsafeFPMath) {
8488 
8489       // Twiddle input to make sure the low 11 bits are zero.  (If this
8490       // is the case, we are guaranteed the value will fit into the 53 bit
8491       // mantissa of an IEEE double-precision value without rounding.)
8492       // If any of those low 11 bits were not zero originally, make sure
8493       // bit 12 (value 2048) is set instead, so that the final rounding
8494       // to single-precision gets the correct result.
8495       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8496                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8497       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8498                           Round, DAG.getConstant(2047, dl, MVT::i64));
8499       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8500       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8501                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8502 
8503       // However, we cannot use that value unconditionally: if the magnitude
8504       // of the input value is small, the bit-twiddling we did above might
8505       // end up visibly changing the output.  Fortunately, in that case, we
8506       // don't need to twiddle bits since the original input will convert
8507       // exactly to double-precision floating-point already.  Therefore,
8508       // construct a conditional to use the original value if the top 11
8509       // bits are all sign-bit copies, and use the rounded value computed
8510       // above otherwise.
8511       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8512                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8513       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8514                          Cond, DAG.getConstant(1, dl, MVT::i64));
8515       Cond = DAG.getSetCC(
8516           dl,
8517           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8518           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8519 
8520       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8521     }
8522 
8523     ReuseLoadInfo RLI;
8524     SDValue Bits;
8525 
8526     MachineFunction &MF = DAG.getMachineFunction();
8527     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8528       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8529                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8530       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8531     } else if (Subtarget.hasLFIWAX() &&
8532                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8533       MachineMemOperand *MMO =
8534         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8535                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8536       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8537       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8538                                      DAG.getVTList(MVT::f64, MVT::Other),
8539                                      Ops, MVT::i32, MMO);
8540       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8541     } else if (Subtarget.hasFPCVT() &&
8542                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8543       MachineMemOperand *MMO =
8544         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8545                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8546       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8547       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8548                                      DAG.getVTList(MVT::f64, MVT::Other),
8549                                      Ops, MVT::i32, MMO);
8550       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8551     } else if (((Subtarget.hasLFIWAX() &&
8552                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8553                 (Subtarget.hasFPCVT() &&
8554                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8555                SINT.getOperand(0).getValueType() == MVT::i32) {
8556       MachineFrameInfo &MFI = MF.getFrameInfo();
8557       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8558 
8559       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8560       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8561 
8562       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8563                                    MachinePointerInfo::getFixedStack(
8564                                        DAG.getMachineFunction(), FrameIdx));
8565       Chain = Store;
8566 
8567       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8568              "Expected an i32 store");
8569 
8570       RLI.Ptr = FIdx;
8571       RLI.Chain = Chain;
8572       RLI.MPI =
8573           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8574       RLI.Alignment = Align(4);
8575 
8576       MachineMemOperand *MMO =
8577         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8578                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8579       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8580       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8581                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8582                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8583                                      Ops, MVT::i32, MMO);
8584       Chain = Bits.getValue(1);
8585     } else
8586       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8587 
8588     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8589     if (IsStrict)
8590       Chain = FP.getValue(1);
8591 
8592     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8593       if (IsStrict)
8594         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8595                          DAG.getVTList(MVT::f32, MVT::Other),
8596                          {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8597       else
8598         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8599                          DAG.getIntPtrConstant(0, dl));
8600     }
8601     return FP;
8602   }
8603 
8604   assert(Src.getValueType() == MVT::i32 &&
8605          "Unhandled INT_TO_FP type in custom expander!");
8606   // Since we only generate this in 64-bit mode, we can take advantage of
8607   // 64-bit registers.  In particular, sign extend the input value into the
8608   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8609   // then lfd it and fcfid it.
8610   MachineFunction &MF = DAG.getMachineFunction();
8611   MachineFrameInfo &MFI = MF.getFrameInfo();
8612   EVT PtrVT = getPointerTy(MF.getDataLayout());
8613 
8614   SDValue Ld;
8615   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8616     ReuseLoadInfo RLI;
8617     bool ReusingLoad;
8618     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8619       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8620       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8621 
8622       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8623                                    MachinePointerInfo::getFixedStack(
8624                                        DAG.getMachineFunction(), FrameIdx));
8625       Chain = Store;
8626 
8627       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8628              "Expected an i32 store");
8629 
8630       RLI.Ptr = FIdx;
8631       RLI.Chain = Chain;
8632       RLI.MPI =
8633           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8634       RLI.Alignment = Align(4);
8635     }
8636 
8637     MachineMemOperand *MMO =
8638       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8639                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8640     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8641     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8642                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8643                                  MVT::i32, MMO);
8644     Chain = Ld.getValue(1);
8645     if (ReusingLoad)
8646       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8647   } else {
8648     assert(Subtarget.isPPC64() &&
8649            "i32->FP without LFIWAX supported only on PPC64");
8650 
8651     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8652     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8653 
8654     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8655 
8656     // STD the extended value into the stack slot.
8657     SDValue Store = DAG.getStore(
8658         Chain, dl, Ext64, FIdx,
8659         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8660     Chain = Store;
8661 
8662     // Load the value as a double.
8663     Ld = DAG.getLoad(
8664         MVT::f64, dl, Chain, FIdx,
8665         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8666     Chain = Ld.getValue(1);
8667   }
8668 
8669   // FCFID it and return it.
8670   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8671   if (IsStrict)
8672     Chain = FP.getValue(1);
8673   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8674     if (IsStrict)
8675       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8676                        DAG.getVTList(MVT::f32, MVT::Other),
8677                        {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8678     else
8679       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8680                        DAG.getIntPtrConstant(0, dl));
8681   }
8682   return FP;
8683 }
8684 
8685 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8686                                             SelectionDAG &DAG) const {
8687   SDLoc dl(Op);
8688   /*
8689    The rounding mode is in bits 30:31 of FPSR, and has the following
8690    settings:
8691      00 Round to nearest
8692      01 Round to 0
8693      10 Round to +inf
8694      11 Round to -inf
8695 
8696   FLT_ROUNDS, on the other hand, expects the following:
8697     -1 Undefined
8698      0 Round to 0
8699      1 Round to nearest
8700      2 Round to +inf
8701      3 Round to -inf
8702 
8703   To perform the conversion, we do:
8704     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8705   */
8706 
8707   MachineFunction &MF = DAG.getMachineFunction();
8708   EVT VT = Op.getValueType();
8709   EVT PtrVT = getPointerTy(MF.getDataLayout());
8710 
8711   // Save FP Control Word to register
8712   SDValue Chain = Op.getOperand(0);
8713   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8714   Chain = MFFS.getValue(1);
8715 
8716   SDValue CWD;
8717   if (isTypeLegal(MVT::i64)) {
8718     CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
8719                       DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
8720   } else {
8721     // Save FP register to stack slot
8722     int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8723     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8724     Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8725 
8726     // Load FP Control Word from low 32 bits of stack slot.
8727     assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) &&
8728            "Stack slot adjustment is valid only on big endian subtargets!");
8729     SDValue Four = DAG.getConstant(4, dl, PtrVT);
8730     SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8731     CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8732     Chain = CWD.getValue(1);
8733   }
8734 
8735   // Transform as necessary
8736   SDValue CWD1 =
8737     DAG.getNode(ISD::AND, dl, MVT::i32,
8738                 CWD, DAG.getConstant(3, dl, MVT::i32));
8739   SDValue CWD2 =
8740     DAG.getNode(ISD::SRL, dl, MVT::i32,
8741                 DAG.getNode(ISD::AND, dl, MVT::i32,
8742                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8743                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8744                             DAG.getConstant(3, dl, MVT::i32)),
8745                 DAG.getConstant(1, dl, MVT::i32));
8746 
8747   SDValue RetVal =
8748     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8749 
8750   RetVal =
8751       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8752                   dl, VT, RetVal);
8753 
8754   return DAG.getMergeValues({RetVal, Chain}, dl);
8755 }
8756 
8757 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8758   EVT VT = Op.getValueType();
8759   unsigned BitWidth = VT.getSizeInBits();
8760   SDLoc dl(Op);
8761   assert(Op.getNumOperands() == 3 &&
8762          VT == Op.getOperand(1).getValueType() &&
8763          "Unexpected SHL!");
8764 
8765   // Expand into a bunch of logical ops.  Note that these ops
8766   // depend on the PPC behavior for oversized shift amounts.
8767   SDValue Lo = Op.getOperand(0);
8768   SDValue Hi = Op.getOperand(1);
8769   SDValue Amt = Op.getOperand(2);
8770   EVT AmtVT = Amt.getValueType();
8771 
8772   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8773                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8774   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8775   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8776   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8777   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8778                              DAG.getConstant(-BitWidth, dl, AmtVT));
8779   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8780   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8781   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8782   SDValue OutOps[] = { OutLo, OutHi };
8783   return DAG.getMergeValues(OutOps, dl);
8784 }
8785 
8786 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8787   EVT VT = Op.getValueType();
8788   SDLoc dl(Op);
8789   unsigned BitWidth = VT.getSizeInBits();
8790   assert(Op.getNumOperands() == 3 &&
8791          VT == Op.getOperand(1).getValueType() &&
8792          "Unexpected SRL!");
8793 
8794   // Expand into a bunch of logical ops.  Note that these ops
8795   // depend on the PPC behavior for oversized shift amounts.
8796   SDValue Lo = Op.getOperand(0);
8797   SDValue Hi = Op.getOperand(1);
8798   SDValue Amt = Op.getOperand(2);
8799   EVT AmtVT = Amt.getValueType();
8800 
8801   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8802                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8803   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8804   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8805   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8806   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8807                              DAG.getConstant(-BitWidth, dl, AmtVT));
8808   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8809   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8810   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8811   SDValue OutOps[] = { OutLo, OutHi };
8812   return DAG.getMergeValues(OutOps, dl);
8813 }
8814 
8815 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8816   SDLoc dl(Op);
8817   EVT VT = Op.getValueType();
8818   unsigned BitWidth = VT.getSizeInBits();
8819   assert(Op.getNumOperands() == 3 &&
8820          VT == Op.getOperand(1).getValueType() &&
8821          "Unexpected SRA!");
8822 
8823   // Expand into a bunch of logical ops, followed by a select_cc.
8824   SDValue Lo = Op.getOperand(0);
8825   SDValue Hi = Op.getOperand(1);
8826   SDValue Amt = Op.getOperand(2);
8827   EVT AmtVT = Amt.getValueType();
8828 
8829   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8830                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8831   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8832   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8833   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8834   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8835                              DAG.getConstant(-BitWidth, dl, AmtVT));
8836   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8837   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8838   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8839                                   Tmp4, Tmp6, ISD::SETLE);
8840   SDValue OutOps[] = { OutLo, OutHi };
8841   return DAG.getMergeValues(OutOps, dl);
8842 }
8843 
8844 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8845                                             SelectionDAG &DAG) const {
8846   SDLoc dl(Op);
8847   EVT VT = Op.getValueType();
8848   unsigned BitWidth = VT.getSizeInBits();
8849 
8850   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8851   SDValue X = Op.getOperand(0);
8852   SDValue Y = Op.getOperand(1);
8853   SDValue Z = Op.getOperand(2);
8854   EVT AmtVT = Z.getValueType();
8855 
8856   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8857   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8858   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8859   // on PowerPC shift by BW being well defined.
8860   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8861                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8862   SDValue SubZ =
8863       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8864   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8865   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8866   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8867 }
8868 
8869 //===----------------------------------------------------------------------===//
8870 // Vector related lowering.
8871 //
8872 
8873 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8874 /// element size of SplatSize. Cast the result to VT.
8875 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8876                                       SelectionDAG &DAG, const SDLoc &dl) {
8877   static const MVT VTys[] = { // canonical VT to use for each size.
8878     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8879   };
8880 
8881   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8882 
8883   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8884   if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
8885     SplatSize = 1;
8886     Val = 0xFF;
8887   }
8888 
8889   EVT CanonicalVT = VTys[SplatSize-1];
8890 
8891   // Build a canonical splat for this value.
8892   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8893 }
8894 
8895 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8896 /// specified intrinsic ID.
8897 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8898                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8899   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8900   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8901                      DAG.getConstant(IID, dl, MVT::i32), Op);
8902 }
8903 
8904 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8905 /// specified intrinsic ID.
8906 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8907                                 SelectionDAG &DAG, const SDLoc &dl,
8908                                 EVT DestVT = MVT::Other) {
8909   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8910   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8911                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8912 }
8913 
8914 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8915 /// specified intrinsic ID.
8916 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8917                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8918                                 EVT DestVT = MVT::Other) {
8919   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8920   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8921                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8922 }
8923 
8924 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8925 /// amount.  The result has the specified value type.
8926 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8927                            SelectionDAG &DAG, const SDLoc &dl) {
8928   // Force LHS/RHS to be the right type.
8929   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8930   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8931 
8932   int Ops[16];
8933   for (unsigned i = 0; i != 16; ++i)
8934     Ops[i] = i + Amt;
8935   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8936   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8937 }
8938 
8939 /// Do we have an efficient pattern in a .td file for this node?
8940 ///
8941 /// \param V - pointer to the BuildVectorSDNode being matched
8942 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8943 ///
8944 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8945 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8946 /// the opposite is true (expansion is beneficial) are:
8947 /// - The node builds a vector out of integers that are not 32 or 64-bits
8948 /// - The node builds a vector out of constants
8949 /// - The node is a "load-and-splat"
8950 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8951 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8952                                             bool HasDirectMove,
8953                                             bool HasP8Vector) {
8954   EVT VecVT = V->getValueType(0);
8955   bool RightType = VecVT == MVT::v2f64 ||
8956     (HasP8Vector && VecVT == MVT::v4f32) ||
8957     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8958   if (!RightType)
8959     return false;
8960 
8961   bool IsSplat = true;
8962   bool IsLoad = false;
8963   SDValue Op0 = V->getOperand(0);
8964 
8965   // This function is called in a block that confirms the node is not a constant
8966   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8967   // different constants.
8968   if (V->isConstant())
8969     return false;
8970   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8971     if (V->getOperand(i).isUndef())
8972       return false;
8973     // We want to expand nodes that represent load-and-splat even if the
8974     // loaded value is a floating point truncation or conversion to int.
8975     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8976         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8977          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8978         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8979          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8980         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8981          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8982       IsLoad = true;
8983     // If the operands are different or the input is not a load and has more
8984     // uses than just this BV node, then it isn't a splat.
8985     if (V->getOperand(i) != Op0 ||
8986         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8987       IsSplat = false;
8988   }
8989   return !(IsSplat && IsLoad);
8990 }
8991 
8992 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8993 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8994 
8995   SDLoc dl(Op);
8996   SDValue Op0 = Op->getOperand(0);
8997 
8998   if ((Op.getValueType() != MVT::f128) ||
8999       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9000       (Op0.getOperand(0).getValueType() != MVT::i64) ||
9001       (Op0.getOperand(1).getValueType() != MVT::i64))
9002     return SDValue();
9003 
9004   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9005                      Op0.getOperand(1));
9006 }
9007 
9008 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9009   const SDValue *InputLoad = &Op;
9010   if (InputLoad->getOpcode() == ISD::BITCAST)
9011     InputLoad = &InputLoad->getOperand(0);
9012   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9013       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9014     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9015     InputLoad = &InputLoad->getOperand(0);
9016   }
9017   if (InputLoad->getOpcode() != ISD::LOAD)
9018     return nullptr;
9019   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9020   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9021 }
9022 
9023 // Convert the argument APFloat to a single precision APFloat if there is no
9024 // loss in information during the conversion to single precision APFloat and the
9025 // resulting number is not a denormal number. Return true if successful.
9026 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9027   APFloat APFloatToConvert = ArgAPFloat;
9028   bool LosesInfo = true;
9029   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9030                            &LosesInfo);
9031   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9032   if (Success)
9033     ArgAPFloat = APFloatToConvert;
9034   return Success;
9035 }
9036 
9037 // Bitcast the argument APInt to a double and convert it to a single precision
9038 // APFloat, bitcast the APFloat to an APInt and assign it to the original
9039 // argument if there is no loss in information during the conversion from
9040 // double to single precision APFloat and the resulting number is not a denormal
9041 // number. Return true if successful.
9042 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9043   double DpValue = ArgAPInt.bitsToDouble();
9044   APFloat APFloatDp(DpValue);
9045   bool Success = convertToNonDenormSingle(APFloatDp);
9046   if (Success)
9047     ArgAPInt = APFloatDp.bitcastToAPInt();
9048   return Success;
9049 }
9050 
9051 // Nondestructive check for convertTonNonDenormSingle.
9052 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) {
9053   // Only convert if it loses info, since XXSPLTIDP should
9054   // handle the other case.
9055   APFloat APFloatToConvert = ArgAPFloat;
9056   bool LosesInfo = true;
9057   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9058                            &LosesInfo);
9059 
9060   return (!LosesInfo && !APFloatToConvert.isDenormal());
9061 }
9062 
9063 // If this is a case we can't handle, return null and let the default
9064 // expansion code take care of it.  If we CAN select this case, and if it
9065 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9066 // this case more efficiently than a constant pool load, lower it to the
9067 // sequence of ops that should be used.
9068 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9069                                              SelectionDAG &DAG) const {
9070   SDLoc dl(Op);
9071   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9072   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9073 
9074   // Check if this is a splat of a constant value.
9075   APInt APSplatBits, APSplatUndef;
9076   unsigned SplatBitSize;
9077   bool HasAnyUndefs;
9078   bool BVNIsConstantSplat =
9079       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9080                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9081 
9082   // If it is a splat of a double, check if we can shrink it to a 32 bit
9083   // non-denormal float which when converted back to double gives us the same
9084   // double. This is to exploit the XXSPLTIDP instruction.
9085   // If we lose precision, we use XXSPLTI32DX.
9086   if (BVNIsConstantSplat && (SplatBitSize == 64) &&
9087       Subtarget.hasPrefixInstrs()) {
9088     // Check the type first to short-circuit so we don't modify APSplatBits if
9089     // this block isn't executed.
9090     if ((Op->getValueType(0) == MVT::v2f64) &&
9091         convertToNonDenormSingle(APSplatBits)) {
9092       SDValue SplatNode = DAG.getNode(
9093           PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9094           DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9095       return DAG.getBitcast(Op.getValueType(), SplatNode);
9096     } else {
9097       // We may lose precision, so we have to use XXSPLTI32DX.
9098 
9099       uint32_t Hi =
9100           (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32);
9101       uint32_t Lo =
9102           (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF);
9103       SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
9104 
9105       if (!Hi || !Lo)
9106         // If either load is 0, then we should generate XXLXOR to set to 0.
9107         SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
9108 
9109       if (Hi)
9110         SplatNode = DAG.getNode(
9111             PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9112             DAG.getTargetConstant(0, dl, MVT::i32),
9113             DAG.getTargetConstant(Hi, dl, MVT::i32));
9114 
9115       if (Lo)
9116         SplatNode =
9117             DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9118                         DAG.getTargetConstant(1, dl, MVT::i32),
9119                         DAG.getTargetConstant(Lo, dl, MVT::i32));
9120 
9121       return DAG.getBitcast(Op.getValueType(), SplatNode);
9122     }
9123   }
9124 
9125   if (!BVNIsConstantSplat || SplatBitSize > 32) {
9126 
9127     bool IsPermutedLoad = false;
9128     const SDValue *InputLoad =
9129         getNormalLoadInput(Op.getOperand(0), IsPermutedLoad);
9130     // Handle load-and-splat patterns as we have instructions that will do this
9131     // in one go.
9132     if (InputLoad && DAG.isSplatValue(Op, true)) {
9133       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9134 
9135       // We have handling for 4 and 8 byte elements.
9136       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9137 
9138       // Checking for a single use of this load, we have to check for vector
9139       // width (128 bits) / ElementSize uses (since each operand of the
9140       // BUILD_VECTOR is a separate use of the value.
9141       unsigned NumUsesOfInputLD = 128 / ElementSize;
9142       for (SDValue BVInOp : Op->ops())
9143         if (BVInOp.isUndef())
9144           NumUsesOfInputLD--;
9145       assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
9146       if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
9147           ((Subtarget.hasVSX() && ElementSize == 64) ||
9148            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9149         SDValue Ops[] = {
9150           LD->getChain(),    // Chain
9151           LD->getBasePtr(),  // Ptr
9152           DAG.getValueType(Op.getValueType()) // VT
9153         };
9154         SDValue LdSplt = DAG.getMemIntrinsicNode(
9155             PPCISD::LD_SPLAT, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
9156             Ops, LD->getMemoryVT(), LD->getMemOperand());
9157         // Replace all uses of the output chain of the original load with the
9158         // output chain of the new load.
9159         DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
9160                                       LdSplt.getValue(1));
9161         return LdSplt;
9162       }
9163     }
9164 
9165     // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
9166     // 32-bits can be lowered to VSX instructions under certain conditions.
9167     // Without VSX, there is no pattern more efficient than expanding the node.
9168     if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
9169         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9170                                         Subtarget.hasP8Vector()))
9171       return Op;
9172     return SDValue();
9173   }
9174 
9175   uint64_t SplatBits = APSplatBits.getZExtValue();
9176   uint64_t SplatUndef = APSplatUndef.getZExtValue();
9177   unsigned SplatSize = SplatBitSize / 8;
9178 
9179   // First, handle single instruction cases.
9180 
9181   // All zeros?
9182   if (SplatBits == 0) {
9183     // Canonicalize all zero vectors to be v4i32.
9184     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9185       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9186       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9187     }
9188     return Op;
9189   }
9190 
9191   // We have XXSPLTIW for constant splats four bytes wide.
9192   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9193   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9194   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9195   // turned into a 4-byte splat of 0xABABABAB.
9196   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9197     return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
9198                                   Op.getValueType(), DAG, dl);
9199 
9200   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9201     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9202                                   dl);
9203 
9204   // We have XXSPLTIB for constant splats one byte wide.
9205   if (Subtarget.hasP9Vector() && SplatSize == 1)
9206     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9207                                   dl);
9208 
9209   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9210   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9211                     (32-SplatBitSize));
9212   if (SextVal >= -16 && SextVal <= 15)
9213     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9214                                   dl);
9215 
9216   // Two instruction sequences.
9217 
9218   // If this value is in the range [-32,30] and is even, use:
9219   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9220   // If this value is in the range [17,31] and is odd, use:
9221   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9222   // If this value is in the range [-31,-17] and is odd, use:
9223   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9224   // Note the last two are three-instruction sequences.
9225   if (SextVal >= -32 && SextVal <= 31) {
9226     // To avoid having these optimizations undone by constant folding,
9227     // we convert to a pseudo that will be expanded later into one of
9228     // the above forms.
9229     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9230     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9231               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9232     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9233     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9234     if (VT == Op.getValueType())
9235       return RetVal;
9236     else
9237       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9238   }
9239 
9240   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9241   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9242   // for fneg/fabs.
9243   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9244     // Make -1 and vspltisw -1:
9245     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9246 
9247     // Make the VSLW intrinsic, computing 0x8000_0000.
9248     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9249                                    OnesV, DAG, dl);
9250 
9251     // xor by OnesV to invert it.
9252     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9253     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9254   }
9255 
9256   // Check to see if this is a wide variety of vsplti*, binop self cases.
9257   static const signed char SplatCsts[] = {
9258     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9259     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9260   };
9261 
9262   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9263     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9264     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9265     int i = SplatCsts[idx];
9266 
9267     // Figure out what shift amount will be used by altivec if shifted by i in
9268     // this splat size.
9269     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9270 
9271     // vsplti + shl self.
9272     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9273       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9274       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9275         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9276         Intrinsic::ppc_altivec_vslw
9277       };
9278       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9279       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9280     }
9281 
9282     // vsplti + srl 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_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9287         Intrinsic::ppc_altivec_vsrw
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 + rol self.
9294     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9295                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9296       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9297       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9298         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9299         Intrinsic::ppc_altivec_vrlw
9300       };
9301       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9302       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9303     }
9304 
9305     // t = vsplti c, result = vsldoi t, t, 1
9306     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9307       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9308       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9309       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9310     }
9311     // t = vsplti c, result = vsldoi t, t, 2
9312     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9313       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9314       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9315       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9316     }
9317     // t = vsplti c, result = vsldoi t, t, 3
9318     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9319       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9320       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9321       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9322     }
9323   }
9324 
9325   return SDValue();
9326 }
9327 
9328 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9329 /// the specified operations to build the shuffle.
9330 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9331                                       SDValue RHS, SelectionDAG &DAG,
9332                                       const SDLoc &dl) {
9333   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9334   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9335   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9336 
9337   enum {
9338     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9339     OP_VMRGHW,
9340     OP_VMRGLW,
9341     OP_VSPLTISW0,
9342     OP_VSPLTISW1,
9343     OP_VSPLTISW2,
9344     OP_VSPLTISW3,
9345     OP_VSLDOI4,
9346     OP_VSLDOI8,
9347     OP_VSLDOI12
9348   };
9349 
9350   if (OpNum == OP_COPY) {
9351     if (LHSID == (1*9+2)*9+3) return LHS;
9352     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9353     return RHS;
9354   }
9355 
9356   SDValue OpLHS, OpRHS;
9357   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9358   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9359 
9360   int ShufIdxs[16];
9361   switch (OpNum) {
9362   default: llvm_unreachable("Unknown i32 permute!");
9363   case OP_VMRGHW:
9364     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9365     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9366     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9367     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9368     break;
9369   case OP_VMRGLW:
9370     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9371     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9372     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9373     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9374     break;
9375   case OP_VSPLTISW0:
9376     for (unsigned i = 0; i != 16; ++i)
9377       ShufIdxs[i] = (i&3)+0;
9378     break;
9379   case OP_VSPLTISW1:
9380     for (unsigned i = 0; i != 16; ++i)
9381       ShufIdxs[i] = (i&3)+4;
9382     break;
9383   case OP_VSPLTISW2:
9384     for (unsigned i = 0; i != 16; ++i)
9385       ShufIdxs[i] = (i&3)+8;
9386     break;
9387   case OP_VSPLTISW3:
9388     for (unsigned i = 0; i != 16; ++i)
9389       ShufIdxs[i] = (i&3)+12;
9390     break;
9391   case OP_VSLDOI4:
9392     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9393   case OP_VSLDOI8:
9394     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9395   case OP_VSLDOI12:
9396     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9397   }
9398   EVT VT = OpLHS.getValueType();
9399   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9400   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9401   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9402   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9403 }
9404 
9405 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9406 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9407 /// SDValue.
9408 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9409                                            SelectionDAG &DAG) const {
9410   const unsigned BytesInVector = 16;
9411   bool IsLE = Subtarget.isLittleEndian();
9412   SDLoc dl(N);
9413   SDValue V1 = N->getOperand(0);
9414   SDValue V2 = N->getOperand(1);
9415   unsigned ShiftElts = 0, InsertAtByte = 0;
9416   bool Swap = false;
9417 
9418   // Shifts required to get the byte we want at element 7.
9419   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9420                                    0, 15, 14, 13, 12, 11, 10, 9};
9421   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9422                                 1, 2,  3,  4,  5,  6,  7,  8};
9423 
9424   ArrayRef<int> Mask = N->getMask();
9425   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9426 
9427   // For each mask element, find out if we're just inserting something
9428   // from V2 into V1 or vice versa.
9429   // Possible permutations inserting an element from V2 into V1:
9430   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9431   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9432   //   ...
9433   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9434   // Inserting from V1 into V2 will be similar, except mask range will be
9435   // [16,31].
9436 
9437   bool FoundCandidate = false;
9438   // If both vector operands for the shuffle are the same vector, the mask
9439   // will contain only elements from the first one and the second one will be
9440   // undef.
9441   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9442   // Go through the mask of half-words to find an element that's being moved
9443   // from one vector to the other.
9444   for (unsigned i = 0; i < BytesInVector; ++i) {
9445     unsigned CurrentElement = Mask[i];
9446     // If 2nd operand is undefined, we should only look for element 7 in the
9447     // Mask.
9448     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9449       continue;
9450 
9451     bool OtherElementsInOrder = true;
9452     // Examine the other elements in the Mask to see if they're in original
9453     // order.
9454     for (unsigned j = 0; j < BytesInVector; ++j) {
9455       if (j == i)
9456         continue;
9457       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9458       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9459       // in which we always assume we're always picking from the 1st operand.
9460       int MaskOffset =
9461           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9462       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9463         OtherElementsInOrder = false;
9464         break;
9465       }
9466     }
9467     // If other elements are in original order, we record the number of shifts
9468     // we need to get the element we want into element 7. Also record which byte
9469     // in the vector we should insert into.
9470     if (OtherElementsInOrder) {
9471       // If 2nd operand is undefined, we assume no shifts and no swapping.
9472       if (V2.isUndef()) {
9473         ShiftElts = 0;
9474         Swap = false;
9475       } else {
9476         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9477         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9478                          : BigEndianShifts[CurrentElement & 0xF];
9479         Swap = CurrentElement < BytesInVector;
9480       }
9481       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9482       FoundCandidate = true;
9483       break;
9484     }
9485   }
9486 
9487   if (!FoundCandidate)
9488     return SDValue();
9489 
9490   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9491   // optionally with VECSHL if shift is required.
9492   if (Swap)
9493     std::swap(V1, V2);
9494   if (V2.isUndef())
9495     V2 = V1;
9496   if (ShiftElts) {
9497     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9498                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9499     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9500                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9501   }
9502   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9503                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9504 }
9505 
9506 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9507 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9508 /// SDValue.
9509 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9510                                            SelectionDAG &DAG) const {
9511   const unsigned NumHalfWords = 8;
9512   const unsigned BytesInVector = NumHalfWords * 2;
9513   // Check that the shuffle is on half-words.
9514   if (!isNByteElemShuffleMask(N, 2, 1))
9515     return SDValue();
9516 
9517   bool IsLE = Subtarget.isLittleEndian();
9518   SDLoc dl(N);
9519   SDValue V1 = N->getOperand(0);
9520   SDValue V2 = N->getOperand(1);
9521   unsigned ShiftElts = 0, InsertAtByte = 0;
9522   bool Swap = false;
9523 
9524   // Shifts required to get the half-word we want at element 3.
9525   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9526   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9527 
9528   uint32_t Mask = 0;
9529   uint32_t OriginalOrderLow = 0x1234567;
9530   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9531   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9532   // 32-bit space, only need 4-bit nibbles per element.
9533   for (unsigned i = 0; i < NumHalfWords; ++i) {
9534     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9535     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9536   }
9537 
9538   // For each mask element, find out if we're just inserting something
9539   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9540   // from V2 into V1:
9541   //   X, 1, 2, 3, 4, 5, 6, 7
9542   //   0, X, 2, 3, 4, 5, 6, 7
9543   //   0, 1, X, 3, 4, 5, 6, 7
9544   //   0, 1, 2, X, 4, 5, 6, 7
9545   //   0, 1, 2, 3, X, 5, 6, 7
9546   //   0, 1, 2, 3, 4, X, 6, 7
9547   //   0, 1, 2, 3, 4, 5, X, 7
9548   //   0, 1, 2, 3, 4, 5, 6, X
9549   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9550 
9551   bool FoundCandidate = false;
9552   // Go through the mask of half-words to find an element that's being moved
9553   // from one vector to the other.
9554   for (unsigned i = 0; i < NumHalfWords; ++i) {
9555     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9556     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9557     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9558     uint32_t TargetOrder = 0x0;
9559 
9560     // If both vector operands for the shuffle are the same vector, the mask
9561     // will contain only elements from the first one and the second one will be
9562     // undef.
9563     if (V2.isUndef()) {
9564       ShiftElts = 0;
9565       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9566       TargetOrder = OriginalOrderLow;
9567       Swap = false;
9568       // Skip if not the correct element or mask of other elements don't equal
9569       // to our expected order.
9570       if (MaskOneElt == VINSERTHSrcElem &&
9571           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9572         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9573         FoundCandidate = true;
9574         break;
9575       }
9576     } else { // If both operands are defined.
9577       // Target order is [8,15] if the current mask is between [0,7].
9578       TargetOrder =
9579           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9580       // Skip if mask of other elements don't equal our expected order.
9581       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9582         // We only need the last 3 bits for the number of shifts.
9583         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9584                          : BigEndianShifts[MaskOneElt & 0x7];
9585         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9586         Swap = MaskOneElt < NumHalfWords;
9587         FoundCandidate = true;
9588         break;
9589       }
9590     }
9591   }
9592 
9593   if (!FoundCandidate)
9594     return SDValue();
9595 
9596   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9597   // optionally with VECSHL if shift is required.
9598   if (Swap)
9599     std::swap(V1, V2);
9600   if (V2.isUndef())
9601     V2 = V1;
9602   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9603   if (ShiftElts) {
9604     // Double ShiftElts because we're left shifting on v16i8 type.
9605     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9606                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9607     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9608     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9609                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9610     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9611   }
9612   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9613   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9614                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9615   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9616 }
9617 
9618 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9619 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9620 /// return the default SDValue.
9621 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9622                                               SelectionDAG &DAG) const {
9623   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9624   // to v16i8. Peek through the bitcasts to get the actual operands.
9625   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9626   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9627 
9628   auto ShuffleMask = SVN->getMask();
9629   SDValue VecShuffle(SVN, 0);
9630   SDLoc DL(SVN);
9631 
9632   // Check that we have a four byte shuffle.
9633   if (!isNByteElemShuffleMask(SVN, 4, 1))
9634     return SDValue();
9635 
9636   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9637   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9638     std::swap(LHS, RHS);
9639     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9640     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9641   }
9642 
9643   // Ensure that the RHS is a vector of constants.
9644   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9645   if (!BVN)
9646     return SDValue();
9647 
9648   // Check if RHS is a splat of 4-bytes (or smaller).
9649   APInt APSplatValue, APSplatUndef;
9650   unsigned SplatBitSize;
9651   bool HasAnyUndefs;
9652   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9653                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9654       SplatBitSize > 32)
9655     return SDValue();
9656 
9657   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9658   // The instruction splats a constant C into two words of the source vector
9659   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9660   // Thus we check that the shuffle mask is the equivalent  of
9661   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9662   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9663   // within each word are consecutive, so we only need to check the first byte.
9664   SDValue Index;
9665   bool IsLE = Subtarget.isLittleEndian();
9666   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9667       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9668        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9669     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9670   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9671            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9672             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9673     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9674   else
9675     return SDValue();
9676 
9677   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9678   // for XXSPLTI32DX.
9679   unsigned SplatVal = APSplatValue.getZExtValue();
9680   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9681     SplatVal |= (SplatVal << SplatBitSize);
9682 
9683   SDValue SplatNode = DAG.getNode(
9684       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9685       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9686   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9687 }
9688 
9689 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9690 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9691 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9692 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9693 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9694   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9695   assert(Op.getValueType() == MVT::v1i128 &&
9696          "Only set v1i128 as custom, other type shouldn't reach here!");
9697   SDLoc dl(Op);
9698   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9699   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9700   unsigned SHLAmt = N1.getConstantOperandVal(0);
9701   if (SHLAmt % 8 == 0) {
9702     SmallVector<int, 16> Mask(16, 0);
9703     std::iota(Mask.begin(), Mask.end(), 0);
9704     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9705     if (SDValue Shuffle =
9706             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9707                                  DAG.getUNDEF(MVT::v16i8), Mask))
9708       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9709   }
9710   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9711   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9712                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9713   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9714                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9715   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9716   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9717 }
9718 
9719 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9720 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9721 /// return the code it can be lowered into.  Worst case, it can always be
9722 /// lowered into a vperm.
9723 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9724                                                SelectionDAG &DAG) const {
9725   SDLoc dl(Op);
9726   SDValue V1 = Op.getOperand(0);
9727   SDValue V2 = Op.getOperand(1);
9728   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9729 
9730   // Any nodes that were combined in the target-independent combiner prior
9731   // to vector legalization will not be sent to the target combine. Try to
9732   // combine it here.
9733   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9734     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9735       return NewShuffle;
9736     Op = NewShuffle;
9737     SVOp = cast<ShuffleVectorSDNode>(Op);
9738     V1 = Op.getOperand(0);
9739     V2 = Op.getOperand(1);
9740   }
9741   EVT VT = Op.getValueType();
9742   bool isLittleEndian = Subtarget.isLittleEndian();
9743 
9744   unsigned ShiftElts, InsertAtByte;
9745   bool Swap = false;
9746 
9747   // If this is a load-and-splat, we can do that with a single instruction
9748   // in some cases. However if the load has multiple uses, we don't want to
9749   // combine it because that will just produce multiple loads.
9750   bool IsPermutedLoad = false;
9751   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9752   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9753       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9754       InputLoad->hasOneUse()) {
9755     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9756     int SplatIdx =
9757       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9758 
9759     // The splat index for permuted loads will be in the left half of the vector
9760     // which is strictly wider than the loaded value by 8 bytes. So we need to
9761     // adjust the splat index to point to the correct address in memory.
9762     if (IsPermutedLoad) {
9763       assert((isLittleEndian || IsFourByte) &&
9764              "Unexpected size for permuted load on big endian target");
9765       SplatIdx += IsFourByte ? 2 : 1;
9766       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9767              "Splat of a value outside of the loaded memory");
9768     }
9769 
9770     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9771     // For 4-byte load-and-splat, we need Power9.
9772     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9773       uint64_t Offset = 0;
9774       if (IsFourByte)
9775         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9776       else
9777         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9778 
9779       // If the width of the load is the same as the width of the splat,
9780       // loading with an offset would load the wrong memory.
9781       if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64))
9782         Offset = 0;
9783 
9784       SDValue BasePtr = LD->getBasePtr();
9785       if (Offset != 0)
9786         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9787                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9788       SDValue Ops[] = {
9789         LD->getChain(),    // Chain
9790         BasePtr,           // BasePtr
9791         DAG.getValueType(Op.getValueType()) // VT
9792       };
9793       SDVTList VTL =
9794         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9795       SDValue LdSplt =
9796         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9797                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9798       DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
9799       if (LdSplt.getValueType() != SVOp->getValueType(0))
9800         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9801       return LdSplt;
9802     }
9803   }
9804   if (Subtarget.hasP9Vector() &&
9805       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9806                            isLittleEndian)) {
9807     if (Swap)
9808       std::swap(V1, V2);
9809     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9810     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9811     if (ShiftElts) {
9812       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9813                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9814       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9815                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9816       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9817     }
9818     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9819                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9820     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9821   }
9822 
9823   if (Subtarget.hasPrefixInstrs()) {
9824     SDValue SplatInsertNode;
9825     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9826       return SplatInsertNode;
9827   }
9828 
9829   if (Subtarget.hasP9Altivec()) {
9830     SDValue NewISDNode;
9831     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9832       return NewISDNode;
9833 
9834     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9835       return NewISDNode;
9836   }
9837 
9838   if (Subtarget.hasVSX() &&
9839       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9840     if (Swap)
9841       std::swap(V1, V2);
9842     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9843     SDValue Conv2 =
9844         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9845 
9846     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9847                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9848     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9849   }
9850 
9851   if (Subtarget.hasVSX() &&
9852     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9853     if (Swap)
9854       std::swap(V1, V2);
9855     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9856     SDValue Conv2 =
9857         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9858 
9859     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9860                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9861     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9862   }
9863 
9864   if (Subtarget.hasP9Vector()) {
9865      if (PPC::isXXBRHShuffleMask(SVOp)) {
9866       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9867       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9868       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9869     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9870       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9871       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9872       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9873     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9874       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9875       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9876       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9877     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9878       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9879       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9880       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9881     }
9882   }
9883 
9884   if (Subtarget.hasVSX()) {
9885     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9886       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9887 
9888       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9889       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9890                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9891       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9892     }
9893 
9894     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9895     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9896       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9897       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9898       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9899     }
9900   }
9901 
9902   // Cases that are handled by instructions that take permute immediates
9903   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9904   // selected by the instruction selector.
9905   if (V2.isUndef()) {
9906     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9907         PPC::isSplatShuffleMask(SVOp, 2) ||
9908         PPC::isSplatShuffleMask(SVOp, 4) ||
9909         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9910         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9911         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9912         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9913         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9914         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9915         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9916         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9917         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9918         (Subtarget.hasP8Altivec() && (
9919          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9920          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9921          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9922       return Op;
9923     }
9924   }
9925 
9926   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9927   // and produce a fixed permutation.  If any of these match, do not lower to
9928   // VPERM.
9929   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9930   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9931       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9932       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9933       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9934       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9935       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9936       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9937       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9938       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9939       (Subtarget.hasP8Altivec() && (
9940        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9941        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9942        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9943     return Op;
9944 
9945   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9946   // perfect shuffle table to emit an optimal matching sequence.
9947   ArrayRef<int> PermMask = SVOp->getMask();
9948 
9949   unsigned PFIndexes[4];
9950   bool isFourElementShuffle = true;
9951   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9952     unsigned EltNo = 8;   // Start out undef.
9953     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9954       if (PermMask[i*4+j] < 0)
9955         continue;   // Undef, ignore it.
9956 
9957       unsigned ByteSource = PermMask[i*4+j];
9958       if ((ByteSource & 3) != j) {
9959         isFourElementShuffle = false;
9960         break;
9961       }
9962 
9963       if (EltNo == 8) {
9964         EltNo = ByteSource/4;
9965       } else if (EltNo != ByteSource/4) {
9966         isFourElementShuffle = false;
9967         break;
9968       }
9969     }
9970     PFIndexes[i] = EltNo;
9971   }
9972 
9973   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9974   // perfect shuffle vector to determine if it is cost effective to do this as
9975   // discrete instructions, or whether we should use a vperm.
9976   // For now, we skip this for little endian until such time as we have a
9977   // little-endian perfect shuffle table.
9978   if (isFourElementShuffle && !isLittleEndian) {
9979     // Compute the index in the perfect shuffle table.
9980     unsigned PFTableIndex =
9981       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9982 
9983     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9984     unsigned Cost  = (PFEntry >> 30);
9985 
9986     // Determining when to avoid vperm is tricky.  Many things affect the cost
9987     // of vperm, particularly how many times the perm mask needs to be computed.
9988     // For example, if the perm mask can be hoisted out of a loop or is already
9989     // used (perhaps because there are multiple permutes with the same shuffle
9990     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9991     // the loop requires an extra register.
9992     //
9993     // As a compromise, we only emit discrete instructions if the shuffle can be
9994     // generated in 3 or fewer operations.  When we have loop information
9995     // available, if this block is within a loop, we should avoid using vperm
9996     // for 3-operation perms and use a constant pool load instead.
9997     if (Cost < 3)
9998       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9999   }
10000 
10001   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10002   // vector that will get spilled to the constant pool.
10003   if (V2.isUndef()) V2 = V1;
10004 
10005   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10006   // that it is in input element units, not in bytes.  Convert now.
10007 
10008   // For little endian, the order of the input vectors is reversed, and
10009   // the permutation mask is complemented with respect to 31.  This is
10010   // necessary to produce proper semantics with the big-endian-biased vperm
10011   // instruction.
10012   EVT EltVT = V1.getValueType().getVectorElementType();
10013   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
10014 
10015   SmallVector<SDValue, 16> ResultMask;
10016   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10017     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10018 
10019     for (unsigned j = 0; j != BytesPerElement; ++j)
10020       if (isLittleEndian)
10021         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
10022                                              dl, MVT::i32));
10023       else
10024         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
10025                                              MVT::i32));
10026   }
10027 
10028   ShufflesHandledWithVPERM++;
10029   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10030   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
10031   LLVM_DEBUG(SVOp->dump());
10032   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
10033   LLVM_DEBUG(VPermMask.dump());
10034 
10035   if (isLittleEndian)
10036     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10037                        V2, V1, VPermMask);
10038   else
10039     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10040                        V1, V2, VPermMask);
10041 }
10042 
10043 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10044 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10045 /// information about the intrinsic.
10046 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10047                                  bool &isDot, const PPCSubtarget &Subtarget) {
10048   unsigned IntrinsicID =
10049       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10050   CompareOpc = -1;
10051   isDot = false;
10052   switch (IntrinsicID) {
10053   default:
10054     return false;
10055   // Comparison predicates.
10056   case Intrinsic::ppc_altivec_vcmpbfp_p:
10057     CompareOpc = 966;
10058     isDot = true;
10059     break;
10060   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10061     CompareOpc = 198;
10062     isDot = true;
10063     break;
10064   case Intrinsic::ppc_altivec_vcmpequb_p:
10065     CompareOpc = 6;
10066     isDot = true;
10067     break;
10068   case Intrinsic::ppc_altivec_vcmpequh_p:
10069     CompareOpc = 70;
10070     isDot = true;
10071     break;
10072   case Intrinsic::ppc_altivec_vcmpequw_p:
10073     CompareOpc = 134;
10074     isDot = true;
10075     break;
10076   case Intrinsic::ppc_altivec_vcmpequd_p:
10077     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10078       CompareOpc = 199;
10079       isDot = true;
10080     } else
10081       return false;
10082     break;
10083   case Intrinsic::ppc_altivec_vcmpneb_p:
10084   case Intrinsic::ppc_altivec_vcmpneh_p:
10085   case Intrinsic::ppc_altivec_vcmpnew_p:
10086   case Intrinsic::ppc_altivec_vcmpnezb_p:
10087   case Intrinsic::ppc_altivec_vcmpnezh_p:
10088   case Intrinsic::ppc_altivec_vcmpnezw_p:
10089     if (Subtarget.hasP9Altivec()) {
10090       switch (IntrinsicID) {
10091       default:
10092         llvm_unreachable("Unknown comparison intrinsic.");
10093       case Intrinsic::ppc_altivec_vcmpneb_p:
10094         CompareOpc = 7;
10095         break;
10096       case Intrinsic::ppc_altivec_vcmpneh_p:
10097         CompareOpc = 71;
10098         break;
10099       case Intrinsic::ppc_altivec_vcmpnew_p:
10100         CompareOpc = 135;
10101         break;
10102       case Intrinsic::ppc_altivec_vcmpnezb_p:
10103         CompareOpc = 263;
10104         break;
10105       case Intrinsic::ppc_altivec_vcmpnezh_p:
10106         CompareOpc = 327;
10107         break;
10108       case Intrinsic::ppc_altivec_vcmpnezw_p:
10109         CompareOpc = 391;
10110         break;
10111       }
10112       isDot = true;
10113     } else
10114       return false;
10115     break;
10116   case Intrinsic::ppc_altivec_vcmpgefp_p:
10117     CompareOpc = 454;
10118     isDot = true;
10119     break;
10120   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10121     CompareOpc = 710;
10122     isDot = true;
10123     break;
10124   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10125     CompareOpc = 774;
10126     isDot = true;
10127     break;
10128   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10129     CompareOpc = 838;
10130     isDot = true;
10131     break;
10132   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10133     CompareOpc = 902;
10134     isDot = true;
10135     break;
10136   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10137     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10138       CompareOpc = 967;
10139       isDot = true;
10140     } else
10141       return false;
10142     break;
10143   case Intrinsic::ppc_altivec_vcmpgtub_p:
10144     CompareOpc = 518;
10145     isDot = true;
10146     break;
10147   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10148     CompareOpc = 582;
10149     isDot = true;
10150     break;
10151   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10152     CompareOpc = 646;
10153     isDot = true;
10154     break;
10155   case Intrinsic::ppc_altivec_vcmpgtud_p:
10156     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10157       CompareOpc = 711;
10158       isDot = true;
10159     } else
10160       return false;
10161     break;
10162 
10163   case Intrinsic::ppc_altivec_vcmpequq:
10164   case Intrinsic::ppc_altivec_vcmpgtsq:
10165   case Intrinsic::ppc_altivec_vcmpgtuq:
10166     if (!Subtarget.isISA3_1())
10167       return false;
10168     switch (IntrinsicID) {
10169     default:
10170       llvm_unreachable("Unknown comparison intrinsic.");
10171     case Intrinsic::ppc_altivec_vcmpequq:
10172       CompareOpc = 455;
10173       break;
10174     case Intrinsic::ppc_altivec_vcmpgtsq:
10175       CompareOpc = 903;
10176       break;
10177     case Intrinsic::ppc_altivec_vcmpgtuq:
10178       CompareOpc = 647;
10179       break;
10180     }
10181     break;
10182 
10183   // VSX predicate comparisons use the same infrastructure
10184   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10185   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10186   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10187   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10188   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10189   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10190     if (Subtarget.hasVSX()) {
10191       switch (IntrinsicID) {
10192       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10193         CompareOpc = 99;
10194         break;
10195       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10196         CompareOpc = 115;
10197         break;
10198       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10199         CompareOpc = 107;
10200         break;
10201       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10202         CompareOpc = 67;
10203         break;
10204       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10205         CompareOpc = 83;
10206         break;
10207       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10208         CompareOpc = 75;
10209         break;
10210       }
10211       isDot = true;
10212     } else
10213       return false;
10214     break;
10215 
10216   // Normal Comparisons.
10217   case Intrinsic::ppc_altivec_vcmpbfp:
10218     CompareOpc = 966;
10219     break;
10220   case Intrinsic::ppc_altivec_vcmpeqfp:
10221     CompareOpc = 198;
10222     break;
10223   case Intrinsic::ppc_altivec_vcmpequb:
10224     CompareOpc = 6;
10225     break;
10226   case Intrinsic::ppc_altivec_vcmpequh:
10227     CompareOpc = 70;
10228     break;
10229   case Intrinsic::ppc_altivec_vcmpequw:
10230     CompareOpc = 134;
10231     break;
10232   case Intrinsic::ppc_altivec_vcmpequd:
10233     if (Subtarget.hasP8Altivec())
10234       CompareOpc = 199;
10235     else
10236       return false;
10237     break;
10238   case Intrinsic::ppc_altivec_vcmpneb:
10239   case Intrinsic::ppc_altivec_vcmpneh:
10240   case Intrinsic::ppc_altivec_vcmpnew:
10241   case Intrinsic::ppc_altivec_vcmpnezb:
10242   case Intrinsic::ppc_altivec_vcmpnezh:
10243   case Intrinsic::ppc_altivec_vcmpnezw:
10244     if (Subtarget.hasP9Altivec())
10245       switch (IntrinsicID) {
10246       default:
10247         llvm_unreachable("Unknown comparison intrinsic.");
10248       case Intrinsic::ppc_altivec_vcmpneb:
10249         CompareOpc = 7;
10250         break;
10251       case Intrinsic::ppc_altivec_vcmpneh:
10252         CompareOpc = 71;
10253         break;
10254       case Intrinsic::ppc_altivec_vcmpnew:
10255         CompareOpc = 135;
10256         break;
10257       case Intrinsic::ppc_altivec_vcmpnezb:
10258         CompareOpc = 263;
10259         break;
10260       case Intrinsic::ppc_altivec_vcmpnezh:
10261         CompareOpc = 327;
10262         break;
10263       case Intrinsic::ppc_altivec_vcmpnezw:
10264         CompareOpc = 391;
10265         break;
10266       }
10267     else
10268       return false;
10269     break;
10270   case Intrinsic::ppc_altivec_vcmpgefp:
10271     CompareOpc = 454;
10272     break;
10273   case Intrinsic::ppc_altivec_vcmpgtfp:
10274     CompareOpc = 710;
10275     break;
10276   case Intrinsic::ppc_altivec_vcmpgtsb:
10277     CompareOpc = 774;
10278     break;
10279   case Intrinsic::ppc_altivec_vcmpgtsh:
10280     CompareOpc = 838;
10281     break;
10282   case Intrinsic::ppc_altivec_vcmpgtsw:
10283     CompareOpc = 902;
10284     break;
10285   case Intrinsic::ppc_altivec_vcmpgtsd:
10286     if (Subtarget.hasP8Altivec())
10287       CompareOpc = 967;
10288     else
10289       return false;
10290     break;
10291   case Intrinsic::ppc_altivec_vcmpgtub:
10292     CompareOpc = 518;
10293     break;
10294   case Intrinsic::ppc_altivec_vcmpgtuh:
10295     CompareOpc = 582;
10296     break;
10297   case Intrinsic::ppc_altivec_vcmpgtuw:
10298     CompareOpc = 646;
10299     break;
10300   case Intrinsic::ppc_altivec_vcmpgtud:
10301     if (Subtarget.hasP8Altivec())
10302       CompareOpc = 711;
10303     else
10304       return false;
10305     break;
10306   case Intrinsic::ppc_altivec_vcmpequq_p:
10307   case Intrinsic::ppc_altivec_vcmpgtsq_p:
10308   case Intrinsic::ppc_altivec_vcmpgtuq_p:
10309     if (!Subtarget.isISA3_1())
10310       return false;
10311     switch (IntrinsicID) {
10312     default:
10313       llvm_unreachable("Unknown comparison intrinsic.");
10314     case Intrinsic::ppc_altivec_vcmpequq_p:
10315       CompareOpc = 455;
10316       break;
10317     case Intrinsic::ppc_altivec_vcmpgtsq_p:
10318       CompareOpc = 903;
10319       break;
10320     case Intrinsic::ppc_altivec_vcmpgtuq_p:
10321       CompareOpc = 647;
10322       break;
10323     }
10324     isDot = true;
10325     break;
10326   }
10327   return true;
10328 }
10329 
10330 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10331 /// lower, do it, otherwise return null.
10332 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10333                                                    SelectionDAG &DAG) const {
10334   unsigned IntrinsicID =
10335     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10336 
10337   SDLoc dl(Op);
10338 
10339   switch (IntrinsicID) {
10340   case Intrinsic::thread_pointer:
10341     // Reads the thread pointer register, used for __builtin_thread_pointer.
10342     if (Subtarget.isPPC64())
10343       return DAG.getRegister(PPC::X13, MVT::i64);
10344     return DAG.getRegister(PPC::R2, MVT::i32);
10345 
10346   case Intrinsic::ppc_mma_disassemble_acc:
10347   case Intrinsic::ppc_vsx_disassemble_pair: {
10348     int NumVecs = 2;
10349     SDValue WideVec = Op.getOperand(1);
10350     if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
10351       NumVecs = 4;
10352       WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
10353     }
10354     SmallVector<SDValue, 4> RetOps;
10355     for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
10356       SDValue Extract = DAG.getNode(
10357           PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
10358           DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
10359                                                      : VecNo,
10360                           dl, getPointerTy(DAG.getDataLayout())));
10361       RetOps.push_back(Extract);
10362     }
10363     return DAG.getMergeValues(RetOps, dl);
10364   }
10365   case Intrinsic::ppc_compare_exp_lt:
10366   case Intrinsic::ppc_compare_exp_gt:
10367   case Intrinsic::ppc_compare_exp_eq:
10368   case Intrinsic::ppc_compare_exp_uo: {
10369     unsigned Pred;
10370     switch (IntrinsicID) {
10371     case Intrinsic::ppc_compare_exp_lt:
10372       Pred = PPC::PRED_LT;
10373       break;
10374     case Intrinsic::ppc_compare_exp_gt:
10375       Pred = PPC::PRED_GT;
10376       break;
10377     case Intrinsic::ppc_compare_exp_eq:
10378       Pred = PPC::PRED_EQ;
10379       break;
10380     case Intrinsic::ppc_compare_exp_uo:
10381       Pred = PPC::PRED_UN;
10382       break;
10383     }
10384     return SDValue(
10385         DAG.getMachineNode(
10386             PPC::SELECT_CC_I4, dl, MVT::i32,
10387             {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32,
10388                                         Op.getOperand(1), Op.getOperand(2)),
10389                      0),
10390              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10391              DAG.getTargetConstant(Pred, dl, MVT::i32)}),
10392         0);
10393   }
10394   case Intrinsic::ppc_test_data_class_d:
10395   case Intrinsic::ppc_test_data_class_f: {
10396     unsigned CmprOpc = PPC::XSTSTDCDP;
10397     if (IntrinsicID == Intrinsic::ppc_test_data_class_f)
10398       CmprOpc = PPC::XSTSTDCSP;
10399     return SDValue(
10400         DAG.getMachineNode(
10401             PPC::SELECT_CC_I4, dl, MVT::i32,
10402             {SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32, Op.getOperand(2),
10403                                         Op.getOperand(1)),
10404                      0),
10405              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10406              DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}),
10407         0);
10408   }
10409   }
10410 
10411   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10412   // opcode number of the comparison.
10413   int CompareOpc;
10414   bool isDot;
10415   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10416     return SDValue();    // Don't custom lower most intrinsics.
10417 
10418   // If this is a non-dot comparison, make the VCMP node and we are done.
10419   if (!isDot) {
10420     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10421                               Op.getOperand(1), Op.getOperand(2),
10422                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10423     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10424   }
10425 
10426   // Create the PPCISD altivec 'dot' comparison node.
10427   SDValue Ops[] = {
10428     Op.getOperand(2),  // LHS
10429     Op.getOperand(3),  // RHS
10430     DAG.getConstant(CompareOpc, dl, MVT::i32)
10431   };
10432   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10433   SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
10434 
10435   // Now that we have the comparison, emit a copy from the CR to a GPR.
10436   // This is flagged to the above dot comparison.
10437   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10438                                 DAG.getRegister(PPC::CR6, MVT::i32),
10439                                 CompNode.getValue(1));
10440 
10441   // Unpack the result based on how the target uses it.
10442   unsigned BitNo;   // Bit # of CR6.
10443   bool InvertBit;   // Invert result?
10444   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10445   default:  // Can't happen, don't crash on invalid number though.
10446   case 0:   // Return the value of the EQ bit of CR6.
10447     BitNo = 0; InvertBit = false;
10448     break;
10449   case 1:   // Return the inverted value of the EQ bit of CR6.
10450     BitNo = 0; InvertBit = true;
10451     break;
10452   case 2:   // Return the value of the LT bit of CR6.
10453     BitNo = 2; InvertBit = false;
10454     break;
10455   case 3:   // Return the inverted value of the LT bit of CR6.
10456     BitNo = 2; InvertBit = true;
10457     break;
10458   }
10459 
10460   // Shift the bit into the low position.
10461   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10462                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10463   // Isolate the bit.
10464   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10465                       DAG.getConstant(1, dl, MVT::i32));
10466 
10467   // If we are supposed to, toggle the bit.
10468   if (InvertBit)
10469     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10470                         DAG.getConstant(1, dl, MVT::i32));
10471   return Flags;
10472 }
10473 
10474 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10475                                                SelectionDAG &DAG) const {
10476   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10477   // the beginning of the argument list.
10478   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10479   SDLoc DL(Op);
10480   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10481   case Intrinsic::ppc_cfence: {
10482     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10483     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10484     SDValue Val = Op.getOperand(ArgStart + 1);
10485     EVT Ty = Val.getValueType();
10486     if (Ty == MVT::i128) {
10487       // FIXME: Testing one of two paired registers is sufficient to guarantee
10488       // ordering?
10489       Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val);
10490     }
10491     return SDValue(
10492         DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10493                            DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Val),
10494                            Op.getOperand(0)),
10495         0);
10496   }
10497   default:
10498     break;
10499   }
10500   return SDValue();
10501 }
10502 
10503 // Lower scalar BSWAP64 to xxbrd.
10504 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10505   SDLoc dl(Op);
10506   if (!Subtarget.isPPC64())
10507     return Op;
10508   // MTVSRDD
10509   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10510                    Op.getOperand(0));
10511   // XXBRD
10512   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10513   // MFVSRD
10514   int VectorIndex = 0;
10515   if (Subtarget.isLittleEndian())
10516     VectorIndex = 1;
10517   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10518                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10519   return Op;
10520 }
10521 
10522 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10523 // compared to a value that is atomically loaded (atomic loads zero-extend).
10524 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10525                                                 SelectionDAG &DAG) const {
10526   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10527          "Expecting an atomic compare-and-swap here.");
10528   SDLoc dl(Op);
10529   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10530   EVT MemVT = AtomicNode->getMemoryVT();
10531   if (MemVT.getSizeInBits() >= 32)
10532     return Op;
10533 
10534   SDValue CmpOp = Op.getOperand(2);
10535   // If this is already correctly zero-extended, leave it alone.
10536   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10537   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10538     return Op;
10539 
10540   // Clear the high bits of the compare operand.
10541   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10542   SDValue NewCmpOp =
10543     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10544                 DAG.getConstant(MaskVal, dl, MVT::i32));
10545 
10546   // Replace the existing compare operand with the properly zero-extended one.
10547   SmallVector<SDValue, 4> Ops;
10548   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10549     Ops.push_back(AtomicNode->getOperand(i));
10550   Ops[2] = NewCmpOp;
10551   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10552   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10553   auto NodeTy =
10554     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10555   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10556 }
10557 
10558 SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op,
10559                                                   SelectionDAG &DAG) const {
10560   AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode());
10561   EVT MemVT = N->getMemoryVT();
10562   assert(MemVT.getSimpleVT() == MVT::i128 &&
10563          "Expect quadword atomic operations");
10564   SDLoc dl(N);
10565   unsigned Opc = N->getOpcode();
10566   switch (Opc) {
10567   case ISD::ATOMIC_LOAD: {
10568     // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be
10569     // lowered to ppc instructions by pattern matching instruction selector.
10570     SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
10571     SmallVector<SDValue, 4> Ops{
10572         N->getOperand(0),
10573         DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)};
10574     for (int I = 1, E = N->getNumOperands(); I < E; ++I)
10575       Ops.push_back(N->getOperand(I));
10576     SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys,
10577                                                 Ops, MemVT, N->getMemOperand());
10578     SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal);
10579     SDValue ValHi =
10580         DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1));
10581     ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi,
10582                         DAG.getConstant(64, dl, MVT::i32));
10583     SDValue Val =
10584         DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi});
10585     return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other},
10586                        {Val, LoadedVal.getValue(2)});
10587   }
10588   case ISD::ATOMIC_STORE: {
10589     // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be
10590     // lowered to ppc instructions by pattern matching instruction selector.
10591     SDVTList Tys = DAG.getVTList(MVT::Other);
10592     SmallVector<SDValue, 4> Ops{
10593         N->getOperand(0),
10594         DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)};
10595     SDValue Val = N->getOperand(2);
10596     SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val);
10597     SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val,
10598                                 DAG.getConstant(64, dl, MVT::i32));
10599     ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi);
10600     Ops.push_back(ValLo);
10601     Ops.push_back(ValHi);
10602     Ops.push_back(N->getOperand(1));
10603     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT,
10604                                    N->getMemOperand());
10605   }
10606   default:
10607     llvm_unreachable("Unexpected atomic opcode");
10608   }
10609 }
10610 
10611 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10612                                                  SelectionDAG &DAG) const {
10613   SDLoc dl(Op);
10614   // Create a stack slot that is 16-byte aligned.
10615   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10616   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10617   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10618   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10619 
10620   // Store the input value into Value#0 of the stack slot.
10621   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10622                                MachinePointerInfo());
10623   // Load it out.
10624   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10625 }
10626 
10627 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10628                                                   SelectionDAG &DAG) const {
10629   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10630          "Should only be called for ISD::INSERT_VECTOR_ELT");
10631 
10632   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10633 
10634   EVT VT = Op.getValueType();
10635   SDLoc dl(Op);
10636   SDValue V1 = Op.getOperand(0);
10637   SDValue V2 = Op.getOperand(1);
10638   SDValue V3 = Op.getOperand(2);
10639 
10640   if (VT == MVT::v2f64 && C)
10641     return Op;
10642 
10643   if (Subtarget.isISA3_1()) {
10644     if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64())
10645       return SDValue();
10646     // On P10, we have legal lowering for constant and variable indices for
10647     // integer vectors.
10648     if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
10649         VT == MVT::v2i64)
10650       return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3);
10651     // For f32 and f64 vectors, we have legal lowering for variable indices.
10652     // For f32 we also have legal lowering when the element is loaded from
10653     // memory.
10654     if (VT == MVT::v4f32 || VT == MVT::v2f64) {
10655       if (!C || (VT == MVT::v4f32 && dyn_cast<LoadSDNode>(V2)))
10656         return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3);
10657       return Op;
10658     }
10659   }
10660 
10661   // Before P10, we have legal lowering for constant indices but not for
10662   // variable ones.
10663   if (!C)
10664     return SDValue();
10665 
10666   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10667   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10668     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10669     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10670     unsigned InsertAtElement = C->getZExtValue();
10671     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10672     if (Subtarget.isLittleEndian()) {
10673       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10674     }
10675     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10676                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10677   }
10678   return Op;
10679 }
10680 
10681 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10682                                            SelectionDAG &DAG) const {
10683   SDLoc dl(Op);
10684   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10685   SDValue LoadChain = LN->getChain();
10686   SDValue BasePtr = LN->getBasePtr();
10687   EVT VT = Op.getValueType();
10688 
10689   if (VT != MVT::v256i1 && VT != MVT::v512i1)
10690     return Op;
10691 
10692   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10693   // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
10694   // 2 or 4 vsx registers.
10695   assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
10696          "Type unsupported without MMA");
10697   assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10698          "Type unsupported without paired vector support");
10699   Align Alignment = LN->getAlign();
10700   SmallVector<SDValue, 4> Loads;
10701   SmallVector<SDValue, 4> LoadChains;
10702   unsigned NumVecs = VT.getSizeInBits() / 128;
10703   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10704     SDValue Load =
10705         DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
10706                     LN->getPointerInfo().getWithOffset(Idx * 16),
10707                     commonAlignment(Alignment, Idx * 16),
10708                     LN->getMemOperand()->getFlags(), LN->getAAInfo());
10709     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10710                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10711     Loads.push_back(Load);
10712     LoadChains.push_back(Load.getValue(1));
10713   }
10714   if (Subtarget.isLittleEndian()) {
10715     std::reverse(Loads.begin(), Loads.end());
10716     std::reverse(LoadChains.begin(), LoadChains.end());
10717   }
10718   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10719   SDValue Value =
10720       DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
10721                   dl, VT, Loads);
10722   SDValue RetOps[] = {Value, TF};
10723   return DAG.getMergeValues(RetOps, dl);
10724 }
10725 
10726 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10727                                             SelectionDAG &DAG) const {
10728   SDLoc dl(Op);
10729   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10730   SDValue StoreChain = SN->getChain();
10731   SDValue BasePtr = SN->getBasePtr();
10732   SDValue Value = SN->getValue();
10733   EVT StoreVT = Value.getValueType();
10734 
10735   if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
10736     return Op;
10737 
10738   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10739   // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
10740   // underlying registers individually.
10741   assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
10742          "Type unsupported without MMA");
10743   assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10744          "Type unsupported without paired vector support");
10745   Align Alignment = SN->getAlign();
10746   SmallVector<SDValue, 4> Stores;
10747   unsigned NumVecs = 2;
10748   if (StoreVT == MVT::v512i1) {
10749     Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
10750     NumVecs = 4;
10751   }
10752   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10753     unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
10754     SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
10755                               DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
10756     SDValue Store =
10757         DAG.getStore(StoreChain, dl, Elt, BasePtr,
10758                      SN->getPointerInfo().getWithOffset(Idx * 16),
10759                      commonAlignment(Alignment, Idx * 16),
10760                      SN->getMemOperand()->getFlags(), SN->getAAInfo());
10761     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10762                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10763     Stores.push_back(Store);
10764   }
10765   SDValue TF = DAG.getTokenFactor(dl, Stores);
10766   return TF;
10767 }
10768 
10769 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10770   SDLoc dl(Op);
10771   if (Op.getValueType() == MVT::v4i32) {
10772     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10773 
10774     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10775     // +16 as shift amt.
10776     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10777     SDValue RHSSwap =   // = vrlw RHS, 16
10778       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10779 
10780     // Shrinkify inputs to v8i16.
10781     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10782     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10783     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10784 
10785     // Low parts multiplied together, generating 32-bit results (we ignore the
10786     // top parts).
10787     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10788                                         LHS, RHS, DAG, dl, MVT::v4i32);
10789 
10790     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10791                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10792     // Shift the high parts up 16 bits.
10793     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10794                               Neg16, DAG, dl);
10795     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10796   } else if (Op.getValueType() == MVT::v16i8) {
10797     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10798     bool isLittleEndian = Subtarget.isLittleEndian();
10799 
10800     // Multiply the even 8-bit parts, producing 16-bit sums.
10801     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10802                                            LHS, RHS, DAG, dl, MVT::v8i16);
10803     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10804 
10805     // Multiply the odd 8-bit parts, producing 16-bit sums.
10806     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10807                                           LHS, RHS, DAG, dl, MVT::v8i16);
10808     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10809 
10810     // Merge the results together.  Because vmuleub and vmuloub are
10811     // instructions with a big-endian bias, we must reverse the
10812     // element numbering and reverse the meaning of "odd" and "even"
10813     // when generating little endian code.
10814     int Ops[16];
10815     for (unsigned i = 0; i != 8; ++i) {
10816       if (isLittleEndian) {
10817         Ops[i*2  ] = 2*i;
10818         Ops[i*2+1] = 2*i+16;
10819       } else {
10820         Ops[i*2  ] = 2*i+1;
10821         Ops[i*2+1] = 2*i+1+16;
10822       }
10823     }
10824     if (isLittleEndian)
10825       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10826     else
10827       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10828   } else {
10829     llvm_unreachable("Unknown mul to lower!");
10830   }
10831 }
10832 
10833 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10834   bool IsStrict = Op->isStrictFPOpcode();
10835   if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
10836       !Subtarget.hasP9Vector())
10837     return SDValue();
10838 
10839   return Op;
10840 }
10841 
10842 // Custom lowering for fpext vf32 to v2f64
10843 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10844 
10845   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10846          "Should only be called for ISD::FP_EXTEND");
10847 
10848   // FIXME: handle extends from half precision float vectors on P9.
10849   // We only want to custom lower an extend from v2f32 to v2f64.
10850   if (Op.getValueType() != MVT::v2f64 ||
10851       Op.getOperand(0).getValueType() != MVT::v2f32)
10852     return SDValue();
10853 
10854   SDLoc dl(Op);
10855   SDValue Op0 = Op.getOperand(0);
10856 
10857   switch (Op0.getOpcode()) {
10858   default:
10859     return SDValue();
10860   case ISD::EXTRACT_SUBVECTOR: {
10861     assert(Op0.getNumOperands() == 2 &&
10862            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10863            "Node should have 2 operands with second one being a constant!");
10864 
10865     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10866       return SDValue();
10867 
10868     // Custom lower is only done for high or low doubleword.
10869     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10870     if (Idx % 2 != 0)
10871       return SDValue();
10872 
10873     // Since input is v4f32, at this point Idx is either 0 or 2.
10874     // Shift to get the doubleword position we want.
10875     int DWord = Idx >> 1;
10876 
10877     // High and low word positions are different on little endian.
10878     if (Subtarget.isLittleEndian())
10879       DWord ^= 0x1;
10880 
10881     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10882                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10883   }
10884   case ISD::FADD:
10885   case ISD::FMUL:
10886   case ISD::FSUB: {
10887     SDValue NewLoad[2];
10888     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10889       // Ensure both input are loads.
10890       SDValue LdOp = Op0.getOperand(i);
10891       if (LdOp.getOpcode() != ISD::LOAD)
10892         return SDValue();
10893       // Generate new load node.
10894       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10895       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10896       NewLoad[i] = DAG.getMemIntrinsicNode(
10897           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10898           LD->getMemoryVT(), LD->getMemOperand());
10899     }
10900     SDValue NewOp =
10901         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10902                     NewLoad[1], Op0.getNode()->getFlags());
10903     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10904                        DAG.getConstant(0, dl, MVT::i32));
10905   }
10906   case ISD::LOAD: {
10907     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10908     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10909     SDValue NewLd = DAG.getMemIntrinsicNode(
10910         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10911         LD->getMemoryVT(), LD->getMemOperand());
10912     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10913                        DAG.getConstant(0, dl, MVT::i32));
10914   }
10915   }
10916   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10917 }
10918 
10919 /// LowerOperation - Provide custom lowering hooks for some operations.
10920 ///
10921 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10922   switch (Op.getOpcode()) {
10923   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10924   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10925   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10926   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10927   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10928   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10929   case ISD::STRICT_FSETCC:
10930   case ISD::STRICT_FSETCCS:
10931   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10932   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10933   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10934 
10935   case ISD::INLINEASM:
10936   case ISD::INLINEASM_BR:       return LowerINLINEASM(Op, DAG);
10937   // Variable argument lowering.
10938   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10939   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10940   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10941 
10942   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10943   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10944   case ISD::GET_DYNAMIC_AREA_OFFSET:
10945     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10946 
10947   // Exception handling lowering.
10948   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10949   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10950   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10951 
10952   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10953   case ISD::STORE:              return LowerSTORE(Op, DAG);
10954   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10955   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10956   case ISD::STRICT_FP_TO_UINT:
10957   case ISD::STRICT_FP_TO_SINT:
10958   case ISD::FP_TO_UINT:
10959   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10960   case ISD::STRICT_UINT_TO_FP:
10961   case ISD::STRICT_SINT_TO_FP:
10962   case ISD::UINT_TO_FP:
10963   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10964   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10965 
10966   // Lower 64-bit shifts.
10967   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10968   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10969   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10970 
10971   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
10972   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
10973 
10974   // Vector-related lowering.
10975   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10976   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10977   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10978   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10979   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10980   case ISD::MUL:                return LowerMUL(Op, DAG);
10981   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10982   case ISD::STRICT_FP_ROUND:
10983   case ISD::FP_ROUND:
10984     return LowerFP_ROUND(Op, DAG);
10985   case ISD::ROTL:               return LowerROTL(Op, DAG);
10986 
10987   // For counter-based loop handling.
10988   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10989 
10990   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10991 
10992   // Frame & Return address.
10993   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10994   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10995 
10996   case ISD::INTRINSIC_VOID:
10997     return LowerINTRINSIC_VOID(Op, DAG);
10998   case ISD::BSWAP:
10999     return LowerBSWAP(Op, DAG);
11000   case ISD::ATOMIC_CMP_SWAP:
11001     return LowerATOMIC_CMP_SWAP(Op, DAG);
11002   case ISD::ATOMIC_STORE:
11003     return LowerATOMIC_LOAD_STORE(Op, DAG);
11004   }
11005 }
11006 
11007 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
11008                                            SmallVectorImpl<SDValue>&Results,
11009                                            SelectionDAG &DAG) const {
11010   SDLoc dl(N);
11011   switch (N->getOpcode()) {
11012   default:
11013     llvm_unreachable("Do not know how to custom type legalize this operation!");
11014   case ISD::ATOMIC_LOAD: {
11015     SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG);
11016     Results.push_back(Res);
11017     Results.push_back(Res.getValue(1));
11018     break;
11019   }
11020   case ISD::READCYCLECOUNTER: {
11021     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11022     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
11023 
11024     Results.push_back(
11025         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
11026     Results.push_back(RTB.getValue(2));
11027     break;
11028   }
11029   case ISD::INTRINSIC_W_CHAIN: {
11030     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
11031         Intrinsic::loop_decrement)
11032       break;
11033 
11034     assert(N->getValueType(0) == MVT::i1 &&
11035            "Unexpected result type for CTR decrement intrinsic");
11036     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11037                                  N->getValueType(0));
11038     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
11039     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
11040                                  N->getOperand(1));
11041 
11042     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
11043     Results.push_back(NewInt.getValue(1));
11044     break;
11045   }
11046   case ISD::VAARG: {
11047     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
11048       return;
11049 
11050     EVT VT = N->getValueType(0);
11051 
11052     if (VT == MVT::i64) {
11053       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
11054 
11055       Results.push_back(NewNode);
11056       Results.push_back(NewNode.getValue(1));
11057     }
11058     return;
11059   }
11060   case ISD::STRICT_FP_TO_SINT:
11061   case ISD::STRICT_FP_TO_UINT:
11062   case ISD::FP_TO_SINT:
11063   case ISD::FP_TO_UINT:
11064     // LowerFP_TO_INT() can only handle f32 and f64.
11065     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
11066         MVT::ppcf128)
11067       return;
11068     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
11069     return;
11070   case ISD::TRUNCATE: {
11071     if (!N->getValueType(0).isVector())
11072       return;
11073     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
11074     if (Lowered)
11075       Results.push_back(Lowered);
11076     return;
11077   }
11078   case ISD::FSHL:
11079   case ISD::FSHR:
11080     // Don't handle funnel shifts here.
11081     return;
11082   case ISD::BITCAST:
11083     // Don't handle bitcast here.
11084     return;
11085   case ISD::FP_EXTEND:
11086     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
11087     if (Lowered)
11088       Results.push_back(Lowered);
11089     return;
11090   }
11091 }
11092 
11093 //===----------------------------------------------------------------------===//
11094 //  Other Lowering Code
11095 //===----------------------------------------------------------------------===//
11096 
11097 static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) {
11098   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11099   Function *Func = Intrinsic::getDeclaration(M, Id);
11100   return Builder.CreateCall(Func, {});
11101 }
11102 
11103 // The mappings for emitLeading/TrailingFence is taken from
11104 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11105 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11106                                                  Instruction *Inst,
11107                                                  AtomicOrdering Ord) const {
11108   if (Ord == AtomicOrdering::SequentiallyConsistent)
11109     return callIntrinsic(Builder, Intrinsic::ppc_sync);
11110   if (isReleaseOrStronger(Ord))
11111     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11112   return nullptr;
11113 }
11114 
11115 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11116                                                   Instruction *Inst,
11117                                                   AtomicOrdering Ord) const {
11118   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11119     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11120     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11121     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11122     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11123       return Builder.CreateCall(
11124           Intrinsic::getDeclaration(
11125               Builder.GetInsertBlock()->getParent()->getParent(),
11126               Intrinsic::ppc_cfence, {Inst->getType()}),
11127           {Inst});
11128     // FIXME: Can use isync for rmw operation.
11129     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11130   }
11131   return nullptr;
11132 }
11133 
11134 MachineBasicBlock *
11135 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11136                                     unsigned AtomicSize,
11137                                     unsigned BinOpcode,
11138                                     unsigned CmpOpcode,
11139                                     unsigned CmpPred) const {
11140   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11141   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11142 
11143   auto LoadMnemonic = PPC::LDARX;
11144   auto StoreMnemonic = PPC::STDCX;
11145   switch (AtomicSize) {
11146   default:
11147     llvm_unreachable("Unexpected size of atomic entity");
11148   case 1:
11149     LoadMnemonic = PPC::LBARX;
11150     StoreMnemonic = PPC::STBCX;
11151     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11152     break;
11153   case 2:
11154     LoadMnemonic = PPC::LHARX;
11155     StoreMnemonic = PPC::STHCX;
11156     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11157     break;
11158   case 4:
11159     LoadMnemonic = PPC::LWARX;
11160     StoreMnemonic = PPC::STWCX;
11161     break;
11162   case 8:
11163     LoadMnemonic = PPC::LDARX;
11164     StoreMnemonic = PPC::STDCX;
11165     break;
11166   }
11167 
11168   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11169   MachineFunction *F = BB->getParent();
11170   MachineFunction::iterator It = ++BB->getIterator();
11171 
11172   Register dest = MI.getOperand(0).getReg();
11173   Register ptrA = MI.getOperand(1).getReg();
11174   Register ptrB = MI.getOperand(2).getReg();
11175   Register incr = MI.getOperand(3).getReg();
11176   DebugLoc dl = MI.getDebugLoc();
11177 
11178   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11179   MachineBasicBlock *loop2MBB =
11180     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11181   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11182   F->insert(It, loopMBB);
11183   if (CmpOpcode)
11184     F->insert(It, loop2MBB);
11185   F->insert(It, exitMBB);
11186   exitMBB->splice(exitMBB->begin(), BB,
11187                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11188   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11189 
11190   MachineRegisterInfo &RegInfo = F->getRegInfo();
11191   Register TmpReg = (!BinOpcode) ? incr :
11192     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11193                                            : &PPC::GPRCRegClass);
11194 
11195   //  thisMBB:
11196   //   ...
11197   //   fallthrough --> loopMBB
11198   BB->addSuccessor(loopMBB);
11199 
11200   //  loopMBB:
11201   //   l[wd]arx dest, ptr
11202   //   add r0, dest, incr
11203   //   st[wd]cx. r0, ptr
11204   //   bne- loopMBB
11205   //   fallthrough --> exitMBB
11206 
11207   // For max/min...
11208   //  loopMBB:
11209   //   l[wd]arx dest, ptr
11210   //   cmpl?[wd] incr, dest
11211   //   bgt exitMBB
11212   //  loop2MBB:
11213   //   st[wd]cx. dest, ptr
11214   //   bne- loopMBB
11215   //   fallthrough --> exitMBB
11216 
11217   BB = loopMBB;
11218   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11219     .addReg(ptrA).addReg(ptrB);
11220   if (BinOpcode)
11221     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11222   if (CmpOpcode) {
11223     // Signed comparisons of byte or halfword values must be sign-extended.
11224     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11225       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11226       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11227               ExtReg).addReg(dest);
11228       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11229         .addReg(incr).addReg(ExtReg);
11230     } else
11231       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11232         .addReg(incr).addReg(dest);
11233 
11234     BuildMI(BB, dl, TII->get(PPC::BCC))
11235       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11236     BB->addSuccessor(loop2MBB);
11237     BB->addSuccessor(exitMBB);
11238     BB = loop2MBB;
11239   }
11240   BuildMI(BB, dl, TII->get(StoreMnemonic))
11241     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11242   BuildMI(BB, dl, TII->get(PPC::BCC))
11243     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11244   BB->addSuccessor(loopMBB);
11245   BB->addSuccessor(exitMBB);
11246 
11247   //  exitMBB:
11248   //   ...
11249   BB = exitMBB;
11250   return BB;
11251 }
11252 
11253 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) {
11254   switch(MI.getOpcode()) {
11255   default:
11256     return false;
11257   case PPC::COPY:
11258     return TII->isSignExtended(MI);
11259   case PPC::LHA:
11260   case PPC::LHA8:
11261   case PPC::LHAU:
11262   case PPC::LHAU8:
11263   case PPC::LHAUX:
11264   case PPC::LHAUX8:
11265   case PPC::LHAX:
11266   case PPC::LHAX8:
11267   case PPC::LWA:
11268   case PPC::LWAUX:
11269   case PPC::LWAX:
11270   case PPC::LWAX_32:
11271   case PPC::LWA_32:
11272   case PPC::PLHA:
11273   case PPC::PLHA8:
11274   case PPC::PLHA8pc:
11275   case PPC::PLHApc:
11276   case PPC::PLWA:
11277   case PPC::PLWA8:
11278   case PPC::PLWA8pc:
11279   case PPC::PLWApc:
11280   case PPC::EXTSB:
11281   case PPC::EXTSB8:
11282   case PPC::EXTSB8_32_64:
11283   case PPC::EXTSB8_rec:
11284   case PPC::EXTSB_rec:
11285   case PPC::EXTSH:
11286   case PPC::EXTSH8:
11287   case PPC::EXTSH8_32_64:
11288   case PPC::EXTSH8_rec:
11289   case PPC::EXTSH_rec:
11290   case PPC::EXTSW:
11291   case PPC::EXTSWSLI:
11292   case PPC::EXTSWSLI_32_64:
11293   case PPC::EXTSWSLI_32_64_rec:
11294   case PPC::EXTSWSLI_rec:
11295   case PPC::EXTSW_32:
11296   case PPC::EXTSW_32_64:
11297   case PPC::EXTSW_32_64_rec:
11298   case PPC::EXTSW_rec:
11299   case PPC::SRAW:
11300   case PPC::SRAWI:
11301   case PPC::SRAWI_rec:
11302   case PPC::SRAW_rec:
11303     return true;
11304   }
11305   return false;
11306 }
11307 
11308 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11309     MachineInstr &MI, MachineBasicBlock *BB,
11310     bool is8bit, // operation
11311     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11312   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11313   const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11314 
11315   // If this is a signed comparison and the value being compared is not known
11316   // to be sign extended, sign extend it here.
11317   DebugLoc dl = MI.getDebugLoc();
11318   MachineFunction *F = BB->getParent();
11319   MachineRegisterInfo &RegInfo = F->getRegInfo();
11320   Register incr = MI.getOperand(3).getReg();
11321   bool IsSignExtended = Register::isVirtualRegister(incr) &&
11322     isSignExtended(*RegInfo.getVRegDef(incr), TII);
11323 
11324   if (CmpOpcode == PPC::CMPW && !IsSignExtended) {
11325     Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11326     BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg)
11327         .addReg(MI.getOperand(3).getReg());
11328     MI.getOperand(3).setReg(ValueReg);
11329   }
11330   // If we support part-word atomic mnemonics, just use them
11331   if (Subtarget.hasPartwordAtomics())
11332     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11333                             CmpPred);
11334 
11335   // In 64 bit mode we have to use 64 bits for addresses, even though the
11336   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11337   // registers without caring whether they're 32 or 64, but here we're
11338   // doing actual arithmetic on the addresses.
11339   bool is64bit = Subtarget.isPPC64();
11340   bool isLittleEndian = Subtarget.isLittleEndian();
11341   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11342 
11343   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11344   MachineFunction::iterator It = ++BB->getIterator();
11345 
11346   Register dest = MI.getOperand(0).getReg();
11347   Register ptrA = MI.getOperand(1).getReg();
11348   Register ptrB = MI.getOperand(2).getReg();
11349 
11350   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11351   MachineBasicBlock *loop2MBB =
11352       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11353   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11354   F->insert(It, loopMBB);
11355   if (CmpOpcode)
11356     F->insert(It, loop2MBB);
11357   F->insert(It, exitMBB);
11358   exitMBB->splice(exitMBB->begin(), BB,
11359                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11360   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11361 
11362   const TargetRegisterClass *RC =
11363       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11364   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11365 
11366   Register PtrReg = RegInfo.createVirtualRegister(RC);
11367   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11368   Register ShiftReg =
11369       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11370   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11371   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11372   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11373   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11374   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11375   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11376   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11377   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11378   Register SrwDestReg = RegInfo.createVirtualRegister(GPRC);
11379   Register Ptr1Reg;
11380   Register TmpReg =
11381       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11382 
11383   //  thisMBB:
11384   //   ...
11385   //   fallthrough --> loopMBB
11386   BB->addSuccessor(loopMBB);
11387 
11388   // The 4-byte load must be aligned, while a char or short may be
11389   // anywhere in the word.  Hence all this nasty bookkeeping code.
11390   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11391   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11392   //   xori shift, shift1, 24 [16]
11393   //   rlwinm ptr, ptr1, 0, 0, 29
11394   //   slw incr2, incr, shift
11395   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11396   //   slw mask, mask2, shift
11397   //  loopMBB:
11398   //   lwarx tmpDest, ptr
11399   //   add tmp, tmpDest, incr2
11400   //   andc tmp2, tmpDest, mask
11401   //   and tmp3, tmp, mask
11402   //   or tmp4, tmp3, tmp2
11403   //   stwcx. tmp4, ptr
11404   //   bne- loopMBB
11405   //   fallthrough --> exitMBB
11406   //   srw SrwDest, tmpDest, shift
11407   //   rlwinm SrwDest, SrwDest, 0, 24 [16], 31
11408   if (ptrA != ZeroReg) {
11409     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11410     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11411         .addReg(ptrA)
11412         .addReg(ptrB);
11413   } else {
11414     Ptr1Reg = ptrB;
11415   }
11416   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11417   // mode.
11418   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11419       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11420       .addImm(3)
11421       .addImm(27)
11422       .addImm(is8bit ? 28 : 27);
11423   if (!isLittleEndian)
11424     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11425         .addReg(Shift1Reg)
11426         .addImm(is8bit ? 24 : 16);
11427   if (is64bit)
11428     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11429         .addReg(Ptr1Reg)
11430         .addImm(0)
11431         .addImm(61);
11432   else
11433     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11434         .addReg(Ptr1Reg)
11435         .addImm(0)
11436         .addImm(0)
11437         .addImm(29);
11438   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11439   if (is8bit)
11440     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11441   else {
11442     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11443     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11444         .addReg(Mask3Reg)
11445         .addImm(65535);
11446   }
11447   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11448       .addReg(Mask2Reg)
11449       .addReg(ShiftReg);
11450 
11451   BB = loopMBB;
11452   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11453       .addReg(ZeroReg)
11454       .addReg(PtrReg);
11455   if (BinOpcode)
11456     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11457         .addReg(Incr2Reg)
11458         .addReg(TmpDestReg);
11459   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11460       .addReg(TmpDestReg)
11461       .addReg(MaskReg);
11462   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11463   if (CmpOpcode) {
11464     // For unsigned comparisons, we can directly compare the shifted values.
11465     // For signed comparisons we shift and sign extend.
11466     Register SReg = RegInfo.createVirtualRegister(GPRC);
11467     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11468         .addReg(TmpDestReg)
11469         .addReg(MaskReg);
11470     unsigned ValueReg = SReg;
11471     unsigned CmpReg = Incr2Reg;
11472     if (CmpOpcode == PPC::CMPW) {
11473       ValueReg = RegInfo.createVirtualRegister(GPRC);
11474       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11475           .addReg(SReg)
11476           .addReg(ShiftReg);
11477       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11478       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11479           .addReg(ValueReg);
11480       ValueReg = ValueSReg;
11481       CmpReg = incr;
11482     }
11483     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11484         .addReg(CmpReg)
11485         .addReg(ValueReg);
11486     BuildMI(BB, dl, TII->get(PPC::BCC))
11487         .addImm(CmpPred)
11488         .addReg(PPC::CR0)
11489         .addMBB(exitMBB);
11490     BB->addSuccessor(loop2MBB);
11491     BB->addSuccessor(exitMBB);
11492     BB = loop2MBB;
11493   }
11494   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11495   BuildMI(BB, dl, TII->get(PPC::STWCX))
11496       .addReg(Tmp4Reg)
11497       .addReg(ZeroReg)
11498       .addReg(PtrReg);
11499   BuildMI(BB, dl, TII->get(PPC::BCC))
11500       .addImm(PPC::PRED_NE)
11501       .addReg(PPC::CR0)
11502       .addMBB(loopMBB);
11503   BB->addSuccessor(loopMBB);
11504   BB->addSuccessor(exitMBB);
11505 
11506   //  exitMBB:
11507   //   ...
11508   BB = exitMBB;
11509   // Since the shift amount is not a constant, we need to clear
11510   // the upper bits with a separate RLWINM.
11511   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest)
11512       .addReg(SrwDestReg)
11513       .addImm(0)
11514       .addImm(is8bit ? 24 : 16)
11515       .addImm(31);
11516   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg)
11517       .addReg(TmpDestReg)
11518       .addReg(ShiftReg);
11519   return BB;
11520 }
11521 
11522 llvm::MachineBasicBlock *
11523 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11524                                     MachineBasicBlock *MBB) const {
11525   DebugLoc DL = MI.getDebugLoc();
11526   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11527   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11528 
11529   MachineFunction *MF = MBB->getParent();
11530   MachineRegisterInfo &MRI = MF->getRegInfo();
11531 
11532   const BasicBlock *BB = MBB->getBasicBlock();
11533   MachineFunction::iterator I = ++MBB->getIterator();
11534 
11535   Register DstReg = MI.getOperand(0).getReg();
11536   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11537   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11538   Register mainDstReg = MRI.createVirtualRegister(RC);
11539   Register restoreDstReg = MRI.createVirtualRegister(RC);
11540 
11541   MVT PVT = getPointerTy(MF->getDataLayout());
11542   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11543          "Invalid Pointer Size!");
11544   // For v = setjmp(buf), we generate
11545   //
11546   // thisMBB:
11547   //  SjLjSetup mainMBB
11548   //  bl mainMBB
11549   //  v_restore = 1
11550   //  b sinkMBB
11551   //
11552   // mainMBB:
11553   //  buf[LabelOffset] = LR
11554   //  v_main = 0
11555   //
11556   // sinkMBB:
11557   //  v = phi(main, restore)
11558   //
11559 
11560   MachineBasicBlock *thisMBB = MBB;
11561   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11562   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11563   MF->insert(I, mainMBB);
11564   MF->insert(I, sinkMBB);
11565 
11566   MachineInstrBuilder MIB;
11567 
11568   // Transfer the remainder of BB and its successor edges to sinkMBB.
11569   sinkMBB->splice(sinkMBB->begin(), MBB,
11570                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11571   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11572 
11573   // Note that the structure of the jmp_buf used here is not compatible
11574   // with that used by libc, and is not designed to be. Specifically, it
11575   // stores only those 'reserved' registers that LLVM does not otherwise
11576   // understand how to spill. Also, by convention, by the time this
11577   // intrinsic is called, Clang has already stored the frame address in the
11578   // first slot of the buffer and stack address in the third. Following the
11579   // X86 target code, we'll store the jump address in the second slot. We also
11580   // need to save the TOC pointer (R2) to handle jumps between shared
11581   // libraries, and that will be stored in the fourth slot. The thread
11582   // identifier (R13) is not affected.
11583 
11584   // thisMBB:
11585   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11586   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11587   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11588 
11589   // Prepare IP either in reg.
11590   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11591   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11592   Register BufReg = MI.getOperand(1).getReg();
11593 
11594   if (Subtarget.is64BitELFABI()) {
11595     setUsesTOCBasePtr(*MBB->getParent());
11596     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11597               .addReg(PPC::X2)
11598               .addImm(TOCOffset)
11599               .addReg(BufReg)
11600               .cloneMemRefs(MI);
11601   }
11602 
11603   // Naked functions never have a base pointer, and so we use r1. For all
11604   // other functions, this decision must be delayed until during PEI.
11605   unsigned BaseReg;
11606   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11607     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11608   else
11609     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11610 
11611   MIB = BuildMI(*thisMBB, MI, DL,
11612                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11613             .addReg(BaseReg)
11614             .addImm(BPOffset)
11615             .addReg(BufReg)
11616             .cloneMemRefs(MI);
11617 
11618   // Setup
11619   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11620   MIB.addRegMask(TRI->getNoPreservedMask());
11621 
11622   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11623 
11624   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11625           .addMBB(mainMBB);
11626   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11627 
11628   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11629   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11630 
11631   // mainMBB:
11632   //  mainDstReg = 0
11633   MIB =
11634       BuildMI(mainMBB, DL,
11635               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11636 
11637   // Store IP
11638   if (Subtarget.isPPC64()) {
11639     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11640             .addReg(LabelReg)
11641             .addImm(LabelOffset)
11642             .addReg(BufReg);
11643   } else {
11644     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11645             .addReg(LabelReg)
11646             .addImm(LabelOffset)
11647             .addReg(BufReg);
11648   }
11649   MIB.cloneMemRefs(MI);
11650 
11651   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11652   mainMBB->addSuccessor(sinkMBB);
11653 
11654   // sinkMBB:
11655   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11656           TII->get(PPC::PHI), DstReg)
11657     .addReg(mainDstReg).addMBB(mainMBB)
11658     .addReg(restoreDstReg).addMBB(thisMBB);
11659 
11660   MI.eraseFromParent();
11661   return sinkMBB;
11662 }
11663 
11664 MachineBasicBlock *
11665 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11666                                      MachineBasicBlock *MBB) const {
11667   DebugLoc DL = MI.getDebugLoc();
11668   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11669 
11670   MachineFunction *MF = MBB->getParent();
11671   MachineRegisterInfo &MRI = MF->getRegInfo();
11672 
11673   MVT PVT = getPointerTy(MF->getDataLayout());
11674   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11675          "Invalid Pointer Size!");
11676 
11677   const TargetRegisterClass *RC =
11678     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11679   Register Tmp = MRI.createVirtualRegister(RC);
11680   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11681   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11682   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11683   unsigned BP =
11684       (PVT == MVT::i64)
11685           ? PPC::X30
11686           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11687                                                               : PPC::R30);
11688 
11689   MachineInstrBuilder MIB;
11690 
11691   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11692   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11693   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11694   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11695 
11696   Register BufReg = MI.getOperand(0).getReg();
11697 
11698   // Reload FP (the jumped-to function may not have had a
11699   // frame pointer, and if so, then its r31 will be restored
11700   // as necessary).
11701   if (PVT == MVT::i64) {
11702     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11703             .addImm(0)
11704             .addReg(BufReg);
11705   } else {
11706     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11707             .addImm(0)
11708             .addReg(BufReg);
11709   }
11710   MIB.cloneMemRefs(MI);
11711 
11712   // Reload IP
11713   if (PVT == MVT::i64) {
11714     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11715             .addImm(LabelOffset)
11716             .addReg(BufReg);
11717   } else {
11718     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11719             .addImm(LabelOffset)
11720             .addReg(BufReg);
11721   }
11722   MIB.cloneMemRefs(MI);
11723 
11724   // Reload SP
11725   if (PVT == MVT::i64) {
11726     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11727             .addImm(SPOffset)
11728             .addReg(BufReg);
11729   } else {
11730     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11731             .addImm(SPOffset)
11732             .addReg(BufReg);
11733   }
11734   MIB.cloneMemRefs(MI);
11735 
11736   // Reload BP
11737   if (PVT == MVT::i64) {
11738     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11739             .addImm(BPOffset)
11740             .addReg(BufReg);
11741   } else {
11742     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11743             .addImm(BPOffset)
11744             .addReg(BufReg);
11745   }
11746   MIB.cloneMemRefs(MI);
11747 
11748   // Reload TOC
11749   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11750     setUsesTOCBasePtr(*MBB->getParent());
11751     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11752               .addImm(TOCOffset)
11753               .addReg(BufReg)
11754               .cloneMemRefs(MI);
11755   }
11756 
11757   // Jump
11758   BuildMI(*MBB, MI, DL,
11759           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11760   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11761 
11762   MI.eraseFromParent();
11763   return MBB;
11764 }
11765 
11766 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11767   // If the function specifically requests inline stack probes, emit them.
11768   if (MF.getFunction().hasFnAttribute("probe-stack"))
11769     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11770            "inline-asm";
11771   return false;
11772 }
11773 
11774 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11775   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11776   unsigned StackAlign = TFI->getStackAlignment();
11777   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11778          "Unexpected stack alignment");
11779   // The default stack probe size is 4096 if the function has no
11780   // stack-probe-size attribute.
11781   unsigned StackProbeSize = 4096;
11782   const Function &Fn = MF.getFunction();
11783   if (Fn.hasFnAttribute("stack-probe-size"))
11784     Fn.getFnAttribute("stack-probe-size")
11785         .getValueAsString()
11786         .getAsInteger(0, StackProbeSize);
11787   // Round down to the stack alignment.
11788   StackProbeSize &= ~(StackAlign - 1);
11789   return StackProbeSize ? StackProbeSize : StackAlign;
11790 }
11791 
11792 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11793 // into three phases. In the first phase, it uses pseudo instruction
11794 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11795 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11796 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11797 // MaxCallFrameSize so that it can calculate correct data area pointer.
11798 MachineBasicBlock *
11799 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11800                                     MachineBasicBlock *MBB) const {
11801   const bool isPPC64 = Subtarget.isPPC64();
11802   MachineFunction *MF = MBB->getParent();
11803   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11804   DebugLoc DL = MI.getDebugLoc();
11805   const unsigned ProbeSize = getStackProbeSize(*MF);
11806   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11807   MachineRegisterInfo &MRI = MF->getRegInfo();
11808   // The CFG of probing stack looks as
11809   //         +-----+
11810   //         | MBB |
11811   //         +--+--+
11812   //            |
11813   //       +----v----+
11814   //  +--->+ TestMBB +---+
11815   //  |    +----+----+   |
11816   //  |         |        |
11817   //  |   +-----v----+   |
11818   //  +---+ BlockMBB |   |
11819   //      +----------+   |
11820   //                     |
11821   //       +---------+   |
11822   //       | TailMBB +<--+
11823   //       +---------+
11824   // In MBB, calculate previous frame pointer and final stack pointer.
11825   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11826   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11827   // TailMBB is spliced via \p MI.
11828   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11829   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11830   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11831 
11832   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11833   MF->insert(MBBIter, TestMBB);
11834   MF->insert(MBBIter, BlockMBB);
11835   MF->insert(MBBIter, TailMBB);
11836 
11837   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11838   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11839 
11840   Register DstReg = MI.getOperand(0).getReg();
11841   Register NegSizeReg = MI.getOperand(1).getReg();
11842   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11843   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11844   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11845   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11846 
11847   // Since value of NegSizeReg might be realigned in prologepilog, insert a
11848   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
11849   // NegSize.
11850   unsigned ProbeOpc;
11851   if (!MRI.hasOneNonDBGUse(NegSizeReg))
11852     ProbeOpc =
11853         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
11854   else
11855     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
11856     // and NegSizeReg will be allocated in the same phyreg to avoid
11857     // redundant copy when NegSizeReg has only one use which is current MI and
11858     // will be replaced by PREPARE_PROBED_ALLOCA then.
11859     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
11860                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
11861   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
11862       .addDef(ActualNegSizeReg)
11863       .addReg(NegSizeReg)
11864       .add(MI.getOperand(2))
11865       .add(MI.getOperand(3));
11866 
11867   // Calculate final stack pointer, which equals to SP + ActualNegSize.
11868   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
11869           FinalStackPtr)
11870       .addReg(SPReg)
11871       .addReg(ActualNegSizeReg);
11872 
11873   // Materialize a scratch register for update.
11874   int64_t NegProbeSize = -(int64_t)ProbeSize;
11875   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
11876   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11877   if (!isInt<16>(NegProbeSize)) {
11878     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11879     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
11880         .addImm(NegProbeSize >> 16);
11881     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
11882             ScratchReg)
11883         .addReg(TempReg)
11884         .addImm(NegProbeSize & 0xFFFF);
11885   } else
11886     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
11887         .addImm(NegProbeSize);
11888 
11889   {
11890     // Probing leading residual part.
11891     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11892     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
11893         .addReg(ActualNegSizeReg)
11894         .addReg(ScratchReg);
11895     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11896     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
11897         .addReg(Div)
11898         .addReg(ScratchReg);
11899     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11900     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
11901         .addReg(Mul)
11902         .addReg(ActualNegSizeReg);
11903     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11904         .addReg(FramePointer)
11905         .addReg(SPReg)
11906         .addReg(NegMod);
11907   }
11908 
11909   {
11910     // Remaining part should be multiple of ProbeSize.
11911     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
11912     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
11913         .addReg(SPReg)
11914         .addReg(FinalStackPtr);
11915     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
11916         .addImm(PPC::PRED_EQ)
11917         .addReg(CmpResult)
11918         .addMBB(TailMBB);
11919     TestMBB->addSuccessor(BlockMBB);
11920     TestMBB->addSuccessor(TailMBB);
11921   }
11922 
11923   {
11924     // Touch the block.
11925     // |P...|P...|P...
11926     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11927         .addReg(FramePointer)
11928         .addReg(SPReg)
11929         .addReg(ScratchReg);
11930     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
11931     BlockMBB->addSuccessor(TestMBB);
11932   }
11933 
11934   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
11935   // DYNAREAOFFSET pseudo instruction to get the future result.
11936   Register MaxCallFrameSizeReg =
11937       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11938   BuildMI(TailMBB, DL,
11939           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
11940           MaxCallFrameSizeReg)
11941       .add(MI.getOperand(2))
11942       .add(MI.getOperand(3));
11943   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
11944       .addReg(SPReg)
11945       .addReg(MaxCallFrameSizeReg);
11946 
11947   // Splice instructions after MI to TailMBB.
11948   TailMBB->splice(TailMBB->end(), MBB,
11949                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11950   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
11951   MBB->addSuccessor(TestMBB);
11952 
11953   // Delete the pseudo instruction.
11954   MI.eraseFromParent();
11955 
11956   ++NumDynamicAllocaProbed;
11957   return TailMBB;
11958 }
11959 
11960 MachineBasicBlock *
11961 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11962                                                MachineBasicBlock *BB) const {
11963   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11964       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11965     if (Subtarget.is64BitELFABI() &&
11966         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11967         !Subtarget.isUsingPCRelativeCalls()) {
11968       // Call lowering should have added an r2 operand to indicate a dependence
11969       // on the TOC base pointer value. It can't however, because there is no
11970       // way to mark the dependence as implicit there, and so the stackmap code
11971       // will confuse it with a regular operand. Instead, add the dependence
11972       // here.
11973       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11974     }
11975 
11976     return emitPatchPoint(MI, BB);
11977   }
11978 
11979   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11980       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11981     return emitEHSjLjSetJmp(MI, BB);
11982   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11983              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11984     return emitEHSjLjLongJmp(MI, BB);
11985   }
11986 
11987   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11988 
11989   // To "insert" these instructions we actually have to insert their
11990   // control-flow patterns.
11991   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11992   MachineFunction::iterator It = ++BB->getIterator();
11993 
11994   MachineFunction *F = BB->getParent();
11995 
11996   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11997       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11998       MI.getOpcode() == PPC::SELECT_I8) {
11999     SmallVector<MachineOperand, 2> Cond;
12000     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12001         MI.getOpcode() == PPC::SELECT_CC_I8)
12002       Cond.push_back(MI.getOperand(4));
12003     else
12004       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
12005     Cond.push_back(MI.getOperand(1));
12006 
12007     DebugLoc dl = MI.getDebugLoc();
12008     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
12009                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
12010   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
12011              MI.getOpcode() == PPC::SELECT_CC_F8 ||
12012              MI.getOpcode() == PPC::SELECT_CC_F16 ||
12013              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
12014              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
12015              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
12016              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
12017              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
12018              MI.getOpcode() == PPC::SELECT_CC_SPE ||
12019              MI.getOpcode() == PPC::SELECT_F4 ||
12020              MI.getOpcode() == PPC::SELECT_F8 ||
12021              MI.getOpcode() == PPC::SELECT_F16 ||
12022              MI.getOpcode() == PPC::SELECT_SPE ||
12023              MI.getOpcode() == PPC::SELECT_SPE4 ||
12024              MI.getOpcode() == PPC::SELECT_VRRC ||
12025              MI.getOpcode() == PPC::SELECT_VSFRC ||
12026              MI.getOpcode() == PPC::SELECT_VSSRC ||
12027              MI.getOpcode() == PPC::SELECT_VSRC) {
12028     // The incoming instruction knows the destination vreg to set, the
12029     // condition code register to branch on, the true/false values to
12030     // select between, and a branch opcode to use.
12031 
12032     //  thisMBB:
12033     //  ...
12034     //   TrueVal = ...
12035     //   cmpTY ccX, r1, r2
12036     //   bCC copy1MBB
12037     //   fallthrough --> copy0MBB
12038     MachineBasicBlock *thisMBB = BB;
12039     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12040     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12041     DebugLoc dl = MI.getDebugLoc();
12042     F->insert(It, copy0MBB);
12043     F->insert(It, sinkMBB);
12044 
12045     // Transfer the remainder of BB and its successor edges to sinkMBB.
12046     sinkMBB->splice(sinkMBB->begin(), BB,
12047                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12048     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12049 
12050     // Next, add the true and fallthrough blocks as its successors.
12051     BB->addSuccessor(copy0MBB);
12052     BB->addSuccessor(sinkMBB);
12053 
12054     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
12055         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
12056         MI.getOpcode() == PPC::SELECT_F16 ||
12057         MI.getOpcode() == PPC::SELECT_SPE4 ||
12058         MI.getOpcode() == PPC::SELECT_SPE ||
12059         MI.getOpcode() == PPC::SELECT_VRRC ||
12060         MI.getOpcode() == PPC::SELECT_VSFRC ||
12061         MI.getOpcode() == PPC::SELECT_VSSRC ||
12062         MI.getOpcode() == PPC::SELECT_VSRC) {
12063       BuildMI(BB, dl, TII->get(PPC::BC))
12064           .addReg(MI.getOperand(1).getReg())
12065           .addMBB(sinkMBB);
12066     } else {
12067       unsigned SelectPred = MI.getOperand(4).getImm();
12068       BuildMI(BB, dl, TII->get(PPC::BCC))
12069           .addImm(SelectPred)
12070           .addReg(MI.getOperand(1).getReg())
12071           .addMBB(sinkMBB);
12072     }
12073 
12074     //  copy0MBB:
12075     //   %FalseValue = ...
12076     //   # fallthrough to sinkMBB
12077     BB = copy0MBB;
12078 
12079     // Update machine-CFG edges
12080     BB->addSuccessor(sinkMBB);
12081 
12082     //  sinkMBB:
12083     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12084     //  ...
12085     BB = sinkMBB;
12086     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
12087         .addReg(MI.getOperand(3).getReg())
12088         .addMBB(copy0MBB)
12089         .addReg(MI.getOperand(2).getReg())
12090         .addMBB(thisMBB);
12091   } else if (MI.getOpcode() == PPC::ReadTB) {
12092     // To read the 64-bit time-base register on a 32-bit target, we read the
12093     // two halves. Should the counter have wrapped while it was being read, we
12094     // need to try again.
12095     // ...
12096     // readLoop:
12097     // mfspr Rx,TBU # load from TBU
12098     // mfspr Ry,TB  # load from TB
12099     // mfspr Rz,TBU # load from TBU
12100     // cmpw crX,Rx,Rz # check if 'old'='new'
12101     // bne readLoop   # branch if they're not equal
12102     // ...
12103 
12104     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
12105     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12106     DebugLoc dl = MI.getDebugLoc();
12107     F->insert(It, readMBB);
12108     F->insert(It, sinkMBB);
12109 
12110     // Transfer the remainder of BB and its successor edges to sinkMBB.
12111     sinkMBB->splice(sinkMBB->begin(), BB,
12112                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12113     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12114 
12115     BB->addSuccessor(readMBB);
12116     BB = readMBB;
12117 
12118     MachineRegisterInfo &RegInfo = F->getRegInfo();
12119     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
12120     Register LoReg = MI.getOperand(0).getReg();
12121     Register HiReg = MI.getOperand(1).getReg();
12122 
12123     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
12124     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
12125     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
12126 
12127     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12128 
12129     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
12130         .addReg(HiReg)
12131         .addReg(ReadAgainReg);
12132     BuildMI(BB, dl, TII->get(PPC::BCC))
12133         .addImm(PPC::PRED_NE)
12134         .addReg(CmpReg)
12135         .addMBB(readMBB);
12136 
12137     BB->addSuccessor(readMBB);
12138     BB->addSuccessor(sinkMBB);
12139   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
12140     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
12141   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
12142     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
12143   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
12144     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
12145   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
12146     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
12147 
12148   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
12149     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
12150   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
12151     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
12152   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
12153     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
12154   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
12155     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
12156 
12157   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
12158     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
12159   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
12160     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
12161   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
12162     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
12163   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
12164     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
12165 
12166   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
12167     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
12168   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
12169     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
12170   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
12171     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
12172   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
12173     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
12174 
12175   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
12176     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
12177   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
12178     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
12179   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
12180     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
12181   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
12182     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
12183 
12184   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
12185     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
12186   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
12187     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
12188   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
12189     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
12190   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
12191     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
12192 
12193   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
12194     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
12195   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
12196     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
12197   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
12198     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
12199   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
12200     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
12201 
12202   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
12203     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
12204   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
12205     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
12206   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
12207     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
12208   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
12209     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
12210 
12211   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
12212     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
12213   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
12214     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
12215   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
12216     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
12217   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
12218     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
12219 
12220   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
12221     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
12222   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
12223     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
12224   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
12225     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
12226   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
12227     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
12228 
12229   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
12230     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
12231   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
12232     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
12233   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
12234     BB = EmitAtomicBinary(MI, BB, 4, 0);
12235   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
12236     BB = EmitAtomicBinary(MI, BB, 8, 0);
12237   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
12238            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
12239            (Subtarget.hasPartwordAtomics() &&
12240             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
12241            (Subtarget.hasPartwordAtomics() &&
12242             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
12243     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
12244 
12245     auto LoadMnemonic = PPC::LDARX;
12246     auto StoreMnemonic = PPC::STDCX;
12247     switch (MI.getOpcode()) {
12248     default:
12249       llvm_unreachable("Compare and swap of unknown size");
12250     case PPC::ATOMIC_CMP_SWAP_I8:
12251       LoadMnemonic = PPC::LBARX;
12252       StoreMnemonic = PPC::STBCX;
12253       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12254       break;
12255     case PPC::ATOMIC_CMP_SWAP_I16:
12256       LoadMnemonic = PPC::LHARX;
12257       StoreMnemonic = PPC::STHCX;
12258       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12259       break;
12260     case PPC::ATOMIC_CMP_SWAP_I32:
12261       LoadMnemonic = PPC::LWARX;
12262       StoreMnemonic = PPC::STWCX;
12263       break;
12264     case PPC::ATOMIC_CMP_SWAP_I64:
12265       LoadMnemonic = PPC::LDARX;
12266       StoreMnemonic = PPC::STDCX;
12267       break;
12268     }
12269     Register dest = MI.getOperand(0).getReg();
12270     Register ptrA = MI.getOperand(1).getReg();
12271     Register ptrB = MI.getOperand(2).getReg();
12272     Register oldval = MI.getOperand(3).getReg();
12273     Register newval = MI.getOperand(4).getReg();
12274     DebugLoc dl = MI.getDebugLoc();
12275 
12276     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12277     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12278     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12279     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12280     F->insert(It, loop1MBB);
12281     F->insert(It, loop2MBB);
12282     F->insert(It, midMBB);
12283     F->insert(It, exitMBB);
12284     exitMBB->splice(exitMBB->begin(), BB,
12285                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12286     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12287 
12288     //  thisMBB:
12289     //   ...
12290     //   fallthrough --> loopMBB
12291     BB->addSuccessor(loop1MBB);
12292 
12293     // loop1MBB:
12294     //   l[bhwd]arx dest, ptr
12295     //   cmp[wd] dest, oldval
12296     //   bne- midMBB
12297     // loop2MBB:
12298     //   st[bhwd]cx. newval, ptr
12299     //   bne- loopMBB
12300     //   b exitBB
12301     // midMBB:
12302     //   st[bhwd]cx. dest, ptr
12303     // exitBB:
12304     BB = loop1MBB;
12305     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12306     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12307         .addReg(oldval)
12308         .addReg(dest);
12309     BuildMI(BB, dl, TII->get(PPC::BCC))
12310         .addImm(PPC::PRED_NE)
12311         .addReg(PPC::CR0)
12312         .addMBB(midMBB);
12313     BB->addSuccessor(loop2MBB);
12314     BB->addSuccessor(midMBB);
12315 
12316     BB = loop2MBB;
12317     BuildMI(BB, dl, TII->get(StoreMnemonic))
12318         .addReg(newval)
12319         .addReg(ptrA)
12320         .addReg(ptrB);
12321     BuildMI(BB, dl, TII->get(PPC::BCC))
12322         .addImm(PPC::PRED_NE)
12323         .addReg(PPC::CR0)
12324         .addMBB(loop1MBB);
12325     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12326     BB->addSuccessor(loop1MBB);
12327     BB->addSuccessor(exitMBB);
12328 
12329     BB = midMBB;
12330     BuildMI(BB, dl, TII->get(StoreMnemonic))
12331         .addReg(dest)
12332         .addReg(ptrA)
12333         .addReg(ptrB);
12334     BB->addSuccessor(exitMBB);
12335 
12336     //  exitMBB:
12337     //   ...
12338     BB = exitMBB;
12339   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12340              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12341     // We must use 64-bit registers for addresses when targeting 64-bit,
12342     // since we're actually doing arithmetic on them.  Other registers
12343     // can be 32-bit.
12344     bool is64bit = Subtarget.isPPC64();
12345     bool isLittleEndian = Subtarget.isLittleEndian();
12346     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12347 
12348     Register dest = MI.getOperand(0).getReg();
12349     Register ptrA = MI.getOperand(1).getReg();
12350     Register ptrB = MI.getOperand(2).getReg();
12351     Register oldval = MI.getOperand(3).getReg();
12352     Register newval = MI.getOperand(4).getReg();
12353     DebugLoc dl = MI.getDebugLoc();
12354 
12355     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12356     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12357     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12358     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12359     F->insert(It, loop1MBB);
12360     F->insert(It, loop2MBB);
12361     F->insert(It, midMBB);
12362     F->insert(It, exitMBB);
12363     exitMBB->splice(exitMBB->begin(), BB,
12364                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12365     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12366 
12367     MachineRegisterInfo &RegInfo = F->getRegInfo();
12368     const TargetRegisterClass *RC =
12369         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12370     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12371 
12372     Register PtrReg = RegInfo.createVirtualRegister(RC);
12373     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12374     Register ShiftReg =
12375         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12376     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12377     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12378     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12379     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12380     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12381     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12382     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12383     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12384     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12385     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12386     Register Ptr1Reg;
12387     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12388     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12389     //  thisMBB:
12390     //   ...
12391     //   fallthrough --> loopMBB
12392     BB->addSuccessor(loop1MBB);
12393 
12394     // The 4-byte load must be aligned, while a char or short may be
12395     // anywhere in the word.  Hence all this nasty bookkeeping code.
12396     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12397     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12398     //   xori shift, shift1, 24 [16]
12399     //   rlwinm ptr, ptr1, 0, 0, 29
12400     //   slw newval2, newval, shift
12401     //   slw oldval2, oldval,shift
12402     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12403     //   slw mask, mask2, shift
12404     //   and newval3, newval2, mask
12405     //   and oldval3, oldval2, mask
12406     // loop1MBB:
12407     //   lwarx tmpDest, ptr
12408     //   and tmp, tmpDest, mask
12409     //   cmpw tmp, oldval3
12410     //   bne- midMBB
12411     // loop2MBB:
12412     //   andc tmp2, tmpDest, mask
12413     //   or tmp4, tmp2, newval3
12414     //   stwcx. tmp4, ptr
12415     //   bne- loop1MBB
12416     //   b exitBB
12417     // midMBB:
12418     //   stwcx. tmpDest, ptr
12419     // exitBB:
12420     //   srw dest, tmpDest, shift
12421     if (ptrA != ZeroReg) {
12422       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12423       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12424           .addReg(ptrA)
12425           .addReg(ptrB);
12426     } else {
12427       Ptr1Reg = ptrB;
12428     }
12429 
12430     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12431     // mode.
12432     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12433         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12434         .addImm(3)
12435         .addImm(27)
12436         .addImm(is8bit ? 28 : 27);
12437     if (!isLittleEndian)
12438       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12439           .addReg(Shift1Reg)
12440           .addImm(is8bit ? 24 : 16);
12441     if (is64bit)
12442       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12443           .addReg(Ptr1Reg)
12444           .addImm(0)
12445           .addImm(61);
12446     else
12447       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12448           .addReg(Ptr1Reg)
12449           .addImm(0)
12450           .addImm(0)
12451           .addImm(29);
12452     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12453         .addReg(newval)
12454         .addReg(ShiftReg);
12455     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12456         .addReg(oldval)
12457         .addReg(ShiftReg);
12458     if (is8bit)
12459       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12460     else {
12461       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12462       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12463           .addReg(Mask3Reg)
12464           .addImm(65535);
12465     }
12466     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12467         .addReg(Mask2Reg)
12468         .addReg(ShiftReg);
12469     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12470         .addReg(NewVal2Reg)
12471         .addReg(MaskReg);
12472     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12473         .addReg(OldVal2Reg)
12474         .addReg(MaskReg);
12475 
12476     BB = loop1MBB;
12477     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12478         .addReg(ZeroReg)
12479         .addReg(PtrReg);
12480     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12481         .addReg(TmpDestReg)
12482         .addReg(MaskReg);
12483     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12484         .addReg(TmpReg)
12485         .addReg(OldVal3Reg);
12486     BuildMI(BB, dl, TII->get(PPC::BCC))
12487         .addImm(PPC::PRED_NE)
12488         .addReg(PPC::CR0)
12489         .addMBB(midMBB);
12490     BB->addSuccessor(loop2MBB);
12491     BB->addSuccessor(midMBB);
12492 
12493     BB = loop2MBB;
12494     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12495         .addReg(TmpDestReg)
12496         .addReg(MaskReg);
12497     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12498         .addReg(Tmp2Reg)
12499         .addReg(NewVal3Reg);
12500     BuildMI(BB, dl, TII->get(PPC::STWCX))
12501         .addReg(Tmp4Reg)
12502         .addReg(ZeroReg)
12503         .addReg(PtrReg);
12504     BuildMI(BB, dl, TII->get(PPC::BCC))
12505         .addImm(PPC::PRED_NE)
12506         .addReg(PPC::CR0)
12507         .addMBB(loop1MBB);
12508     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12509     BB->addSuccessor(loop1MBB);
12510     BB->addSuccessor(exitMBB);
12511 
12512     BB = midMBB;
12513     BuildMI(BB, dl, TII->get(PPC::STWCX))
12514         .addReg(TmpDestReg)
12515         .addReg(ZeroReg)
12516         .addReg(PtrReg);
12517     BB->addSuccessor(exitMBB);
12518 
12519     //  exitMBB:
12520     //   ...
12521     BB = exitMBB;
12522     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12523         .addReg(TmpReg)
12524         .addReg(ShiftReg);
12525   } else if (MI.getOpcode() == PPC::FADDrtz) {
12526     // This pseudo performs an FADD with rounding mode temporarily forced
12527     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12528     // is not modeled at the SelectionDAG level.
12529     Register Dest = MI.getOperand(0).getReg();
12530     Register Src1 = MI.getOperand(1).getReg();
12531     Register Src2 = MI.getOperand(2).getReg();
12532     DebugLoc dl = MI.getDebugLoc();
12533 
12534     MachineRegisterInfo &RegInfo = F->getRegInfo();
12535     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12536 
12537     // Save FPSCR value.
12538     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12539 
12540     // Set rounding mode to round-to-zero.
12541     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12542         .addImm(31)
12543         .addReg(PPC::RM, RegState::ImplicitDefine);
12544 
12545     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12546         .addImm(30)
12547         .addReg(PPC::RM, RegState::ImplicitDefine);
12548 
12549     // Perform addition.
12550     auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
12551                    .addReg(Src1)
12552                    .addReg(Src2);
12553     if (MI.getFlag(MachineInstr::NoFPExcept))
12554       MIB.setMIFlag(MachineInstr::NoFPExcept);
12555 
12556     // Restore FPSCR value.
12557     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12558   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12559              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12560              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12561              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12562     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12563                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12564                           ? PPC::ANDI8_rec
12565                           : PPC::ANDI_rec;
12566     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12567                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12568 
12569     MachineRegisterInfo &RegInfo = F->getRegInfo();
12570     Register Dest = RegInfo.createVirtualRegister(
12571         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12572 
12573     DebugLoc Dl = MI.getDebugLoc();
12574     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12575         .addReg(MI.getOperand(1).getReg())
12576         .addImm(1);
12577     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12578             MI.getOperand(0).getReg())
12579         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12580   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12581     DebugLoc Dl = MI.getDebugLoc();
12582     MachineRegisterInfo &RegInfo = F->getRegInfo();
12583     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12584     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12585     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12586             MI.getOperand(0).getReg())
12587         .addReg(CRReg);
12588   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12589     DebugLoc Dl = MI.getDebugLoc();
12590     unsigned Imm = MI.getOperand(1).getImm();
12591     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12592     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12593             MI.getOperand(0).getReg())
12594         .addReg(PPC::CR0EQ);
12595   } else if (MI.getOpcode() == PPC::SETRNDi) {
12596     DebugLoc dl = MI.getDebugLoc();
12597     Register OldFPSCRReg = MI.getOperand(0).getReg();
12598 
12599     // Save FPSCR value.
12600     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12601 
12602     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12603     // the following settings:
12604     //   00 Round to nearest
12605     //   01 Round to 0
12606     //   10 Round to +inf
12607     //   11 Round to -inf
12608 
12609     // When the operand is immediate, using the two least significant bits of
12610     // the immediate to set the bits 62:63 of FPSCR.
12611     unsigned Mode = MI.getOperand(1).getImm();
12612     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12613         .addImm(31)
12614         .addReg(PPC::RM, RegState::ImplicitDefine);
12615 
12616     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12617         .addImm(30)
12618         .addReg(PPC::RM, RegState::ImplicitDefine);
12619   } else if (MI.getOpcode() == PPC::SETRND) {
12620     DebugLoc dl = MI.getDebugLoc();
12621 
12622     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12623     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12624     // If the target doesn't have DirectMove, we should use stack to do the
12625     // conversion, because the target doesn't have the instructions like mtvsrd
12626     // or mfvsrd to do this conversion directly.
12627     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12628       if (Subtarget.hasDirectMove()) {
12629         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12630           .addReg(SrcReg);
12631       } else {
12632         // Use stack to do the register copy.
12633         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12634         MachineRegisterInfo &RegInfo = F->getRegInfo();
12635         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12636         if (RC == &PPC::F8RCRegClass) {
12637           // Copy register from F8RCRegClass to G8RCRegclass.
12638           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12639                  "Unsupported RegClass.");
12640 
12641           StoreOp = PPC::STFD;
12642           LoadOp = PPC::LD;
12643         } else {
12644           // Copy register from G8RCRegClass to F8RCRegclass.
12645           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12646                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12647                  "Unsupported RegClass.");
12648         }
12649 
12650         MachineFrameInfo &MFI = F->getFrameInfo();
12651         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12652 
12653         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12654             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12655             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12656             MFI.getObjectAlign(FrameIdx));
12657 
12658         // Store the SrcReg into the stack.
12659         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12660           .addReg(SrcReg)
12661           .addImm(0)
12662           .addFrameIndex(FrameIdx)
12663           .addMemOperand(MMOStore);
12664 
12665         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12666             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12667             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12668             MFI.getObjectAlign(FrameIdx));
12669 
12670         // Load from the stack where SrcReg is stored, and save to DestReg,
12671         // so we have done the RegClass conversion from RegClass::SrcReg to
12672         // RegClass::DestReg.
12673         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12674           .addImm(0)
12675           .addFrameIndex(FrameIdx)
12676           .addMemOperand(MMOLoad);
12677       }
12678     };
12679 
12680     Register OldFPSCRReg = MI.getOperand(0).getReg();
12681 
12682     // Save FPSCR value.
12683     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12684 
12685     // When the operand is gprc register, use two least significant bits of the
12686     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12687     //
12688     // copy OldFPSCRTmpReg, OldFPSCRReg
12689     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12690     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12691     // copy NewFPSCRReg, NewFPSCRTmpReg
12692     // mtfsf 255, NewFPSCRReg
12693     MachineOperand SrcOp = MI.getOperand(1);
12694     MachineRegisterInfo &RegInfo = F->getRegInfo();
12695     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12696 
12697     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12698 
12699     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12700     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12701 
12702     // The first operand of INSERT_SUBREG should be a register which has
12703     // subregisters, we only care about its RegClass, so we should use an
12704     // IMPLICIT_DEF register.
12705     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12706     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12707       .addReg(ImDefReg)
12708       .add(SrcOp)
12709       .addImm(1);
12710 
12711     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12712     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12713       .addReg(OldFPSCRTmpReg)
12714       .addReg(ExtSrcReg)
12715       .addImm(0)
12716       .addImm(62);
12717 
12718     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12719     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12720 
12721     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12722     // bits of FPSCR.
12723     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12724       .addImm(255)
12725       .addReg(NewFPSCRReg)
12726       .addImm(0)
12727       .addImm(0);
12728   } else if (MI.getOpcode() == PPC::SETFLM) {
12729     DebugLoc Dl = MI.getDebugLoc();
12730 
12731     // Result of setflm is previous FPSCR content, so we need to save it first.
12732     Register OldFPSCRReg = MI.getOperand(0).getReg();
12733     BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12734 
12735     // Put bits in 32:63 to FPSCR.
12736     Register NewFPSCRReg = MI.getOperand(1).getReg();
12737     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12738         .addImm(255)
12739         .addReg(NewFPSCRReg)
12740         .addImm(0)
12741         .addImm(0);
12742   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12743              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12744     return emitProbedAlloca(MI, BB);
12745   } else if (MI.getOpcode() == PPC::SPLIT_QUADWORD) {
12746     DebugLoc DL = MI.getDebugLoc();
12747     Register Src = MI.getOperand(2).getReg();
12748     Register Lo = MI.getOperand(0).getReg();
12749     Register Hi = MI.getOperand(1).getReg();
12750     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12751         .addDef(Lo)
12752         .addUse(Src, 0, PPC::sub_gp8_x1);
12753     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12754         .addDef(Hi)
12755         .addUse(Src, 0, PPC::sub_gp8_x0);
12756   } else if (MI.getOpcode() == PPC::LQX_PSEUDO ||
12757              MI.getOpcode() == PPC::STQX_PSEUDO) {
12758     DebugLoc DL = MI.getDebugLoc();
12759     // Ptr is used as the ptr_rc_no_r0 part
12760     // of LQ/STQ's memory operand and adding result of RA and RB,
12761     // so it has to be g8rc_and_g8rc_nox0.
12762     Register Ptr =
12763         F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
12764     Register Val = MI.getOperand(0).getReg();
12765     Register RA = MI.getOperand(1).getReg();
12766     Register RB = MI.getOperand(2).getReg();
12767     BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB);
12768     BuildMI(*BB, MI, DL,
12769             MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ)
12770                                               : TII->get(PPC::STQ))
12771         .addReg(Val, MI.getOpcode() == PPC::LQX_PSEUDO ? RegState::Define : 0)
12772         .addImm(0)
12773         .addReg(Ptr);
12774   } else {
12775     llvm_unreachable("Unexpected instr type to insert");
12776   }
12777 
12778   MI.eraseFromParent(); // The pseudo instruction is gone now.
12779   return BB;
12780 }
12781 
12782 //===----------------------------------------------------------------------===//
12783 // Target Optimization Hooks
12784 //===----------------------------------------------------------------------===//
12785 
12786 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12787   // For the estimates, convergence is quadratic, so we essentially double the
12788   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12789   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12790   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12791   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12792   if (VT.getScalarType() == MVT::f64)
12793     RefinementSteps++;
12794   return RefinementSteps;
12795 }
12796 
12797 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
12798                                             const DenormalMode &Mode) const {
12799   // We only have VSX Vector Test for software Square Root.
12800   EVT VT = Op.getValueType();
12801   if (!isTypeLegal(MVT::i1) ||
12802       (VT != MVT::f64 &&
12803        ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
12804     return TargetLowering::getSqrtInputTest(Op, DAG, Mode);
12805 
12806   SDLoc DL(Op);
12807   // The output register of FTSQRT is CR field.
12808   SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
12809   // ftsqrt BF,FRB
12810   // Let e_b be the unbiased exponent of the double-precision
12811   // floating-point operand in register FRB.
12812   // fe_flag is set to 1 if either of the following conditions occurs.
12813   //   - The double-precision floating-point operand in register FRB is a zero,
12814   //     a NaN, or an infinity, or a negative value.
12815   //   - e_b is less than or equal to -970.
12816   // Otherwise fe_flag is set to 0.
12817   // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
12818   // not eligible for iteration. (zero/negative/infinity/nan or unbiased
12819   // exponent is less than -970)
12820   SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
12821   return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
12822                                     FTSQRT, SRIdxVal),
12823                  0);
12824 }
12825 
12826 SDValue
12827 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
12828                                                SelectionDAG &DAG) const {
12829   // We only have VSX Vector Square Root.
12830   EVT VT = Op.getValueType();
12831   if (VT != MVT::f64 &&
12832       ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
12833     return TargetLowering::getSqrtResultForDenormInput(Op, DAG);
12834 
12835   return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
12836 }
12837 
12838 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12839                                            int Enabled, int &RefinementSteps,
12840                                            bool &UseOneConstNR,
12841                                            bool Reciprocal) const {
12842   EVT VT = Operand.getValueType();
12843   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12844       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12845       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12846       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12847     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12848       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12849 
12850     // The Newton-Raphson computation with a single constant does not provide
12851     // enough accuracy on some CPUs.
12852     UseOneConstNR = !Subtarget.needsTwoConstNR();
12853     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12854   }
12855   return SDValue();
12856 }
12857 
12858 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12859                                             int Enabled,
12860                                             int &RefinementSteps) const {
12861   EVT VT = Operand.getValueType();
12862   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12863       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12864       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12865       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12866     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12867       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12868     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12869   }
12870   return SDValue();
12871 }
12872 
12873 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12874   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12875   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12876   // enabled for division), this functionality is redundant with the default
12877   // combiner logic (once the division -> reciprocal/multiply transformation
12878   // has taken place). As a result, this matters more for older cores than for
12879   // newer ones.
12880 
12881   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12882   // reciprocal if there are two or more FDIVs (for embedded cores with only
12883   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12884   switch (Subtarget.getCPUDirective()) {
12885   default:
12886     return 3;
12887   case PPC::DIR_440:
12888   case PPC::DIR_A2:
12889   case PPC::DIR_E500:
12890   case PPC::DIR_E500mc:
12891   case PPC::DIR_E5500:
12892     return 2;
12893   }
12894 }
12895 
12896 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12897 // collapsed, and so we need to look through chains of them.
12898 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12899                                      int64_t& Offset, SelectionDAG &DAG) {
12900   if (DAG.isBaseWithConstantOffset(Loc)) {
12901     Base = Loc.getOperand(0);
12902     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12903 
12904     // The base might itself be a base plus an offset, and if so, accumulate
12905     // that as well.
12906     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12907   }
12908 }
12909 
12910 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12911                             unsigned Bytes, int Dist,
12912                             SelectionDAG &DAG) {
12913   if (VT.getSizeInBits() / 8 != Bytes)
12914     return false;
12915 
12916   SDValue BaseLoc = Base->getBasePtr();
12917   if (Loc.getOpcode() == ISD::FrameIndex) {
12918     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12919       return false;
12920     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12921     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12922     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12923     int FS  = MFI.getObjectSize(FI);
12924     int BFS = MFI.getObjectSize(BFI);
12925     if (FS != BFS || FS != (int)Bytes) return false;
12926     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12927   }
12928 
12929   SDValue Base1 = Loc, Base2 = BaseLoc;
12930   int64_t Offset1 = 0, Offset2 = 0;
12931   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12932   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12933   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12934     return true;
12935 
12936   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12937   const GlobalValue *GV1 = nullptr;
12938   const GlobalValue *GV2 = nullptr;
12939   Offset1 = 0;
12940   Offset2 = 0;
12941   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12942   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12943   if (isGA1 && isGA2 && GV1 == GV2)
12944     return Offset1 == (Offset2 + Dist*Bytes);
12945   return false;
12946 }
12947 
12948 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12949 // not enforce equality of the chain operands.
12950 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12951                             unsigned Bytes, int Dist,
12952                             SelectionDAG &DAG) {
12953   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12954     EVT VT = LS->getMemoryVT();
12955     SDValue Loc = LS->getBasePtr();
12956     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12957   }
12958 
12959   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12960     EVT VT;
12961     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12962     default: return false;
12963     case Intrinsic::ppc_altivec_lvx:
12964     case Intrinsic::ppc_altivec_lvxl:
12965     case Intrinsic::ppc_vsx_lxvw4x:
12966     case Intrinsic::ppc_vsx_lxvw4x_be:
12967       VT = MVT::v4i32;
12968       break;
12969     case Intrinsic::ppc_vsx_lxvd2x:
12970     case Intrinsic::ppc_vsx_lxvd2x_be:
12971       VT = MVT::v2f64;
12972       break;
12973     case Intrinsic::ppc_altivec_lvebx:
12974       VT = MVT::i8;
12975       break;
12976     case Intrinsic::ppc_altivec_lvehx:
12977       VT = MVT::i16;
12978       break;
12979     case Intrinsic::ppc_altivec_lvewx:
12980       VT = MVT::i32;
12981       break;
12982     }
12983 
12984     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12985   }
12986 
12987   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12988     EVT VT;
12989     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12990     default: return false;
12991     case Intrinsic::ppc_altivec_stvx:
12992     case Intrinsic::ppc_altivec_stvxl:
12993     case Intrinsic::ppc_vsx_stxvw4x:
12994       VT = MVT::v4i32;
12995       break;
12996     case Intrinsic::ppc_vsx_stxvd2x:
12997       VT = MVT::v2f64;
12998       break;
12999     case Intrinsic::ppc_vsx_stxvw4x_be:
13000       VT = MVT::v4i32;
13001       break;
13002     case Intrinsic::ppc_vsx_stxvd2x_be:
13003       VT = MVT::v2f64;
13004       break;
13005     case Intrinsic::ppc_altivec_stvebx:
13006       VT = MVT::i8;
13007       break;
13008     case Intrinsic::ppc_altivec_stvehx:
13009       VT = MVT::i16;
13010       break;
13011     case Intrinsic::ppc_altivec_stvewx:
13012       VT = MVT::i32;
13013       break;
13014     }
13015 
13016     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
13017   }
13018 
13019   return false;
13020 }
13021 
13022 // Return true is there is a nearyby consecutive load to the one provided
13023 // (regardless of alignment). We search up and down the chain, looking though
13024 // token factors and other loads (but nothing else). As a result, a true result
13025 // indicates that it is safe to create a new consecutive load adjacent to the
13026 // load provided.
13027 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
13028   SDValue Chain = LD->getChain();
13029   EVT VT = LD->getMemoryVT();
13030 
13031   SmallSet<SDNode *, 16> LoadRoots;
13032   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
13033   SmallSet<SDNode *, 16> Visited;
13034 
13035   // First, search up the chain, branching to follow all token-factor operands.
13036   // If we find a consecutive load, then we're done, otherwise, record all
13037   // nodes just above the top-level loads and token factors.
13038   while (!Queue.empty()) {
13039     SDNode *ChainNext = Queue.pop_back_val();
13040     if (!Visited.insert(ChainNext).second)
13041       continue;
13042 
13043     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
13044       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13045         return true;
13046 
13047       if (!Visited.count(ChainLD->getChain().getNode()))
13048         Queue.push_back(ChainLD->getChain().getNode());
13049     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
13050       for (const SDUse &O : ChainNext->ops())
13051         if (!Visited.count(O.getNode()))
13052           Queue.push_back(O.getNode());
13053     } else
13054       LoadRoots.insert(ChainNext);
13055   }
13056 
13057   // Second, search down the chain, starting from the top-level nodes recorded
13058   // in the first phase. These top-level nodes are the nodes just above all
13059   // loads and token factors. Starting with their uses, recursively look though
13060   // all loads (just the chain uses) and token factors to find a consecutive
13061   // load.
13062   Visited.clear();
13063   Queue.clear();
13064 
13065   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
13066        IE = LoadRoots.end(); I != IE; ++I) {
13067     Queue.push_back(*I);
13068 
13069     while (!Queue.empty()) {
13070       SDNode *LoadRoot = Queue.pop_back_val();
13071       if (!Visited.insert(LoadRoot).second)
13072         continue;
13073 
13074       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
13075         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13076           return true;
13077 
13078       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
13079            UE = LoadRoot->use_end(); UI != UE; ++UI)
13080         if (((isa<MemSDNode>(*UI) &&
13081             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
13082             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
13083           Queue.push_back(*UI);
13084     }
13085   }
13086 
13087   return false;
13088 }
13089 
13090 /// This function is called when we have proved that a SETCC node can be replaced
13091 /// by subtraction (and other supporting instructions) so that the result of
13092 /// comparison is kept in a GPR instead of CR. This function is purely for
13093 /// codegen purposes and has some flags to guide the codegen process.
13094 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
13095                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
13096   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13097 
13098   // Zero extend the operands to the largest legal integer. Originally, they
13099   // must be of a strictly smaller size.
13100   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
13101                          DAG.getConstant(Size, DL, MVT::i32));
13102   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
13103                          DAG.getConstant(Size, DL, MVT::i32));
13104 
13105   // Swap if needed. Depends on the condition code.
13106   if (Swap)
13107     std::swap(Op0, Op1);
13108 
13109   // Subtract extended integers.
13110   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
13111 
13112   // Move the sign bit to the least significant position and zero out the rest.
13113   // Now the least significant bit carries the result of original comparison.
13114   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
13115                              DAG.getConstant(Size - 1, DL, MVT::i32));
13116   auto Final = Shifted;
13117 
13118   // Complement the result if needed. Based on the condition code.
13119   if (Complement)
13120     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
13121                         DAG.getConstant(1, DL, MVT::i64));
13122 
13123   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
13124 }
13125 
13126 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
13127                                                   DAGCombinerInfo &DCI) const {
13128   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13129 
13130   SelectionDAG &DAG = DCI.DAG;
13131   SDLoc DL(N);
13132 
13133   // Size of integers being compared has a critical role in the following
13134   // analysis, so we prefer to do this when all types are legal.
13135   if (!DCI.isAfterLegalizeDAG())
13136     return SDValue();
13137 
13138   // If all users of SETCC extend its value to a legal integer type
13139   // then we replace SETCC with a subtraction
13140   for (SDNode::use_iterator UI = N->use_begin(),
13141        UE = N->use_end(); UI != UE; ++UI) {
13142     if (UI->getOpcode() != ISD::ZERO_EXTEND)
13143       return SDValue();
13144   }
13145 
13146   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13147   auto OpSize = N->getOperand(0).getValueSizeInBits();
13148 
13149   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
13150 
13151   if (OpSize < Size) {
13152     switch (CC) {
13153     default: break;
13154     case ISD::SETULT:
13155       return generateEquivalentSub(N, Size, false, false, DL, DAG);
13156     case ISD::SETULE:
13157       return generateEquivalentSub(N, Size, true, true, DL, DAG);
13158     case ISD::SETUGT:
13159       return generateEquivalentSub(N, Size, false, true, DL, DAG);
13160     case ISD::SETUGE:
13161       return generateEquivalentSub(N, Size, true, false, DL, DAG);
13162     }
13163   }
13164 
13165   return SDValue();
13166 }
13167 
13168 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
13169                                                   DAGCombinerInfo &DCI) const {
13170   SelectionDAG &DAG = DCI.DAG;
13171   SDLoc dl(N);
13172 
13173   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
13174   // If we're tracking CR bits, we need to be careful that we don't have:
13175   //   trunc(binary-ops(zext(x), zext(y)))
13176   // or
13177   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
13178   // such that we're unnecessarily moving things into GPRs when it would be
13179   // better to keep them in CR bits.
13180 
13181   // Note that trunc here can be an actual i1 trunc, or can be the effective
13182   // truncation that comes from a setcc or select_cc.
13183   if (N->getOpcode() == ISD::TRUNCATE &&
13184       N->getValueType(0) != MVT::i1)
13185     return SDValue();
13186 
13187   if (N->getOperand(0).getValueType() != MVT::i32 &&
13188       N->getOperand(0).getValueType() != MVT::i64)
13189     return SDValue();
13190 
13191   if (N->getOpcode() == ISD::SETCC ||
13192       N->getOpcode() == ISD::SELECT_CC) {
13193     // If we're looking at a comparison, then we need to make sure that the
13194     // high bits (all except for the first) don't matter the result.
13195     ISD::CondCode CC =
13196       cast<CondCodeSDNode>(N->getOperand(
13197         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
13198     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
13199 
13200     if (ISD::isSignedIntSetCC(CC)) {
13201       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
13202           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
13203         return SDValue();
13204     } else if (ISD::isUnsignedIntSetCC(CC)) {
13205       if (!DAG.MaskedValueIsZero(N->getOperand(0),
13206                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
13207           !DAG.MaskedValueIsZero(N->getOperand(1),
13208                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
13209         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
13210                                              : SDValue());
13211     } else {
13212       // This is neither a signed nor an unsigned comparison, just make sure
13213       // that the high bits are equal.
13214       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
13215       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
13216 
13217       // We don't really care about what is known about the first bit (if
13218       // anything), so pretend that it is known zero for both to ensure they can
13219       // be compared as constants.
13220       Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
13221       Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
13222 
13223       if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
13224           Op1Known.getConstant() != Op2Known.getConstant())
13225         return SDValue();
13226     }
13227   }
13228 
13229   // We now know that the higher-order bits are irrelevant, we just need to
13230   // make sure that all of the intermediate operations are bit operations, and
13231   // all inputs are extensions.
13232   if (N->getOperand(0).getOpcode() != ISD::AND &&
13233       N->getOperand(0).getOpcode() != ISD::OR  &&
13234       N->getOperand(0).getOpcode() != ISD::XOR &&
13235       N->getOperand(0).getOpcode() != ISD::SELECT &&
13236       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
13237       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
13238       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
13239       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
13240       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
13241     return SDValue();
13242 
13243   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
13244       N->getOperand(1).getOpcode() != ISD::AND &&
13245       N->getOperand(1).getOpcode() != ISD::OR  &&
13246       N->getOperand(1).getOpcode() != ISD::XOR &&
13247       N->getOperand(1).getOpcode() != ISD::SELECT &&
13248       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
13249       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
13250       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
13251       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
13252       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
13253     return SDValue();
13254 
13255   SmallVector<SDValue, 4> Inputs;
13256   SmallVector<SDValue, 8> BinOps, PromOps;
13257   SmallPtrSet<SDNode *, 16> Visited;
13258 
13259   for (unsigned i = 0; i < 2; ++i) {
13260     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13261           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13262           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13263           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13264         isa<ConstantSDNode>(N->getOperand(i)))
13265       Inputs.push_back(N->getOperand(i));
13266     else
13267       BinOps.push_back(N->getOperand(i));
13268 
13269     if (N->getOpcode() == ISD::TRUNCATE)
13270       break;
13271   }
13272 
13273   // Visit all inputs, collect all binary operations (and, or, xor and
13274   // select) that are all fed by extensions.
13275   while (!BinOps.empty()) {
13276     SDValue BinOp = BinOps.pop_back_val();
13277 
13278     if (!Visited.insert(BinOp.getNode()).second)
13279       continue;
13280 
13281     PromOps.push_back(BinOp);
13282 
13283     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13284       // The condition of the select is not promoted.
13285       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13286         continue;
13287       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13288         continue;
13289 
13290       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13291             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13292             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13293            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13294           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13295         Inputs.push_back(BinOp.getOperand(i));
13296       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13297                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13298                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13299                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13300                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
13301                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13302                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13303                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13304                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
13305         BinOps.push_back(BinOp.getOperand(i));
13306       } else {
13307         // We have an input that is not an extension or another binary
13308         // operation; we'll abort this transformation.
13309         return SDValue();
13310       }
13311     }
13312   }
13313 
13314   // Make sure that this is a self-contained cluster of operations (which
13315   // is not quite the same thing as saying that everything has only one
13316   // use).
13317   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13318     if (isa<ConstantSDNode>(Inputs[i]))
13319       continue;
13320 
13321     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13322                               UE = Inputs[i].getNode()->use_end();
13323          UI != UE; ++UI) {
13324       SDNode *User = *UI;
13325       if (User != N && !Visited.count(User))
13326         return SDValue();
13327 
13328       // Make sure that we're not going to promote the non-output-value
13329       // operand(s) or SELECT or SELECT_CC.
13330       // FIXME: Although we could sometimes handle this, and it does occur in
13331       // practice that one of the condition inputs to the select is also one of
13332       // the outputs, we currently can't deal with this.
13333       if (User->getOpcode() == ISD::SELECT) {
13334         if (User->getOperand(0) == Inputs[i])
13335           return SDValue();
13336       } else if (User->getOpcode() == ISD::SELECT_CC) {
13337         if (User->getOperand(0) == Inputs[i] ||
13338             User->getOperand(1) == Inputs[i])
13339           return SDValue();
13340       }
13341     }
13342   }
13343 
13344   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13345     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13346                               UE = PromOps[i].getNode()->use_end();
13347          UI != UE; ++UI) {
13348       SDNode *User = *UI;
13349       if (User != N && !Visited.count(User))
13350         return SDValue();
13351 
13352       // Make sure that we're not going to promote the non-output-value
13353       // operand(s) or SELECT or SELECT_CC.
13354       // FIXME: Although we could sometimes handle this, and it does occur in
13355       // practice that one of the condition inputs to the select is also one of
13356       // the outputs, we currently can't deal with this.
13357       if (User->getOpcode() == ISD::SELECT) {
13358         if (User->getOperand(0) == PromOps[i])
13359           return SDValue();
13360       } else if (User->getOpcode() == ISD::SELECT_CC) {
13361         if (User->getOperand(0) == PromOps[i] ||
13362             User->getOperand(1) == PromOps[i])
13363           return SDValue();
13364       }
13365     }
13366   }
13367 
13368   // Replace all inputs with the extension operand.
13369   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13370     // Constants may have users outside the cluster of to-be-promoted nodes,
13371     // and so we need to replace those as we do the promotions.
13372     if (isa<ConstantSDNode>(Inputs[i]))
13373       continue;
13374     else
13375       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13376   }
13377 
13378   std::list<HandleSDNode> PromOpHandles;
13379   for (auto &PromOp : PromOps)
13380     PromOpHandles.emplace_back(PromOp);
13381 
13382   // Replace all operations (these are all the same, but have a different
13383   // (i1) return type). DAG.getNode will validate that the types of
13384   // a binary operator match, so go through the list in reverse so that
13385   // we've likely promoted both operands first. Any intermediate truncations or
13386   // extensions disappear.
13387   while (!PromOpHandles.empty()) {
13388     SDValue PromOp = PromOpHandles.back().getValue();
13389     PromOpHandles.pop_back();
13390 
13391     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13392         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13393         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13394         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13395       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13396           PromOp.getOperand(0).getValueType() != MVT::i1) {
13397         // The operand is not yet ready (see comment below).
13398         PromOpHandles.emplace_front(PromOp);
13399         continue;
13400       }
13401 
13402       SDValue RepValue = PromOp.getOperand(0);
13403       if (isa<ConstantSDNode>(RepValue))
13404         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13405 
13406       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13407       continue;
13408     }
13409 
13410     unsigned C;
13411     switch (PromOp.getOpcode()) {
13412     default:             C = 0; break;
13413     case ISD::SELECT:    C = 1; break;
13414     case ISD::SELECT_CC: C = 2; break;
13415     }
13416 
13417     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13418          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13419         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13420          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13421       // The to-be-promoted operands of this node have not yet been
13422       // promoted (this should be rare because we're going through the
13423       // list backward, but if one of the operands has several users in
13424       // this cluster of to-be-promoted nodes, it is possible).
13425       PromOpHandles.emplace_front(PromOp);
13426       continue;
13427     }
13428 
13429     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13430                                 PromOp.getNode()->op_end());
13431 
13432     // If there are any constant inputs, make sure they're replaced now.
13433     for (unsigned i = 0; i < 2; ++i)
13434       if (isa<ConstantSDNode>(Ops[C+i]))
13435         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13436 
13437     DAG.ReplaceAllUsesOfValueWith(PromOp,
13438       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13439   }
13440 
13441   // Now we're left with the initial truncation itself.
13442   if (N->getOpcode() == ISD::TRUNCATE)
13443     return N->getOperand(0);
13444 
13445   // Otherwise, this is a comparison. The operands to be compared have just
13446   // changed type (to i1), but everything else is the same.
13447   return SDValue(N, 0);
13448 }
13449 
13450 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13451                                                   DAGCombinerInfo &DCI) const {
13452   SelectionDAG &DAG = DCI.DAG;
13453   SDLoc dl(N);
13454 
13455   // If we're tracking CR bits, we need to be careful that we don't have:
13456   //   zext(binary-ops(trunc(x), trunc(y)))
13457   // or
13458   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13459   // such that we're unnecessarily moving things into CR bits that can more
13460   // efficiently stay in GPRs. Note that if we're not certain that the high
13461   // bits are set as required by the final extension, we still may need to do
13462   // some masking to get the proper behavior.
13463 
13464   // This same functionality is important on PPC64 when dealing with
13465   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13466   // the return values of functions. Because it is so similar, it is handled
13467   // here as well.
13468 
13469   if (N->getValueType(0) != MVT::i32 &&
13470       N->getValueType(0) != MVT::i64)
13471     return SDValue();
13472 
13473   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13474         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13475     return SDValue();
13476 
13477   if (N->getOperand(0).getOpcode() != ISD::AND &&
13478       N->getOperand(0).getOpcode() != ISD::OR  &&
13479       N->getOperand(0).getOpcode() != ISD::XOR &&
13480       N->getOperand(0).getOpcode() != ISD::SELECT &&
13481       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13482     return SDValue();
13483 
13484   SmallVector<SDValue, 4> Inputs;
13485   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13486   SmallPtrSet<SDNode *, 16> Visited;
13487 
13488   // Visit all inputs, collect all binary operations (and, or, xor and
13489   // select) that are all fed by truncations.
13490   while (!BinOps.empty()) {
13491     SDValue BinOp = BinOps.pop_back_val();
13492 
13493     if (!Visited.insert(BinOp.getNode()).second)
13494       continue;
13495 
13496     PromOps.push_back(BinOp);
13497 
13498     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13499       // The condition of the select is not promoted.
13500       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13501         continue;
13502       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13503         continue;
13504 
13505       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13506           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13507         Inputs.push_back(BinOp.getOperand(i));
13508       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13509                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13510                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13511                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13512                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13513         BinOps.push_back(BinOp.getOperand(i));
13514       } else {
13515         // We have an input that is not a truncation or another binary
13516         // operation; we'll abort this transformation.
13517         return SDValue();
13518       }
13519     }
13520   }
13521 
13522   // The operands of a select that must be truncated when the select is
13523   // promoted because the operand is actually part of the to-be-promoted set.
13524   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13525 
13526   // Make sure that this is a self-contained cluster of operations (which
13527   // is not quite the same thing as saying that everything has only one
13528   // use).
13529   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13530     if (isa<ConstantSDNode>(Inputs[i]))
13531       continue;
13532 
13533     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13534                               UE = Inputs[i].getNode()->use_end();
13535          UI != UE; ++UI) {
13536       SDNode *User = *UI;
13537       if (User != N && !Visited.count(User))
13538         return SDValue();
13539 
13540       // If we're going to promote the non-output-value operand(s) or SELECT or
13541       // SELECT_CC, record them for truncation.
13542       if (User->getOpcode() == ISD::SELECT) {
13543         if (User->getOperand(0) == Inputs[i])
13544           SelectTruncOp[0].insert(std::make_pair(User,
13545                                     User->getOperand(0).getValueType()));
13546       } else if (User->getOpcode() == ISD::SELECT_CC) {
13547         if (User->getOperand(0) == Inputs[i])
13548           SelectTruncOp[0].insert(std::make_pair(User,
13549                                     User->getOperand(0).getValueType()));
13550         if (User->getOperand(1) == Inputs[i])
13551           SelectTruncOp[1].insert(std::make_pair(User,
13552                                     User->getOperand(1).getValueType()));
13553       }
13554     }
13555   }
13556 
13557   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13558     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13559                               UE = PromOps[i].getNode()->use_end();
13560          UI != UE; ++UI) {
13561       SDNode *User = *UI;
13562       if (User != N && !Visited.count(User))
13563         return SDValue();
13564 
13565       // If we're going to promote the non-output-value operand(s) or SELECT or
13566       // SELECT_CC, record them for truncation.
13567       if (User->getOpcode() == ISD::SELECT) {
13568         if (User->getOperand(0) == PromOps[i])
13569           SelectTruncOp[0].insert(std::make_pair(User,
13570                                     User->getOperand(0).getValueType()));
13571       } else if (User->getOpcode() == ISD::SELECT_CC) {
13572         if (User->getOperand(0) == PromOps[i])
13573           SelectTruncOp[0].insert(std::make_pair(User,
13574                                     User->getOperand(0).getValueType()));
13575         if (User->getOperand(1) == PromOps[i])
13576           SelectTruncOp[1].insert(std::make_pair(User,
13577                                     User->getOperand(1).getValueType()));
13578       }
13579     }
13580   }
13581 
13582   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13583   bool ReallyNeedsExt = false;
13584   if (N->getOpcode() != ISD::ANY_EXTEND) {
13585     // If all of the inputs are not already sign/zero extended, then
13586     // we'll still need to do that at the end.
13587     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13588       if (isa<ConstantSDNode>(Inputs[i]))
13589         continue;
13590 
13591       unsigned OpBits =
13592         Inputs[i].getOperand(0).getValueSizeInBits();
13593       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13594 
13595       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13596            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13597                                   APInt::getHighBitsSet(OpBits,
13598                                                         OpBits-PromBits))) ||
13599           (N->getOpcode() == ISD::SIGN_EXTEND &&
13600            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13601              (OpBits-(PromBits-1)))) {
13602         ReallyNeedsExt = true;
13603         break;
13604       }
13605     }
13606   }
13607 
13608   // Replace all inputs, either with the truncation operand, or a
13609   // truncation or extension to the final output type.
13610   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13611     // Constant inputs need to be replaced with the to-be-promoted nodes that
13612     // use them because they might have users outside of the cluster of
13613     // promoted nodes.
13614     if (isa<ConstantSDNode>(Inputs[i]))
13615       continue;
13616 
13617     SDValue InSrc = Inputs[i].getOperand(0);
13618     if (Inputs[i].getValueType() == N->getValueType(0))
13619       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13620     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13621       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13622         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13623     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13624       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13625         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13626     else
13627       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13628         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13629   }
13630 
13631   std::list<HandleSDNode> PromOpHandles;
13632   for (auto &PromOp : PromOps)
13633     PromOpHandles.emplace_back(PromOp);
13634 
13635   // Replace all operations (these are all the same, but have a different
13636   // (promoted) return type). DAG.getNode will validate that the types of
13637   // a binary operator match, so go through the list in reverse so that
13638   // we've likely promoted both operands first.
13639   while (!PromOpHandles.empty()) {
13640     SDValue PromOp = PromOpHandles.back().getValue();
13641     PromOpHandles.pop_back();
13642 
13643     unsigned C;
13644     switch (PromOp.getOpcode()) {
13645     default:             C = 0; break;
13646     case ISD::SELECT:    C = 1; break;
13647     case ISD::SELECT_CC: C = 2; break;
13648     }
13649 
13650     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13651          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13652         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13653          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13654       // The to-be-promoted operands of this node have not yet been
13655       // promoted (this should be rare because we're going through the
13656       // list backward, but if one of the operands has several users in
13657       // this cluster of to-be-promoted nodes, it is possible).
13658       PromOpHandles.emplace_front(PromOp);
13659       continue;
13660     }
13661 
13662     // For SELECT and SELECT_CC nodes, we do a similar check for any
13663     // to-be-promoted comparison inputs.
13664     if (PromOp.getOpcode() == ISD::SELECT ||
13665         PromOp.getOpcode() == ISD::SELECT_CC) {
13666       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13667            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13668           (SelectTruncOp[1].count(PromOp.getNode()) &&
13669            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13670         PromOpHandles.emplace_front(PromOp);
13671         continue;
13672       }
13673     }
13674 
13675     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13676                                 PromOp.getNode()->op_end());
13677 
13678     // If this node has constant inputs, then they'll need to be promoted here.
13679     for (unsigned i = 0; i < 2; ++i) {
13680       if (!isa<ConstantSDNode>(Ops[C+i]))
13681         continue;
13682       if (Ops[C+i].getValueType() == N->getValueType(0))
13683         continue;
13684 
13685       if (N->getOpcode() == ISD::SIGN_EXTEND)
13686         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13687       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13688         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13689       else
13690         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13691     }
13692 
13693     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13694     // truncate them again to the original value type.
13695     if (PromOp.getOpcode() == ISD::SELECT ||
13696         PromOp.getOpcode() == ISD::SELECT_CC) {
13697       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13698       if (SI0 != SelectTruncOp[0].end())
13699         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13700       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13701       if (SI1 != SelectTruncOp[1].end())
13702         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13703     }
13704 
13705     DAG.ReplaceAllUsesOfValueWith(PromOp,
13706       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13707   }
13708 
13709   // Now we're left with the initial extension itself.
13710   if (!ReallyNeedsExt)
13711     return N->getOperand(0);
13712 
13713   // To zero extend, just mask off everything except for the first bit (in the
13714   // i1 case).
13715   if (N->getOpcode() == ISD::ZERO_EXTEND)
13716     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13717                        DAG.getConstant(APInt::getLowBitsSet(
13718                                          N->getValueSizeInBits(0), PromBits),
13719                                        dl, N->getValueType(0)));
13720 
13721   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13722          "Invalid extension type");
13723   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13724   SDValue ShiftCst =
13725       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13726   return DAG.getNode(
13727       ISD::SRA, dl, N->getValueType(0),
13728       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13729       ShiftCst);
13730 }
13731 
13732 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13733                                         DAGCombinerInfo &DCI) const {
13734   assert(N->getOpcode() == ISD::SETCC &&
13735          "Should be called with a SETCC node");
13736 
13737   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13738   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13739     SDValue LHS = N->getOperand(0);
13740     SDValue RHS = N->getOperand(1);
13741 
13742     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13743     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13744         LHS.hasOneUse())
13745       std::swap(LHS, RHS);
13746 
13747     // x == 0-y --> x+y == 0
13748     // x != 0-y --> x+y != 0
13749     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13750         RHS.hasOneUse()) {
13751       SDLoc DL(N);
13752       SelectionDAG &DAG = DCI.DAG;
13753       EVT VT = N->getValueType(0);
13754       EVT OpVT = LHS.getValueType();
13755       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13756       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13757     }
13758   }
13759 
13760   return DAGCombineTruncBoolExt(N, DCI);
13761 }
13762 
13763 // Is this an extending load from an f32 to an f64?
13764 static bool isFPExtLoad(SDValue Op) {
13765   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13766     return LD->getExtensionType() == ISD::EXTLOAD &&
13767       Op.getValueType() == MVT::f64;
13768   return false;
13769 }
13770 
13771 /// Reduces the number of fp-to-int conversion when building a vector.
13772 ///
13773 /// If this vector is built out of floating to integer conversions,
13774 /// transform it to a vector built out of floating point values followed by a
13775 /// single floating to integer conversion of the vector.
13776 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13777 /// becomes (fptosi (build_vector ($A, $B, ...)))
13778 SDValue PPCTargetLowering::
13779 combineElementTruncationToVectorTruncation(SDNode *N,
13780                                            DAGCombinerInfo &DCI) const {
13781   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13782          "Should be called with a BUILD_VECTOR node");
13783 
13784   SelectionDAG &DAG = DCI.DAG;
13785   SDLoc dl(N);
13786 
13787   SDValue FirstInput = N->getOperand(0);
13788   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13789          "The input operand must be an fp-to-int conversion.");
13790 
13791   // This combine happens after legalization so the fp_to_[su]i nodes are
13792   // already converted to PPCSISD nodes.
13793   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13794   if (FirstConversion == PPCISD::FCTIDZ ||
13795       FirstConversion == PPCISD::FCTIDUZ ||
13796       FirstConversion == PPCISD::FCTIWZ ||
13797       FirstConversion == PPCISD::FCTIWUZ) {
13798     bool IsSplat = true;
13799     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13800       FirstConversion == PPCISD::FCTIWUZ;
13801     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13802     SmallVector<SDValue, 4> Ops;
13803     EVT TargetVT = N->getValueType(0);
13804     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13805       SDValue NextOp = N->getOperand(i);
13806       if (NextOp.getOpcode() != PPCISD::MFVSR)
13807         return SDValue();
13808       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13809       if (NextConversion != FirstConversion)
13810         return SDValue();
13811       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13812       // This is not valid if the input was originally double precision. It is
13813       // also not profitable to do unless this is an extending load in which
13814       // case doing this combine will allow us to combine consecutive loads.
13815       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13816         return SDValue();
13817       if (N->getOperand(i) != FirstInput)
13818         IsSplat = false;
13819     }
13820 
13821     // If this is a splat, we leave it as-is since there will be only a single
13822     // fp-to-int conversion followed by a splat of the integer. This is better
13823     // for 32-bit and smaller ints and neutral for 64-bit ints.
13824     if (IsSplat)
13825       return SDValue();
13826 
13827     // Now that we know we have the right type of node, get its operands
13828     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13829       SDValue In = N->getOperand(i).getOperand(0);
13830       if (Is32Bit) {
13831         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13832         // here, we know that all inputs are extending loads so this is safe).
13833         if (In.isUndef())
13834           Ops.push_back(DAG.getUNDEF(SrcVT));
13835         else {
13836           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13837                                       MVT::f32, In.getOperand(0),
13838                                       DAG.getIntPtrConstant(1, dl));
13839           Ops.push_back(Trunc);
13840         }
13841       } else
13842         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13843     }
13844 
13845     unsigned Opcode;
13846     if (FirstConversion == PPCISD::FCTIDZ ||
13847         FirstConversion == PPCISD::FCTIWZ)
13848       Opcode = ISD::FP_TO_SINT;
13849     else
13850       Opcode = ISD::FP_TO_UINT;
13851 
13852     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13853     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13854     return DAG.getNode(Opcode, dl, TargetVT, BV);
13855   }
13856   return SDValue();
13857 }
13858 
13859 /// Reduce the number of loads when building a vector.
13860 ///
13861 /// Building a vector out of multiple loads can be converted to a load
13862 /// of the vector type if the loads are consecutive. If the loads are
13863 /// consecutive but in descending order, a shuffle is added at the end
13864 /// to reorder the vector.
13865 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13866   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13867          "Should be called with a BUILD_VECTOR node");
13868 
13869   SDLoc dl(N);
13870 
13871   // Return early for non byte-sized type, as they can't be consecutive.
13872   if (!N->getValueType(0).getVectorElementType().isByteSized())
13873     return SDValue();
13874 
13875   bool InputsAreConsecutiveLoads = true;
13876   bool InputsAreReverseConsecutive = true;
13877   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13878   SDValue FirstInput = N->getOperand(0);
13879   bool IsRoundOfExtLoad = false;
13880 
13881   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13882       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13883     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13884     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13885   }
13886   // Not a build vector of (possibly fp_rounded) loads.
13887   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13888       N->getNumOperands() == 1)
13889     return SDValue();
13890 
13891   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13892     // If any inputs are fp_round(extload), they all must be.
13893     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13894       return SDValue();
13895 
13896     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13897       N->getOperand(i);
13898     if (NextInput.getOpcode() != ISD::LOAD)
13899       return SDValue();
13900 
13901     SDValue PreviousInput =
13902       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13903     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13904     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13905 
13906     // If any inputs are fp_round(extload), they all must be.
13907     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13908       return SDValue();
13909 
13910     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13911       InputsAreConsecutiveLoads = false;
13912     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13913       InputsAreReverseConsecutive = false;
13914 
13915     // Exit early if the loads are neither consecutive nor reverse consecutive.
13916     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13917       return SDValue();
13918   }
13919 
13920   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13921          "The loads cannot be both consecutive and reverse consecutive.");
13922 
13923   SDValue FirstLoadOp =
13924     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13925   SDValue LastLoadOp =
13926     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13927                        N->getOperand(N->getNumOperands()-1);
13928 
13929   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13930   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13931   if (InputsAreConsecutiveLoads) {
13932     assert(LD1 && "Input needs to be a LoadSDNode.");
13933     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13934                        LD1->getBasePtr(), LD1->getPointerInfo(),
13935                        LD1->getAlignment());
13936   }
13937   if (InputsAreReverseConsecutive) {
13938     assert(LDL && "Input needs to be a LoadSDNode.");
13939     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13940                                LDL->getBasePtr(), LDL->getPointerInfo(),
13941                                LDL->getAlignment());
13942     SmallVector<int, 16> Ops;
13943     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13944       Ops.push_back(i);
13945 
13946     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13947                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13948   }
13949   return SDValue();
13950 }
13951 
13952 // This function adds the required vector_shuffle needed to get
13953 // the elements of the vector extract in the correct position
13954 // as specified by the CorrectElems encoding.
13955 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13956                                       SDValue Input, uint64_t Elems,
13957                                       uint64_t CorrectElems) {
13958   SDLoc dl(N);
13959 
13960   unsigned NumElems = Input.getValueType().getVectorNumElements();
13961   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13962 
13963   // Knowing the element indices being extracted from the original
13964   // vector and the order in which they're being inserted, just put
13965   // them at element indices required for the instruction.
13966   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13967     if (DAG.getDataLayout().isLittleEndian())
13968       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13969     else
13970       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13971     CorrectElems = CorrectElems >> 8;
13972     Elems = Elems >> 8;
13973   }
13974 
13975   SDValue Shuffle =
13976       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13977                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13978 
13979   EVT VT = N->getValueType(0);
13980   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13981 
13982   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13983                                Input.getValueType().getVectorElementType(),
13984                                VT.getVectorNumElements());
13985   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13986                      DAG.getValueType(ExtVT));
13987 }
13988 
13989 // Look for build vector patterns where input operands come from sign
13990 // extended vector_extract elements of specific indices. If the correct indices
13991 // aren't used, add a vector shuffle to fix up the indices and create
13992 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13993 // during instruction selection.
13994 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13995   // This array encodes the indices that the vector sign extend instructions
13996   // extract from when extending from one type to another for both BE and LE.
13997   // The right nibble of each byte corresponds to the LE incides.
13998   // and the left nibble of each byte corresponds to the BE incides.
13999   // For example: 0x3074B8FC  byte->word
14000   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
14001   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
14002   // For example: 0x000070F8  byte->double word
14003   // For LE: the allowed indices are: 0x0,0x8
14004   // For BE: the allowed indices are: 0x7,0xF
14005   uint64_t TargetElems[] = {
14006       0x3074B8FC, // b->w
14007       0x000070F8, // b->d
14008       0x10325476, // h->w
14009       0x00003074, // h->d
14010       0x00001032, // w->d
14011   };
14012 
14013   uint64_t Elems = 0;
14014   int Index;
14015   SDValue Input;
14016 
14017   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
14018     if (!Op)
14019       return false;
14020     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
14021         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
14022       return false;
14023 
14024     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
14025     // of the right width.
14026     SDValue Extract = Op.getOperand(0);
14027     if (Extract.getOpcode() == ISD::ANY_EXTEND)
14028       Extract = Extract.getOperand(0);
14029     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14030       return false;
14031 
14032     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
14033     if (!ExtOp)
14034       return false;
14035 
14036     Index = ExtOp->getZExtValue();
14037     if (Input && Input != Extract.getOperand(0))
14038       return false;
14039 
14040     if (!Input)
14041       Input = Extract.getOperand(0);
14042 
14043     Elems = Elems << 8;
14044     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
14045     Elems |= Index;
14046 
14047     return true;
14048   };
14049 
14050   // If the build vector operands aren't sign extended vector extracts,
14051   // of the same input vector, then return.
14052   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14053     if (!isSExtOfVecExtract(N->getOperand(i))) {
14054       return SDValue();
14055     }
14056   }
14057 
14058   // If the vector extract indicies are not correct, add the appropriate
14059   // vector_shuffle.
14060   int TgtElemArrayIdx;
14061   int InputSize = Input.getValueType().getScalarSizeInBits();
14062   int OutputSize = N->getValueType(0).getScalarSizeInBits();
14063   if (InputSize + OutputSize == 40)
14064     TgtElemArrayIdx = 0;
14065   else if (InputSize + OutputSize == 72)
14066     TgtElemArrayIdx = 1;
14067   else if (InputSize + OutputSize == 48)
14068     TgtElemArrayIdx = 2;
14069   else if (InputSize + OutputSize == 80)
14070     TgtElemArrayIdx = 3;
14071   else if (InputSize + OutputSize == 96)
14072     TgtElemArrayIdx = 4;
14073   else
14074     return SDValue();
14075 
14076   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
14077   CorrectElems = DAG.getDataLayout().isLittleEndian()
14078                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
14079                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
14080   if (Elems != CorrectElems) {
14081     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
14082   }
14083 
14084   // Regular lowering will catch cases where a shuffle is not needed.
14085   return SDValue();
14086 }
14087 
14088 // Look for the pattern of a load from a narrow width to i128, feeding
14089 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
14090 // (LXVRZX). This node represents a zero extending load that will be matched
14091 // to the Load VSX Vector Rightmost instructions.
14092 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
14093   SDLoc DL(N);
14094 
14095   // This combine is only eligible for a BUILD_VECTOR of v1i128.
14096   if (N->getValueType(0) != MVT::v1i128)
14097     return SDValue();
14098 
14099   SDValue Operand = N->getOperand(0);
14100   // Proceed with the transformation if the operand to the BUILD_VECTOR
14101   // is a load instruction.
14102   if (Operand.getOpcode() != ISD::LOAD)
14103     return SDValue();
14104 
14105   auto *LD = cast<LoadSDNode>(Operand);
14106   EVT MemoryType = LD->getMemoryVT();
14107 
14108   // This transformation is only valid if the we are loading either a byte,
14109   // halfword, word, or doubleword.
14110   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
14111                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
14112 
14113   // Ensure that the load from the narrow width is being zero extended to i128.
14114   if (!ValidLDType ||
14115       (LD->getExtensionType() != ISD::ZEXTLOAD &&
14116        LD->getExtensionType() != ISD::EXTLOAD))
14117     return SDValue();
14118 
14119   SDValue LoadOps[] = {
14120       LD->getChain(), LD->getBasePtr(),
14121       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
14122 
14123   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
14124                                  DAG.getVTList(MVT::v1i128, MVT::Other),
14125                                  LoadOps, MemoryType, LD->getMemOperand());
14126 }
14127 
14128 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
14129                                                  DAGCombinerInfo &DCI) const {
14130   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14131          "Should be called with a BUILD_VECTOR node");
14132 
14133   SelectionDAG &DAG = DCI.DAG;
14134   SDLoc dl(N);
14135 
14136   if (!Subtarget.hasVSX())
14137     return SDValue();
14138 
14139   // The target independent DAG combiner will leave a build_vector of
14140   // float-to-int conversions intact. We can generate MUCH better code for
14141   // a float-to-int conversion of a vector of floats.
14142   SDValue FirstInput = N->getOperand(0);
14143   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
14144     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
14145     if (Reduced)
14146       return Reduced;
14147   }
14148 
14149   // If we're building a vector out of consecutive loads, just load that
14150   // vector type.
14151   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
14152   if (Reduced)
14153     return Reduced;
14154 
14155   // If we're building a vector out of extended elements from another vector
14156   // we have P9 vector integer extend instructions. The code assumes legal
14157   // input types (i.e. it can't handle things like v4i16) so do not run before
14158   // legalization.
14159   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
14160     Reduced = combineBVOfVecSExt(N, DAG);
14161     if (Reduced)
14162       return Reduced;
14163   }
14164 
14165   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
14166   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
14167   // is a load from <valid narrow width> to i128.
14168   if (Subtarget.isISA3_1()) {
14169     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
14170     if (BVOfZLoad)
14171       return BVOfZLoad;
14172   }
14173 
14174   if (N->getValueType(0) != MVT::v2f64)
14175     return SDValue();
14176 
14177   // Looking for:
14178   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
14179   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
14180       FirstInput.getOpcode() != ISD::UINT_TO_FP)
14181     return SDValue();
14182   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
14183       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
14184     return SDValue();
14185   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
14186     return SDValue();
14187 
14188   SDValue Ext1 = FirstInput.getOperand(0);
14189   SDValue Ext2 = N->getOperand(1).getOperand(0);
14190   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14191      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14192     return SDValue();
14193 
14194   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
14195   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
14196   if (!Ext1Op || !Ext2Op)
14197     return SDValue();
14198   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
14199       Ext1.getOperand(0) != Ext2.getOperand(0))
14200     return SDValue();
14201 
14202   int FirstElem = Ext1Op->getZExtValue();
14203   int SecondElem = Ext2Op->getZExtValue();
14204   int SubvecIdx;
14205   if (FirstElem == 0 && SecondElem == 1)
14206     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
14207   else if (FirstElem == 2 && SecondElem == 3)
14208     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
14209   else
14210     return SDValue();
14211 
14212   SDValue SrcVec = Ext1.getOperand(0);
14213   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
14214     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
14215   return DAG.getNode(NodeType, dl, MVT::v2f64,
14216                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
14217 }
14218 
14219 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
14220                                               DAGCombinerInfo &DCI) const {
14221   assert((N->getOpcode() == ISD::SINT_TO_FP ||
14222           N->getOpcode() == ISD::UINT_TO_FP) &&
14223          "Need an int -> FP conversion node here");
14224 
14225   if (useSoftFloat() || !Subtarget.has64BitSupport())
14226     return SDValue();
14227 
14228   SelectionDAG &DAG = DCI.DAG;
14229   SDLoc dl(N);
14230   SDValue Op(N, 0);
14231 
14232   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
14233   // from the hardware.
14234   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
14235     return SDValue();
14236   if (!Op.getOperand(0).getValueType().isSimple())
14237     return SDValue();
14238   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
14239       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
14240     return SDValue();
14241 
14242   SDValue FirstOperand(Op.getOperand(0));
14243   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
14244     (FirstOperand.getValueType() == MVT::i8 ||
14245      FirstOperand.getValueType() == MVT::i16);
14246   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
14247     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
14248     bool DstDouble = Op.getValueType() == MVT::f64;
14249     unsigned ConvOp = Signed ?
14250       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
14251       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
14252     SDValue WidthConst =
14253       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
14254                             dl, false);
14255     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
14256     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
14257     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
14258                                          DAG.getVTList(MVT::f64, MVT::Other),
14259                                          Ops, MVT::i8, LDN->getMemOperand());
14260 
14261     // For signed conversion, we need to sign-extend the value in the VSR
14262     if (Signed) {
14263       SDValue ExtOps[] = { Ld, WidthConst };
14264       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
14265       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
14266     } else
14267       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
14268   }
14269 
14270 
14271   // For i32 intermediate values, unfortunately, the conversion functions
14272   // leave the upper 32 bits of the value are undefined. Within the set of
14273   // scalar instructions, we have no method for zero- or sign-extending the
14274   // value. Thus, we cannot handle i32 intermediate values here.
14275   if (Op.getOperand(0).getValueType() == MVT::i32)
14276     return SDValue();
14277 
14278   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
14279          "UINT_TO_FP is supported only with FPCVT");
14280 
14281   // If we have FCFIDS, then use it when converting to single-precision.
14282   // Otherwise, convert to double-precision and then round.
14283   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14284                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
14285                                                             : PPCISD::FCFIDS)
14286                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
14287                                                             : PPCISD::FCFID);
14288   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14289                   ? MVT::f32
14290                   : MVT::f64;
14291 
14292   // If we're converting from a float, to an int, and back to a float again,
14293   // then we don't need the store/load pair at all.
14294   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
14295        Subtarget.hasFPCVT()) ||
14296       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
14297     SDValue Src = Op.getOperand(0).getOperand(0);
14298     if (Src.getValueType() == MVT::f32) {
14299       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
14300       DCI.AddToWorklist(Src.getNode());
14301     } else if (Src.getValueType() != MVT::f64) {
14302       // Make sure that we don't pick up a ppc_fp128 source value.
14303       return SDValue();
14304     }
14305 
14306     unsigned FCTOp =
14307       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
14308                                                         PPCISD::FCTIDUZ;
14309 
14310     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
14311     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
14312 
14313     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
14314       FP = DAG.getNode(ISD::FP_ROUND, dl,
14315                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
14316       DCI.AddToWorklist(FP.getNode());
14317     }
14318 
14319     return FP;
14320   }
14321 
14322   return SDValue();
14323 }
14324 
14325 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
14326 // builtins) into loads with swaps.
14327 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
14328                                               DAGCombinerInfo &DCI) const {
14329   SelectionDAG &DAG = DCI.DAG;
14330   SDLoc dl(N);
14331   SDValue Chain;
14332   SDValue Base;
14333   MachineMemOperand *MMO;
14334 
14335   switch (N->getOpcode()) {
14336   default:
14337     llvm_unreachable("Unexpected opcode for little endian VSX load");
14338   case ISD::LOAD: {
14339     LoadSDNode *LD = cast<LoadSDNode>(N);
14340     Chain = LD->getChain();
14341     Base = LD->getBasePtr();
14342     MMO = LD->getMemOperand();
14343     // If the MMO suggests this isn't a load of a full vector, leave
14344     // things alone.  For a built-in, we have to make the change for
14345     // correctness, so if there is a size problem that will be a bug.
14346     if (MMO->getSize() < 16)
14347       return SDValue();
14348     break;
14349   }
14350   case ISD::INTRINSIC_W_CHAIN: {
14351     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14352     Chain = Intrin->getChain();
14353     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
14354     // us what we want. Get operand 2 instead.
14355     Base = Intrin->getOperand(2);
14356     MMO = Intrin->getMemOperand();
14357     break;
14358   }
14359   }
14360 
14361   MVT VecTy = N->getValueType(0).getSimpleVT();
14362 
14363   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
14364   // aligned and the type is a vector with elements up to 4 bytes
14365   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14366       VecTy.getScalarSizeInBits() <= 32) {
14367     return SDValue();
14368   }
14369 
14370   SDValue LoadOps[] = { Chain, Base };
14371   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14372                                          DAG.getVTList(MVT::v2f64, MVT::Other),
14373                                          LoadOps, MVT::v2f64, MMO);
14374 
14375   DCI.AddToWorklist(Load.getNode());
14376   Chain = Load.getValue(1);
14377   SDValue Swap = DAG.getNode(
14378       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14379   DCI.AddToWorklist(Swap.getNode());
14380 
14381   // Add a bitcast if the resulting load type doesn't match v2f64.
14382   if (VecTy != MVT::v2f64) {
14383     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14384     DCI.AddToWorklist(N.getNode());
14385     // Package {bitcast value, swap's chain} to match Load's shape.
14386     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14387                        N, Swap.getValue(1));
14388   }
14389 
14390   return Swap;
14391 }
14392 
14393 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14394 // builtins) into stores with swaps.
14395 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14396                                                DAGCombinerInfo &DCI) const {
14397   SelectionDAG &DAG = DCI.DAG;
14398   SDLoc dl(N);
14399   SDValue Chain;
14400   SDValue Base;
14401   unsigned SrcOpnd;
14402   MachineMemOperand *MMO;
14403 
14404   switch (N->getOpcode()) {
14405   default:
14406     llvm_unreachable("Unexpected opcode for little endian VSX store");
14407   case ISD::STORE: {
14408     StoreSDNode *ST = cast<StoreSDNode>(N);
14409     Chain = ST->getChain();
14410     Base = ST->getBasePtr();
14411     MMO = ST->getMemOperand();
14412     SrcOpnd = 1;
14413     // If the MMO suggests this isn't a store of a full vector, leave
14414     // things alone.  For a built-in, we have to make the change for
14415     // correctness, so if there is a size problem that will be a bug.
14416     if (MMO->getSize() < 16)
14417       return SDValue();
14418     break;
14419   }
14420   case ISD::INTRINSIC_VOID: {
14421     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14422     Chain = Intrin->getChain();
14423     // Intrin->getBasePtr() oddly does not get what we want.
14424     Base = Intrin->getOperand(3);
14425     MMO = Intrin->getMemOperand();
14426     SrcOpnd = 2;
14427     break;
14428   }
14429   }
14430 
14431   SDValue Src = N->getOperand(SrcOpnd);
14432   MVT VecTy = Src.getValueType().getSimpleVT();
14433 
14434   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14435   // aligned and the type is a vector with elements up to 4 bytes
14436   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14437       VecTy.getScalarSizeInBits() <= 32) {
14438     return SDValue();
14439   }
14440 
14441   // All stores are done as v2f64 and possible bit cast.
14442   if (VecTy != MVT::v2f64) {
14443     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14444     DCI.AddToWorklist(Src.getNode());
14445   }
14446 
14447   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14448                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14449   DCI.AddToWorklist(Swap.getNode());
14450   Chain = Swap.getValue(1);
14451   SDValue StoreOps[] = { Chain, Swap, Base };
14452   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14453                                           DAG.getVTList(MVT::Other),
14454                                           StoreOps, VecTy, MMO);
14455   DCI.AddToWorklist(Store.getNode());
14456   return Store;
14457 }
14458 
14459 // Handle DAG combine for STORE (FP_TO_INT F).
14460 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14461                                                DAGCombinerInfo &DCI) const {
14462 
14463   SelectionDAG &DAG = DCI.DAG;
14464   SDLoc dl(N);
14465   unsigned Opcode = N->getOperand(1).getOpcode();
14466 
14467   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14468          && "Not a FP_TO_INT Instruction!");
14469 
14470   SDValue Val = N->getOperand(1).getOperand(0);
14471   EVT Op1VT = N->getOperand(1).getValueType();
14472   EVT ResVT = Val.getValueType();
14473 
14474   if (!isTypeLegal(ResVT))
14475     return SDValue();
14476 
14477   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14478   bool ValidTypeForStoreFltAsInt =
14479         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14480          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14481 
14482   if (ResVT == MVT::f128 && !Subtarget.hasP9Vector())
14483     return SDValue();
14484 
14485   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14486       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14487     return SDValue();
14488 
14489   // Extend f32 values to f64
14490   if (ResVT.getScalarSizeInBits() == 32) {
14491     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14492     DCI.AddToWorklist(Val.getNode());
14493   }
14494 
14495   // Set signed or unsigned conversion opcode.
14496   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14497                           PPCISD::FP_TO_SINT_IN_VSR :
14498                           PPCISD::FP_TO_UINT_IN_VSR;
14499 
14500   Val = DAG.getNode(ConvOpcode,
14501                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14502   DCI.AddToWorklist(Val.getNode());
14503 
14504   // Set number of bytes being converted.
14505   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14506   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14507                     DAG.getIntPtrConstant(ByteSize, dl, false),
14508                     DAG.getValueType(Op1VT) };
14509 
14510   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14511           DAG.getVTList(MVT::Other), Ops,
14512           cast<StoreSDNode>(N)->getMemoryVT(),
14513           cast<StoreSDNode>(N)->getMemOperand());
14514 
14515   DCI.AddToWorklist(Val.getNode());
14516   return Val;
14517 }
14518 
14519 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14520   // Check that the source of the element keeps flipping
14521   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14522   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14523   for (int i = 1, e = Mask.size(); i < e; i++) {
14524     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14525       return false;
14526     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14527       return false;
14528     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14529   }
14530   return true;
14531 }
14532 
14533 static bool isSplatBV(SDValue Op) {
14534   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14535     return false;
14536   SDValue FirstOp;
14537 
14538   // Find first non-undef input.
14539   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14540     FirstOp = Op.getOperand(i);
14541     if (!FirstOp.isUndef())
14542       break;
14543   }
14544 
14545   // All inputs are undef or the same as the first non-undef input.
14546   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14547     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14548       return false;
14549   return true;
14550 }
14551 
14552 static SDValue isScalarToVec(SDValue Op) {
14553   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14554     return Op;
14555   if (Op.getOpcode() != ISD::BITCAST)
14556     return SDValue();
14557   Op = Op.getOperand(0);
14558   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14559     return Op;
14560   return SDValue();
14561 }
14562 
14563 // Fix up the shuffle mask to account for the fact that the result of
14564 // scalar_to_vector is not in lane zero. This just takes all values in
14565 // the ranges specified by the min/max indices and adds the number of
14566 // elements required to ensure each element comes from the respective
14567 // position in the valid lane.
14568 // On little endian, that's just the corresponding element in the other
14569 // half of the vector. On big endian, it is in the same half but right
14570 // justified rather than left justified in that half.
14571 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14572                                             int LHSMaxIdx, int RHSMinIdx,
14573                                             int RHSMaxIdx, int HalfVec,
14574                                             unsigned ValidLaneWidth,
14575                                             const PPCSubtarget &Subtarget) {
14576   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14577     int Idx = ShuffV[i];
14578     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14579       ShuffV[i] +=
14580           Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth;
14581   }
14582 }
14583 
14584 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14585 // the original is:
14586 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14587 // In such a case, just change the shuffle mask to extract the element
14588 // from the permuted index.
14589 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG,
14590                                const PPCSubtarget &Subtarget) {
14591   SDLoc dl(OrigSToV);
14592   EVT VT = OrigSToV.getValueType();
14593   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14594          "Expecting a SCALAR_TO_VECTOR here");
14595   SDValue Input = OrigSToV.getOperand(0);
14596 
14597   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14598     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14599     SDValue OrigVector = Input.getOperand(0);
14600 
14601     // Can't handle non-const element indices or different vector types
14602     // for the input to the extract and the output of the scalar_to_vector.
14603     if (Idx && VT == OrigVector.getValueType()) {
14604       unsigned NumElts = VT.getVectorNumElements();
14605       assert(
14606           NumElts > 1 &&
14607           "Cannot produce a permuted scalar_to_vector for one element vector");
14608       SmallVector<int, 16> NewMask(NumElts, -1);
14609       unsigned ResultInElt = NumElts / 2;
14610       ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1;
14611       NewMask[ResultInElt] = Idx->getZExtValue();
14612       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14613     }
14614   }
14615   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14616                      OrigSToV.getOperand(0));
14617 }
14618 
14619 // On little endian subtargets, combine shuffles such as:
14620 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14621 // into:
14622 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14623 // because the latter can be matched to a single instruction merge.
14624 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14625 // to put the value into element zero. Adjust the shuffle mask so that the
14626 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14627 // On big endian targets, this is still useful for SCALAR_TO_VECTOR
14628 // nodes with elements smaller than doubleword because all the ways
14629 // of getting scalar data into a vector register put the value in the
14630 // rightmost element of the left half of the vector.
14631 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14632                                                 SelectionDAG &DAG) const {
14633   SDValue LHS = SVN->getOperand(0);
14634   SDValue RHS = SVN->getOperand(1);
14635   auto Mask = SVN->getMask();
14636   int NumElts = LHS.getValueType().getVectorNumElements();
14637   SDValue Res(SVN, 0);
14638   SDLoc dl(SVN);
14639   bool IsLittleEndian = Subtarget.isLittleEndian();
14640 
14641   // On big endian targets this is only useful for subtargets with direct moves.
14642   // On little endian targets it would be useful for all subtargets with VSX.
14643   // However adding special handling for LE subtargets without direct moves
14644   // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8)
14645   // which includes direct moves.
14646   if (!Subtarget.hasDirectMove())
14647     return Res;
14648 
14649   // If this is not a shuffle of a shuffle and the first element comes from
14650   // the second vector, canonicalize to the commuted form. This will make it
14651   // more likely to match one of the single instruction patterns.
14652   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14653       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14654     std::swap(LHS, RHS);
14655     Res = DAG.getCommutedVectorShuffle(*SVN);
14656     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14657   }
14658 
14659   // Adjust the shuffle mask if either input vector comes from a
14660   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14661   // form (to prevent the need for a swap).
14662   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14663   SDValue SToVLHS = isScalarToVec(LHS);
14664   SDValue SToVRHS = isScalarToVec(RHS);
14665   if (SToVLHS || SToVRHS) {
14666     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14667                             : SToVRHS.getValueType().getVectorNumElements();
14668     int NumEltsOut = ShuffV.size();
14669     // The width of the "valid lane" (i.e. the lane that contains the value that
14670     // is vectorized) needs to be expressed in terms of the number of elements
14671     // of the shuffle. It is thereby the ratio of the values before and after
14672     // any bitcast.
14673     unsigned ValidLaneWidth =
14674         SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() /
14675                       LHS.getValueType().getScalarSizeInBits()
14676                 : SToVRHS.getValueType().getScalarSizeInBits() /
14677                       RHS.getValueType().getScalarSizeInBits();
14678 
14679     // Initially assume that neither input is permuted. These will be adjusted
14680     // accordingly if either input is.
14681     int LHSMaxIdx = -1;
14682     int RHSMinIdx = -1;
14683     int RHSMaxIdx = -1;
14684     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14685 
14686     // Get the permuted scalar to vector nodes for the source(s) that come from
14687     // ISD::SCALAR_TO_VECTOR.
14688     // On big endian systems, this only makes sense for element sizes smaller
14689     // than 64 bits since for 64-bit elements, all instructions already put
14690     // the value into element zero. Since scalar size of LHS and RHS may differ
14691     // after isScalarToVec, this should be checked using their own sizes.
14692     if (SToVLHS) {
14693       if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64)
14694         return Res;
14695       // Set up the values for the shuffle vector fixup.
14696       LHSMaxIdx = NumEltsOut / NumEltsIn;
14697       SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget);
14698       if (SToVLHS.getValueType() != LHS.getValueType())
14699         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14700       LHS = SToVLHS;
14701     }
14702     if (SToVRHS) {
14703       if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64)
14704         return Res;
14705       RHSMinIdx = NumEltsOut;
14706       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14707       SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget);
14708       if (SToVRHS.getValueType() != RHS.getValueType())
14709         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14710       RHS = SToVRHS;
14711     }
14712 
14713     // Fix up the shuffle mask to reflect where the desired element actually is.
14714     // The minimum and maximum indices that correspond to element zero for both
14715     // the LHS and RHS are computed and will control which shuffle mask entries
14716     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14717     // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted.
14718     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14719                                     HalfVec, ValidLaneWidth, Subtarget);
14720     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14721 
14722     // We may have simplified away the shuffle. We won't be able to do anything
14723     // further with it here.
14724     if (!isa<ShuffleVectorSDNode>(Res))
14725       return Res;
14726     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14727   }
14728 
14729   SDValue TheSplat = IsLittleEndian ? RHS : LHS;
14730   // The common case after we commuted the shuffle is that the RHS is a splat
14731   // and we have elements coming in from the splat at indices that are not
14732   // conducive to using a merge.
14733   // Example:
14734   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14735   if (!isSplatBV(TheSplat))
14736     return Res;
14737 
14738   // We are looking for a mask such that all even elements are from
14739   // one vector and all odd elements from the other.
14740   if (!isAlternatingShuffMask(Mask, NumElts))
14741     return Res;
14742 
14743   // Adjust the mask so we are pulling in the same index from the splat
14744   // as the index from the interesting vector in consecutive elements.
14745   if (IsLittleEndian) {
14746     // Example (even elements from first vector):
14747     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14748     if (Mask[0] < NumElts)
14749       for (int i = 1, e = Mask.size(); i < e; i += 2)
14750         ShuffV[i] = (ShuffV[i - 1] + NumElts);
14751     // Example (odd elements from first vector):
14752     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14753     else
14754       for (int i = 0, e = Mask.size(); i < e; i += 2)
14755         ShuffV[i] = (ShuffV[i + 1] + NumElts);
14756   } else {
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> <zero>, t1
14759     if (Mask[0] < NumElts)
14760       for (int i = 0, 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> <zero>, t1
14764     else
14765       for (int i = 1, e = Mask.size(); i < e; i += 2)
14766         ShuffV[i] = ShuffV[i - 1] - NumElts;
14767   }
14768 
14769   // If the RHS has undefs, we need to remove them since we may have created
14770   // a shuffle that adds those instead of the splat value.
14771   SDValue SplatVal =
14772       cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue();
14773   TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal);
14774 
14775   if (IsLittleEndian)
14776     RHS = TheSplat;
14777   else
14778     LHS = TheSplat;
14779   return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14780 }
14781 
14782 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14783                                                 LSBaseSDNode *LSBase,
14784                                                 DAGCombinerInfo &DCI) const {
14785   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14786         "Not a reverse memop pattern!");
14787 
14788   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14789     auto Mask = SVN->getMask();
14790     int i = 0;
14791     auto I = Mask.rbegin();
14792     auto E = Mask.rend();
14793 
14794     for (; I != E; ++I) {
14795       if (*I != i)
14796         return false;
14797       i++;
14798     }
14799     return true;
14800   };
14801 
14802   SelectionDAG &DAG = DCI.DAG;
14803   EVT VT = SVN->getValueType(0);
14804 
14805   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14806     return SDValue();
14807 
14808   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14809   // See comment in PPCVSXSwapRemoval.cpp.
14810   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14811   if (!Subtarget.hasP9Vector())
14812     return SDValue();
14813 
14814   if(!IsElementReverse(SVN))
14815     return SDValue();
14816 
14817   if (LSBase->getOpcode() == ISD::LOAD) {
14818     // If the load return value 0 has more than one user except the
14819     // shufflevector instruction, it is not profitable to replace the
14820     // shufflevector with a reverse load.
14821     for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end();
14822          UI != UE; ++UI)
14823       if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE)
14824         return SDValue();
14825 
14826     SDLoc dl(LSBase);
14827     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14828     return DAG.getMemIntrinsicNode(
14829         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14830         LSBase->getMemoryVT(), LSBase->getMemOperand());
14831   }
14832 
14833   if (LSBase->getOpcode() == ISD::STORE) {
14834     // If there are other uses of the shuffle, the swap cannot be avoided.
14835     // Forcing the use of an X-Form (since swapped stores only have
14836     // X-Forms) without removing the swap is unprofitable.
14837     if (!SVN->hasOneUse())
14838       return SDValue();
14839 
14840     SDLoc dl(LSBase);
14841     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14842                           LSBase->getBasePtr()};
14843     return DAG.getMemIntrinsicNode(
14844         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14845         LSBase->getMemoryVT(), LSBase->getMemOperand());
14846   }
14847 
14848   llvm_unreachable("Expected a load or store node here");
14849 }
14850 
14851 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14852                                              DAGCombinerInfo &DCI) const {
14853   SelectionDAG &DAG = DCI.DAG;
14854   SDLoc dl(N);
14855   switch (N->getOpcode()) {
14856   default: break;
14857   case ISD::ADD:
14858     return combineADD(N, DCI);
14859   case ISD::SHL:
14860     return combineSHL(N, DCI);
14861   case ISD::SRA:
14862     return combineSRA(N, DCI);
14863   case ISD::SRL:
14864     return combineSRL(N, DCI);
14865   case ISD::MUL:
14866     return combineMUL(N, DCI);
14867   case ISD::FMA:
14868   case PPCISD::FNMSUB:
14869     return combineFMALike(N, DCI);
14870   case PPCISD::SHL:
14871     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14872         return N->getOperand(0);
14873     break;
14874   case PPCISD::SRL:
14875     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14876         return N->getOperand(0);
14877     break;
14878   case PPCISD::SRA:
14879     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14880       if (C->isZero() ||  //  0 >>s V -> 0.
14881           C->isAllOnes()) // -1 >>s V -> -1.
14882         return N->getOperand(0);
14883     }
14884     break;
14885   case ISD::SIGN_EXTEND:
14886   case ISD::ZERO_EXTEND:
14887   case ISD::ANY_EXTEND:
14888     return DAGCombineExtBoolTrunc(N, DCI);
14889   case ISD::TRUNCATE:
14890     return combineTRUNCATE(N, DCI);
14891   case ISD::SETCC:
14892     if (SDValue CSCC = combineSetCC(N, DCI))
14893       return CSCC;
14894     LLVM_FALLTHROUGH;
14895   case ISD::SELECT_CC:
14896     return DAGCombineTruncBoolExt(N, DCI);
14897   case ISD::SINT_TO_FP:
14898   case ISD::UINT_TO_FP:
14899     return combineFPToIntToFP(N, DCI);
14900   case ISD::VECTOR_SHUFFLE:
14901     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14902       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14903       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14904     }
14905     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14906   case ISD::STORE: {
14907 
14908     EVT Op1VT = N->getOperand(1).getValueType();
14909     unsigned Opcode = N->getOperand(1).getOpcode();
14910 
14911     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14912       SDValue Val= combineStoreFPToInt(N, DCI);
14913       if (Val)
14914         return Val;
14915     }
14916 
14917     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14918       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14919       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14920       if (Val)
14921         return Val;
14922     }
14923 
14924     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14925     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14926         N->getOperand(1).getNode()->hasOneUse() &&
14927         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14928          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14929 
14930       // STBRX can only handle simple types and it makes no sense to store less
14931       // two bytes in byte-reversed order.
14932       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14933       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14934         break;
14935 
14936       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14937       // Do an any-extend to 32-bits if this is a half-word input.
14938       if (BSwapOp.getValueType() == MVT::i16)
14939         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14940 
14941       // If the type of BSWAP operand is wider than stored memory width
14942       // it need to be shifted to the right side before STBRX.
14943       if (Op1VT.bitsGT(mVT)) {
14944         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14945         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14946                               DAG.getConstant(Shift, dl, MVT::i32));
14947         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14948         if (Op1VT == MVT::i64)
14949           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14950       }
14951 
14952       SDValue Ops[] = {
14953         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14954       };
14955       return
14956         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14957                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14958                                 cast<StoreSDNode>(N)->getMemOperand());
14959     }
14960 
14961     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14962     // So it can increase the chance of CSE constant construction.
14963     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14964         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14965       // Need to sign-extended to 64-bits to handle negative values.
14966       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14967       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14968                                     MemVT.getSizeInBits());
14969       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14970 
14971       // DAG.getTruncStore() can't be used here because it doesn't accept
14972       // the general (base + offset) addressing mode.
14973       // So we use UpdateNodeOperands and setTruncatingStore instead.
14974       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14975                              N->getOperand(3));
14976       cast<StoreSDNode>(N)->setTruncatingStore(true);
14977       return SDValue(N, 0);
14978     }
14979 
14980     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14981     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14982     if (Op1VT.isSimple()) {
14983       MVT StoreVT = Op1VT.getSimpleVT();
14984       if (Subtarget.needsSwapsForVSXMemOps() &&
14985           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14986            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14987         return expandVSXStoreForLE(N, DCI);
14988     }
14989     break;
14990   }
14991   case ISD::LOAD: {
14992     LoadSDNode *LD = cast<LoadSDNode>(N);
14993     EVT VT = LD->getValueType(0);
14994 
14995     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14996     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14997     if (VT.isSimple()) {
14998       MVT LoadVT = VT.getSimpleVT();
14999       if (Subtarget.needsSwapsForVSXMemOps() &&
15000           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
15001            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
15002         return expandVSXLoadForLE(N, DCI);
15003     }
15004 
15005     // We sometimes end up with a 64-bit integer load, from which we extract
15006     // two single-precision floating-point numbers. This happens with
15007     // std::complex<float>, and other similar structures, because of the way we
15008     // canonicalize structure copies. However, if we lack direct moves,
15009     // then the final bitcasts from the extracted integer values to the
15010     // floating-point numbers turn into store/load pairs. Even with direct moves,
15011     // just loading the two floating-point numbers is likely better.
15012     auto ReplaceTwoFloatLoad = [&]() {
15013       if (VT != MVT::i64)
15014         return false;
15015 
15016       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
15017           LD->isVolatile())
15018         return false;
15019 
15020       //  We're looking for a sequence like this:
15021       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
15022       //      t16: i64 = srl t13, Constant:i32<32>
15023       //    t17: i32 = truncate t16
15024       //  t18: f32 = bitcast t17
15025       //    t19: i32 = truncate t13
15026       //  t20: f32 = bitcast t19
15027 
15028       if (!LD->hasNUsesOfValue(2, 0))
15029         return false;
15030 
15031       auto UI = LD->use_begin();
15032       while (UI.getUse().getResNo() != 0) ++UI;
15033       SDNode *Trunc = *UI++;
15034       while (UI.getUse().getResNo() != 0) ++UI;
15035       SDNode *RightShift = *UI;
15036       if (Trunc->getOpcode() != ISD::TRUNCATE)
15037         std::swap(Trunc, RightShift);
15038 
15039       if (Trunc->getOpcode() != ISD::TRUNCATE ||
15040           Trunc->getValueType(0) != MVT::i32 ||
15041           !Trunc->hasOneUse())
15042         return false;
15043       if (RightShift->getOpcode() != ISD::SRL ||
15044           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
15045           RightShift->getConstantOperandVal(1) != 32 ||
15046           !RightShift->hasOneUse())
15047         return false;
15048 
15049       SDNode *Trunc2 = *RightShift->use_begin();
15050       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
15051           Trunc2->getValueType(0) != MVT::i32 ||
15052           !Trunc2->hasOneUse())
15053         return false;
15054 
15055       SDNode *Bitcast = *Trunc->use_begin();
15056       SDNode *Bitcast2 = *Trunc2->use_begin();
15057 
15058       if (Bitcast->getOpcode() != ISD::BITCAST ||
15059           Bitcast->getValueType(0) != MVT::f32)
15060         return false;
15061       if (Bitcast2->getOpcode() != ISD::BITCAST ||
15062           Bitcast2->getValueType(0) != MVT::f32)
15063         return false;
15064 
15065       if (Subtarget.isLittleEndian())
15066         std::swap(Bitcast, Bitcast2);
15067 
15068       // Bitcast has the second float (in memory-layout order) and Bitcast2
15069       // has the first one.
15070 
15071       SDValue BasePtr = LD->getBasePtr();
15072       if (LD->isIndexed()) {
15073         assert(LD->getAddressingMode() == ISD::PRE_INC &&
15074                "Non-pre-inc AM on PPC?");
15075         BasePtr =
15076           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15077                       LD->getOffset());
15078       }
15079 
15080       auto MMOFlags =
15081           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
15082       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
15083                                       LD->getPointerInfo(), LD->getAlignment(),
15084                                       MMOFlags, LD->getAAInfo());
15085       SDValue AddPtr =
15086         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
15087                     BasePtr, DAG.getIntPtrConstant(4, dl));
15088       SDValue FloatLoad2 = DAG.getLoad(
15089           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
15090           LD->getPointerInfo().getWithOffset(4),
15091           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
15092 
15093       if (LD->isIndexed()) {
15094         // Note that DAGCombine should re-form any pre-increment load(s) from
15095         // what is produced here if that makes sense.
15096         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
15097       }
15098 
15099       DCI.CombineTo(Bitcast2, FloatLoad);
15100       DCI.CombineTo(Bitcast, FloatLoad2);
15101 
15102       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
15103                                     SDValue(FloatLoad2.getNode(), 1));
15104       return true;
15105     };
15106 
15107     if (ReplaceTwoFloatLoad())
15108       return SDValue(N, 0);
15109 
15110     EVT MemVT = LD->getMemoryVT();
15111     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
15112     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
15113     if (LD->isUnindexed() && VT.isVector() &&
15114         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
15115           // P8 and later hardware should just use LOAD.
15116           !Subtarget.hasP8Vector() &&
15117           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
15118            VT == MVT::v4f32))) &&
15119         LD->getAlign() < ABIAlignment) {
15120       // This is a type-legal unaligned Altivec load.
15121       SDValue Chain = LD->getChain();
15122       SDValue Ptr = LD->getBasePtr();
15123       bool isLittleEndian = Subtarget.isLittleEndian();
15124 
15125       // This implements the loading of unaligned vectors as described in
15126       // the venerable Apple Velocity Engine overview. Specifically:
15127       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
15128       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
15129       //
15130       // The general idea is to expand a sequence of one or more unaligned
15131       // loads into an alignment-based permutation-control instruction (lvsl
15132       // or lvsr), a series of regular vector loads (which always truncate
15133       // their input address to an aligned address), and a series of
15134       // permutations.  The results of these permutations are the requested
15135       // loaded values.  The trick is that the last "extra" load is not taken
15136       // from the address you might suspect (sizeof(vector) bytes after the
15137       // last requested load), but rather sizeof(vector) - 1 bytes after the
15138       // last requested vector. The point of this is to avoid a page fault if
15139       // the base address happened to be aligned. This works because if the
15140       // base address is aligned, then adding less than a full vector length
15141       // will cause the last vector in the sequence to be (re)loaded.
15142       // Otherwise, the next vector will be fetched as you might suspect was
15143       // necessary.
15144 
15145       // We might be able to reuse the permutation generation from
15146       // a different base address offset from this one by an aligned amount.
15147       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
15148       // optimization later.
15149       Intrinsic::ID Intr, IntrLD, IntrPerm;
15150       MVT PermCntlTy, PermTy, LDTy;
15151       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15152                             : Intrinsic::ppc_altivec_lvsl;
15153       IntrLD = Intrinsic::ppc_altivec_lvx;
15154       IntrPerm = Intrinsic::ppc_altivec_vperm;
15155       PermCntlTy = MVT::v16i8;
15156       PermTy = MVT::v4i32;
15157       LDTy = MVT::v4i32;
15158 
15159       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
15160 
15161       // Create the new MMO for the new base load. It is like the original MMO,
15162       // but represents an area in memory almost twice the vector size centered
15163       // on the original address. If the address is unaligned, we might start
15164       // reading up to (sizeof(vector)-1) bytes below the address of the
15165       // original unaligned load.
15166       MachineFunction &MF = DAG.getMachineFunction();
15167       MachineMemOperand *BaseMMO =
15168         MF.getMachineMemOperand(LD->getMemOperand(),
15169                                 -(long)MemVT.getStoreSize()+1,
15170                                 2*MemVT.getStoreSize()-1);
15171 
15172       // Create the new base load.
15173       SDValue LDXIntID =
15174           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
15175       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
15176       SDValue BaseLoad =
15177         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15178                                 DAG.getVTList(PermTy, MVT::Other),
15179                                 BaseLoadOps, LDTy, BaseMMO);
15180 
15181       // Note that the value of IncOffset (which is provided to the next
15182       // load's pointer info offset value, and thus used to calculate the
15183       // alignment), and the value of IncValue (which is actually used to
15184       // increment the pointer value) are different! This is because we
15185       // require the next load to appear to be aligned, even though it
15186       // is actually offset from the base pointer by a lesser amount.
15187       int IncOffset = VT.getSizeInBits() / 8;
15188       int IncValue = IncOffset;
15189 
15190       // Walk (both up and down) the chain looking for another load at the real
15191       // (aligned) offset (the alignment of the other load does not matter in
15192       // this case). If found, then do not use the offset reduction trick, as
15193       // that will prevent the loads from being later combined (as they would
15194       // otherwise be duplicates).
15195       if (!findConsecutiveLoad(LD, DAG))
15196         --IncValue;
15197 
15198       SDValue Increment =
15199           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
15200       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15201 
15202       MachineMemOperand *ExtraMMO =
15203         MF.getMachineMemOperand(LD->getMemOperand(),
15204                                 1, 2*MemVT.getStoreSize()-1);
15205       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
15206       SDValue ExtraLoad =
15207         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15208                                 DAG.getVTList(PermTy, MVT::Other),
15209                                 ExtraLoadOps, LDTy, ExtraMMO);
15210 
15211       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15212         BaseLoad.getValue(1), ExtraLoad.getValue(1));
15213 
15214       // Because vperm has a big-endian bias, we must reverse the order
15215       // of the input vectors and complement the permute control vector
15216       // when generating little endian code.  We have already handled the
15217       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
15218       // and ExtraLoad here.
15219       SDValue Perm;
15220       if (isLittleEndian)
15221         Perm = BuildIntrinsicOp(IntrPerm,
15222                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
15223       else
15224         Perm = BuildIntrinsicOp(IntrPerm,
15225                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
15226 
15227       if (VT != PermTy)
15228         Perm = Subtarget.hasAltivec()
15229                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
15230                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
15231                                  DAG.getTargetConstant(1, dl, MVT::i64));
15232                                // second argument is 1 because this rounding
15233                                // is always exact.
15234 
15235       // The output of the permutation is our loaded result, the TokenFactor is
15236       // our new chain.
15237       DCI.CombineTo(N, Perm, TF);
15238       return SDValue(N, 0);
15239     }
15240     }
15241     break;
15242     case ISD::INTRINSIC_WO_CHAIN: {
15243       bool isLittleEndian = Subtarget.isLittleEndian();
15244       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15245       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15246                                            : Intrinsic::ppc_altivec_lvsl);
15247       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
15248         SDValue Add = N->getOperand(1);
15249 
15250         int Bits = 4 /* 16 byte alignment */;
15251 
15252         if (DAG.MaskedValueIsZero(Add->getOperand(1),
15253                                   APInt::getAllOnes(Bits /* alignment */)
15254                                       .zext(Add.getScalarValueSizeInBits()))) {
15255           SDNode *BasePtr = Add->getOperand(0).getNode();
15256           for (SDNode::use_iterator UI = BasePtr->use_begin(),
15257                                     UE = BasePtr->use_end();
15258                UI != UE; ++UI) {
15259             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15260                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
15261                     IID) {
15262               // We've found another LVSL/LVSR, and this address is an aligned
15263               // multiple of that one. The results will be the same, so use the
15264               // one we've just found instead.
15265 
15266               return SDValue(*UI, 0);
15267             }
15268           }
15269         }
15270 
15271         if (isa<ConstantSDNode>(Add->getOperand(1))) {
15272           SDNode *BasePtr = Add->getOperand(0).getNode();
15273           for (SDNode::use_iterator UI = BasePtr->use_begin(),
15274                UE = BasePtr->use_end(); UI != UE; ++UI) {
15275             if (UI->getOpcode() == ISD::ADD &&
15276                 isa<ConstantSDNode>(UI->getOperand(1)) &&
15277                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
15278                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
15279                 (1ULL << Bits) == 0) {
15280               SDNode *OtherAdd = *UI;
15281               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
15282                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
15283                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15284                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
15285                   return SDValue(*VI, 0);
15286                 }
15287               }
15288             }
15289           }
15290         }
15291       }
15292 
15293       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
15294       // Expose the vabsduw/h/b opportunity for down stream
15295       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
15296           (IID == Intrinsic::ppc_altivec_vmaxsw ||
15297            IID == Intrinsic::ppc_altivec_vmaxsh ||
15298            IID == Intrinsic::ppc_altivec_vmaxsb)) {
15299         SDValue V1 = N->getOperand(1);
15300         SDValue V2 = N->getOperand(2);
15301         if ((V1.getSimpleValueType() == MVT::v4i32 ||
15302              V1.getSimpleValueType() == MVT::v8i16 ||
15303              V1.getSimpleValueType() == MVT::v16i8) &&
15304             V1.getSimpleValueType() == V2.getSimpleValueType()) {
15305           // (0-a, a)
15306           if (V1.getOpcode() == ISD::SUB &&
15307               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
15308               V1.getOperand(1) == V2) {
15309             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
15310           }
15311           // (a, 0-a)
15312           if (V2.getOpcode() == ISD::SUB &&
15313               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
15314               V2.getOperand(1) == V1) {
15315             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15316           }
15317           // (x-y, y-x)
15318           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
15319               V1.getOperand(0) == V2.getOperand(1) &&
15320               V1.getOperand(1) == V2.getOperand(0)) {
15321             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15322           }
15323         }
15324       }
15325     }
15326 
15327     break;
15328   case ISD::INTRINSIC_W_CHAIN:
15329     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15330     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15331     if (Subtarget.needsSwapsForVSXMemOps()) {
15332       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15333       default:
15334         break;
15335       case Intrinsic::ppc_vsx_lxvw4x:
15336       case Intrinsic::ppc_vsx_lxvd2x:
15337         return expandVSXLoadForLE(N, DCI);
15338       }
15339     }
15340     break;
15341   case ISD::INTRINSIC_VOID:
15342     // For little endian, VSX stores require generating xxswapd/stxvd2x.
15343     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15344     if (Subtarget.needsSwapsForVSXMemOps()) {
15345       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15346       default:
15347         break;
15348       case Intrinsic::ppc_vsx_stxvw4x:
15349       case Intrinsic::ppc_vsx_stxvd2x:
15350         return expandVSXStoreForLE(N, DCI);
15351       }
15352     }
15353     break;
15354   case ISD::BSWAP: {
15355     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
15356     // For subtargets without LDBRX, we can still do better than the default
15357     // expansion even for 64-bit BSWAP (LOAD).
15358     bool Is64BitBswapOn64BitTgt =
15359         Subtarget.isPPC64() && N->getValueType(0) == MVT::i64;
15360     bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) &&
15361                                N->getOperand(0).hasOneUse();
15362     if (IsSingleUseNormalLd &&
15363         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
15364          (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) {
15365       SDValue Load = N->getOperand(0);
15366       LoadSDNode *LD = cast<LoadSDNode>(Load);
15367       // Create the byte-swapping load.
15368       SDValue Ops[] = {
15369         LD->getChain(),    // Chain
15370         LD->getBasePtr(),  // Ptr
15371         DAG.getValueType(N->getValueType(0)) // VT
15372       };
15373       SDValue BSLoad =
15374         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
15375                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
15376                                               MVT::i64 : MVT::i32, MVT::Other),
15377                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
15378 
15379       // If this is an i16 load, insert the truncate.
15380       SDValue ResVal = BSLoad;
15381       if (N->getValueType(0) == MVT::i16)
15382         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
15383 
15384       // First, combine the bswap away.  This makes the value produced by the
15385       // load dead.
15386       DCI.CombineTo(N, ResVal);
15387 
15388       // Next, combine the load away, we give it a bogus result value but a real
15389       // chain result.  The result value is dead because the bswap is dead.
15390       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
15391 
15392       // Return N so it doesn't get rechecked!
15393       return SDValue(N, 0);
15394     }
15395     // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only
15396     // before legalization so that the BUILD_PAIR is handled correctly.
15397     if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt ||
15398         !IsSingleUseNormalLd)
15399       return SDValue();
15400     LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0));
15401 
15402     // Can't split volatile or atomic loads.
15403     if (!LD->isSimple())
15404       return SDValue();
15405     SDValue BasePtr = LD->getBasePtr();
15406     SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr,
15407                              LD->getPointerInfo(), LD->getAlignment());
15408     Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo);
15409     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15410                           DAG.getIntPtrConstant(4, dl));
15411     MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand(
15412         LD->getMemOperand(), 4, 4);
15413     SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO);
15414     Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi);
15415     SDValue Res;
15416     if (Subtarget.isLittleEndian())
15417       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo);
15418     else
15419       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
15420     SDValue TF =
15421         DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15422                     Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1));
15423     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF);
15424     return Res;
15425   }
15426   case PPCISD::VCMP:
15427     // If a VCMP_rec node already exists with exactly the same operands as this
15428     // node, use its result instead of this node (VCMP_rec computes both a CR6
15429     // and a normal output).
15430     //
15431     if (!N->getOperand(0).hasOneUse() &&
15432         !N->getOperand(1).hasOneUse() &&
15433         !N->getOperand(2).hasOneUse()) {
15434 
15435       // Scan all of the users of the LHS, looking for VCMP_rec's that match.
15436       SDNode *VCMPrecNode = nullptr;
15437 
15438       SDNode *LHSN = N->getOperand(0).getNode();
15439       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
15440            UI != E; ++UI)
15441         if (UI->getOpcode() == PPCISD::VCMP_rec &&
15442             UI->getOperand(1) == N->getOperand(1) &&
15443             UI->getOperand(2) == N->getOperand(2) &&
15444             UI->getOperand(0) == N->getOperand(0)) {
15445           VCMPrecNode = *UI;
15446           break;
15447         }
15448 
15449       // If there is no VCMP_rec node, or if the flag value has a single use,
15450       // don't transform this.
15451       if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
15452         break;
15453 
15454       // Look at the (necessarily single) use of the flag value.  If it has a
15455       // chain, this transformation is more complex.  Note that multiple things
15456       // could use the value result, which we should ignore.
15457       SDNode *FlagUser = nullptr;
15458       for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
15459            FlagUser == nullptr; ++UI) {
15460         assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
15461         SDNode *User = *UI;
15462         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
15463           if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
15464             FlagUser = User;
15465             break;
15466           }
15467         }
15468       }
15469 
15470       // If the user is a MFOCRF instruction, we know this is safe.
15471       // Otherwise we give up for right now.
15472       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
15473         return SDValue(VCMPrecNode, 0);
15474     }
15475     break;
15476   case ISD::BRCOND: {
15477     SDValue Cond = N->getOperand(1);
15478     SDValue Target = N->getOperand(2);
15479 
15480     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15481         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15482           Intrinsic::loop_decrement) {
15483 
15484       // We now need to make the intrinsic dead (it cannot be instruction
15485       // selected).
15486       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15487       assert(Cond.getNode()->hasOneUse() &&
15488              "Counter decrement has more than one use");
15489 
15490       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15491                          N->getOperand(0), Target);
15492     }
15493   }
15494   break;
15495   case ISD::BR_CC: {
15496     // If this is a branch on an altivec predicate comparison, lower this so
15497     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15498     // lowering is done pre-legalize, because the legalizer lowers the predicate
15499     // compare down to code that is difficult to reassemble.
15500     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15501     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15502 
15503     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15504     // value. If so, pass-through the AND to get to the intrinsic.
15505     if (LHS.getOpcode() == ISD::AND &&
15506         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15507         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15508           Intrinsic::loop_decrement &&
15509         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15510         !isNullConstant(LHS.getOperand(1)))
15511       LHS = LHS.getOperand(0);
15512 
15513     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15514         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15515           Intrinsic::loop_decrement &&
15516         isa<ConstantSDNode>(RHS)) {
15517       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15518              "Counter decrement comparison is not EQ or NE");
15519 
15520       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15521       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15522                     (CC == ISD::SETNE && !Val);
15523 
15524       // We now need to make the intrinsic dead (it cannot be instruction
15525       // selected).
15526       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15527       assert(LHS.getNode()->hasOneUse() &&
15528              "Counter decrement has more than one use");
15529 
15530       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15531                          N->getOperand(0), N->getOperand(4));
15532     }
15533 
15534     int CompareOpc;
15535     bool isDot;
15536 
15537     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15538         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15539         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15540       assert(isDot && "Can't compare against a vector result!");
15541 
15542       // If this is a comparison against something other than 0/1, then we know
15543       // that the condition is never/always true.
15544       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15545       if (Val != 0 && Val != 1) {
15546         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15547           return N->getOperand(0);
15548         // Always !=, turn it into an unconditional branch.
15549         return DAG.getNode(ISD::BR, dl, MVT::Other,
15550                            N->getOperand(0), N->getOperand(4));
15551       }
15552 
15553       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15554 
15555       // Create the PPCISD altivec 'dot' comparison node.
15556       SDValue Ops[] = {
15557         LHS.getOperand(2),  // LHS of compare
15558         LHS.getOperand(3),  // RHS of compare
15559         DAG.getConstant(CompareOpc, dl, MVT::i32)
15560       };
15561       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15562       SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
15563 
15564       // Unpack the result based on how the target uses it.
15565       PPC::Predicate CompOpc;
15566       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15567       default:  // Can't happen, don't crash on invalid number though.
15568       case 0:   // Branch on the value of the EQ bit of CR6.
15569         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15570         break;
15571       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15572         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15573         break;
15574       case 2:   // Branch on the value of the LT bit of CR6.
15575         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15576         break;
15577       case 3:   // Branch on the inverted value of the LT bit of CR6.
15578         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15579         break;
15580       }
15581 
15582       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15583                          DAG.getConstant(CompOpc, dl, MVT::i32),
15584                          DAG.getRegister(PPC::CR6, MVT::i32),
15585                          N->getOperand(4), CompNode.getValue(1));
15586     }
15587     break;
15588   }
15589   case ISD::BUILD_VECTOR:
15590     return DAGCombineBuildVector(N, DCI);
15591   case ISD::ABS:
15592     return combineABS(N, DCI);
15593   case ISD::VSELECT:
15594     return combineVSelect(N, DCI);
15595   }
15596 
15597   return SDValue();
15598 }
15599 
15600 SDValue
15601 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15602                                  SelectionDAG &DAG,
15603                                  SmallVectorImpl<SDNode *> &Created) const {
15604   // fold (sdiv X, pow2)
15605   EVT VT = N->getValueType(0);
15606   if (VT == MVT::i64 && !Subtarget.isPPC64())
15607     return SDValue();
15608   if ((VT != MVT::i32 && VT != MVT::i64) ||
15609       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
15610     return SDValue();
15611 
15612   SDLoc DL(N);
15613   SDValue N0 = N->getOperand(0);
15614 
15615   bool IsNegPow2 = (-Divisor).isPowerOf2();
15616   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15617   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15618 
15619   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15620   Created.push_back(Op.getNode());
15621 
15622   if (IsNegPow2) {
15623     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15624     Created.push_back(Op.getNode());
15625   }
15626 
15627   return Op;
15628 }
15629 
15630 //===----------------------------------------------------------------------===//
15631 // Inline Assembly Support
15632 //===----------------------------------------------------------------------===//
15633 
15634 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15635                                                       KnownBits &Known,
15636                                                       const APInt &DemandedElts,
15637                                                       const SelectionDAG &DAG,
15638                                                       unsigned Depth) const {
15639   Known.resetAll();
15640   switch (Op.getOpcode()) {
15641   default: break;
15642   case PPCISD::LBRX: {
15643     // lhbrx is known to have the top bits cleared out.
15644     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15645       Known.Zero = 0xFFFF0000;
15646     break;
15647   }
15648   case ISD::INTRINSIC_WO_CHAIN: {
15649     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15650     default: break;
15651     case Intrinsic::ppc_altivec_vcmpbfp_p:
15652     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15653     case Intrinsic::ppc_altivec_vcmpequb_p:
15654     case Intrinsic::ppc_altivec_vcmpequh_p:
15655     case Intrinsic::ppc_altivec_vcmpequw_p:
15656     case Intrinsic::ppc_altivec_vcmpequd_p:
15657     case Intrinsic::ppc_altivec_vcmpequq_p:
15658     case Intrinsic::ppc_altivec_vcmpgefp_p:
15659     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15660     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15661     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15662     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15663     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15664     case Intrinsic::ppc_altivec_vcmpgtsq_p:
15665     case Intrinsic::ppc_altivec_vcmpgtub_p:
15666     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15667     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15668     case Intrinsic::ppc_altivec_vcmpgtud_p:
15669     case Intrinsic::ppc_altivec_vcmpgtuq_p:
15670       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15671       break;
15672     }
15673     break;
15674   }
15675   case ISD::INTRINSIC_W_CHAIN: {
15676     switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
15677     default:
15678       break;
15679     case Intrinsic::ppc_load2r:
15680       // Top bits are cleared for load2r (which is the same as lhbrx).
15681       Known.Zero = 0xFFFF0000;
15682       break;
15683     }
15684     break;
15685   }
15686   }
15687 }
15688 
15689 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15690   switch (Subtarget.getCPUDirective()) {
15691   default: break;
15692   case PPC::DIR_970:
15693   case PPC::DIR_PWR4:
15694   case PPC::DIR_PWR5:
15695   case PPC::DIR_PWR5X:
15696   case PPC::DIR_PWR6:
15697   case PPC::DIR_PWR6X:
15698   case PPC::DIR_PWR7:
15699   case PPC::DIR_PWR8:
15700   case PPC::DIR_PWR9:
15701   case PPC::DIR_PWR10:
15702   case PPC::DIR_PWR_FUTURE: {
15703     if (!ML)
15704       break;
15705 
15706     if (!DisableInnermostLoopAlign32) {
15707       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15708       // so that we can decrease cache misses and branch-prediction misses.
15709       // Actual alignment of the loop will depend on the hotness check and other
15710       // logic in alignBlocks.
15711       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15712         return Align(32);
15713     }
15714 
15715     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15716 
15717     // For small loops (between 5 and 8 instructions), align to a 32-byte
15718     // boundary so that the entire loop fits in one instruction-cache line.
15719     uint64_t LoopSize = 0;
15720     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15721       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15722         LoopSize += TII->getInstSizeInBytes(*J);
15723         if (LoopSize > 32)
15724           break;
15725       }
15726 
15727     if (LoopSize > 16 && LoopSize <= 32)
15728       return Align(32);
15729 
15730     break;
15731   }
15732   }
15733 
15734   return TargetLowering::getPrefLoopAlignment(ML);
15735 }
15736 
15737 /// getConstraintType - Given a constraint, return the type of
15738 /// constraint it is for this target.
15739 PPCTargetLowering::ConstraintType
15740 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15741   if (Constraint.size() == 1) {
15742     switch (Constraint[0]) {
15743     default: break;
15744     case 'b':
15745     case 'r':
15746     case 'f':
15747     case 'd':
15748     case 'v':
15749     case 'y':
15750       return C_RegisterClass;
15751     case 'Z':
15752       // FIXME: While Z does indicate a memory constraint, it specifically
15753       // indicates an r+r address (used in conjunction with the 'y' modifier
15754       // in the replacement string). Currently, we're forcing the base
15755       // register to be r0 in the asm printer (which is interpreted as zero)
15756       // and forming the complete address in the second register. This is
15757       // suboptimal.
15758       return C_Memory;
15759     }
15760   } else if (Constraint == "wc") { // individual CR bits.
15761     return C_RegisterClass;
15762   } else if (Constraint == "wa" || Constraint == "wd" ||
15763              Constraint == "wf" || Constraint == "ws" ||
15764              Constraint == "wi" || Constraint == "ww") {
15765     return C_RegisterClass; // VSX registers.
15766   }
15767   return TargetLowering::getConstraintType(Constraint);
15768 }
15769 
15770 /// Examine constraint type and operand type and determine a weight value.
15771 /// This object must already have been set up with the operand type
15772 /// and the current alternative constraint selected.
15773 TargetLowering::ConstraintWeight
15774 PPCTargetLowering::getSingleConstraintMatchWeight(
15775     AsmOperandInfo &info, const char *constraint) const {
15776   ConstraintWeight weight = CW_Invalid;
15777   Value *CallOperandVal = info.CallOperandVal;
15778     // If we don't have a value, we can't do a match,
15779     // but allow it at the lowest weight.
15780   if (!CallOperandVal)
15781     return CW_Default;
15782   Type *type = CallOperandVal->getType();
15783 
15784   // Look at the constraint type.
15785   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15786     return CW_Register; // an individual CR bit.
15787   else if ((StringRef(constraint) == "wa" ||
15788             StringRef(constraint) == "wd" ||
15789             StringRef(constraint) == "wf") &&
15790            type->isVectorTy())
15791     return CW_Register;
15792   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15793     return CW_Register; // just hold 64-bit integers data.
15794   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15795     return CW_Register;
15796   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15797     return CW_Register;
15798 
15799   switch (*constraint) {
15800   default:
15801     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15802     break;
15803   case 'b':
15804     if (type->isIntegerTy())
15805       weight = CW_Register;
15806     break;
15807   case 'f':
15808     if (type->isFloatTy())
15809       weight = CW_Register;
15810     break;
15811   case 'd':
15812     if (type->isDoubleTy())
15813       weight = CW_Register;
15814     break;
15815   case 'v':
15816     if (type->isVectorTy())
15817       weight = CW_Register;
15818     break;
15819   case 'y':
15820     weight = CW_Register;
15821     break;
15822   case 'Z':
15823     weight = CW_Memory;
15824     break;
15825   }
15826   return weight;
15827 }
15828 
15829 std::pair<unsigned, const TargetRegisterClass *>
15830 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15831                                                 StringRef Constraint,
15832                                                 MVT VT) const {
15833   if (Constraint.size() == 1) {
15834     // GCC RS6000 Constraint Letters
15835     switch (Constraint[0]) {
15836     case 'b':   // R1-R31
15837       if (VT == MVT::i64 && Subtarget.isPPC64())
15838         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15839       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15840     case 'r':   // R0-R31
15841       if (VT == MVT::i64 && Subtarget.isPPC64())
15842         return std::make_pair(0U, &PPC::G8RCRegClass);
15843       return std::make_pair(0U, &PPC::GPRCRegClass);
15844     // 'd' and 'f' constraints are both defined to be "the floating point
15845     // registers", where one is for 32-bit and the other for 64-bit. We don't
15846     // really care overly much here so just give them all the same reg classes.
15847     case 'd':
15848     case 'f':
15849       if (Subtarget.hasSPE()) {
15850         if (VT == MVT::f32 || VT == MVT::i32)
15851           return std::make_pair(0U, &PPC::GPRCRegClass);
15852         if (VT == MVT::f64 || VT == MVT::i64)
15853           return std::make_pair(0U, &PPC::SPERCRegClass);
15854       } else {
15855         if (VT == MVT::f32 || VT == MVT::i32)
15856           return std::make_pair(0U, &PPC::F4RCRegClass);
15857         if (VT == MVT::f64 || VT == MVT::i64)
15858           return std::make_pair(0U, &PPC::F8RCRegClass);
15859       }
15860       break;
15861     case 'v':
15862       if (Subtarget.hasAltivec())
15863         return std::make_pair(0U, &PPC::VRRCRegClass);
15864       break;
15865     case 'y':   // crrc
15866       return std::make_pair(0U, &PPC::CRRCRegClass);
15867     }
15868   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15869     // An individual CR bit.
15870     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15871   } else if ((Constraint == "wa" || Constraint == "wd" ||
15872              Constraint == "wf" || Constraint == "wi") &&
15873              Subtarget.hasVSX()) {
15874     // A VSX register for either a scalar (FP) or vector. There is no
15875     // support for single precision scalars on subtargets prior to Power8.
15876     if (VT.isVector())
15877       return std::make_pair(0U, &PPC::VSRCRegClass);
15878     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15879       return std::make_pair(0U, &PPC::VSSRCRegClass);
15880     return std::make_pair(0U, &PPC::VSFRCRegClass);
15881   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15882     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15883       return std::make_pair(0U, &PPC::VSSRCRegClass);
15884     else
15885       return std::make_pair(0U, &PPC::VSFRCRegClass);
15886   } else if (Constraint == "lr") {
15887     if (VT == MVT::i64)
15888       return std::make_pair(0U, &PPC::LR8RCRegClass);
15889     else
15890       return std::make_pair(0U, &PPC::LRRCRegClass);
15891   }
15892 
15893   // Handle special cases of physical registers that are not properly handled
15894   // by the base class.
15895   if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
15896     // If we name a VSX register, we can't defer to the base class because it
15897     // will not recognize the correct register (their names will be VSL{0-31}
15898     // and V{0-31} so they won't match). So we match them here.
15899     if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15900       int VSNum = atoi(Constraint.data() + 3);
15901       assert(VSNum >= 0 && VSNum <= 63 &&
15902              "Attempted to access a vsr out of range");
15903       if (VSNum < 32)
15904         return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15905       return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15906     }
15907 
15908     // For float registers, we can't defer to the base class as it will match
15909     // the SPILLTOVSRRC class.
15910     if (Constraint.size() > 3 && Constraint[1] == 'f') {
15911       int RegNum = atoi(Constraint.data() + 2);
15912       if (RegNum > 31 || RegNum < 0)
15913         report_fatal_error("Invalid floating point register number");
15914       if (VT == MVT::f32 || VT == MVT::i32)
15915         return Subtarget.hasSPE()
15916                    ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
15917                    : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
15918       if (VT == MVT::f64 || VT == MVT::i64)
15919         return Subtarget.hasSPE()
15920                    ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
15921                    : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
15922     }
15923   }
15924 
15925   std::pair<unsigned, const TargetRegisterClass *> R =
15926       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15927 
15928   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15929   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15930   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15931   // register.
15932   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15933   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15934   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15935       PPC::GPRCRegClass.contains(R.first))
15936     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15937                             PPC::sub_32, &PPC::G8RCRegClass),
15938                           &PPC::G8RCRegClass);
15939 
15940   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15941   if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) {
15942     R.first = PPC::CR0;
15943     R.second = &PPC::CRRCRegClass;
15944   }
15945   // FIXME: This warning should ideally be emitted in the front end.
15946   const auto &TM = getTargetMachine();
15947   if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) {
15948     if (((R.first >= PPC::V20 && R.first <= PPC::V31) ||
15949          (R.first >= PPC::VF20 && R.first <= PPC::VF31)) &&
15950         (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass))
15951       errs() << "warning: vector registers 20 to 32 are reserved in the "
15952                 "default AIX AltiVec ABI and cannot be used\n";
15953   }
15954 
15955   return R;
15956 }
15957 
15958 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15959 /// vector.  If it is invalid, don't add anything to Ops.
15960 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15961                                                      std::string &Constraint,
15962                                                      std::vector<SDValue>&Ops,
15963                                                      SelectionDAG &DAG) const {
15964   SDValue Result;
15965 
15966   // Only support length 1 constraints.
15967   if (Constraint.length() > 1) return;
15968 
15969   char Letter = Constraint[0];
15970   switch (Letter) {
15971   default: break;
15972   case 'I':
15973   case 'J':
15974   case 'K':
15975   case 'L':
15976   case 'M':
15977   case 'N':
15978   case 'O':
15979   case 'P': {
15980     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15981     if (!CST) return; // Must be an immediate to match.
15982     SDLoc dl(Op);
15983     int64_t Value = CST->getSExtValue();
15984     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15985                          // numbers are printed as such.
15986     switch (Letter) {
15987     default: llvm_unreachable("Unknown constraint letter!");
15988     case 'I':  // "I" is a signed 16-bit constant.
15989       if (isInt<16>(Value))
15990         Result = DAG.getTargetConstant(Value, dl, TCVT);
15991       break;
15992     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15993       if (isShiftedUInt<16, 16>(Value))
15994         Result = DAG.getTargetConstant(Value, dl, TCVT);
15995       break;
15996     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15997       if (isShiftedInt<16, 16>(Value))
15998         Result = DAG.getTargetConstant(Value, dl, TCVT);
15999       break;
16000     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
16001       if (isUInt<16>(Value))
16002         Result = DAG.getTargetConstant(Value, dl, TCVT);
16003       break;
16004     case 'M':  // "M" is a constant that is greater than 31.
16005       if (Value > 31)
16006         Result = DAG.getTargetConstant(Value, dl, TCVT);
16007       break;
16008     case 'N':  // "N" is a positive constant that is an exact power of two.
16009       if (Value > 0 && isPowerOf2_64(Value))
16010         Result = DAG.getTargetConstant(Value, dl, TCVT);
16011       break;
16012     case 'O':  // "O" is the constant zero.
16013       if (Value == 0)
16014         Result = DAG.getTargetConstant(Value, dl, TCVT);
16015       break;
16016     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
16017       if (isInt<16>(-Value))
16018         Result = DAG.getTargetConstant(Value, dl, TCVT);
16019       break;
16020     }
16021     break;
16022   }
16023   }
16024 
16025   if (Result.getNode()) {
16026     Ops.push_back(Result);
16027     return;
16028   }
16029 
16030   // Handle standard constraint letters.
16031   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16032 }
16033 
16034 // isLegalAddressingMode - Return true if the addressing mode represented
16035 // by AM is legal for this target, for a load/store of the specified type.
16036 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
16037                                               const AddrMode &AM, Type *Ty,
16038                                               unsigned AS,
16039                                               Instruction *I) const {
16040   // Vector type r+i form is supported since power9 as DQ form. We don't check
16041   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
16042   // imm form is preferred and the offset can be adjusted to use imm form later
16043   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
16044   // max offset to check legal addressing mode, we should be a little aggressive
16045   // to contain other offsets for that LSRUse.
16046   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
16047     return false;
16048 
16049   // PPC allows a sign-extended 16-bit immediate field.
16050   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
16051     return false;
16052 
16053   // No global is ever allowed as a base.
16054   if (AM.BaseGV)
16055     return false;
16056 
16057   // PPC only support r+r,
16058   switch (AM.Scale) {
16059   case 0:  // "r+i" or just "i", depending on HasBaseReg.
16060     break;
16061   case 1:
16062     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
16063       return false;
16064     // Otherwise we have r+r or r+i.
16065     break;
16066   case 2:
16067     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
16068       return false;
16069     // Allow 2*r as r+r.
16070     break;
16071   default:
16072     // No other scales are supported.
16073     return false;
16074   }
16075 
16076   return true;
16077 }
16078 
16079 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
16080                                            SelectionDAG &DAG) const {
16081   MachineFunction &MF = DAG.getMachineFunction();
16082   MachineFrameInfo &MFI = MF.getFrameInfo();
16083   MFI.setReturnAddressIsTaken(true);
16084 
16085   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16086     return SDValue();
16087 
16088   SDLoc dl(Op);
16089   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16090 
16091   // Make sure the function does not optimize away the store of the RA to
16092   // the stack.
16093   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
16094   FuncInfo->setLRStoreRequired();
16095   bool isPPC64 = Subtarget.isPPC64();
16096   auto PtrVT = getPointerTy(MF.getDataLayout());
16097 
16098   if (Depth > 0) {
16099     // The link register (return address) is saved in the caller's frame
16100     // not the callee's stack frame. So we must get the caller's frame
16101     // address and load the return address at the LR offset from there.
16102     SDValue FrameAddr =
16103         DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16104                     LowerFRAMEADDR(Op, DAG), MachinePointerInfo());
16105     SDValue Offset =
16106         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
16107                         isPPC64 ? MVT::i64 : MVT::i32);
16108     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16109                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
16110                        MachinePointerInfo());
16111   }
16112 
16113   // Just load the return address off the stack.
16114   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
16115   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
16116                      MachinePointerInfo());
16117 }
16118 
16119 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
16120                                           SelectionDAG &DAG) const {
16121   SDLoc dl(Op);
16122   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16123 
16124   MachineFunction &MF = DAG.getMachineFunction();
16125   MachineFrameInfo &MFI = MF.getFrameInfo();
16126   MFI.setFrameAddressIsTaken(true);
16127 
16128   EVT PtrVT = getPointerTy(MF.getDataLayout());
16129   bool isPPC64 = PtrVT == MVT::i64;
16130 
16131   // Naked functions never have a frame pointer, and so we use r1. For all
16132   // other functions, this decision must be delayed until during PEI.
16133   unsigned FrameReg;
16134   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
16135     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
16136   else
16137     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
16138 
16139   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
16140                                          PtrVT);
16141   while (Depth--)
16142     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16143                             FrameAddr, MachinePointerInfo());
16144   return FrameAddr;
16145 }
16146 
16147 // FIXME? Maybe this could be a TableGen attribute on some registers and
16148 // this table could be generated automatically from RegInfo.
16149 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
16150                                               const MachineFunction &MF) const {
16151   bool isPPC64 = Subtarget.isPPC64();
16152 
16153   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
16154   if (!is64Bit && VT != LLT::scalar(32))
16155     report_fatal_error("Invalid register global variable type");
16156 
16157   Register Reg = StringSwitch<Register>(RegName)
16158                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
16159                      .Case("r2", isPPC64 ? Register() : PPC::R2)
16160                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
16161                      .Default(Register());
16162 
16163   if (Reg)
16164     return Reg;
16165   report_fatal_error("Invalid register name global variable");
16166 }
16167 
16168 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
16169   // 32-bit SVR4 ABI access everything as got-indirect.
16170   if (Subtarget.is32BitELFABI())
16171     return true;
16172 
16173   // AIX accesses everything indirectly through the TOC, which is similar to
16174   // the GOT.
16175   if (Subtarget.isAIXABI())
16176     return true;
16177 
16178   CodeModel::Model CModel = getTargetMachine().getCodeModel();
16179   // If it is small or large code model, module locals are accessed
16180   // indirectly by loading their address from .toc/.got.
16181   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
16182     return true;
16183 
16184   // JumpTable and BlockAddress are accessed as got-indirect.
16185   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
16186     return true;
16187 
16188   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
16189     return Subtarget.isGVIndirectSymbol(G->getGlobal());
16190 
16191   return false;
16192 }
16193 
16194 bool
16195 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
16196   // The PowerPC target isn't yet aware of offsets.
16197   return false;
16198 }
16199 
16200 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
16201                                            const CallInst &I,
16202                                            MachineFunction &MF,
16203                                            unsigned Intrinsic) const {
16204   switch (Intrinsic) {
16205   case Intrinsic::ppc_atomicrmw_xchg_i128:
16206   case Intrinsic::ppc_atomicrmw_add_i128:
16207   case Intrinsic::ppc_atomicrmw_sub_i128:
16208   case Intrinsic::ppc_atomicrmw_nand_i128:
16209   case Intrinsic::ppc_atomicrmw_and_i128:
16210   case Intrinsic::ppc_atomicrmw_or_i128:
16211   case Intrinsic::ppc_atomicrmw_xor_i128:
16212   case Intrinsic::ppc_cmpxchg_i128:
16213     Info.opc = ISD::INTRINSIC_W_CHAIN;
16214     Info.memVT = MVT::i128;
16215     Info.ptrVal = I.getArgOperand(0);
16216     Info.offset = 0;
16217     Info.align = Align(16);
16218     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
16219                  MachineMemOperand::MOVolatile;
16220     return true;
16221   case Intrinsic::ppc_atomic_load_i128:
16222     Info.opc = ISD::INTRINSIC_W_CHAIN;
16223     Info.memVT = MVT::i128;
16224     Info.ptrVal = I.getArgOperand(0);
16225     Info.offset = 0;
16226     Info.align = Align(16);
16227     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16228     return true;
16229   case Intrinsic::ppc_atomic_store_i128:
16230     Info.opc = ISD::INTRINSIC_VOID;
16231     Info.memVT = MVT::i128;
16232     Info.ptrVal = I.getArgOperand(2);
16233     Info.offset = 0;
16234     Info.align = Align(16);
16235     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16236     return true;
16237   case Intrinsic::ppc_altivec_lvx:
16238   case Intrinsic::ppc_altivec_lvxl:
16239   case Intrinsic::ppc_altivec_lvebx:
16240   case Intrinsic::ppc_altivec_lvehx:
16241   case Intrinsic::ppc_altivec_lvewx:
16242   case Intrinsic::ppc_vsx_lxvd2x:
16243   case Intrinsic::ppc_vsx_lxvw4x:
16244   case Intrinsic::ppc_vsx_lxvd2x_be:
16245   case Intrinsic::ppc_vsx_lxvw4x_be:
16246   case Intrinsic::ppc_vsx_lxvl:
16247   case Intrinsic::ppc_vsx_lxvll: {
16248     EVT VT;
16249     switch (Intrinsic) {
16250     case Intrinsic::ppc_altivec_lvebx:
16251       VT = MVT::i8;
16252       break;
16253     case Intrinsic::ppc_altivec_lvehx:
16254       VT = MVT::i16;
16255       break;
16256     case Intrinsic::ppc_altivec_lvewx:
16257       VT = MVT::i32;
16258       break;
16259     case Intrinsic::ppc_vsx_lxvd2x:
16260     case Intrinsic::ppc_vsx_lxvd2x_be:
16261       VT = MVT::v2f64;
16262       break;
16263     default:
16264       VT = MVT::v4i32;
16265       break;
16266     }
16267 
16268     Info.opc = ISD::INTRINSIC_W_CHAIN;
16269     Info.memVT = VT;
16270     Info.ptrVal = I.getArgOperand(0);
16271     Info.offset = -VT.getStoreSize()+1;
16272     Info.size = 2*VT.getStoreSize()-1;
16273     Info.align = Align(1);
16274     Info.flags = MachineMemOperand::MOLoad;
16275     return true;
16276   }
16277   case Intrinsic::ppc_altivec_stvx:
16278   case Intrinsic::ppc_altivec_stvxl:
16279   case Intrinsic::ppc_altivec_stvebx:
16280   case Intrinsic::ppc_altivec_stvehx:
16281   case Intrinsic::ppc_altivec_stvewx:
16282   case Intrinsic::ppc_vsx_stxvd2x:
16283   case Intrinsic::ppc_vsx_stxvw4x:
16284   case Intrinsic::ppc_vsx_stxvd2x_be:
16285   case Intrinsic::ppc_vsx_stxvw4x_be:
16286   case Intrinsic::ppc_vsx_stxvl:
16287   case Intrinsic::ppc_vsx_stxvll: {
16288     EVT VT;
16289     switch (Intrinsic) {
16290     case Intrinsic::ppc_altivec_stvebx:
16291       VT = MVT::i8;
16292       break;
16293     case Intrinsic::ppc_altivec_stvehx:
16294       VT = MVT::i16;
16295       break;
16296     case Intrinsic::ppc_altivec_stvewx:
16297       VT = MVT::i32;
16298       break;
16299     case Intrinsic::ppc_vsx_stxvd2x:
16300     case Intrinsic::ppc_vsx_stxvd2x_be:
16301       VT = MVT::v2f64;
16302       break;
16303     default:
16304       VT = MVT::v4i32;
16305       break;
16306     }
16307 
16308     Info.opc = ISD::INTRINSIC_VOID;
16309     Info.memVT = VT;
16310     Info.ptrVal = I.getArgOperand(1);
16311     Info.offset = -VT.getStoreSize()+1;
16312     Info.size = 2*VT.getStoreSize()-1;
16313     Info.align = Align(1);
16314     Info.flags = MachineMemOperand::MOStore;
16315     return true;
16316   }
16317   default:
16318     break;
16319   }
16320 
16321   return false;
16322 }
16323 
16324 /// It returns EVT::Other if the type should be determined using generic
16325 /// target-independent logic.
16326 EVT PPCTargetLowering::getOptimalMemOpType(
16327     const MemOp &Op, const AttributeList &FuncAttributes) const {
16328   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
16329     // We should use Altivec/VSX loads and stores when available. For unaligned
16330     // addresses, unaligned VSX loads are only fast starting with the P8.
16331     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
16332         (Op.isAligned(Align(16)) ||
16333          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
16334       return MVT::v4i32;
16335   }
16336 
16337   if (Subtarget.isPPC64()) {
16338     return MVT::i64;
16339   }
16340 
16341   return MVT::i32;
16342 }
16343 
16344 /// Returns true if it is beneficial to convert a load of a constant
16345 /// to just the constant itself.
16346 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16347                                                           Type *Ty) const {
16348   assert(Ty->isIntegerTy());
16349 
16350   unsigned BitSize = Ty->getPrimitiveSizeInBits();
16351   return !(BitSize == 0 || BitSize > 64);
16352 }
16353 
16354 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16355   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16356     return false;
16357   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16358   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16359   return NumBits1 == 64 && NumBits2 == 32;
16360 }
16361 
16362 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16363   if (!VT1.isInteger() || !VT2.isInteger())
16364     return false;
16365   unsigned NumBits1 = VT1.getSizeInBits();
16366   unsigned NumBits2 = VT2.getSizeInBits();
16367   return NumBits1 == 64 && NumBits2 == 32;
16368 }
16369 
16370 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16371   // Generally speaking, zexts are not free, but they are free when they can be
16372   // folded with other operations.
16373   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
16374     EVT MemVT = LD->getMemoryVT();
16375     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
16376          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
16377         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
16378          LD->getExtensionType() == ISD::ZEXTLOAD))
16379       return true;
16380   }
16381 
16382   // FIXME: Add other cases...
16383   //  - 32-bit shifts with a zext to i64
16384   //  - zext after ctlz, bswap, etc.
16385   //  - zext after and by a constant mask
16386 
16387   return TargetLowering::isZExtFree(Val, VT2);
16388 }
16389 
16390 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
16391   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
16392          "invalid fpext types");
16393   // Extending to float128 is not free.
16394   if (DestVT == MVT::f128)
16395     return false;
16396   return true;
16397 }
16398 
16399 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16400   return isInt<16>(Imm) || isUInt<16>(Imm);
16401 }
16402 
16403 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16404   return isInt<16>(Imm) || isUInt<16>(Imm);
16405 }
16406 
16407 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align,
16408                                                        MachineMemOperand::Flags,
16409                                                        bool *Fast) const {
16410   if (DisablePPCUnaligned)
16411     return false;
16412 
16413   // PowerPC supports unaligned memory access for simple non-vector types.
16414   // Although accessing unaligned addresses is not as efficient as accessing
16415   // aligned addresses, it is generally more efficient than manual expansion,
16416   // and generally only traps for software emulation when crossing page
16417   // boundaries.
16418 
16419   if (!VT.isSimple())
16420     return false;
16421 
16422   if (VT.isFloatingPoint() && !VT.isVector() &&
16423       !Subtarget.allowsUnalignedFPAccess())
16424     return false;
16425 
16426   if (VT.getSimpleVT().isVector()) {
16427     if (Subtarget.hasVSX()) {
16428       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
16429           VT != MVT::v4f32 && VT != MVT::v4i32)
16430         return false;
16431     } else {
16432       return false;
16433     }
16434   }
16435 
16436   if (VT == MVT::ppcf128)
16437     return false;
16438 
16439   if (Fast)
16440     *Fast = true;
16441 
16442   return true;
16443 }
16444 
16445 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
16446                                                SDValue C) const {
16447   // Check integral scalar types.
16448   if (!VT.isScalarInteger())
16449     return false;
16450   if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
16451     if (!ConstNode->getAPIntValue().isSignedIntN(64))
16452       return false;
16453     // This transformation will generate >= 2 operations. But the following
16454     // cases will generate <= 2 instructions during ISEL. So exclude them.
16455     // 1. If the constant multiplier fits 16 bits, it can be handled by one
16456     // HW instruction, ie. MULLI
16457     // 2. If the multiplier after shifted fits 16 bits, an extra shift
16458     // instruction is needed than case 1, ie. MULLI and RLDICR
16459     int64_t Imm = ConstNode->getSExtValue();
16460     unsigned Shift = countTrailingZeros<uint64_t>(Imm);
16461     Imm >>= Shift;
16462     if (isInt<16>(Imm))
16463       return false;
16464     uint64_t UImm = static_cast<uint64_t>(Imm);
16465     if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
16466         isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
16467       return true;
16468   }
16469   return false;
16470 }
16471 
16472 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16473                                                    EVT VT) const {
16474   return isFMAFasterThanFMulAndFAdd(
16475       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
16476 }
16477 
16478 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
16479                                                    Type *Ty) const {
16480   switch (Ty->getScalarType()->getTypeID()) {
16481   case Type::FloatTyID:
16482   case Type::DoubleTyID:
16483     return true;
16484   case Type::FP128TyID:
16485     return Subtarget.hasP9Vector();
16486   default:
16487     return false;
16488   }
16489 }
16490 
16491 // FIXME: add more patterns which are not profitable to hoist.
16492 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
16493   if (!I->hasOneUse())
16494     return true;
16495 
16496   Instruction *User = I->user_back();
16497   assert(User && "A single use instruction with no uses.");
16498 
16499   switch (I->getOpcode()) {
16500   case Instruction::FMul: {
16501     // Don't break FMA, PowerPC prefers FMA.
16502     if (User->getOpcode() != Instruction::FSub &&
16503         User->getOpcode() != Instruction::FAdd)
16504       return true;
16505 
16506     const TargetOptions &Options = getTargetMachine().Options;
16507     const Function *F = I->getFunction();
16508     const DataLayout &DL = F->getParent()->getDataLayout();
16509     Type *Ty = User->getOperand(0)->getType();
16510 
16511     return !(
16512         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
16513         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
16514         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
16515   }
16516   case Instruction::Load: {
16517     // Don't break "store (load float*)" pattern, this pattern will be combined
16518     // to "store (load int32)" in later InstCombine pass. See function
16519     // combineLoadToOperationType. On PowerPC, loading a float point takes more
16520     // cycles than loading a 32 bit integer.
16521     LoadInst *LI = cast<LoadInst>(I);
16522     // For the loads that combineLoadToOperationType does nothing, like
16523     // ordered load, it should be profitable to hoist them.
16524     // For swifterror load, it can only be used for pointer to pointer type, so
16525     // later type check should get rid of this case.
16526     if (!LI->isUnordered())
16527       return true;
16528 
16529     if (User->getOpcode() != Instruction::Store)
16530       return true;
16531 
16532     if (I->getType()->getTypeID() != Type::FloatTyID)
16533       return true;
16534 
16535     return false;
16536   }
16537   default:
16538     return true;
16539   }
16540   return true;
16541 }
16542 
16543 const MCPhysReg *
16544 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
16545   // LR is a callee-save register, but we must treat it as clobbered by any call
16546   // site. Hence we include LR in the scratch registers, which are in turn added
16547   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
16548   // to CTR, which is used by any indirect call.
16549   static const MCPhysReg ScratchRegs[] = {
16550     PPC::X12, PPC::LR8, PPC::CTR8, 0
16551   };
16552 
16553   return ScratchRegs;
16554 }
16555 
16556 Register PPCTargetLowering::getExceptionPointerRegister(
16557     const Constant *PersonalityFn) const {
16558   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
16559 }
16560 
16561 Register PPCTargetLowering::getExceptionSelectorRegister(
16562     const Constant *PersonalityFn) const {
16563   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
16564 }
16565 
16566 bool
16567 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
16568                      EVT VT , unsigned DefinedValues) const {
16569   if (VT == MVT::v2i64)
16570     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
16571 
16572   if (Subtarget.hasVSX())
16573     return true;
16574 
16575   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
16576 }
16577 
16578 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16579   if (DisableILPPref || Subtarget.enableMachineScheduler())
16580     return TargetLowering::getSchedulingPreference(N);
16581 
16582   return Sched::ILP;
16583 }
16584 
16585 // Create a fast isel object.
16586 FastISel *
16587 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16588                                   const TargetLibraryInfo *LibInfo) const {
16589   return PPC::createFastISel(FuncInfo, LibInfo);
16590 }
16591 
16592 // 'Inverted' means the FMA opcode after negating one multiplicand.
16593 // For example, (fma -a b c) = (fnmsub a b c)
16594 static unsigned invertFMAOpcode(unsigned Opc) {
16595   switch (Opc) {
16596   default:
16597     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16598   case ISD::FMA:
16599     return PPCISD::FNMSUB;
16600   case PPCISD::FNMSUB:
16601     return ISD::FMA;
16602   }
16603 }
16604 
16605 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16606                                                 bool LegalOps, bool OptForSize,
16607                                                 NegatibleCost &Cost,
16608                                                 unsigned Depth) const {
16609   if (Depth > SelectionDAG::MaxRecursionDepth)
16610     return SDValue();
16611 
16612   unsigned Opc = Op.getOpcode();
16613   EVT VT = Op.getValueType();
16614   SDNodeFlags Flags = Op.getNode()->getFlags();
16615 
16616   switch (Opc) {
16617   case PPCISD::FNMSUB:
16618     if (!Op.hasOneUse() || !isTypeLegal(VT))
16619       break;
16620 
16621     const TargetOptions &Options = getTargetMachine().Options;
16622     SDValue N0 = Op.getOperand(0);
16623     SDValue N1 = Op.getOperand(1);
16624     SDValue N2 = Op.getOperand(2);
16625     SDLoc Loc(Op);
16626 
16627     NegatibleCost N2Cost = NegatibleCost::Expensive;
16628     SDValue NegN2 =
16629         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16630 
16631     if (!NegN2)
16632       return SDValue();
16633 
16634     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16635     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16636     // These transformations may change sign of zeroes. For example,
16637     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16638     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16639       // Try and choose the cheaper one to negate.
16640       NegatibleCost N0Cost = NegatibleCost::Expensive;
16641       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16642                                            N0Cost, Depth + 1);
16643 
16644       NegatibleCost N1Cost = NegatibleCost::Expensive;
16645       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16646                                            N1Cost, Depth + 1);
16647 
16648       if (NegN0 && N0Cost <= N1Cost) {
16649         Cost = std::min(N0Cost, N2Cost);
16650         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16651       } else if (NegN1) {
16652         Cost = std::min(N1Cost, N2Cost);
16653         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16654       }
16655     }
16656 
16657     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16658     if (isOperationLegal(ISD::FMA, VT)) {
16659       Cost = N2Cost;
16660       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16661     }
16662 
16663     break;
16664   }
16665 
16666   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16667                                               Cost, Depth);
16668 }
16669 
16670 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16671 bool PPCTargetLowering::useLoadStackGuardNode() const {
16672   if (!Subtarget.isTargetLinux())
16673     return TargetLowering::useLoadStackGuardNode();
16674   return true;
16675 }
16676 
16677 // Override to disable global variable loading on Linux and insert AIX canary
16678 // word declaration.
16679 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16680   if (Subtarget.isAIXABI()) {
16681     M.getOrInsertGlobal(AIXSSPCanaryWordName,
16682                         Type::getInt8PtrTy(M.getContext()));
16683     return;
16684   }
16685   if (!Subtarget.isTargetLinux())
16686     return TargetLowering::insertSSPDeclarations(M);
16687 }
16688 
16689 Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const {
16690   if (Subtarget.isAIXABI())
16691     return M.getGlobalVariable(AIXSSPCanaryWordName);
16692   return TargetLowering::getSDagStackGuard(M);
16693 }
16694 
16695 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16696                                      bool ForCodeSize) const {
16697   if (!VT.isSimple() || !Subtarget.hasVSX())
16698     return false;
16699 
16700   switch(VT.getSimpleVT().SimpleTy) {
16701   default:
16702     // For FP types that are currently not supported by PPC backend, return
16703     // false. Examples: f16, f80.
16704     return false;
16705   case MVT::f32:
16706   case MVT::f64:
16707     if (Subtarget.hasPrefixInstrs()) {
16708       // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP.
16709       return true;
16710     }
16711     LLVM_FALLTHROUGH;
16712   case MVT::ppcf128:
16713     return Imm.isPosZero();
16714   }
16715 }
16716 
16717 // For vector shift operation op, fold
16718 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16719 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16720                                   SelectionDAG &DAG) {
16721   SDValue N0 = N->getOperand(0);
16722   SDValue N1 = N->getOperand(1);
16723   EVT VT = N0.getValueType();
16724   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16725   unsigned Opcode = N->getOpcode();
16726   unsigned TargetOpcode;
16727 
16728   switch (Opcode) {
16729   default:
16730     llvm_unreachable("Unexpected shift operation");
16731   case ISD::SHL:
16732     TargetOpcode = PPCISD::SHL;
16733     break;
16734   case ISD::SRL:
16735     TargetOpcode = PPCISD::SRL;
16736     break;
16737   case ISD::SRA:
16738     TargetOpcode = PPCISD::SRA;
16739     break;
16740   }
16741 
16742   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16743       N1->getOpcode() == ISD::AND)
16744     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16745       if (Mask->getZExtValue() == OpSizeInBits - 1)
16746         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16747 
16748   return SDValue();
16749 }
16750 
16751 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16752   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16753     return Value;
16754 
16755   SDValue N0 = N->getOperand(0);
16756   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16757   if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
16758       N0.getOpcode() != ISD::SIGN_EXTEND ||
16759       N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
16760       N->getValueType(0) != MVT::i64)
16761     return SDValue();
16762 
16763   // We can't save an operation here if the value is already extended, and
16764   // the existing shift is easier to combine.
16765   SDValue ExtsSrc = N0.getOperand(0);
16766   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16767       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16768     return SDValue();
16769 
16770   SDLoc DL(N0);
16771   SDValue ShiftBy = SDValue(CN1, 0);
16772   // We want the shift amount to be i32 on the extswli, but the shift could
16773   // have an i64.
16774   if (ShiftBy.getValueType() == MVT::i64)
16775     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16776 
16777   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16778                          ShiftBy);
16779 }
16780 
16781 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16782   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16783     return Value;
16784 
16785   return SDValue();
16786 }
16787 
16788 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16789   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16790     return Value;
16791 
16792   return SDValue();
16793 }
16794 
16795 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16796 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16797 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16798 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16799 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16800                                  const PPCSubtarget &Subtarget) {
16801   if (!Subtarget.isPPC64())
16802     return SDValue();
16803 
16804   SDValue LHS = N->getOperand(0);
16805   SDValue RHS = N->getOperand(1);
16806 
16807   auto isZextOfCompareWithConstant = [](SDValue Op) {
16808     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16809         Op.getValueType() != MVT::i64)
16810       return false;
16811 
16812     SDValue Cmp = Op.getOperand(0);
16813     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16814         Cmp.getOperand(0).getValueType() != MVT::i64)
16815       return false;
16816 
16817     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
16818       int64_t NegConstant = 0 - Constant->getSExtValue();
16819       // Due to the limitations of the addi instruction,
16820       // -C is required to be [-32768, 32767].
16821       return isInt<16>(NegConstant);
16822     }
16823 
16824     return false;
16825   };
16826 
16827   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
16828   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16829 
16830   // If there is a pattern, canonicalize a zext operand to the RHS.
16831   if (LHSHasPattern && !RHSHasPattern)
16832     std::swap(LHS, RHS);
16833   else if (!LHSHasPattern && !RHSHasPattern)
16834     return SDValue();
16835 
16836   SDLoc DL(N);
16837   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16838   SDValue Cmp = RHS.getOperand(0);
16839   SDValue Z = Cmp.getOperand(0);
16840   auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1));
16841   int64_t NegConstant = 0 - Constant->getSExtValue();
16842 
16843   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16844   default: break;
16845   case ISD::SETNE: {
16846     //                                 when C == 0
16847     //                             --> addze X, (addic Z, -1).carry
16848     //                            /
16849     // add X, (zext(setne Z, C))--
16850     //                            \    when -32768 <= -C <= 32767 && C != 0
16851     //                             --> addze X, (addic (addi Z, -C), -1).carry
16852     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16853                               DAG.getConstant(NegConstant, DL, MVT::i64));
16854     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16855     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16856                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16857     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16858                        SDValue(Addc.getNode(), 1));
16859     }
16860   case ISD::SETEQ: {
16861     //                                 when C == 0
16862     //                             --> addze X, (subfic Z, 0).carry
16863     //                            /
16864     // add X, (zext(sete  Z, C))--
16865     //                            \    when -32768 <= -C <= 32767 && C != 0
16866     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16867     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16868                               DAG.getConstant(NegConstant, DL, MVT::i64));
16869     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16870     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16871                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16872     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16873                        SDValue(Subc.getNode(), 1));
16874     }
16875   }
16876 
16877   return SDValue();
16878 }
16879 
16880 // Transform
16881 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16882 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16883 // In this case both C1 and C2 must be known constants.
16884 // C1+C2 must fit into a 34 bit signed integer.
16885 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16886                                           const PPCSubtarget &Subtarget) {
16887   if (!Subtarget.isUsingPCRelativeCalls())
16888     return SDValue();
16889 
16890   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16891   // If we find that node try to cast the Global Address and the Constant.
16892   SDValue LHS = N->getOperand(0);
16893   SDValue RHS = N->getOperand(1);
16894 
16895   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16896     std::swap(LHS, RHS);
16897 
16898   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16899     return SDValue();
16900 
16901   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16902   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16903   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16904 
16905   // Check that both casts succeeded.
16906   if (!GSDN || !ConstNode)
16907     return SDValue();
16908 
16909   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16910   SDLoc DL(GSDN);
16911 
16912   // The signed int offset needs to fit in 34 bits.
16913   if (!isInt<34>(NewOffset))
16914     return SDValue();
16915 
16916   // The new global address is a copy of the old global address except
16917   // that it has the updated Offset.
16918   SDValue GA =
16919       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16920                                  NewOffset, GSDN->getTargetFlags());
16921   SDValue MatPCRel =
16922       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16923   return MatPCRel;
16924 }
16925 
16926 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16927   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16928     return Value;
16929 
16930   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16931     return Value;
16932 
16933   return SDValue();
16934 }
16935 
16936 // Detect TRUNCATE operations on bitcasts of float128 values.
16937 // What we are looking for here is the situtation where we extract a subset
16938 // of bits from a 128 bit float.
16939 // This can be of two forms:
16940 // 1) BITCAST of f128 feeding TRUNCATE
16941 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16942 // The reason this is required is because we do not have a legal i128 type
16943 // and so we want to prevent having to store the f128 and then reload part
16944 // of it.
16945 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16946                                            DAGCombinerInfo &DCI) const {
16947   // If we are using CRBits then try that first.
16948   if (Subtarget.useCRBits()) {
16949     // Check if CRBits did anything and return that if it did.
16950     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16951       return CRTruncValue;
16952   }
16953 
16954   SDLoc dl(N);
16955   SDValue Op0 = N->getOperand(0);
16956 
16957   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
16958   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
16959     EVT VT = N->getValueType(0);
16960     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16961       return SDValue();
16962     SDValue Sub = Op0.getOperand(0);
16963     if (Sub.getOpcode() == ISD::SUB) {
16964       SDValue SubOp0 = Sub.getOperand(0);
16965       SDValue SubOp1 = Sub.getOperand(1);
16966       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16967           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16968         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16969                                SubOp1.getOperand(0),
16970                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16971       }
16972     }
16973   }
16974 
16975   // Looking for a truncate of i128 to i64.
16976   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16977     return SDValue();
16978 
16979   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16980 
16981   // SRL feeding TRUNCATE.
16982   if (Op0.getOpcode() == ISD::SRL) {
16983     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16984     // The right shift has to be by 64 bits.
16985     if (!ConstNode || ConstNode->getZExtValue() != 64)
16986       return SDValue();
16987 
16988     // Switch the element number to extract.
16989     EltToExtract = EltToExtract ? 0 : 1;
16990     // Update Op0 past the SRL.
16991     Op0 = Op0.getOperand(0);
16992   }
16993 
16994   // BITCAST feeding a TRUNCATE possibly via SRL.
16995   if (Op0.getOpcode() == ISD::BITCAST &&
16996       Op0.getValueType() == MVT::i128 &&
16997       Op0.getOperand(0).getValueType() == MVT::f128) {
16998     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16999     return DCI.DAG.getNode(
17000         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
17001         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
17002   }
17003   return SDValue();
17004 }
17005 
17006 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
17007   SelectionDAG &DAG = DCI.DAG;
17008 
17009   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
17010   if (!ConstOpOrElement)
17011     return SDValue();
17012 
17013   // An imul is usually smaller than the alternative sequence for legal type.
17014   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
17015       isOperationLegal(ISD::MUL, N->getValueType(0)))
17016     return SDValue();
17017 
17018   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
17019     switch (this->Subtarget.getCPUDirective()) {
17020     default:
17021       // TODO: enhance the condition for subtarget before pwr8
17022       return false;
17023     case PPC::DIR_PWR8:
17024       //  type        mul     add    shl
17025       // scalar        4       1      1
17026       // vector        7       2      2
17027       return true;
17028     case PPC::DIR_PWR9:
17029     case PPC::DIR_PWR10:
17030     case PPC::DIR_PWR_FUTURE:
17031       //  type        mul     add    shl
17032       // scalar        5       2      2
17033       // vector        7       2      2
17034 
17035       // The cycle RATIO of related operations are showed as a table above.
17036       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
17037       // scalar and vector type. For 2 instrs patterns, add/sub + shl
17038       // are 4, it is always profitable; but for 3 instrs patterns
17039       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
17040       // So we should only do it for vector type.
17041       return IsAddOne && IsNeg ? VT.isVector() : true;
17042     }
17043   };
17044 
17045   EVT VT = N->getValueType(0);
17046   SDLoc DL(N);
17047 
17048   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
17049   bool IsNeg = MulAmt.isNegative();
17050   APInt MulAmtAbs = MulAmt.abs();
17051 
17052   if ((MulAmtAbs - 1).isPowerOf2()) {
17053     // (mul x, 2^N + 1) => (add (shl x, N), x)
17054     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
17055 
17056     if (!IsProfitable(IsNeg, true, VT))
17057       return SDValue();
17058 
17059     SDValue Op0 = N->getOperand(0);
17060     SDValue Op1 =
17061         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17062                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
17063     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
17064 
17065     if (!IsNeg)
17066       return Res;
17067 
17068     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
17069   } else if ((MulAmtAbs + 1).isPowerOf2()) {
17070     // (mul x, 2^N - 1) => (sub (shl x, N), x)
17071     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
17072 
17073     if (!IsProfitable(IsNeg, false, VT))
17074       return SDValue();
17075 
17076     SDValue Op0 = N->getOperand(0);
17077     SDValue Op1 =
17078         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17079                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
17080 
17081     if (!IsNeg)
17082       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
17083     else
17084       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
17085 
17086   } else {
17087     return SDValue();
17088   }
17089 }
17090 
17091 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
17092 // in combiner since we need to check SD flags and other subtarget features.
17093 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
17094                                           DAGCombinerInfo &DCI) const {
17095   SDValue N0 = N->getOperand(0);
17096   SDValue N1 = N->getOperand(1);
17097   SDValue N2 = N->getOperand(2);
17098   SDNodeFlags Flags = N->getFlags();
17099   EVT VT = N->getValueType(0);
17100   SelectionDAG &DAG = DCI.DAG;
17101   const TargetOptions &Options = getTargetMachine().Options;
17102   unsigned Opc = N->getOpcode();
17103   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
17104   bool LegalOps = !DCI.isBeforeLegalizeOps();
17105   SDLoc Loc(N);
17106 
17107   if (!isOperationLegal(ISD::FMA, VT))
17108     return SDValue();
17109 
17110   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
17111   // since (fnmsub a b c)=-0 while c-ab=+0.
17112   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
17113     return SDValue();
17114 
17115   // (fma (fneg a) b c) => (fnmsub a b c)
17116   // (fnmsub (fneg a) b c) => (fma a b c)
17117   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
17118     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
17119 
17120   // (fma a (fneg b) c) => (fnmsub a b c)
17121   // (fnmsub a (fneg b) c) => (fma a b c)
17122   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
17123     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
17124 
17125   return SDValue();
17126 }
17127 
17128 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
17129   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
17130   if (!Subtarget.is64BitELFABI())
17131     return false;
17132 
17133   // If not a tail call then no need to proceed.
17134   if (!CI->isTailCall())
17135     return false;
17136 
17137   // If sibling calls have been disabled and tail-calls aren't guaranteed
17138   // there is no reason to duplicate.
17139   auto &TM = getTargetMachine();
17140   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
17141     return false;
17142 
17143   // Can't tail call a function called indirectly, or if it has variadic args.
17144   const Function *Callee = CI->getCalledFunction();
17145   if (!Callee || Callee->isVarArg())
17146     return false;
17147 
17148   // Make sure the callee and caller calling conventions are eligible for tco.
17149   const Function *Caller = CI->getParent()->getParent();
17150   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
17151                                            CI->getCallingConv()))
17152       return false;
17153 
17154   // If the function is local then we have a good chance at tail-calling it
17155   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
17156 }
17157 
17158 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
17159   if (!Subtarget.hasVSX())
17160     return false;
17161   if (Subtarget.hasP9Vector() && VT == MVT::f128)
17162     return true;
17163   return VT == MVT::f32 || VT == MVT::f64 ||
17164     VT == MVT::v4f32 || VT == MVT::v2f64;
17165 }
17166 
17167 bool PPCTargetLowering::
17168 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
17169   const Value *Mask = AndI.getOperand(1);
17170   // If the mask is suitable for andi. or andis. we should sink the and.
17171   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
17172     // Can't handle constants wider than 64-bits.
17173     if (CI->getBitWidth() > 64)
17174       return false;
17175     int64_t ConstVal = CI->getZExtValue();
17176     return isUInt<16>(ConstVal) ||
17177       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
17178   }
17179 
17180   // For non-constant masks, we can always use the record-form and.
17181   return true;
17182 }
17183 
17184 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
17185 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
17186 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
17187 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
17188 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
17189 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
17190   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
17191   assert(Subtarget.hasP9Altivec() &&
17192          "Only combine this when P9 altivec supported!");
17193   EVT VT = N->getValueType(0);
17194   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17195     return SDValue();
17196 
17197   SelectionDAG &DAG = DCI.DAG;
17198   SDLoc dl(N);
17199   if (N->getOperand(0).getOpcode() == ISD::SUB) {
17200     // Even for signed integers, if it's known to be positive (as signed
17201     // integer) due to zero-extended inputs.
17202     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
17203     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
17204     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
17205          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
17206         (SubOpcd1 == ISD::ZERO_EXTEND ||
17207          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
17208       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17209                          N->getOperand(0)->getOperand(0),
17210                          N->getOperand(0)->getOperand(1),
17211                          DAG.getTargetConstant(0, dl, MVT::i32));
17212     }
17213 
17214     // For type v4i32, it can be optimized with xvnegsp + vabsduw
17215     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
17216         N->getOperand(0).hasOneUse()) {
17217       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17218                          N->getOperand(0)->getOperand(0),
17219                          N->getOperand(0)->getOperand(1),
17220                          DAG.getTargetConstant(1, dl, MVT::i32));
17221     }
17222   }
17223 
17224   return SDValue();
17225 }
17226 
17227 // For type v4i32/v8ii16/v16i8, transform
17228 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
17229 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
17230 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
17231 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
17232 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
17233                                           DAGCombinerInfo &DCI) const {
17234   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
17235   assert(Subtarget.hasP9Altivec() &&
17236          "Only combine this when P9 altivec supported!");
17237 
17238   SelectionDAG &DAG = DCI.DAG;
17239   SDLoc dl(N);
17240   SDValue Cond = N->getOperand(0);
17241   SDValue TrueOpnd = N->getOperand(1);
17242   SDValue FalseOpnd = N->getOperand(2);
17243   EVT VT = N->getOperand(1).getValueType();
17244 
17245   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
17246       FalseOpnd.getOpcode() != ISD::SUB)
17247     return SDValue();
17248 
17249   // ABSD only available for type v4i32/v8i16/v16i8
17250   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17251     return SDValue();
17252 
17253   // At least to save one more dependent computation
17254   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
17255     return SDValue();
17256 
17257   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17258 
17259   // Can only handle unsigned comparison here
17260   switch (CC) {
17261   default:
17262     return SDValue();
17263   case ISD::SETUGT:
17264   case ISD::SETUGE:
17265     break;
17266   case ISD::SETULT:
17267   case ISD::SETULE:
17268     std::swap(TrueOpnd, FalseOpnd);
17269     break;
17270   }
17271 
17272   SDValue CmpOpnd1 = Cond.getOperand(0);
17273   SDValue CmpOpnd2 = Cond.getOperand(1);
17274 
17275   // SETCC CmpOpnd1 CmpOpnd2 cond
17276   // TrueOpnd = CmpOpnd1 - CmpOpnd2
17277   // FalseOpnd = CmpOpnd2 - CmpOpnd1
17278   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
17279       TrueOpnd.getOperand(1) == CmpOpnd2 &&
17280       FalseOpnd.getOperand(0) == CmpOpnd2 &&
17281       FalseOpnd.getOperand(1) == CmpOpnd1) {
17282     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
17283                        CmpOpnd1, CmpOpnd2,
17284                        DAG.getTargetConstant(0, dl, MVT::i32));
17285   }
17286 
17287   return SDValue();
17288 }
17289 
17290 /// getAddrModeForFlags - Based on the set of address flags, select the most
17291 /// optimal instruction format to match by.
17292 PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const {
17293   // This is not a node we should be handling here.
17294   if (Flags == PPC::MOF_None)
17295     return PPC::AM_None;
17296   // Unaligned D-Forms are tried first, followed by the aligned D-Forms.
17297   for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm))
17298     if ((Flags & FlagSet) == FlagSet)
17299       return PPC::AM_DForm;
17300   for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm))
17301     if ((Flags & FlagSet) == FlagSet)
17302       return PPC::AM_DSForm;
17303   for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm))
17304     if ((Flags & FlagSet) == FlagSet)
17305       return PPC::AM_DQForm;
17306   for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm))
17307     if ((Flags & FlagSet) == FlagSet)
17308       return PPC::AM_PrefixDForm;
17309   // If no other forms are selected, return an X-Form as it is the most
17310   // general addressing mode.
17311   return PPC::AM_XForm;
17312 }
17313 
17314 /// Set alignment flags based on whether or not the Frame Index is aligned.
17315 /// Utilized when computing flags for address computation when selecting
17316 /// load and store instructions.
17317 static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet,
17318                                SelectionDAG &DAG) {
17319   bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR));
17320   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N);
17321   if (!FI)
17322     return;
17323   const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17324   unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value();
17325   // If this is (add $FI, $S16Imm), the alignment flags are already set
17326   // based on the immediate. We just need to clear the alignment flags
17327   // if the FI alignment is weaker.
17328   if ((FrameIndexAlign % 4) != 0)
17329     FlagSet &= ~PPC::MOF_RPlusSImm16Mult4;
17330   if ((FrameIndexAlign % 16) != 0)
17331     FlagSet &= ~PPC::MOF_RPlusSImm16Mult16;
17332   // If the address is a plain FrameIndex, set alignment flags based on
17333   // FI alignment.
17334   if (!IsAdd) {
17335     if ((FrameIndexAlign % 4) == 0)
17336       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17337     if ((FrameIndexAlign % 16) == 0)
17338       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17339   }
17340 }
17341 
17342 /// Given a node, compute flags that are used for address computation when
17343 /// selecting load and store instructions. The flags computed are stored in
17344 /// FlagSet. This function takes into account whether the node is a constant,
17345 /// an ADD, OR, or a constant, and computes the address flags accordingly.
17346 static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet,
17347                                               SelectionDAG &DAG) {
17348   // Set the alignment flags for the node depending on if the node is
17349   // 4-byte or 16-byte aligned.
17350   auto SetAlignFlagsForImm = [&](uint64_t Imm) {
17351     if ((Imm & 0x3) == 0)
17352       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17353     if ((Imm & 0xf) == 0)
17354       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17355   };
17356 
17357   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
17358     // All 32-bit constants can be computed as LIS + Disp.
17359     const APInt &ConstImm = CN->getAPIntValue();
17360     if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants.
17361       FlagSet |= PPC::MOF_AddrIsSImm32;
17362       SetAlignFlagsForImm(ConstImm.getZExtValue());
17363       setAlignFlagsForFI(N, FlagSet, DAG);
17364     }
17365     if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants.
17366       FlagSet |= PPC::MOF_RPlusSImm34;
17367     else // Let constant materialization handle large constants.
17368       FlagSet |= PPC::MOF_NotAddNorCst;
17369   } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) {
17370     // This address can be represented as an addition of:
17371     // - Register + Imm16 (possibly a multiple of 4/16)
17372     // - Register + Imm34
17373     // - Register + PPCISD::Lo
17374     // - Register + Register
17375     // In any case, we won't have to match this as Base + Zero.
17376     SDValue RHS = N.getOperand(1);
17377     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) {
17378       const APInt &ConstImm = CN->getAPIntValue();
17379       if (ConstImm.isSignedIntN(16)) {
17380         FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates.
17381         SetAlignFlagsForImm(ConstImm.getZExtValue());
17382         setAlignFlagsForFI(N, FlagSet, DAG);
17383       }
17384       if (ConstImm.isSignedIntN(34))
17385         FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates.
17386       else
17387         FlagSet |= PPC::MOF_RPlusR; // Register.
17388     } else if (RHS.getOpcode() == PPCISD::Lo &&
17389                !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue())
17390       FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo.
17391     else
17392       FlagSet |= PPC::MOF_RPlusR;
17393   } else { // The address computation is not a constant or an addition.
17394     setAlignFlagsForFI(N, FlagSet, DAG);
17395     FlagSet |= PPC::MOF_NotAddNorCst;
17396   }
17397 }
17398 
17399 static bool isPCRelNode(SDValue N) {
17400   return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR ||
17401       isValidPCRelNode<ConstantPoolSDNode>(N) ||
17402       isValidPCRelNode<GlobalAddressSDNode>(N) ||
17403       isValidPCRelNode<JumpTableSDNode>(N) ||
17404       isValidPCRelNode<BlockAddressSDNode>(N));
17405 }
17406 
17407 /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute
17408 /// the address flags of the load/store instruction that is to be matched.
17409 unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N,
17410                                            SelectionDAG &DAG) const {
17411   unsigned FlagSet = PPC::MOF_None;
17412 
17413   // Compute subtarget flags.
17414   if (!Subtarget.hasP9Vector())
17415     FlagSet |= PPC::MOF_SubtargetBeforeP9;
17416   else {
17417     FlagSet |= PPC::MOF_SubtargetP9;
17418     if (Subtarget.hasPrefixInstrs())
17419       FlagSet |= PPC::MOF_SubtargetP10;
17420   }
17421   if (Subtarget.hasSPE())
17422     FlagSet |= PPC::MOF_SubtargetSPE;
17423 
17424   // Check if we have a PCRel node and return early.
17425   if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N))
17426     return FlagSet;
17427 
17428   // If the node is the paired load/store intrinsics, compute flags for
17429   // address computation and return early.
17430   unsigned ParentOp = Parent->getOpcode();
17431   if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) ||
17432                                (ParentOp == ISD::INTRINSIC_VOID))) {
17433     unsigned ID = cast<ConstantSDNode>(Parent->getOperand(1))->getZExtValue();
17434     assert(
17435         ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) &&
17436         "Only the paired load and store (lxvp/stxvp) intrinsics are valid.");
17437     SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp) ? Parent->getOperand(2)
17438                                                        : Parent->getOperand(3);
17439     computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG);
17440     FlagSet |= PPC::MOF_Vector;
17441     return FlagSet;
17442   }
17443 
17444   // Mark this as something we don't want to handle here if it is atomic
17445   // or pre-increment instruction.
17446   if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent))
17447     if (LSB->isIndexed())
17448       return PPC::MOF_None;
17449 
17450   // Compute in-memory type flags. This is based on if there are scalars,
17451   // floats or vectors.
17452   const MemSDNode *MN = dyn_cast<MemSDNode>(Parent);
17453   assert(MN && "Parent should be a MemSDNode!");
17454   EVT MemVT = MN->getMemoryVT();
17455   unsigned Size = MemVT.getSizeInBits();
17456   if (MemVT.isScalarInteger()) {
17457     assert(Size <= 128 &&
17458            "Not expecting scalar integers larger than 16 bytes!");
17459     if (Size < 32)
17460       FlagSet |= PPC::MOF_SubWordInt;
17461     else if (Size == 32)
17462       FlagSet |= PPC::MOF_WordInt;
17463     else
17464       FlagSet |= PPC::MOF_DoubleWordInt;
17465   } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors.
17466     if (Size == 128)
17467       FlagSet |= PPC::MOF_Vector;
17468     else if (Size == 256) {
17469       assert(Subtarget.pairedVectorMemops() &&
17470              "256-bit vectors are only available when paired vector memops is "
17471              "enabled!");
17472       FlagSet |= PPC::MOF_Vector;
17473     } else
17474       llvm_unreachable("Not expecting illegal vectors!");
17475   } else { // Floating point type: can be scalar, f128 or vector types.
17476     if (Size == 32 || Size == 64)
17477       FlagSet |= PPC::MOF_ScalarFloat;
17478     else if (MemVT == MVT::f128 || MemVT.isVector())
17479       FlagSet |= PPC::MOF_Vector;
17480     else
17481       llvm_unreachable("Not expecting illegal scalar floats!");
17482   }
17483 
17484   // Compute flags for address computation.
17485   computeFlagsForAddressComputation(N, FlagSet, DAG);
17486 
17487   // Compute type extension flags.
17488   if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) {
17489     switch (LN->getExtensionType()) {
17490     case ISD::SEXTLOAD:
17491       FlagSet |= PPC::MOF_SExt;
17492       break;
17493     case ISD::EXTLOAD:
17494     case ISD::ZEXTLOAD:
17495       FlagSet |= PPC::MOF_ZExt;
17496       break;
17497     case ISD::NON_EXTLOAD:
17498       FlagSet |= PPC::MOF_NoExt;
17499       break;
17500     }
17501   } else
17502     FlagSet |= PPC::MOF_NoExt;
17503 
17504   // For integers, no extension is the same as zero extension.
17505   // We set the extension mode to zero extension so we don't have
17506   // to add separate entries in AddrModesMap for loads and stores.
17507   if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) {
17508     FlagSet |= PPC::MOF_ZExt;
17509     FlagSet &= ~PPC::MOF_NoExt;
17510   }
17511 
17512   // If we don't have prefixed instructions, 34-bit constants should be
17513   // treated as PPC::MOF_NotAddNorCst so they can match D-Forms.
17514   bool IsNonP1034BitConst =
17515       ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) &
17516        FlagSet) == PPC::MOF_RPlusSImm34;
17517   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR &&
17518       IsNonP1034BitConst)
17519     FlagSet |= PPC::MOF_NotAddNorCst;
17520 
17521   return FlagSet;
17522 }
17523 
17524 /// SelectForceXFormMode - Given the specified address, force it to be
17525 /// represented as an indexed [r+r] operation (an XForm instruction).
17526 PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp,
17527                                                       SDValue &Base,
17528                                                       SelectionDAG &DAG) const {
17529 
17530   PPC::AddrMode Mode = PPC::AM_XForm;
17531   int16_t ForceXFormImm = 0;
17532   if (provablyDisjointOr(DAG, N) &&
17533       !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) {
17534     Disp = N.getOperand(0);
17535     Base = N.getOperand(1);
17536     return Mode;
17537   }
17538 
17539   // If the address is the result of an add, we will utilize the fact that the
17540   // address calculation includes an implicit add.  However, we can reduce
17541   // register pressure if we do not materialize a constant just for use as the
17542   // index register.  We only get rid of the add if it is not an add of a
17543   // value and a 16-bit signed constant and both have a single use.
17544   if (N.getOpcode() == ISD::ADD &&
17545       (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) ||
17546        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
17547     Disp = N.getOperand(0);
17548     Base = N.getOperand(1);
17549     return Mode;
17550   }
17551 
17552   // Otherwise, use R0 as the base register.
17553   Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17554                          N.getValueType());
17555   Base = N;
17556 
17557   return Mode;
17558 }
17559 
17560 // If we happen to match to an aligned D-Form, check if the Frame Index is
17561 // adequately aligned. If it is not, reset the mode to match to X-Form.
17562 static void setXFormForUnalignedFI(SDValue N, unsigned Flags,
17563                                    PPC::AddrMode &Mode) {
17564   if (!isa<FrameIndexSDNode>(N))
17565     return;
17566   if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) ||
17567       (Mode == PPC::AM_DQForm && !(Flags & PPC::MOF_RPlusSImm16Mult16)))
17568     Mode = PPC::AM_XForm;
17569 }
17570 
17571 /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode),
17572 /// compute the address flags of the node, get the optimal address mode based
17573 /// on the flags, and set the Base and Disp based on the address mode.
17574 PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent,
17575                                                        SDValue N, SDValue &Disp,
17576                                                        SDValue &Base,
17577                                                        SelectionDAG &DAG,
17578                                                        MaybeAlign Align) const {
17579   SDLoc DL(Parent);
17580 
17581   // Compute the address flags.
17582   unsigned Flags = computeMOFlags(Parent, N, DAG);
17583 
17584   // Get the optimal address mode based on the Flags.
17585   PPC::AddrMode Mode = getAddrModeForFlags(Flags);
17586 
17587   // If the address mode is DS-Form or DQ-Form, check if the FI is aligned.
17588   // Select an X-Form load if it is not.
17589   setXFormForUnalignedFI(N, Flags, Mode);
17590 
17591   // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node.
17592   if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) {
17593     assert(Subtarget.isUsingPCRelativeCalls() &&
17594            "Must be using PC-Relative calls when a valid PC-Relative node is "
17595            "present!");
17596     Mode = PPC::AM_PCRel;
17597   }
17598 
17599   // Set Base and Disp accordingly depending on the address mode.
17600   switch (Mode) {
17601   case PPC::AM_DForm:
17602   case PPC::AM_DSForm:
17603   case PPC::AM_DQForm: {
17604     // This is a register plus a 16-bit immediate. The base will be the
17605     // register and the displacement will be the immediate unless it
17606     // isn't sufficiently aligned.
17607     if (Flags & PPC::MOF_RPlusSImm16) {
17608       SDValue Op0 = N.getOperand(0);
17609       SDValue Op1 = N.getOperand(1);
17610       int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue();
17611       if (!Align || isAligned(*Align, Imm)) {
17612         Disp = DAG.getTargetConstant(Imm, DL, N.getValueType());
17613         Base = Op0;
17614         if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) {
17615           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17616           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17617         }
17618         break;
17619       }
17620     }
17621     // This is a register plus the @lo relocation. The base is the register
17622     // and the displacement is the global address.
17623     else if (Flags & PPC::MOF_RPlusLo) {
17624       Disp = N.getOperand(1).getOperand(0); // The global address.
17625       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
17626              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
17627              Disp.getOpcode() == ISD::TargetConstantPool ||
17628              Disp.getOpcode() == ISD::TargetJumpTable);
17629       Base = N.getOperand(0);
17630       break;
17631     }
17632     // This is a constant address at most 32 bits. The base will be
17633     // zero or load-immediate-shifted and the displacement will be
17634     // the low 16 bits of the address.
17635     else if (Flags & PPC::MOF_AddrIsSImm32) {
17636       auto *CN = cast<ConstantSDNode>(N);
17637       EVT CNType = CN->getValueType(0);
17638       uint64_t CNImm = CN->getZExtValue();
17639       // If this address fits entirely in a 16-bit sext immediate field, codegen
17640       // this as "d, 0".
17641       int16_t Imm;
17642       if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) {
17643         Disp = DAG.getTargetConstant(Imm, DL, CNType);
17644         Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17645                                CNType);
17646         break;
17647       }
17648       // Handle 32-bit sext immediate with LIS + Addr mode.
17649       if ((CNType == MVT::i32 || isInt<32>(CNImm)) &&
17650           (!Align || isAligned(*Align, CNImm))) {
17651         int32_t Addr = (int32_t)CNImm;
17652         // Otherwise, break this down into LIS + Disp.
17653         Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32);
17654         Base =
17655             DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32);
17656         uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8;
17657         Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0);
17658         break;
17659       }
17660     }
17661     // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable.
17662     Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout()));
17663     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
17664       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17665       fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17666     } else
17667       Base = N;
17668     break;
17669   }
17670   case PPC::AM_PrefixDForm: {
17671     int64_t Imm34 = 0;
17672     unsigned Opcode = N.getOpcode();
17673     if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) &&
17674         (isIntS34Immediate(N.getOperand(1), Imm34))) {
17675       // N is an Add/OR Node, and it's operand is a 34-bit signed immediate.
17676       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
17677       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
17678         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17679       else
17680         Base = N.getOperand(0);
17681     } else if (isIntS34Immediate(N, Imm34)) {
17682       // The address is a 34-bit signed immediate.
17683       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
17684       Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
17685     }
17686     break;
17687   }
17688   case PPC::AM_PCRel: {
17689     // When selecting PC-Relative instructions, "Base" is not utilized as
17690     // we select the address as [PC+imm].
17691     Disp = N;
17692     break;
17693   }
17694   case PPC::AM_None:
17695     break;
17696   default: { // By default, X-Form is always available to be selected.
17697     // When a frame index is not aligned, we also match by XForm.
17698     FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N);
17699     Base = FI ? N : N.getOperand(1);
17700     Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17701                                 N.getValueType())
17702               : N.getOperand(0);
17703     break;
17704   }
17705   }
17706   return Mode;
17707 }
17708 
17709 CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC,
17710                                                  bool Return,
17711                                                  bool IsVarArg) const {
17712   switch (CC) {
17713   case CallingConv::Cold:
17714     return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS);
17715   default:
17716     return CC_PPC64_ELF_FIS;
17717   }
17718 }
17719 
17720 TargetLowering::AtomicExpansionKind
17721 PPCTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17722   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
17723   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
17724     return AtomicExpansionKind::MaskedIntrinsic;
17725   return TargetLowering::shouldExpandAtomicRMWInIR(AI);
17726 }
17727 
17728 TargetLowering::AtomicExpansionKind
17729 PPCTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
17730   unsigned Size = AI->getNewValOperand()->getType()->getPrimitiveSizeInBits();
17731   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
17732     return AtomicExpansionKind::MaskedIntrinsic;
17733   return TargetLowering::shouldExpandAtomicCmpXchgInIR(AI);
17734 }
17735 
17736 static Intrinsic::ID
17737 getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp) {
17738   switch (BinOp) {
17739   default:
17740     llvm_unreachable("Unexpected AtomicRMW BinOp");
17741   case AtomicRMWInst::Xchg:
17742     return Intrinsic::ppc_atomicrmw_xchg_i128;
17743   case AtomicRMWInst::Add:
17744     return Intrinsic::ppc_atomicrmw_add_i128;
17745   case AtomicRMWInst::Sub:
17746     return Intrinsic::ppc_atomicrmw_sub_i128;
17747   case AtomicRMWInst::And:
17748     return Intrinsic::ppc_atomicrmw_and_i128;
17749   case AtomicRMWInst::Or:
17750     return Intrinsic::ppc_atomicrmw_or_i128;
17751   case AtomicRMWInst::Xor:
17752     return Intrinsic::ppc_atomicrmw_xor_i128;
17753   case AtomicRMWInst::Nand:
17754     return Intrinsic::ppc_atomicrmw_nand_i128;
17755   }
17756 }
17757 
17758 Value *PPCTargetLowering::emitMaskedAtomicRMWIntrinsic(
17759     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
17760     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
17761   assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
17762          "Only support quadword now");
17763   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17764   Type *ValTy = cast<PointerType>(AlignedAddr->getType())->getElementType();
17765   assert(ValTy->getPrimitiveSizeInBits() == 128);
17766   Function *RMW = Intrinsic::getDeclaration(
17767       M, getIntrinsicForAtomicRMWBinOp128(AI->getOperation()));
17768   Type *Int64Ty = Type::getInt64Ty(M->getContext());
17769   Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo");
17770   Value *IncrHi =
17771       Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi");
17772   Value *Addr =
17773       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
17774   Value *LoHi = Builder.CreateCall(RMW, {Addr, IncrLo, IncrHi});
17775   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
17776   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
17777   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
17778   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
17779   return Builder.CreateOr(
17780       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
17781 }
17782 
17783 Value *PPCTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
17784     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
17785     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
17786   assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
17787          "Only support quadword now");
17788   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17789   Type *ValTy = cast<PointerType>(AlignedAddr->getType())->getElementType();
17790   assert(ValTy->getPrimitiveSizeInBits() == 128);
17791   Function *IntCmpXchg =
17792       Intrinsic::getDeclaration(M, Intrinsic::ppc_cmpxchg_i128);
17793   Type *Int64Ty = Type::getInt64Ty(M->getContext());
17794   Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo");
17795   Value *CmpHi =
17796       Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi");
17797   Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo");
17798   Value *NewHi =
17799       Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi");
17800   Value *Addr =
17801       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
17802   emitLeadingFence(Builder, CI, Ord);
17803   Value *LoHi =
17804       Builder.CreateCall(IntCmpXchg, {Addr, CmpLo, CmpHi, NewLo, NewHi});
17805   emitTrailingFence(Builder, CI, Ord);
17806   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
17807   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
17808   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
17809   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
17810   return Builder.CreateOr(
17811       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
17812 }
17813