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 // TODO - Remove this option if soft fp128 has been fully supported .
125 static cl::opt<bool>
126     EnableSoftFP128("enable-soft-fp128",
127                     cl::desc("temp option to enable soft fp128"), 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 // FIXME: Remove this once the bug has been fixed!
139 extern cl::opt<bool> ANDIGlueBug;
140 
141 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
142                                      const PPCSubtarget &STI)
143     : TargetLowering(TM), Subtarget(STI) {
144   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
145   // arguments are at least 4/8 bytes aligned.
146   bool isPPC64 = Subtarget.isPPC64();
147   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
148 
149   // Set up the register classes.
150   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
151   if (!useSoftFloat()) {
152     if (hasSPE()) {
153       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
154       // EFPU2 APU only supports f32
155       if (!Subtarget.hasEFPU2())
156         addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
157     } else {
158       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
159       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
160     }
161   }
162 
163   // Match BITREVERSE to customized fast code sequence in the td file.
164   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
165   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
166 
167   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
168   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
169 
170   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
171   for (MVT VT : MVT::integer_valuetypes()) {
172     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
173     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
174   }
175 
176   if (Subtarget.isISA3_0()) {
177     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
178     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
179     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
180     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
181   } else {
182     // No extending loads from f16 or HW conversions back and forth.
183     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
184     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
185     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
186     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
187     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
188     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
189     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
190     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
191   }
192 
193   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
194 
195   // PowerPC has pre-inc load and store's.
196   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
197   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
198   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
199   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
200   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
201   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
202   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
203   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
204   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
205   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
206   if (!Subtarget.hasSPE()) {
207     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
208     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
209     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
210     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
211   }
212 
213   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
214   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
215   for (MVT VT : ScalarIntVTs) {
216     setOperationAction(ISD::ADDC, VT, Legal);
217     setOperationAction(ISD::ADDE, VT, Legal);
218     setOperationAction(ISD::SUBC, VT, Legal);
219     setOperationAction(ISD::SUBE, VT, Legal);
220   }
221 
222   if (Subtarget.useCRBits()) {
223     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
224 
225     if (isPPC64 || Subtarget.hasFPCVT()) {
226       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote);
227       AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1,
228                         isPPC64 ? MVT::i64 : MVT::i32);
229       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote);
230       AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1,
231                         isPPC64 ? MVT::i64 : MVT::i32);
232 
233       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
234       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
235                          isPPC64 ? MVT::i64 : MVT::i32);
236       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
237       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
238                         isPPC64 ? MVT::i64 : MVT::i32);
239 
240       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote);
241       AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1,
242                         isPPC64 ? MVT::i64 : MVT::i32);
243       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote);
244       AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1,
245                         isPPC64 ? MVT::i64 : MVT::i32);
246 
247       setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
248       AddPromotedToType(ISD::FP_TO_SINT, MVT::i1,
249                         isPPC64 ? MVT::i64 : MVT::i32);
250       setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
251       AddPromotedToType(ISD::FP_TO_UINT, MVT::i1,
252                         isPPC64 ? MVT::i64 : MVT::i32);
253     } else {
254       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom);
255       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom);
256       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
257       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
258     }
259 
260     // PowerPC does not support direct load/store of condition registers.
261     setOperationAction(ISD::LOAD, MVT::i1, Custom);
262     setOperationAction(ISD::STORE, MVT::i1, Custom);
263 
264     // FIXME: Remove this once the ANDI glue bug is fixed:
265     if (ANDIGlueBug)
266       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
267 
268     for (MVT VT : MVT::integer_valuetypes()) {
269       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
270       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
271       setTruncStoreAction(VT, MVT::i1, Expand);
272     }
273 
274     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
275   }
276 
277   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
278   // PPC (the libcall is not available).
279   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
280   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
281   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom);
282   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom);
283 
284   // We do not currently implement these libm ops for PowerPC.
285   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
286   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
287   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
288   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
289   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
290   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
291 
292   // PowerPC has no SREM/UREM instructions unless we are on P9
293   // On P9 we may use a hardware instruction to compute the remainder.
294   // When the result of both the remainder and the division is required it is
295   // more efficient to compute the remainder from the result of the division
296   // rather than use the remainder instruction. The instructions are legalized
297   // directly because the DivRemPairsPass performs the transformation at the IR
298   // level.
299   if (Subtarget.isISA3_0()) {
300     setOperationAction(ISD::SREM, MVT::i32, Legal);
301     setOperationAction(ISD::UREM, MVT::i32, Legal);
302     setOperationAction(ISD::SREM, MVT::i64, Legal);
303     setOperationAction(ISD::UREM, MVT::i64, Legal);
304   } else {
305     setOperationAction(ISD::SREM, MVT::i32, Expand);
306     setOperationAction(ISD::UREM, MVT::i32, Expand);
307     setOperationAction(ISD::SREM, MVT::i64, Expand);
308     setOperationAction(ISD::UREM, MVT::i64, Expand);
309   }
310 
311   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
312   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
313   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
314   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
315   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
316   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
317   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
318   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
319   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
320 
321   // Handle constrained floating-point operations of scalar.
322   // TODO: Handle SPE specific operation.
323   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
324   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
325   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
326   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
327   setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
328   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
329 
330   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
331   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
332   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
333   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
334   setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
335   if (Subtarget.hasVSX()) {
336     setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal);
337     setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal);
338   }
339 
340   if (Subtarget.hasFSQRT()) {
341     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
342     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
343   }
344 
345   if (Subtarget.hasFPRND()) {
346     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
347     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
348     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
349     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
350 
351     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
352     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
353     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
354     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
355   }
356 
357   // We don't support sin/cos/sqrt/fmod/pow
358   setOperationAction(ISD::FSIN , MVT::f64, Expand);
359   setOperationAction(ISD::FCOS , MVT::f64, Expand);
360   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
361   setOperationAction(ISD::FREM , MVT::f64, Expand);
362   setOperationAction(ISD::FPOW , MVT::f64, Expand);
363   setOperationAction(ISD::FSIN , MVT::f32, Expand);
364   setOperationAction(ISD::FCOS , MVT::f32, Expand);
365   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
366   setOperationAction(ISD::FREM , MVT::f32, Expand);
367   setOperationAction(ISD::FPOW , MVT::f32, Expand);
368   if (Subtarget.hasSPE()) {
369     setOperationAction(ISD::FMA  , MVT::f64, Expand);
370     setOperationAction(ISD::FMA  , MVT::f32, Expand);
371   } else {
372     setOperationAction(ISD::FMA  , MVT::f64, Legal);
373     setOperationAction(ISD::FMA  , MVT::f32, Legal);
374   }
375 
376   if (Subtarget.hasSPE())
377     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
378 
379   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
380 
381   // If we're enabling GP optimizations, use hardware square root
382   if (!Subtarget.hasFSQRT() &&
383       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
384         Subtarget.hasFRE()))
385     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
386 
387   if (!Subtarget.hasFSQRT() &&
388       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
389         Subtarget.hasFRES()))
390     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
391 
392   if (Subtarget.hasFCPSGN()) {
393     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
394     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
395   } else {
396     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
397     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
398   }
399 
400   if (Subtarget.hasFPRND()) {
401     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
402     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
403     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
404     setOperationAction(ISD::FROUND, MVT::f64, Legal);
405 
406     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
407     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
408     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
409     setOperationAction(ISD::FROUND, MVT::f32, Legal);
410   }
411 
412   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
413   // to speed up scalar BSWAP64.
414   // CTPOP or CTTZ were introduced in P8/P9 respectively
415   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
416   if (Subtarget.hasP9Vector())
417     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
418   else
419     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
420   if (Subtarget.isISA3_0()) {
421     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
422     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
423   } else {
424     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
425     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
426   }
427 
428   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
429     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
430     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
431   } else {
432     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
433     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
434   }
435 
436   // PowerPC does not have ROTR
437   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
438   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
439 
440   if (!Subtarget.useCRBits()) {
441     // PowerPC does not have Select
442     setOperationAction(ISD::SELECT, MVT::i32, Expand);
443     setOperationAction(ISD::SELECT, MVT::i64, Expand);
444     setOperationAction(ISD::SELECT, MVT::f32, Expand);
445     setOperationAction(ISD::SELECT, MVT::f64, Expand);
446   }
447 
448   // PowerPC wants to turn select_cc of FP into fsel when possible.
449   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
450   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
451 
452   // PowerPC wants to optimize integer setcc a bit
453   if (!Subtarget.useCRBits())
454     setOperationAction(ISD::SETCC, MVT::i32, Custom);
455 
456   if (Subtarget.hasFPU()) {
457     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
458     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
459     setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
460 
461     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
462     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
463     setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
464   }
465 
466   // PowerPC does not have BRCOND which requires SetCC
467   if (!Subtarget.useCRBits())
468     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
469 
470   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
471 
472   if (Subtarget.hasSPE()) {
473     // SPE has built-in conversions
474     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
475     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
476     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
477     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
478     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
479     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
480   } else {
481     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
482     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
483     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
484 
485     // PowerPC does not have [U|S]INT_TO_FP
486     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand);
487     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand);
488     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
489     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
490   }
491 
492   if (Subtarget.hasDirectMove() && isPPC64) {
493     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
494     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
495     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
496     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
497     if (TM.Options.UnsafeFPMath) {
498       setOperationAction(ISD::LRINT, MVT::f64, Legal);
499       setOperationAction(ISD::LRINT, MVT::f32, Legal);
500       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
501       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
502       setOperationAction(ISD::LROUND, MVT::f64, Legal);
503       setOperationAction(ISD::LROUND, MVT::f32, Legal);
504       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
505       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
506     }
507   } else {
508     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
509     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
510     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
511     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
512   }
513 
514   // We cannot sextinreg(i1).  Expand to shifts.
515   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
516 
517   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
518   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
519   // support continuation, user-level threading, and etc.. As a result, no
520   // other SjLj exception interfaces are implemented and please don't build
521   // your own exception handling based on them.
522   // LLVM/Clang supports zero-cost DWARF exception handling.
523   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
524   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
525 
526   // We want to legalize GlobalAddress and ConstantPool nodes into the
527   // appropriate instructions to materialize the address.
528   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
529   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
530   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
531   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
532   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
533   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
534   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
535   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
536   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
537   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
538 
539   // TRAP is legal.
540   setOperationAction(ISD::TRAP, MVT::Other, Legal);
541 
542   // TRAMPOLINE is custom lowered.
543   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
544   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
545 
546   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
547   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
548 
549   if (Subtarget.is64BitELFABI()) {
550     // VAARG always uses double-word chunks, so promote anything smaller.
551     setOperationAction(ISD::VAARG, MVT::i1, Promote);
552     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
553     setOperationAction(ISD::VAARG, MVT::i8, Promote);
554     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
555     setOperationAction(ISD::VAARG, MVT::i16, Promote);
556     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
557     setOperationAction(ISD::VAARG, MVT::i32, Promote);
558     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
559     setOperationAction(ISD::VAARG, MVT::Other, Expand);
560   } else if (Subtarget.is32BitELFABI()) {
561     // VAARG is custom lowered with the 32-bit SVR4 ABI.
562     setOperationAction(ISD::VAARG, MVT::Other, Custom);
563     setOperationAction(ISD::VAARG, MVT::i64, Custom);
564   } else
565     setOperationAction(ISD::VAARG, MVT::Other, Expand);
566 
567   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
568   if (Subtarget.is32BitELFABI())
569     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
570   else
571     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
572 
573   // Use the default implementation.
574   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
575   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
576   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
577   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
578   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
579   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
580   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
581   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
582   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
583 
584   // We want to custom lower some of our intrinsics.
585   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
586 
587   // To handle counter-based loop conditions.
588   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
589 
590   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
591   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
592   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
593   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
594 
595   // Comparisons that require checking two conditions.
596   if (Subtarget.hasSPE()) {
597     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
598     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
599     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
600     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
601   }
602   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
603   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
604   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
605   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
606   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
607   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
608   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
609   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
610   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
611   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
612   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
613   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
614 
615   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
616   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
617 
618   if (Subtarget.has64BitSupport()) {
619     // They also have instructions for converting between i64 and fp.
620     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
621     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
622     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
623     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
624     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
625     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
626     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
627     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
628     // This is just the low 32 bits of a (signed) fp->i64 conversion.
629     // We cannot do this with Promote because i64 is not a legal type.
630     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
631     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
632 
633     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
634       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
635       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
636     }
637   } else {
638     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
639     if (Subtarget.hasSPE()) {
640       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
641       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
642     } else {
643       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
644       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
645     }
646   }
647 
648   // With the instructions enabled under FPCVT, we can do everything.
649   if (Subtarget.hasFPCVT()) {
650     if (Subtarget.has64BitSupport()) {
651       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
652       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
653       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
654       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
655       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
656       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
657       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
658       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
659     }
660 
661     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
662     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
663     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
664     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
665     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
666     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
667     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
668     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
669   }
670 
671   if (Subtarget.use64BitRegs()) {
672     // 64-bit PowerPC implementations can support i64 types directly
673     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
674     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
675     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
676     // 64-bit PowerPC wants to expand i128 shifts itself.
677     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
678     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
679     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
680   } else {
681     // 32-bit PowerPC wants to expand i64 shifts itself.
682     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
683     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
684     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
685   }
686 
687   // PowerPC has better expansions for funnel shifts than the generic
688   // TargetLowering::expandFunnelShift.
689   if (Subtarget.has64BitSupport()) {
690     setOperationAction(ISD::FSHL, MVT::i64, Custom);
691     setOperationAction(ISD::FSHR, MVT::i64, Custom);
692   }
693   setOperationAction(ISD::FSHL, MVT::i32, Custom);
694   setOperationAction(ISD::FSHR, MVT::i32, Custom);
695 
696   if (Subtarget.hasVSX()) {
697     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
698     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
699     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
700     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
701   }
702 
703   if (Subtarget.hasAltivec()) {
704     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
705       setOperationAction(ISD::SADDSAT, VT, Legal);
706       setOperationAction(ISD::SSUBSAT, VT, Legal);
707       setOperationAction(ISD::UADDSAT, VT, Legal);
708       setOperationAction(ISD::USUBSAT, VT, Legal);
709     }
710     // First set operation action for all vector types to expand. Then we
711     // will selectively turn on ones that can be effectively codegen'd.
712     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
713       // add/sub are legal for all supported vector VT's.
714       setOperationAction(ISD::ADD, VT, Legal);
715       setOperationAction(ISD::SUB, VT, Legal);
716 
717       // For v2i64, these are only valid with P8Vector. This is corrected after
718       // the loop.
719       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
720         setOperationAction(ISD::SMAX, VT, Legal);
721         setOperationAction(ISD::SMIN, VT, Legal);
722         setOperationAction(ISD::UMAX, VT, Legal);
723         setOperationAction(ISD::UMIN, VT, Legal);
724       }
725       else {
726         setOperationAction(ISD::SMAX, VT, Expand);
727         setOperationAction(ISD::SMIN, VT, Expand);
728         setOperationAction(ISD::UMAX, VT, Expand);
729         setOperationAction(ISD::UMIN, VT, Expand);
730       }
731 
732       if (Subtarget.hasVSX()) {
733         setOperationAction(ISD::FMAXNUM, VT, Legal);
734         setOperationAction(ISD::FMINNUM, VT, Legal);
735       }
736 
737       // Vector instructions introduced in P8
738       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
739         setOperationAction(ISD::CTPOP, VT, Legal);
740         setOperationAction(ISD::CTLZ, VT, Legal);
741       }
742       else {
743         setOperationAction(ISD::CTPOP, VT, Expand);
744         setOperationAction(ISD::CTLZ, VT, Expand);
745       }
746 
747       // Vector instructions introduced in P9
748       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
749         setOperationAction(ISD::CTTZ, VT, Legal);
750       else
751         setOperationAction(ISD::CTTZ, VT, Expand);
752 
753       // We promote all shuffles to v16i8.
754       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
755       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
756 
757       // We promote all non-typed operations to v4i32.
758       setOperationAction(ISD::AND   , VT, Promote);
759       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
760       setOperationAction(ISD::OR    , VT, Promote);
761       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
762       setOperationAction(ISD::XOR   , VT, Promote);
763       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
764       setOperationAction(ISD::LOAD  , VT, Promote);
765       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
766       setOperationAction(ISD::SELECT, VT, Promote);
767       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
768       setOperationAction(ISD::VSELECT, VT, Legal);
769       setOperationAction(ISD::SELECT_CC, VT, Promote);
770       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
771       setOperationAction(ISD::STORE, VT, Promote);
772       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
773 
774       // No other operations are legal.
775       setOperationAction(ISD::MUL , VT, Expand);
776       setOperationAction(ISD::SDIV, VT, Expand);
777       setOperationAction(ISD::SREM, VT, Expand);
778       setOperationAction(ISD::UDIV, VT, Expand);
779       setOperationAction(ISD::UREM, VT, Expand);
780       setOperationAction(ISD::FDIV, VT, Expand);
781       setOperationAction(ISD::FREM, VT, Expand);
782       setOperationAction(ISD::FNEG, VT, Expand);
783       setOperationAction(ISD::FSQRT, VT, Expand);
784       setOperationAction(ISD::FLOG, VT, Expand);
785       setOperationAction(ISD::FLOG10, VT, Expand);
786       setOperationAction(ISD::FLOG2, VT, Expand);
787       setOperationAction(ISD::FEXP, VT, Expand);
788       setOperationAction(ISD::FEXP2, VT, Expand);
789       setOperationAction(ISD::FSIN, VT, Expand);
790       setOperationAction(ISD::FCOS, VT, Expand);
791       setOperationAction(ISD::FABS, VT, Expand);
792       setOperationAction(ISD::FFLOOR, VT, Expand);
793       setOperationAction(ISD::FCEIL,  VT, Expand);
794       setOperationAction(ISD::FTRUNC, VT, Expand);
795       setOperationAction(ISD::FRINT,  VT, Expand);
796       setOperationAction(ISD::FNEARBYINT, VT, Expand);
797       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
798       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
799       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
800       setOperationAction(ISD::MULHU, VT, Expand);
801       setOperationAction(ISD::MULHS, VT, Expand);
802       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
803       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
804       setOperationAction(ISD::UDIVREM, VT, Expand);
805       setOperationAction(ISD::SDIVREM, VT, Expand);
806       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
807       setOperationAction(ISD::FPOW, VT, Expand);
808       setOperationAction(ISD::BSWAP, VT, Expand);
809       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
810       setOperationAction(ISD::ROTL, VT, Expand);
811       setOperationAction(ISD::ROTR, VT, Expand);
812 
813       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
814         setTruncStoreAction(VT, InnerVT, Expand);
815         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
816         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
817         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
818       }
819     }
820     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
821     if (!Subtarget.hasP8Vector()) {
822       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
823       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
824       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
825       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
826     }
827 
828     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
829     // with merges, splats, etc.
830     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
831 
832     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
833     // are cheap, so handle them before they get expanded to scalar.
834     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
835     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
836     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
837     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
838     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
839 
840     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
841     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
842     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
843     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
844     setOperationAction(ISD::SELECT, MVT::v4i32,
845                        Subtarget.useCRBits() ? Legal : Expand);
846     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
847     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
848     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
849     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
850     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
851     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
852     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
853     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
854     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
855     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
856     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
857     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
858     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
859 
860     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
861     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
862     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
863     if (Subtarget.hasAltivec())
864       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
865         setOperationAction(ISD::ROTL, VT, Legal);
866     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
867     if (Subtarget.hasP8Altivec())
868       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
869 
870     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
871     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
872     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
873     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
874 
875     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
876     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
877 
878     if (Subtarget.hasVSX()) {
879       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
880       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
881     }
882 
883     if (Subtarget.hasP8Altivec())
884       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
885     else
886       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
887 
888     if (Subtarget.isISA3_1()) {
889       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
890       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
891       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
892       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
893       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
894       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
895       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
896       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
897       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
898       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
899       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
900       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
901       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
902       setOperationAction(ISD::UREM, MVT::v1i128, Legal);
903       setOperationAction(ISD::SREM, MVT::v1i128, Legal);
904       setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
905       setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
906       setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
907     }
908 
909     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
910     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
911 
912     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
913     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
914 
915     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
916     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
917     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
918     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
919 
920     // Altivec does not contain unordered floating-point compare instructions
921     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
922     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
923     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
924     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
925 
926     if (Subtarget.hasVSX()) {
927       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
928       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
929       if (Subtarget.hasP8Vector()) {
930         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
931         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
932       }
933       if (Subtarget.hasDirectMove() && isPPC64) {
934         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
935         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
936         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
937         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
938         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
939         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
940         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
941         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
942       }
943       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
944 
945       // The nearbyint variants are not allowed to raise the inexact exception
946       // so we can only code-gen them with unsafe math.
947       if (TM.Options.UnsafeFPMath) {
948         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
949         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
950       }
951 
952       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
953       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
954       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
955       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
956       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
957       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
958       setOperationAction(ISD::FROUND, MVT::f64, Legal);
959       setOperationAction(ISD::FRINT, MVT::f64, Legal);
960 
961       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
962       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
963       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
964       setOperationAction(ISD::FROUND, MVT::f32, Legal);
965       setOperationAction(ISD::FRINT, MVT::f32, Legal);
966 
967       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
968       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
969 
970       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
971       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
972 
973       // Share the Altivec comparison restrictions.
974       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
975       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
976       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
977       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
978 
979       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
980       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
981 
982       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
983 
984       if (Subtarget.hasP8Vector())
985         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
986 
987       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
988 
989       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
990       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
991       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
992 
993       if (Subtarget.hasP8Altivec()) {
994         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
995         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
996         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
997 
998         // 128 bit shifts can be accomplished via 3 instructions for SHL and
999         // SRL, but not for SRA because of the instructions available:
1000         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1001         // doing
1002         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
1003         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
1004         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1005 
1006         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
1007       }
1008       else {
1009         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
1010         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1011         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1012 
1013         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1014 
1015         // VSX v2i64 only supports non-arithmetic operations.
1016         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1017         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1018       }
1019 
1020       if (Subtarget.isISA3_1())
1021         setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1022       else
1023         setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1024 
1025       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1026       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1027       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1028       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1029 
1030       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
1031 
1032       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1033       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1034       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1035       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1036       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1037       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1038       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1039       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1040 
1041       // Custom handling for partial vectors of integers converted to
1042       // floating point. We already have optimal handling for v2i32 through
1043       // the DAG combine, so those aren't necessary.
1044       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1045       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1046       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1047       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1048       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1049       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1050       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1051       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1052       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1053       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1054       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1055       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1056       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1057       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1058       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1059       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1060 
1061       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1062       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1063       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1064       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1065       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1066       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1067 
1068       if (Subtarget.hasDirectMove())
1069         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1070       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1071 
1072       // Handle constrained floating-point operations of vector.
1073       // The predictor is `hasVSX` because altivec instruction has
1074       // no exception but VSX vector instruction has.
1075       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1076       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1077       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1078       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1079       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1080       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1081       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1082       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1083       setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
1084       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1085       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1086       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1087       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1088 
1089       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1090       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1091       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1092       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1093       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1094       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1095       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1096       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1097       setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
1098       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1099       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1100       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1101       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1102 
1103       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1104     }
1105 
1106     if (Subtarget.hasP8Altivec()) {
1107       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1108       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1109     }
1110 
1111     if (Subtarget.hasP9Vector()) {
1112       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1113       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1114 
1115       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1116       // SRL, but not for SRA because of the instructions available:
1117       // VS{RL} and VS{RL}O.
1118       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1119       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1120       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1121 
1122       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1123       setOperationAction(ISD::FADD, MVT::f128, Legal);
1124       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1125       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1126       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1127       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1128       // No extending loads to f128 on PPC.
1129       for (MVT FPT : MVT::fp_valuetypes())
1130         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1131       setOperationAction(ISD::FMA, MVT::f128, Legal);
1132       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1133       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1134       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1135       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1136       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1137       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1138 
1139       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1140       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1141       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1142       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1143       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1144       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1145 
1146       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1147       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1148       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1149       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1150       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1151       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1152       // No implementation for these ops for PowerPC.
1153       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1154       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1155       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1156       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1157       setOperationAction(ISD::FREM, MVT::f128, Expand);
1158 
1159       // Handle constrained floating-point operations of fp128
1160       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1161       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1162       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1163       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1164       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1165       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1166       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1167       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1168       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1169       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1170       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1171       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1172       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1173       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1174       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1175       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1176       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1177       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1178       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1179       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1180     } else if (Subtarget.hasAltivec() && EnableSoftFP128) {
1181       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1182 
1183       for (MVT FPT : MVT::fp_valuetypes())
1184         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1185 
1186       setOperationAction(ISD::LOAD, MVT::f128, Promote);
1187       setOperationAction(ISD::STORE, MVT::f128, Promote);
1188 
1189       AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
1190       AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
1191 
1192       // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1193       // fp_to_uint and int_to_fp.
1194       setOperationAction(ISD::FADD, MVT::f128, LibCall);
1195       setOperationAction(ISD::FSUB, MVT::f128, LibCall);
1196 
1197       setOperationAction(ISD::FMUL, MVT::f128, Expand);
1198       setOperationAction(ISD::FDIV, MVT::f128, Expand);
1199       setOperationAction(ISD::FNEG, MVT::f128, Expand);
1200       setOperationAction(ISD::FABS, MVT::f128, Expand);
1201       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1202       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1203       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1204       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1205       setOperationAction(ISD::FREM, MVT::f128, Expand);
1206       setOperationAction(ISD::FSQRT, MVT::f128, Expand);
1207       setOperationAction(ISD::FMA, MVT::f128, Expand);
1208       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
1209 
1210       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1211       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1212 
1213       // Expand the fp_extend if the target type is fp128.
1214       setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand);
1215       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand);
1216 
1217       // Expand the fp_round if the source type is fp128.
1218       for (MVT VT : {MVT::f32, MVT::f64}) {
1219         setOperationAction(ISD::FP_ROUND, VT, Custom);
1220         setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom);
1221       }
1222     }
1223 
1224     if (Subtarget.hasP9Altivec()) {
1225       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1226       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1227 
1228       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1229       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1230       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1231       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1232       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1233       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1234       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1235     }
1236 
1237     if (Subtarget.isISA3_1()) {
1238       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1239       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
1240     }
1241   }
1242 
1243   if (Subtarget.pairedVectorMemops()) {
1244     addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1245     setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1246     setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1247   }
1248   if (Subtarget.hasMMA()) {
1249     addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1250     setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1251     setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1252     setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom);
1253   }
1254 
1255   if (Subtarget.has64BitSupport())
1256     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1257 
1258   if (Subtarget.isISA3_1())
1259     setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1260 
1261   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1262 
1263   if (!isPPC64) {
1264     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1265     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1266   }
1267 
1268   setBooleanContents(ZeroOrOneBooleanContent);
1269 
1270   if (Subtarget.hasAltivec()) {
1271     // Altivec instructions set fields to all zeros or all ones.
1272     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1273   }
1274 
1275   if (!isPPC64) {
1276     // These libcalls are not available in 32-bit.
1277     setLibcallName(RTLIB::SHL_I128, nullptr);
1278     setLibcallName(RTLIB::SRL_I128, nullptr);
1279     setLibcallName(RTLIB::SRA_I128, nullptr);
1280   }
1281 
1282   if (!isPPC64)
1283     setMaxAtomicSizeInBitsSupported(32);
1284 
1285   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1286 
1287   // We have target-specific dag combine patterns for the following nodes:
1288   setTargetDAGCombine(ISD::ADD);
1289   setTargetDAGCombine(ISD::SHL);
1290   setTargetDAGCombine(ISD::SRA);
1291   setTargetDAGCombine(ISD::SRL);
1292   setTargetDAGCombine(ISD::MUL);
1293   setTargetDAGCombine(ISD::FMA);
1294   setTargetDAGCombine(ISD::SINT_TO_FP);
1295   setTargetDAGCombine(ISD::BUILD_VECTOR);
1296   if (Subtarget.hasFPCVT())
1297     setTargetDAGCombine(ISD::UINT_TO_FP);
1298   setTargetDAGCombine(ISD::LOAD);
1299   setTargetDAGCombine(ISD::STORE);
1300   setTargetDAGCombine(ISD::BR_CC);
1301   if (Subtarget.useCRBits())
1302     setTargetDAGCombine(ISD::BRCOND);
1303   setTargetDAGCombine(ISD::BSWAP);
1304   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1305   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1306   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1307 
1308   setTargetDAGCombine(ISD::SIGN_EXTEND);
1309   setTargetDAGCombine(ISD::ZERO_EXTEND);
1310   setTargetDAGCombine(ISD::ANY_EXTEND);
1311 
1312   setTargetDAGCombine(ISD::TRUNCATE);
1313   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1314 
1315 
1316   if (Subtarget.useCRBits()) {
1317     setTargetDAGCombine(ISD::TRUNCATE);
1318     setTargetDAGCombine(ISD::SETCC);
1319     setTargetDAGCombine(ISD::SELECT_CC);
1320   }
1321 
1322   if (Subtarget.hasP9Altivec()) {
1323     setTargetDAGCombine(ISD::ABS);
1324     setTargetDAGCombine(ISD::VSELECT);
1325   }
1326 
1327   setLibcallName(RTLIB::LOG_F128, "logf128");
1328   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1329   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1330   setLibcallName(RTLIB::EXP_F128, "expf128");
1331   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1332   setLibcallName(RTLIB::SIN_F128, "sinf128");
1333   setLibcallName(RTLIB::COS_F128, "cosf128");
1334   setLibcallName(RTLIB::POW_F128, "powf128");
1335   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1336   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1337   setLibcallName(RTLIB::REM_F128, "fmodf128");
1338   setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1339   setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1340   setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1341   setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1342   setLibcallName(RTLIB::ROUND_F128, "roundf128");
1343   setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1344   setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1345   setLibcallName(RTLIB::RINT_F128, "rintf128");
1346   setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1347   setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1348   setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1349   setLibcallName(RTLIB::FMA_F128, "fmaf128");
1350 
1351   // With 32 condition bits, we don't need to sink (and duplicate) compares
1352   // aggressively in CodeGenPrep.
1353   if (Subtarget.useCRBits()) {
1354     setHasMultipleConditionRegisters();
1355     setJumpIsExpensive();
1356   }
1357 
1358   setMinFunctionAlignment(Align(4));
1359 
1360   switch (Subtarget.getCPUDirective()) {
1361   default: break;
1362   case PPC::DIR_970:
1363   case PPC::DIR_A2:
1364   case PPC::DIR_E500:
1365   case PPC::DIR_E500mc:
1366   case PPC::DIR_E5500:
1367   case PPC::DIR_PWR4:
1368   case PPC::DIR_PWR5:
1369   case PPC::DIR_PWR5X:
1370   case PPC::DIR_PWR6:
1371   case PPC::DIR_PWR6X:
1372   case PPC::DIR_PWR7:
1373   case PPC::DIR_PWR8:
1374   case PPC::DIR_PWR9:
1375   case PPC::DIR_PWR10:
1376   case PPC::DIR_PWR_FUTURE:
1377     setPrefLoopAlignment(Align(16));
1378     setPrefFunctionAlignment(Align(16));
1379     break;
1380   }
1381 
1382   if (Subtarget.enableMachineScheduler())
1383     setSchedulingPreference(Sched::Source);
1384   else
1385     setSchedulingPreference(Sched::Hybrid);
1386 
1387   computeRegisterProperties(STI.getRegisterInfo());
1388 
1389   // The Freescale cores do better with aggressive inlining of memcpy and
1390   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1391   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1392       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1393     MaxStoresPerMemset = 32;
1394     MaxStoresPerMemsetOptSize = 16;
1395     MaxStoresPerMemcpy = 32;
1396     MaxStoresPerMemcpyOptSize = 8;
1397     MaxStoresPerMemmove = 32;
1398     MaxStoresPerMemmoveOptSize = 8;
1399   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1400     // The A2 also benefits from (very) aggressive inlining of memcpy and
1401     // friends. The overhead of a the function call, even when warm, can be
1402     // over one hundred cycles.
1403     MaxStoresPerMemset = 128;
1404     MaxStoresPerMemcpy = 128;
1405     MaxStoresPerMemmove = 128;
1406     MaxLoadsPerMemcmp = 128;
1407   } else {
1408     MaxLoadsPerMemcmp = 8;
1409     MaxLoadsPerMemcmpOptSize = 4;
1410   }
1411 
1412   IsStrictFPEnabled = true;
1413 
1414   // Let the subtarget (CPU) decide if a predictable select is more expensive
1415   // than the corresponding branch. This information is used in CGP to decide
1416   // when to convert selects into branches.
1417   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1418 }
1419 
1420 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1421 /// the desired ByVal argument alignment.
1422 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1423   if (MaxAlign == MaxMaxAlign)
1424     return;
1425   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1426     if (MaxMaxAlign >= 32 &&
1427         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1428       MaxAlign = Align(32);
1429     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1430              MaxAlign < 16)
1431       MaxAlign = Align(16);
1432   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1433     Align EltAlign;
1434     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1435     if (EltAlign > MaxAlign)
1436       MaxAlign = EltAlign;
1437   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1438     for (auto *EltTy : STy->elements()) {
1439       Align EltAlign;
1440       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1441       if (EltAlign > MaxAlign)
1442         MaxAlign = EltAlign;
1443       if (MaxAlign == MaxMaxAlign)
1444         break;
1445     }
1446   }
1447 }
1448 
1449 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1450 /// function arguments in the caller parameter area.
1451 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1452                                                   const DataLayout &DL) const {
1453   // 16byte and wider vectors are passed on 16byte boundary.
1454   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1455   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1456   if (Subtarget.hasAltivec())
1457     getMaxByValAlign(Ty, Alignment, Align(16));
1458   return Alignment.value();
1459 }
1460 
1461 bool PPCTargetLowering::useSoftFloat() const {
1462   return Subtarget.useSoftFloat();
1463 }
1464 
1465 bool PPCTargetLowering::hasSPE() const {
1466   return Subtarget.hasSPE();
1467 }
1468 
1469 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1470   return VT.isScalarInteger();
1471 }
1472 
1473 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1474   switch ((PPCISD::NodeType)Opcode) {
1475   case PPCISD::FIRST_NUMBER:    break;
1476   case PPCISD::FSEL:            return "PPCISD::FSEL";
1477   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1478   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1479   case PPCISD::FCFID:           return "PPCISD::FCFID";
1480   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1481   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1482   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1483   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1484   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1485   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1486   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1487   case PPCISD::FP_TO_UINT_IN_VSR:
1488                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1489   case PPCISD::FP_TO_SINT_IN_VSR:
1490                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1491   case PPCISD::FRE:             return "PPCISD::FRE";
1492   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1493   case PPCISD::FTSQRT:
1494     return "PPCISD::FTSQRT";
1495   case PPCISD::FSQRT:
1496     return "PPCISD::FSQRT";
1497   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1498   case PPCISD::VPERM:           return "PPCISD::VPERM";
1499   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1500   case PPCISD::XXSPLTI_SP_TO_DP:
1501     return "PPCISD::XXSPLTI_SP_TO_DP";
1502   case PPCISD::XXSPLTI32DX:
1503     return "PPCISD::XXSPLTI32DX";
1504   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1505   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1506   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1507   case PPCISD::CMPB:            return "PPCISD::CMPB";
1508   case PPCISD::Hi:              return "PPCISD::Hi";
1509   case PPCISD::Lo:              return "PPCISD::Lo";
1510   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1511   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1512   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1513   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1514   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1515   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1516   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1517   case PPCISD::SRL:             return "PPCISD::SRL";
1518   case PPCISD::SRA:             return "PPCISD::SRA";
1519   case PPCISD::SHL:             return "PPCISD::SHL";
1520   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1521   case PPCISD::CALL:            return "PPCISD::CALL";
1522   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1523   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1524   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1525   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1526   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1527   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1528   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1529   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1530   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1531   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1532   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1533   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1534   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1535   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1536   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1537   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1538     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1539   case PPCISD::ANDI_rec_1_EQ_BIT:
1540     return "PPCISD::ANDI_rec_1_EQ_BIT";
1541   case PPCISD::ANDI_rec_1_GT_BIT:
1542     return "PPCISD::ANDI_rec_1_GT_BIT";
1543   case PPCISD::VCMP:            return "PPCISD::VCMP";
1544   case PPCISD::VCMP_rec:        return "PPCISD::VCMP_rec";
1545   case PPCISD::LBRX:            return "PPCISD::LBRX";
1546   case PPCISD::STBRX:           return "PPCISD::STBRX";
1547   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1548   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1549   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1550   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1551   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1552   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1553   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1554   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1555   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1556   case PPCISD::ST_VSR_SCAL_INT:
1557                                 return "PPCISD::ST_VSR_SCAL_INT";
1558   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1559   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1560   case PPCISD::BDZ:             return "PPCISD::BDZ";
1561   case PPCISD::MFFS:            return "PPCISD::MFFS";
1562   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1563   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1564   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1565   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1566   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1567   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1568   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1569   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1570   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1571   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1572   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1573   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1574   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1575   case PPCISD::TLSGD_AIX:       return "PPCISD::TLSGD_AIX";
1576   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1577   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1578   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1579   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1580   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1581   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1582   case PPCISD::PADDI_DTPREL:
1583     return "PPCISD::PADDI_DTPREL";
1584   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1585   case PPCISD::SC:              return "PPCISD::SC";
1586   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1587   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1588   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1589   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1590   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1591   case PPCISD::VABSD:           return "PPCISD::VABSD";
1592   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1593   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1594   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1595   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1596   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1597   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1598   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1599   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1600     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1601   case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1602     return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1603   case PPCISD::ACC_BUILD:       return "PPCISD::ACC_BUILD";
1604   case PPCISD::PAIR_BUILD:      return "PPCISD::PAIR_BUILD";
1605   case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1606   case PPCISD::XXMFACC:         return "PPCISD::XXMFACC";
1607   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1608   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1609   case PPCISD::STRICT_FADDRTZ:
1610     return "PPCISD::STRICT_FADDRTZ";
1611   case PPCISD::STRICT_FCTIDZ:
1612     return "PPCISD::STRICT_FCTIDZ";
1613   case PPCISD::STRICT_FCTIWZ:
1614     return "PPCISD::STRICT_FCTIWZ";
1615   case PPCISD::STRICT_FCTIDUZ:
1616     return "PPCISD::STRICT_FCTIDUZ";
1617   case PPCISD::STRICT_FCTIWUZ:
1618     return "PPCISD::STRICT_FCTIWUZ";
1619   case PPCISD::STRICT_FCFID:
1620     return "PPCISD::STRICT_FCFID";
1621   case PPCISD::STRICT_FCFIDU:
1622     return "PPCISD::STRICT_FCFIDU";
1623   case PPCISD::STRICT_FCFIDS:
1624     return "PPCISD::STRICT_FCFIDS";
1625   case PPCISD::STRICT_FCFIDUS:
1626     return "PPCISD::STRICT_FCFIDUS";
1627   case PPCISD::LXVRZX:          return "PPCISD::LXVRZX";
1628   }
1629   return nullptr;
1630 }
1631 
1632 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1633                                           EVT VT) const {
1634   if (!VT.isVector())
1635     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1636 
1637   return VT.changeVectorElementTypeToInteger();
1638 }
1639 
1640 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1641   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1642   return true;
1643 }
1644 
1645 //===----------------------------------------------------------------------===//
1646 // Node matching predicates, for use by the tblgen matching code.
1647 //===----------------------------------------------------------------------===//
1648 
1649 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1650 static bool isFloatingPointZero(SDValue Op) {
1651   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1652     return CFP->getValueAPF().isZero();
1653   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1654     // Maybe this has already been legalized into the constant pool?
1655     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1656       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1657         return CFP->getValueAPF().isZero();
1658   }
1659   return false;
1660 }
1661 
1662 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1663 /// true if Op is undef or if it matches the specified value.
1664 static bool isConstantOrUndef(int Op, int Val) {
1665   return Op < 0 || Op == Val;
1666 }
1667 
1668 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1669 /// VPKUHUM instruction.
1670 /// The ShuffleKind distinguishes between big-endian operations with
1671 /// two different inputs (0), either-endian operations with two identical
1672 /// inputs (1), and little-endian operations with two different inputs (2).
1673 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1674 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1675                                SelectionDAG &DAG) {
1676   bool IsLE = DAG.getDataLayout().isLittleEndian();
1677   if (ShuffleKind == 0) {
1678     if (IsLE)
1679       return false;
1680     for (unsigned i = 0; i != 16; ++i)
1681       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1682         return false;
1683   } else if (ShuffleKind == 2) {
1684     if (!IsLE)
1685       return false;
1686     for (unsigned i = 0; i != 16; ++i)
1687       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1688         return false;
1689   } else if (ShuffleKind == 1) {
1690     unsigned j = IsLE ? 0 : 1;
1691     for (unsigned i = 0; i != 8; ++i)
1692       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1693           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1694         return false;
1695   }
1696   return true;
1697 }
1698 
1699 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1700 /// VPKUWUM instruction.
1701 /// The ShuffleKind distinguishes between big-endian operations with
1702 /// two different inputs (0), either-endian operations with two identical
1703 /// inputs (1), and little-endian operations with two different inputs (2).
1704 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1705 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1706                                SelectionDAG &DAG) {
1707   bool IsLE = DAG.getDataLayout().isLittleEndian();
1708   if (ShuffleKind == 0) {
1709     if (IsLE)
1710       return false;
1711     for (unsigned i = 0; i != 16; i += 2)
1712       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1713           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1714         return false;
1715   } else if (ShuffleKind == 2) {
1716     if (!IsLE)
1717       return false;
1718     for (unsigned i = 0; i != 16; i += 2)
1719       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1720           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1721         return false;
1722   } else if (ShuffleKind == 1) {
1723     unsigned j = IsLE ? 0 : 2;
1724     for (unsigned i = 0; i != 8; i += 2)
1725       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1726           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1727           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1728           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1729         return false;
1730   }
1731   return true;
1732 }
1733 
1734 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1735 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1736 /// current subtarget.
1737 ///
1738 /// The ShuffleKind distinguishes between big-endian operations with
1739 /// two different inputs (0), either-endian operations with two identical
1740 /// inputs (1), and little-endian operations with two different inputs (2).
1741 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1742 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1743                                SelectionDAG &DAG) {
1744   const PPCSubtarget& Subtarget =
1745       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1746   if (!Subtarget.hasP8Vector())
1747     return false;
1748 
1749   bool IsLE = DAG.getDataLayout().isLittleEndian();
1750   if (ShuffleKind == 0) {
1751     if (IsLE)
1752       return false;
1753     for (unsigned i = 0; i != 16; i += 4)
1754       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1755           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1756           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1757           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1758         return false;
1759   } else if (ShuffleKind == 2) {
1760     if (!IsLE)
1761       return false;
1762     for (unsigned i = 0; i != 16; i += 4)
1763       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1764           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1765           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1766           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1767         return false;
1768   } else if (ShuffleKind == 1) {
1769     unsigned j = IsLE ? 0 : 4;
1770     for (unsigned i = 0; i != 8; i += 4)
1771       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1772           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1773           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1774           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1775           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1776           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1777           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1778           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1779         return false;
1780   }
1781   return true;
1782 }
1783 
1784 /// isVMerge - Common function, used to match vmrg* shuffles.
1785 ///
1786 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1787                      unsigned LHSStart, unsigned RHSStart) {
1788   if (N->getValueType(0) != MVT::v16i8)
1789     return false;
1790   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1791          "Unsupported merge size!");
1792 
1793   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1794     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1795       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1796                              LHSStart+j+i*UnitSize) ||
1797           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1798                              RHSStart+j+i*UnitSize))
1799         return false;
1800     }
1801   return true;
1802 }
1803 
1804 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1805 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1806 /// The ShuffleKind distinguishes between big-endian merges with two
1807 /// different inputs (0), either-endian merges with two identical inputs (1),
1808 /// and little-endian merges with two different inputs (2).  For the latter,
1809 /// the input operands are swapped (see PPCInstrAltivec.td).
1810 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1811                              unsigned ShuffleKind, SelectionDAG &DAG) {
1812   if (DAG.getDataLayout().isLittleEndian()) {
1813     if (ShuffleKind == 1) // unary
1814       return isVMerge(N, UnitSize, 0, 0);
1815     else if (ShuffleKind == 2) // swapped
1816       return isVMerge(N, UnitSize, 0, 16);
1817     else
1818       return false;
1819   } else {
1820     if (ShuffleKind == 1) // unary
1821       return isVMerge(N, UnitSize, 8, 8);
1822     else if (ShuffleKind == 0) // normal
1823       return isVMerge(N, UnitSize, 8, 24);
1824     else
1825       return false;
1826   }
1827 }
1828 
1829 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1830 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1831 /// The ShuffleKind distinguishes between big-endian merges with two
1832 /// different inputs (0), either-endian merges with two identical inputs (1),
1833 /// and little-endian merges with two different inputs (2).  For the latter,
1834 /// the input operands are swapped (see PPCInstrAltivec.td).
1835 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1836                              unsigned ShuffleKind, SelectionDAG &DAG) {
1837   if (DAG.getDataLayout().isLittleEndian()) {
1838     if (ShuffleKind == 1) // unary
1839       return isVMerge(N, UnitSize, 8, 8);
1840     else if (ShuffleKind == 2) // swapped
1841       return isVMerge(N, UnitSize, 8, 24);
1842     else
1843       return false;
1844   } else {
1845     if (ShuffleKind == 1) // unary
1846       return isVMerge(N, UnitSize, 0, 0);
1847     else if (ShuffleKind == 0) // normal
1848       return isVMerge(N, UnitSize, 0, 16);
1849     else
1850       return false;
1851   }
1852 }
1853 
1854 /**
1855  * Common function used to match vmrgew and vmrgow shuffles
1856  *
1857  * The indexOffset determines whether to look for even or odd words in
1858  * the shuffle mask. This is based on the of the endianness of the target
1859  * machine.
1860  *   - Little Endian:
1861  *     - Use offset of 0 to check for odd elements
1862  *     - Use offset of 4 to check for even elements
1863  *   - Big Endian:
1864  *     - Use offset of 0 to check for even elements
1865  *     - Use offset of 4 to check for odd elements
1866  * A detailed description of the vector element ordering for little endian and
1867  * big endian can be found at
1868  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1869  * Targeting your applications - what little endian and big endian IBM XL C/C++
1870  * compiler differences mean to you
1871  *
1872  * The mask to the shuffle vector instruction specifies the indices of the
1873  * elements from the two input vectors to place in the result. The elements are
1874  * numbered in array-access order, starting with the first vector. These vectors
1875  * are always of type v16i8, thus each vector will contain 16 elements of size
1876  * 8. More info on the shuffle vector can be found in the
1877  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1878  * Language Reference.
1879  *
1880  * The RHSStartValue indicates whether the same input vectors are used (unary)
1881  * or two different input vectors are used, based on the following:
1882  *   - If the instruction uses the same vector for both inputs, the range of the
1883  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1884  *     be 0.
1885  *   - If the instruction has two different vectors then the range of the
1886  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1887  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1888  *     to 31 specify elements in the second vector).
1889  *
1890  * \param[in] N The shuffle vector SD Node to analyze
1891  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1892  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1893  * vector to the shuffle_vector instruction
1894  * \return true iff this shuffle vector represents an even or odd word merge
1895  */
1896 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1897                      unsigned RHSStartValue) {
1898   if (N->getValueType(0) != MVT::v16i8)
1899     return false;
1900 
1901   for (unsigned i = 0; i < 2; ++i)
1902     for (unsigned j = 0; j < 4; ++j)
1903       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1904                              i*RHSStartValue+j+IndexOffset) ||
1905           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1906                              i*RHSStartValue+j+IndexOffset+8))
1907         return false;
1908   return true;
1909 }
1910 
1911 /**
1912  * Determine if the specified shuffle mask is suitable for the vmrgew or
1913  * vmrgow instructions.
1914  *
1915  * \param[in] N The shuffle vector SD Node to analyze
1916  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1917  * \param[in] ShuffleKind Identify the type of merge:
1918  *   - 0 = big-endian merge with two different inputs;
1919  *   - 1 = either-endian merge with two identical inputs;
1920  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1921  *     little-endian merges).
1922  * \param[in] DAG The current SelectionDAG
1923  * \return true iff this shuffle mask
1924  */
1925 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1926                               unsigned ShuffleKind, SelectionDAG &DAG) {
1927   if (DAG.getDataLayout().isLittleEndian()) {
1928     unsigned indexOffset = CheckEven ? 4 : 0;
1929     if (ShuffleKind == 1) // Unary
1930       return isVMerge(N, indexOffset, 0);
1931     else if (ShuffleKind == 2) // swapped
1932       return isVMerge(N, indexOffset, 16);
1933     else
1934       return false;
1935   }
1936   else {
1937     unsigned indexOffset = CheckEven ? 0 : 4;
1938     if (ShuffleKind == 1) // Unary
1939       return isVMerge(N, indexOffset, 0);
1940     else if (ShuffleKind == 0) // Normal
1941       return isVMerge(N, indexOffset, 16);
1942     else
1943       return false;
1944   }
1945   return false;
1946 }
1947 
1948 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1949 /// amount, otherwise return -1.
1950 /// The ShuffleKind distinguishes between big-endian operations with two
1951 /// different inputs (0), either-endian operations with two identical inputs
1952 /// (1), and little-endian operations with two different inputs (2).  For the
1953 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1954 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1955                              SelectionDAG &DAG) {
1956   if (N->getValueType(0) != MVT::v16i8)
1957     return -1;
1958 
1959   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1960 
1961   // Find the first non-undef value in the shuffle mask.
1962   unsigned i;
1963   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1964     /*search*/;
1965 
1966   if (i == 16) return -1;  // all undef.
1967 
1968   // Otherwise, check to see if the rest of the elements are consecutively
1969   // numbered from this value.
1970   unsigned ShiftAmt = SVOp->getMaskElt(i);
1971   if (ShiftAmt < i) return -1;
1972 
1973   ShiftAmt -= i;
1974   bool isLE = DAG.getDataLayout().isLittleEndian();
1975 
1976   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1977     // Check the rest of the elements to see if they are consecutive.
1978     for (++i; i != 16; ++i)
1979       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1980         return -1;
1981   } else if (ShuffleKind == 1) {
1982     // Check the rest of the elements to see if they are consecutive.
1983     for (++i; i != 16; ++i)
1984       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1985         return -1;
1986   } else
1987     return -1;
1988 
1989   if (isLE)
1990     ShiftAmt = 16 - ShiftAmt;
1991 
1992   return ShiftAmt;
1993 }
1994 
1995 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1996 /// specifies a splat of a single element that is suitable for input to
1997 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1998 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1999   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
2000          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2001 
2002   // The consecutive indices need to specify an element, not part of two
2003   // different elements.  So abandon ship early if this isn't the case.
2004   if (N->getMaskElt(0) % EltSize != 0)
2005     return false;
2006 
2007   // This is a splat operation if each element of the permute is the same, and
2008   // if the value doesn't reference the second vector.
2009   unsigned ElementBase = N->getMaskElt(0);
2010 
2011   // FIXME: Handle UNDEF elements too!
2012   if (ElementBase >= 16)
2013     return false;
2014 
2015   // Check that the indices are consecutive, in the case of a multi-byte element
2016   // splatted with a v16i8 mask.
2017   for (unsigned i = 1; i != EltSize; ++i)
2018     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2019       return false;
2020 
2021   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2022     if (N->getMaskElt(i) < 0) continue;
2023     for (unsigned j = 0; j != EltSize; ++j)
2024       if (N->getMaskElt(i+j) != N->getMaskElt(j))
2025         return false;
2026   }
2027   return true;
2028 }
2029 
2030 /// Check that the mask is shuffling N byte elements. Within each N byte
2031 /// element of the mask, the indices could be either in increasing or
2032 /// decreasing order as long as they are consecutive.
2033 /// \param[in] N the shuffle vector SD Node to analyze
2034 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2035 /// Word/DoubleWord/QuadWord).
2036 /// \param[in] StepLen the delta indices number among the N byte element, if
2037 /// the mask is in increasing/decreasing order then it is 1/-1.
2038 /// \return true iff the mask is shuffling N byte elements.
2039 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2040                                    int StepLen) {
2041   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2042          "Unexpected element width.");
2043   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2044 
2045   unsigned NumOfElem = 16 / Width;
2046   unsigned MaskVal[16]; //  Width is never greater than 16
2047   for (unsigned i = 0; i < NumOfElem; ++i) {
2048     MaskVal[0] = N->getMaskElt(i * Width);
2049     if ((StepLen == 1) && (MaskVal[0] % Width)) {
2050       return false;
2051     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2052       return false;
2053     }
2054 
2055     for (unsigned int j = 1; j < Width; ++j) {
2056       MaskVal[j] = N->getMaskElt(i * Width + j);
2057       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2058         return false;
2059       }
2060     }
2061   }
2062 
2063   return true;
2064 }
2065 
2066 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2067                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2068   if (!isNByteElemShuffleMask(N, 4, 1))
2069     return false;
2070 
2071   // Now we look at mask elements 0,4,8,12
2072   unsigned M0 = N->getMaskElt(0) / 4;
2073   unsigned M1 = N->getMaskElt(4) / 4;
2074   unsigned M2 = N->getMaskElt(8) / 4;
2075   unsigned M3 = N->getMaskElt(12) / 4;
2076   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2077   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2078 
2079   // Below, let H and L be arbitrary elements of the shuffle mask
2080   // where H is in the range [4,7] and L is in the range [0,3].
2081   // H, 1, 2, 3 or L, 5, 6, 7
2082   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2083       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2084     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2085     InsertAtByte = IsLE ? 12 : 0;
2086     Swap = M0 < 4;
2087     return true;
2088   }
2089   // 0, H, 2, 3 or 4, L, 6, 7
2090   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2091       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2092     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2093     InsertAtByte = IsLE ? 8 : 4;
2094     Swap = M1 < 4;
2095     return true;
2096   }
2097   // 0, 1, H, 3 or 4, 5, L, 7
2098   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2099       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2100     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2101     InsertAtByte = IsLE ? 4 : 8;
2102     Swap = M2 < 4;
2103     return true;
2104   }
2105   // 0, 1, 2, H or 4, 5, 6, L
2106   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2107       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2108     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2109     InsertAtByte = IsLE ? 0 : 12;
2110     Swap = M3 < 4;
2111     return true;
2112   }
2113 
2114   // If both vector operands for the shuffle are the same vector, the mask will
2115   // contain only elements from the first one and the second one will be undef.
2116   if (N->getOperand(1).isUndef()) {
2117     ShiftElts = 0;
2118     Swap = true;
2119     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2120     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2121       InsertAtByte = IsLE ? 12 : 0;
2122       return true;
2123     }
2124     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2125       InsertAtByte = IsLE ? 8 : 4;
2126       return true;
2127     }
2128     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2129       InsertAtByte = IsLE ? 4 : 8;
2130       return true;
2131     }
2132     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2133       InsertAtByte = IsLE ? 0 : 12;
2134       return true;
2135     }
2136   }
2137 
2138   return false;
2139 }
2140 
2141 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2142                                bool &Swap, bool IsLE) {
2143   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2144   // Ensure each byte index of the word is consecutive.
2145   if (!isNByteElemShuffleMask(N, 4, 1))
2146     return false;
2147 
2148   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2149   unsigned M0 = N->getMaskElt(0) / 4;
2150   unsigned M1 = N->getMaskElt(4) / 4;
2151   unsigned M2 = N->getMaskElt(8) / 4;
2152   unsigned M3 = N->getMaskElt(12) / 4;
2153 
2154   // If both vector operands for the shuffle are the same vector, the mask will
2155   // contain only elements from the first one and the second one will be undef.
2156   if (N->getOperand(1).isUndef()) {
2157     assert(M0 < 4 && "Indexing into an undef vector?");
2158     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2159       return false;
2160 
2161     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2162     Swap = false;
2163     return true;
2164   }
2165 
2166   // Ensure each word index of the ShuffleVector Mask is consecutive.
2167   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2168     return false;
2169 
2170   if (IsLE) {
2171     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2172       // Input vectors don't need to be swapped if the leading element
2173       // of the result is one of the 3 left elements of the second vector
2174       // (or if there is no shift to be done at all).
2175       Swap = false;
2176       ShiftElts = (8 - M0) % 8;
2177     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2178       // Input vectors need to be swapped if the leading element
2179       // of the result is one of the 3 left elements of the first vector
2180       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2181       Swap = true;
2182       ShiftElts = (4 - M0) % 4;
2183     }
2184 
2185     return true;
2186   } else {                                          // BE
2187     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2188       // Input vectors don't need to be swapped if the leading element
2189       // of the result is one of the 4 elements of the first vector.
2190       Swap = false;
2191       ShiftElts = M0;
2192     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2193       // Input vectors need to be swapped if the leading element
2194       // of the result is one of the 4 elements of the right vector.
2195       Swap = true;
2196       ShiftElts = M0 - 4;
2197     }
2198 
2199     return true;
2200   }
2201 }
2202 
2203 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2204   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2205 
2206   if (!isNByteElemShuffleMask(N, Width, -1))
2207     return false;
2208 
2209   for (int i = 0; i < 16; i += Width)
2210     if (N->getMaskElt(i) != i + Width - 1)
2211       return false;
2212 
2213   return true;
2214 }
2215 
2216 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2217   return isXXBRShuffleMaskHelper(N, 2);
2218 }
2219 
2220 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2221   return isXXBRShuffleMaskHelper(N, 4);
2222 }
2223 
2224 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2225   return isXXBRShuffleMaskHelper(N, 8);
2226 }
2227 
2228 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2229   return isXXBRShuffleMaskHelper(N, 16);
2230 }
2231 
2232 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2233 /// if the inputs to the instruction should be swapped and set \p DM to the
2234 /// value for the immediate.
2235 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2236 /// AND element 0 of the result comes from the first input (LE) or second input
2237 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2238 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2239 /// mask.
2240 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2241                                bool &Swap, bool IsLE) {
2242   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2243 
2244   // Ensure each byte index of the double word is consecutive.
2245   if (!isNByteElemShuffleMask(N, 8, 1))
2246     return false;
2247 
2248   unsigned M0 = N->getMaskElt(0) / 8;
2249   unsigned M1 = N->getMaskElt(8) / 8;
2250   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2251 
2252   // If both vector operands for the shuffle are the same vector, the mask will
2253   // contain only elements from the first one and the second one will be undef.
2254   if (N->getOperand(1).isUndef()) {
2255     if ((M0 | M1) < 2) {
2256       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2257       Swap = false;
2258       return true;
2259     } else
2260       return false;
2261   }
2262 
2263   if (IsLE) {
2264     if (M0 > 1 && M1 < 2) {
2265       Swap = false;
2266     } else if (M0 < 2 && M1 > 1) {
2267       M0 = (M0 + 2) % 4;
2268       M1 = (M1 + 2) % 4;
2269       Swap = true;
2270     } else
2271       return false;
2272 
2273     // Note: if control flow comes here that means Swap is already set above
2274     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2275     return true;
2276   } else { // BE
2277     if (M0 < 2 && M1 > 1) {
2278       Swap = false;
2279     } else if (M0 > 1 && M1 < 2) {
2280       M0 = (M0 + 2) % 4;
2281       M1 = (M1 + 2) % 4;
2282       Swap = true;
2283     } else
2284       return false;
2285 
2286     // Note: if control flow comes here that means Swap is already set above
2287     DM = (M0 << 1) + (M1 & 1);
2288     return true;
2289   }
2290 }
2291 
2292 
2293 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2294 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2295 /// elements are counted from the left of the vector register).
2296 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2297                                          SelectionDAG &DAG) {
2298   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2299   assert(isSplatShuffleMask(SVOp, EltSize));
2300   if (DAG.getDataLayout().isLittleEndian())
2301     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2302   else
2303     return SVOp->getMaskElt(0) / EltSize;
2304 }
2305 
2306 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2307 /// by using a vspltis[bhw] instruction of the specified element size, return
2308 /// the constant being splatted.  The ByteSize field indicates the number of
2309 /// bytes of each element [124] -> [bhw].
2310 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2311   SDValue OpVal(nullptr, 0);
2312 
2313   // If ByteSize of the splat is bigger than the element size of the
2314   // build_vector, then we have a case where we are checking for a splat where
2315   // multiple elements of the buildvector are folded together into a single
2316   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2317   unsigned EltSize = 16/N->getNumOperands();
2318   if (EltSize < ByteSize) {
2319     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2320     SDValue UniquedVals[4];
2321     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2322 
2323     // See if all of the elements in the buildvector agree across.
2324     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2325       if (N->getOperand(i).isUndef()) continue;
2326       // If the element isn't a constant, bail fully out.
2327       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2328 
2329       if (!UniquedVals[i&(Multiple-1)].getNode())
2330         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2331       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2332         return SDValue();  // no match.
2333     }
2334 
2335     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2336     // either constant or undef values that are identical for each chunk.  See
2337     // if these chunks can form into a larger vspltis*.
2338 
2339     // Check to see if all of the leading entries are either 0 or -1.  If
2340     // neither, then this won't fit into the immediate field.
2341     bool LeadingZero = true;
2342     bool LeadingOnes = true;
2343     for (unsigned i = 0; i != Multiple-1; ++i) {
2344       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2345 
2346       LeadingZero &= isNullConstant(UniquedVals[i]);
2347       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2348     }
2349     // Finally, check the least significant entry.
2350     if (LeadingZero) {
2351       if (!UniquedVals[Multiple-1].getNode())
2352         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2353       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2354       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2355         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2356     }
2357     if (LeadingOnes) {
2358       if (!UniquedVals[Multiple-1].getNode())
2359         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2360       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2361       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2362         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2363     }
2364 
2365     return SDValue();
2366   }
2367 
2368   // Check to see if this buildvec has a single non-undef value in its elements.
2369   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2370     if (N->getOperand(i).isUndef()) continue;
2371     if (!OpVal.getNode())
2372       OpVal = N->getOperand(i);
2373     else if (OpVal != N->getOperand(i))
2374       return SDValue();
2375   }
2376 
2377   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2378 
2379   unsigned ValSizeInBytes = EltSize;
2380   uint64_t Value = 0;
2381   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2382     Value = CN->getZExtValue();
2383   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2384     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2385     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2386   }
2387 
2388   // If the splat value is larger than the element value, then we can never do
2389   // this splat.  The only case that we could fit the replicated bits into our
2390   // immediate field for would be zero, and we prefer to use vxor for it.
2391   if (ValSizeInBytes < ByteSize) return SDValue();
2392 
2393   // If the element value is larger than the splat value, check if it consists
2394   // of a repeated bit pattern of size ByteSize.
2395   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2396     return SDValue();
2397 
2398   // Properly sign extend the value.
2399   int MaskVal = SignExtend32(Value, ByteSize * 8);
2400 
2401   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2402   if (MaskVal == 0) return SDValue();
2403 
2404   // Finally, if this value fits in a 5 bit sext field, return it
2405   if (SignExtend32<5>(MaskVal) == MaskVal)
2406     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2407   return SDValue();
2408 }
2409 
2410 //===----------------------------------------------------------------------===//
2411 //  Addressing Mode Selection
2412 //===----------------------------------------------------------------------===//
2413 
2414 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2415 /// or 64-bit immediate, and if the value can be accurately represented as a
2416 /// sign extension from a 16-bit value.  If so, this returns true and the
2417 /// immediate.
2418 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2419   if (!isa<ConstantSDNode>(N))
2420     return false;
2421 
2422   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2423   if (N->getValueType(0) == MVT::i32)
2424     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2425   else
2426     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2427 }
2428 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2429   return isIntS16Immediate(Op.getNode(), Imm);
2430 }
2431 
2432 
2433 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2434 /// be represented as an indexed [r+r] operation.
2435 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2436                                                SDValue &Index,
2437                                                SelectionDAG &DAG) const {
2438   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2439       UI != E; ++UI) {
2440     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2441       if (Memop->getMemoryVT() == MVT::f64) {
2442           Base = N.getOperand(0);
2443           Index = N.getOperand(1);
2444           return true;
2445       }
2446     }
2447   }
2448   return false;
2449 }
2450 
2451 /// isIntS34Immediate - This method tests if value of node given can be
2452 /// accurately represented as a sign extension from a 34-bit value.  If so,
2453 /// this returns true and the immediate.
2454 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2455   if (!isa<ConstantSDNode>(N))
2456     return false;
2457 
2458   Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2459   return isInt<34>(Imm);
2460 }
2461 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2462   return isIntS34Immediate(Op.getNode(), Imm);
2463 }
2464 
2465 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2466 /// can be represented as an indexed [r+r] operation.  Returns false if it
2467 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2468 /// non-zero and N can be represented by a base register plus a signed 16-bit
2469 /// displacement, make a more precise judgement by checking (displacement % \p
2470 /// EncodingAlignment).
2471 bool PPCTargetLowering::SelectAddressRegReg(
2472     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2473     MaybeAlign EncodingAlignment) const {
2474   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2475   // a [pc+imm].
2476   if (SelectAddressPCRel(N, Base))
2477     return false;
2478 
2479   int16_t Imm = 0;
2480   if (N.getOpcode() == ISD::ADD) {
2481     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2482     // SPE load/store can only handle 8-bit offsets.
2483     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2484         return true;
2485     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2486         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2487       return false; // r+i
2488     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2489       return false;    // r+i
2490 
2491     Base = N.getOperand(0);
2492     Index = N.getOperand(1);
2493     return true;
2494   } else if (N.getOpcode() == ISD::OR) {
2495     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2496         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2497       return false; // r+i can fold it if we can.
2498 
2499     // If this is an or of disjoint bitfields, we can codegen this as an add
2500     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2501     // disjoint.
2502     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2503 
2504     if (LHSKnown.Zero.getBoolValue()) {
2505       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2506       // If all of the bits are known zero on the LHS or RHS, the add won't
2507       // carry.
2508       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2509         Base = N.getOperand(0);
2510         Index = N.getOperand(1);
2511         return true;
2512       }
2513     }
2514   }
2515 
2516   return false;
2517 }
2518 
2519 // If we happen to be doing an i64 load or store into a stack slot that has
2520 // less than a 4-byte alignment, then the frame-index elimination may need to
2521 // use an indexed load or store instruction (because the offset may not be a
2522 // multiple of 4). The extra register needed to hold the offset comes from the
2523 // register scavenger, and it is possible that the scavenger will need to use
2524 // an emergency spill slot. As a result, we need to make sure that a spill slot
2525 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2526 // stack slot.
2527 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2528   // FIXME: This does not handle the LWA case.
2529   if (VT != MVT::i64)
2530     return;
2531 
2532   // NOTE: We'll exclude negative FIs here, which come from argument
2533   // lowering, because there are no known test cases triggering this problem
2534   // using packed structures (or similar). We can remove this exclusion if
2535   // we find such a test case. The reason why this is so test-case driven is
2536   // because this entire 'fixup' is only to prevent crashes (from the
2537   // register scavenger) on not-really-valid inputs. For example, if we have:
2538   //   %a = alloca i1
2539   //   %b = bitcast i1* %a to i64*
2540   //   store i64* a, i64 b
2541   // then the store should really be marked as 'align 1', but is not. If it
2542   // were marked as 'align 1' then the indexed form would have been
2543   // instruction-selected initially, and the problem this 'fixup' is preventing
2544   // won't happen regardless.
2545   if (FrameIdx < 0)
2546     return;
2547 
2548   MachineFunction &MF = DAG.getMachineFunction();
2549   MachineFrameInfo &MFI = MF.getFrameInfo();
2550 
2551   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2552     return;
2553 
2554   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2555   FuncInfo->setHasNonRISpills();
2556 }
2557 
2558 /// Returns true if the address N can be represented by a base register plus
2559 /// a signed 16-bit displacement [r+imm], and if it is not better
2560 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2561 /// displacements that are multiples of that value.
2562 bool PPCTargetLowering::SelectAddressRegImm(
2563     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2564     MaybeAlign EncodingAlignment) const {
2565   // FIXME dl should come from parent load or store, not from address
2566   SDLoc dl(N);
2567 
2568   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2569   // a [pc+imm].
2570   if (SelectAddressPCRel(N, Base))
2571     return false;
2572 
2573   // If this can be more profitably realized as r+r, fail.
2574   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2575     return false;
2576 
2577   if (N.getOpcode() == ISD::ADD) {
2578     int16_t imm = 0;
2579     if (isIntS16Immediate(N.getOperand(1), imm) &&
2580         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2581       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2582       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2583         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2584         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2585       } else {
2586         Base = N.getOperand(0);
2587       }
2588       return true; // [r+i]
2589     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2590       // Match LOAD (ADD (X, Lo(G))).
2591       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2592              && "Cannot handle constant offsets yet!");
2593       Disp = N.getOperand(1).getOperand(0);  // The global address.
2594       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2595              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2596              Disp.getOpcode() == ISD::TargetConstantPool ||
2597              Disp.getOpcode() == ISD::TargetJumpTable);
2598       Base = N.getOperand(0);
2599       return true;  // [&g+r]
2600     }
2601   } else if (N.getOpcode() == ISD::OR) {
2602     int16_t imm = 0;
2603     if (isIntS16Immediate(N.getOperand(1), imm) &&
2604         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2605       // If this is an or of disjoint bitfields, we can codegen this as an add
2606       // (for better address arithmetic) if the LHS and RHS of the OR are
2607       // provably disjoint.
2608       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2609 
2610       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2611         // If all of the bits are known zero on the LHS or RHS, the add won't
2612         // carry.
2613         if (FrameIndexSDNode *FI =
2614               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2615           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2616           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2617         } else {
2618           Base = N.getOperand(0);
2619         }
2620         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2621         return true;
2622       }
2623     }
2624   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2625     // Loading from a constant address.
2626 
2627     // If this address fits entirely in a 16-bit sext immediate field, codegen
2628     // this as "d, 0"
2629     int16_t Imm;
2630     if (isIntS16Immediate(CN, Imm) &&
2631         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2632       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2633       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2634                              CN->getValueType(0));
2635       return true;
2636     }
2637 
2638     // Handle 32-bit sext immediates with LIS + addr mode.
2639     if ((CN->getValueType(0) == MVT::i32 ||
2640          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2641         (!EncodingAlignment ||
2642          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2643       int Addr = (int)CN->getZExtValue();
2644 
2645       // Otherwise, break this down into an LIS + disp.
2646       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2647 
2648       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2649                                    MVT::i32);
2650       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2651       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2652       return true;
2653     }
2654   }
2655 
2656   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2657   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2658     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2659     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2660   } else
2661     Base = N;
2662   return true;      // [r+0]
2663 }
2664 
2665 /// Similar to the 16-bit case but for instructions that take a 34-bit
2666 /// displacement field (prefixed loads/stores).
2667 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp,
2668                                               SDValue &Base,
2669                                               SelectionDAG &DAG) const {
2670   // Only on 64-bit targets.
2671   if (N.getValueType() != MVT::i64)
2672     return false;
2673 
2674   SDLoc dl(N);
2675   int64_t Imm = 0;
2676 
2677   if (N.getOpcode() == ISD::ADD) {
2678     if (!isIntS34Immediate(N.getOperand(1), Imm))
2679       return false;
2680     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2681     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2682       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2683     else
2684       Base = N.getOperand(0);
2685     return true;
2686   }
2687 
2688   if (N.getOpcode() == ISD::OR) {
2689     if (!isIntS34Immediate(N.getOperand(1), Imm))
2690       return false;
2691     // If this is an or of disjoint bitfields, we can codegen this as an add
2692     // (for better address arithmetic) if the LHS and RHS of the OR are
2693     // provably disjoint.
2694     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2695     if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2696       return false;
2697     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2698       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2699     else
2700       Base = N.getOperand(0);
2701     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2702     return true;
2703   }
2704 
2705   if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2706     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2707     Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2708     return true;
2709   }
2710 
2711   return false;
2712 }
2713 
2714 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2715 /// represented as an indexed [r+r] operation.
2716 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2717                                                 SDValue &Index,
2718                                                 SelectionDAG &DAG) const {
2719   // Check to see if we can easily represent this as an [r+r] address.  This
2720   // will fail if it thinks that the address is more profitably represented as
2721   // reg+imm, e.g. where imm = 0.
2722   if (SelectAddressRegReg(N, Base, Index, DAG))
2723     return true;
2724 
2725   // If the address is the result of an add, we will utilize the fact that the
2726   // address calculation includes an implicit add.  However, we can reduce
2727   // register pressure if we do not materialize a constant just for use as the
2728   // index register.  We only get rid of the add if it is not an add of a
2729   // value and a 16-bit signed constant and both have a single use.
2730   int16_t imm = 0;
2731   if (N.getOpcode() == ISD::ADD &&
2732       (!isIntS16Immediate(N.getOperand(1), imm) ||
2733        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2734     Base = N.getOperand(0);
2735     Index = N.getOperand(1);
2736     return true;
2737   }
2738 
2739   // Otherwise, do it the hard way, using R0 as the base register.
2740   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2741                          N.getValueType());
2742   Index = N;
2743   return true;
2744 }
2745 
2746 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2747   Ty *PCRelCand = dyn_cast<Ty>(N);
2748   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2749 }
2750 
2751 /// Returns true if this address is a PC Relative address.
2752 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2753 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2754 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2755   // This is a materialize PC Relative node. Always select this as PC Relative.
2756   Base = N;
2757   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2758     return true;
2759   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2760       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2761       isValidPCRelNode<JumpTableSDNode>(N) ||
2762       isValidPCRelNode<BlockAddressSDNode>(N))
2763     return true;
2764   return false;
2765 }
2766 
2767 /// Returns true if we should use a direct load into vector instruction
2768 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2769 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2770 
2771   // If there are any other uses other than scalar to vector, then we should
2772   // keep it as a scalar load -> direct move pattern to prevent multiple
2773   // loads.
2774   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2775   if (!LD)
2776     return false;
2777 
2778   EVT MemVT = LD->getMemoryVT();
2779   if (!MemVT.isSimple())
2780     return false;
2781   switch(MemVT.getSimpleVT().SimpleTy) {
2782   case MVT::i64:
2783     break;
2784   case MVT::i32:
2785     if (!ST.hasP8Vector())
2786       return false;
2787     break;
2788   case MVT::i16:
2789   case MVT::i8:
2790     if (!ST.hasP9Vector())
2791       return false;
2792     break;
2793   default:
2794     return false;
2795   }
2796 
2797   SDValue LoadedVal(N, 0);
2798   if (!LoadedVal.hasOneUse())
2799     return false;
2800 
2801   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2802        UI != UE; ++UI)
2803     if (UI.getUse().get().getResNo() == 0 &&
2804         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2805         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2806       return false;
2807 
2808   return true;
2809 }
2810 
2811 /// getPreIndexedAddressParts - returns true by value, base pointer and
2812 /// offset pointer and addressing mode by reference if the node's address
2813 /// can be legally represented as pre-indexed load / store address.
2814 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2815                                                   SDValue &Offset,
2816                                                   ISD::MemIndexedMode &AM,
2817                                                   SelectionDAG &DAG) const {
2818   if (DisablePPCPreinc) return false;
2819 
2820   bool isLoad = true;
2821   SDValue Ptr;
2822   EVT VT;
2823   unsigned Alignment;
2824   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2825     Ptr = LD->getBasePtr();
2826     VT = LD->getMemoryVT();
2827     Alignment = LD->getAlignment();
2828   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2829     Ptr = ST->getBasePtr();
2830     VT  = ST->getMemoryVT();
2831     Alignment = ST->getAlignment();
2832     isLoad = false;
2833   } else
2834     return false;
2835 
2836   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2837   // instructions because we can fold these into a more efficient instruction
2838   // instead, (such as LXSD).
2839   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2840     return false;
2841   }
2842 
2843   // PowerPC doesn't have preinc load/store instructions for vectors
2844   if (VT.isVector())
2845     return false;
2846 
2847   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2848     // Common code will reject creating a pre-inc form if the base pointer
2849     // is a frame index, or if N is a store and the base pointer is either
2850     // the same as or a predecessor of the value being stored.  Check for
2851     // those situations here, and try with swapped Base/Offset instead.
2852     bool Swap = false;
2853 
2854     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2855       Swap = true;
2856     else if (!isLoad) {
2857       SDValue Val = cast<StoreSDNode>(N)->getValue();
2858       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2859         Swap = true;
2860     }
2861 
2862     if (Swap)
2863       std::swap(Base, Offset);
2864 
2865     AM = ISD::PRE_INC;
2866     return true;
2867   }
2868 
2869   // LDU/STU can only handle immediates that are a multiple of 4.
2870   if (VT != MVT::i64) {
2871     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2872       return false;
2873   } else {
2874     // LDU/STU need an address with at least 4-byte alignment.
2875     if (Alignment < 4)
2876       return false;
2877 
2878     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
2879       return false;
2880   }
2881 
2882   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2883     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2884     // sext i32 to i64 when addr mode is r+i.
2885     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2886         LD->getExtensionType() == ISD::SEXTLOAD &&
2887         isa<ConstantSDNode>(Offset))
2888       return false;
2889   }
2890 
2891   AM = ISD::PRE_INC;
2892   return true;
2893 }
2894 
2895 //===----------------------------------------------------------------------===//
2896 //  LowerOperation implementation
2897 //===----------------------------------------------------------------------===//
2898 
2899 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2900 /// and LoOpFlags to the target MO flags.
2901 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2902                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2903                                const GlobalValue *GV = nullptr) {
2904   HiOpFlags = PPCII::MO_HA;
2905   LoOpFlags = PPCII::MO_LO;
2906 
2907   // Don't use the pic base if not in PIC relocation model.
2908   if (IsPIC) {
2909     HiOpFlags |= PPCII::MO_PIC_FLAG;
2910     LoOpFlags |= PPCII::MO_PIC_FLAG;
2911   }
2912 }
2913 
2914 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2915                              SelectionDAG &DAG) {
2916   SDLoc DL(HiPart);
2917   EVT PtrVT = HiPart.getValueType();
2918   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2919 
2920   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2921   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2922 
2923   // With PIC, the first instruction is actually "GR+hi(&G)".
2924   if (isPIC)
2925     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2926                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2927 
2928   // Generate non-pic code that has direct accesses to the constant pool.
2929   // The address of the global is just (hi(&g)+lo(&g)).
2930   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2931 }
2932 
2933 static void setUsesTOCBasePtr(MachineFunction &MF) {
2934   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2935   FuncInfo->setUsesTOCBasePtr();
2936 }
2937 
2938 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2939   setUsesTOCBasePtr(DAG.getMachineFunction());
2940 }
2941 
2942 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2943                                        SDValue GA) const {
2944   const bool Is64Bit = Subtarget.isPPC64();
2945   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2946   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2947                         : Subtarget.isAIXABI()
2948                               ? DAG.getRegister(PPC::R2, VT)
2949                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2950   SDValue Ops[] = { GA, Reg };
2951   return DAG.getMemIntrinsicNode(
2952       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2953       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2954       MachineMemOperand::MOLoad);
2955 }
2956 
2957 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2958                                              SelectionDAG &DAG) const {
2959   EVT PtrVT = Op.getValueType();
2960   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2961   const Constant *C = CP->getConstVal();
2962 
2963   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2964   // The actual address of the GlobalValue is stored in the TOC.
2965   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2966     if (Subtarget.isUsingPCRelativeCalls()) {
2967       SDLoc DL(CP);
2968       EVT Ty = getPointerTy(DAG.getDataLayout());
2969       SDValue ConstPool = DAG.getTargetConstantPool(
2970           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2971       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2972     }
2973     setUsesTOCBasePtr(DAG);
2974     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2975     return getTOCEntry(DAG, SDLoc(CP), GA);
2976   }
2977 
2978   unsigned MOHiFlag, MOLoFlag;
2979   bool IsPIC = isPositionIndependent();
2980   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2981 
2982   if (IsPIC && Subtarget.isSVR4ABI()) {
2983     SDValue GA =
2984         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2985     return getTOCEntry(DAG, SDLoc(CP), GA);
2986   }
2987 
2988   SDValue CPIHi =
2989       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
2990   SDValue CPILo =
2991       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
2992   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2993 }
2994 
2995 // For 64-bit PowerPC, prefer the more compact relative encodings.
2996 // This trades 32 bits per jump table entry for one or two instructions
2997 // on the jump site.
2998 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2999   if (isJumpTableRelative())
3000     return MachineJumpTableInfo::EK_LabelDifference32;
3001 
3002   return TargetLowering::getJumpTableEncoding();
3003 }
3004 
3005 bool PPCTargetLowering::isJumpTableRelative() const {
3006   if (UseAbsoluteJumpTables)
3007     return false;
3008   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3009     return true;
3010   return TargetLowering::isJumpTableRelative();
3011 }
3012 
3013 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
3014                                                     SelectionDAG &DAG) const {
3015   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3016     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3017 
3018   switch (getTargetMachine().getCodeModel()) {
3019   case CodeModel::Small:
3020   case CodeModel::Medium:
3021     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3022   default:
3023     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3024                        getPointerTy(DAG.getDataLayout()));
3025   }
3026 }
3027 
3028 const MCExpr *
3029 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
3030                                                 unsigned JTI,
3031                                                 MCContext &Ctx) const {
3032   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3033     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3034 
3035   switch (getTargetMachine().getCodeModel()) {
3036   case CodeModel::Small:
3037   case CodeModel::Medium:
3038     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3039   default:
3040     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3041   }
3042 }
3043 
3044 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3045   EVT PtrVT = Op.getValueType();
3046   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3047 
3048   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3049   if (Subtarget.isUsingPCRelativeCalls()) {
3050     SDLoc DL(JT);
3051     EVT Ty = getPointerTy(DAG.getDataLayout());
3052     SDValue GA =
3053         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3054     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3055     return MatAddr;
3056   }
3057 
3058   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3059   // The actual address of the GlobalValue is stored in the TOC.
3060   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3061     setUsesTOCBasePtr(DAG);
3062     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3063     return getTOCEntry(DAG, SDLoc(JT), GA);
3064   }
3065 
3066   unsigned MOHiFlag, MOLoFlag;
3067   bool IsPIC = isPositionIndependent();
3068   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3069 
3070   if (IsPIC && Subtarget.isSVR4ABI()) {
3071     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3072                                         PPCII::MO_PIC_FLAG);
3073     return getTOCEntry(DAG, SDLoc(GA), GA);
3074   }
3075 
3076   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3077   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3078   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3079 }
3080 
3081 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3082                                              SelectionDAG &DAG) const {
3083   EVT PtrVT = Op.getValueType();
3084   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3085   const BlockAddress *BA = BASDN->getBlockAddress();
3086 
3087   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3088   if (Subtarget.isUsingPCRelativeCalls()) {
3089     SDLoc DL(BASDN);
3090     EVT Ty = getPointerTy(DAG.getDataLayout());
3091     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3092                                            PPCII::MO_PCREL_FLAG);
3093     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3094     return MatAddr;
3095   }
3096 
3097   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3098   // The actual BlockAddress is stored in the TOC.
3099   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3100     setUsesTOCBasePtr(DAG);
3101     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3102     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3103   }
3104 
3105   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3106   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3107     return getTOCEntry(
3108         DAG, SDLoc(BASDN),
3109         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3110 
3111   unsigned MOHiFlag, MOLoFlag;
3112   bool IsPIC = isPositionIndependent();
3113   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3114   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3115   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3116   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3117 }
3118 
3119 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3120                                               SelectionDAG &DAG) const {
3121   if (Subtarget.isAIXABI())
3122     return LowerGlobalTLSAddressAIX(Op, DAG);
3123 
3124   return LowerGlobalTLSAddressLinux(Op, DAG);
3125 }
3126 
3127 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3128                                                     SelectionDAG &DAG) const {
3129   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3130 
3131   if (DAG.getTarget().useEmulatedTLS())
3132     report_fatal_error("Emulated TLS is not yet supported on AIX");
3133 
3134   SDLoc dl(GA);
3135   const GlobalValue *GV = GA->getGlobal();
3136   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3137 
3138   // The general-dynamic model is the only access model supported for now, so
3139   // all the GlobalTLSAddress nodes are lowered with this model.
3140   // We need to generate two TOC entries, one for the variable offset, one for
3141   // the region handle. The global address for the TOC entry of the region
3142   // handle is created with the MO_TLSGD_FLAG flag so we can easily identify
3143   // this entry and add the right relocation.
3144   SDValue VariableOffsetTGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3145   SDValue RegionHandleTGA =
3146       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3147   SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3148   SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3149   return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3150                      RegionHandle);
3151 }
3152 
3153 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3154                                                       SelectionDAG &DAG) const {
3155   // FIXME: TLS addresses currently use medium model code sequences,
3156   // which is the most useful form.  Eventually support for small and
3157   // large models could be added if users need it, at the cost of
3158   // additional complexity.
3159   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3160   if (DAG.getTarget().useEmulatedTLS())
3161     return LowerToTLSEmulatedModel(GA, DAG);
3162 
3163   SDLoc dl(GA);
3164   const GlobalValue *GV = GA->getGlobal();
3165   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3166   bool is64bit = Subtarget.isPPC64();
3167   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3168   PICLevel::Level picLevel = M->getPICLevel();
3169 
3170   const TargetMachine &TM = getTargetMachine();
3171   TLSModel::Model Model = TM.getTLSModel(GV);
3172 
3173   if (Model == TLSModel::LocalExec) {
3174     if (Subtarget.isUsingPCRelativeCalls()) {
3175       SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3176       SDValue TGA = DAG.getTargetGlobalAddress(
3177           GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3178       SDValue MatAddr =
3179           DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3180       return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3181     }
3182 
3183     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3184                                                PPCII::MO_TPREL_HA);
3185     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3186                                                PPCII::MO_TPREL_LO);
3187     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3188                              : DAG.getRegister(PPC::R2, MVT::i32);
3189 
3190     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3191     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3192   }
3193 
3194   if (Model == TLSModel::InitialExec) {
3195     bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3196     SDValue TGA = DAG.getTargetGlobalAddress(
3197         GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3198     SDValue TGATLS = DAG.getTargetGlobalAddress(
3199         GV, dl, PtrVT, 0,
3200         IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3201     SDValue TPOffset;
3202     if (IsPCRel) {
3203       SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3204       TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3205                              MachinePointerInfo());
3206     } else {
3207       SDValue GOTPtr;
3208       if (is64bit) {
3209         setUsesTOCBasePtr(DAG);
3210         SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3211         GOTPtr =
3212             DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3213       } else {
3214         if (!TM.isPositionIndependent())
3215           GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3216         else if (picLevel == PICLevel::SmallPIC)
3217           GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3218         else
3219           GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3220       }
3221       TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3222     }
3223     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3224   }
3225 
3226   if (Model == TLSModel::GeneralDynamic) {
3227     if (Subtarget.isUsingPCRelativeCalls()) {
3228       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3229                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3230       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3231     }
3232 
3233     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3234     SDValue GOTPtr;
3235     if (is64bit) {
3236       setUsesTOCBasePtr(DAG);
3237       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3238       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3239                                    GOTReg, TGA);
3240     } else {
3241       if (picLevel == PICLevel::SmallPIC)
3242         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3243       else
3244         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3245     }
3246     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3247                        GOTPtr, TGA, TGA);
3248   }
3249 
3250   if (Model == TLSModel::LocalDynamic) {
3251     if (Subtarget.isUsingPCRelativeCalls()) {
3252       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3253                                                PPCII::MO_GOT_TLSLD_PCREL_FLAG);
3254       SDValue MatPCRel =
3255           DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3256       return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3257     }
3258 
3259     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3260     SDValue GOTPtr;
3261     if (is64bit) {
3262       setUsesTOCBasePtr(DAG);
3263       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3264       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3265                            GOTReg, TGA);
3266     } else {
3267       if (picLevel == PICLevel::SmallPIC)
3268         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3269       else
3270         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3271     }
3272     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3273                                   PtrVT, GOTPtr, TGA, TGA);
3274     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3275                                       PtrVT, TLSAddr, TGA);
3276     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3277   }
3278 
3279   llvm_unreachable("Unknown TLS model!");
3280 }
3281 
3282 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3283                                               SelectionDAG &DAG) const {
3284   EVT PtrVT = Op.getValueType();
3285   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3286   SDLoc DL(GSDN);
3287   const GlobalValue *GV = GSDN->getGlobal();
3288 
3289   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3290   // The actual address of the GlobalValue is stored in the TOC.
3291   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3292     if (Subtarget.isUsingPCRelativeCalls()) {
3293       EVT Ty = getPointerTy(DAG.getDataLayout());
3294       if (isAccessedAsGotIndirect(Op)) {
3295         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3296                                                 PPCII::MO_PCREL_FLAG |
3297                                                     PPCII::MO_GOT_FLAG);
3298         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3299         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3300                                    MachinePointerInfo());
3301         return Load;
3302       } else {
3303         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3304                                                 PPCII::MO_PCREL_FLAG);
3305         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3306       }
3307     }
3308     setUsesTOCBasePtr(DAG);
3309     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3310     return getTOCEntry(DAG, DL, GA);
3311   }
3312 
3313   unsigned MOHiFlag, MOLoFlag;
3314   bool IsPIC = isPositionIndependent();
3315   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3316 
3317   if (IsPIC && Subtarget.isSVR4ABI()) {
3318     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3319                                             GSDN->getOffset(),
3320                                             PPCII::MO_PIC_FLAG);
3321     return getTOCEntry(DAG, DL, GA);
3322   }
3323 
3324   SDValue GAHi =
3325     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3326   SDValue GALo =
3327     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3328 
3329   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3330 }
3331 
3332 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3333   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3334   SDLoc dl(Op);
3335 
3336   if (Op.getValueType() == MVT::v2i64) {
3337     // When the operands themselves are v2i64 values, we need to do something
3338     // special because VSX has no underlying comparison operations for these.
3339     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3340       // Equality can be handled by casting to the legal type for Altivec
3341       // comparisons, everything else needs to be expanded.
3342       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3343         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3344                  DAG.getSetCC(dl, MVT::v4i32,
3345                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3346                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3347                    CC));
3348       }
3349 
3350       return SDValue();
3351     }
3352 
3353     // We handle most of these in the usual way.
3354     return Op;
3355   }
3356 
3357   // If we're comparing for equality to zero, expose the fact that this is
3358   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3359   // fold the new nodes.
3360   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3361     return V;
3362 
3363   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3364     // Leave comparisons against 0 and -1 alone for now, since they're usually
3365     // optimized.  FIXME: revisit this when we can custom lower all setcc
3366     // optimizations.
3367     if (C->isAllOnesValue() || C->isNullValue())
3368       return SDValue();
3369   }
3370 
3371   // If we have an integer seteq/setne, turn it into a compare against zero
3372   // by xor'ing the rhs with the lhs, which is faster than setting a
3373   // condition register, reading it back out, and masking the correct bit.  The
3374   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3375   // the result to other bit-twiddling opportunities.
3376   EVT LHSVT = Op.getOperand(0).getValueType();
3377   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3378     EVT VT = Op.getValueType();
3379     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3380                                 Op.getOperand(1));
3381     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3382   }
3383   return SDValue();
3384 }
3385 
3386 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3387   SDNode *Node = Op.getNode();
3388   EVT VT = Node->getValueType(0);
3389   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3390   SDValue InChain = Node->getOperand(0);
3391   SDValue VAListPtr = Node->getOperand(1);
3392   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3393   SDLoc dl(Node);
3394 
3395   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3396 
3397   // gpr_index
3398   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3399                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3400   InChain = GprIndex.getValue(1);
3401 
3402   if (VT == MVT::i64) {
3403     // Check if GprIndex is even
3404     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3405                                  DAG.getConstant(1, dl, MVT::i32));
3406     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3407                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3408     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3409                                           DAG.getConstant(1, dl, MVT::i32));
3410     // Align GprIndex to be even if it isn't
3411     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3412                            GprIndex);
3413   }
3414 
3415   // fpr index is 1 byte after gpr
3416   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3417                                DAG.getConstant(1, dl, MVT::i32));
3418 
3419   // fpr
3420   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3421                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3422   InChain = FprIndex.getValue(1);
3423 
3424   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3425                                        DAG.getConstant(8, dl, MVT::i32));
3426 
3427   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3428                                         DAG.getConstant(4, dl, MVT::i32));
3429 
3430   // areas
3431   SDValue OverflowArea =
3432       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3433   InChain = OverflowArea.getValue(1);
3434 
3435   SDValue RegSaveArea =
3436       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3437   InChain = RegSaveArea.getValue(1);
3438 
3439   // select overflow_area if index > 8
3440   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3441                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3442 
3443   // adjustment constant gpr_index * 4/8
3444   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3445                                     VT.isInteger() ? GprIndex : FprIndex,
3446                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3447                                                     MVT::i32));
3448 
3449   // OurReg = RegSaveArea + RegConstant
3450   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3451                                RegConstant);
3452 
3453   // Floating types are 32 bytes into RegSaveArea
3454   if (VT.isFloatingPoint())
3455     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3456                          DAG.getConstant(32, dl, MVT::i32));
3457 
3458   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3459   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3460                                    VT.isInteger() ? GprIndex : FprIndex,
3461                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3462                                                    MVT::i32));
3463 
3464   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3465                               VT.isInteger() ? VAListPtr : FprPtr,
3466                               MachinePointerInfo(SV), MVT::i8);
3467 
3468   // determine if we should load from reg_save_area or overflow_area
3469   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3470 
3471   // increase overflow_area by 4/8 if gpr/fpr > 8
3472   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3473                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3474                                           dl, MVT::i32));
3475 
3476   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3477                              OverflowAreaPlusN);
3478 
3479   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3480                               MachinePointerInfo(), MVT::i32);
3481 
3482   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3483 }
3484 
3485 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3486   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3487 
3488   // We have to copy the entire va_list struct:
3489   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3490   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3491                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3492                        false, true, false, MachinePointerInfo(),
3493                        MachinePointerInfo());
3494 }
3495 
3496 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3497                                                   SelectionDAG &DAG) const {
3498   if (Subtarget.isAIXABI())
3499     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3500 
3501   return Op.getOperand(0);
3502 }
3503 
3504 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3505                                                 SelectionDAG &DAG) const {
3506   if (Subtarget.isAIXABI())
3507     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3508 
3509   SDValue Chain = Op.getOperand(0);
3510   SDValue Trmp = Op.getOperand(1); // trampoline
3511   SDValue FPtr = Op.getOperand(2); // nested function
3512   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3513   SDLoc dl(Op);
3514 
3515   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3516   bool isPPC64 = (PtrVT == MVT::i64);
3517   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3518 
3519   TargetLowering::ArgListTy Args;
3520   TargetLowering::ArgListEntry Entry;
3521 
3522   Entry.Ty = IntPtrTy;
3523   Entry.Node = Trmp; Args.push_back(Entry);
3524 
3525   // TrampSize == (isPPC64 ? 48 : 40);
3526   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3527                                isPPC64 ? MVT::i64 : MVT::i32);
3528   Args.push_back(Entry);
3529 
3530   Entry.Node = FPtr; Args.push_back(Entry);
3531   Entry.Node = Nest; Args.push_back(Entry);
3532 
3533   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3534   TargetLowering::CallLoweringInfo CLI(DAG);
3535   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3536       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3537       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3538 
3539   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3540   return CallResult.second;
3541 }
3542 
3543 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3544   MachineFunction &MF = DAG.getMachineFunction();
3545   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3546   EVT PtrVT = getPointerTy(MF.getDataLayout());
3547 
3548   SDLoc dl(Op);
3549 
3550   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3551     // vastart just stores the address of the VarArgsFrameIndex slot into the
3552     // memory location argument.
3553     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3554     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3555     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3556                         MachinePointerInfo(SV));
3557   }
3558 
3559   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3560   // We suppose the given va_list is already allocated.
3561   //
3562   // typedef struct {
3563   //  char gpr;     /* index into the array of 8 GPRs
3564   //                 * stored in the register save area
3565   //                 * gpr=0 corresponds to r3,
3566   //                 * gpr=1 to r4, etc.
3567   //                 */
3568   //  char fpr;     /* index into the array of 8 FPRs
3569   //                 * stored in the register save area
3570   //                 * fpr=0 corresponds to f1,
3571   //                 * fpr=1 to f2, etc.
3572   //                 */
3573   //  char *overflow_arg_area;
3574   //                /* location on stack that holds
3575   //                 * the next overflow argument
3576   //                 */
3577   //  char *reg_save_area;
3578   //               /* where r3:r10 and f1:f8 (if saved)
3579   //                * are stored
3580   //                */
3581   // } va_list[1];
3582 
3583   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3584   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3585   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3586                                             PtrVT);
3587   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3588                                  PtrVT);
3589 
3590   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3591   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3592 
3593   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3594   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3595 
3596   uint64_t FPROffset = 1;
3597   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3598 
3599   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3600 
3601   // Store first byte : number of int regs
3602   SDValue firstStore =
3603       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3604                         MachinePointerInfo(SV), MVT::i8);
3605   uint64_t nextOffset = FPROffset;
3606   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3607                                   ConstFPROffset);
3608 
3609   // Store second byte : number of float regs
3610   SDValue secondStore =
3611       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3612                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3613   nextOffset += StackOffset;
3614   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3615 
3616   // Store second word : arguments given on stack
3617   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3618                                     MachinePointerInfo(SV, nextOffset));
3619   nextOffset += FrameOffset;
3620   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3621 
3622   // Store third word : arguments given in registers
3623   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3624                       MachinePointerInfo(SV, nextOffset));
3625 }
3626 
3627 /// FPR - The set of FP registers that should be allocated for arguments
3628 /// on Darwin and AIX.
3629 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3630                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3631                                 PPC::F11, PPC::F12, PPC::F13};
3632 
3633 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3634 /// the stack.
3635 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3636                                        unsigned PtrByteSize) {
3637   unsigned ArgSize = ArgVT.getStoreSize();
3638   if (Flags.isByVal())
3639     ArgSize = Flags.getByValSize();
3640 
3641   // Round up to multiples of the pointer size, except for array members,
3642   // which are always packed.
3643   if (!Flags.isInConsecutiveRegs())
3644     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3645 
3646   return ArgSize;
3647 }
3648 
3649 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3650 /// on the stack.
3651 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3652                                          ISD::ArgFlagsTy Flags,
3653                                          unsigned PtrByteSize) {
3654   Align Alignment(PtrByteSize);
3655 
3656   // Altivec parameters are padded to a 16 byte boundary.
3657   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3658       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3659       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3660       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3661     Alignment = Align(16);
3662 
3663   // ByVal parameters are aligned as requested.
3664   if (Flags.isByVal()) {
3665     auto BVAlign = Flags.getNonZeroByValAlign();
3666     if (BVAlign > PtrByteSize) {
3667       if (BVAlign.value() % PtrByteSize != 0)
3668         llvm_unreachable(
3669             "ByVal alignment is not a multiple of the pointer size");
3670 
3671       Alignment = BVAlign;
3672     }
3673   }
3674 
3675   // Array members are always packed to their original alignment.
3676   if (Flags.isInConsecutiveRegs()) {
3677     // If the array member was split into multiple registers, the first
3678     // needs to be aligned to the size of the full type.  (Except for
3679     // ppcf128, which is only aligned as its f64 components.)
3680     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3681       Alignment = Align(OrigVT.getStoreSize());
3682     else
3683       Alignment = Align(ArgVT.getStoreSize());
3684   }
3685 
3686   return Alignment;
3687 }
3688 
3689 /// CalculateStackSlotUsed - Return whether this argument will use its
3690 /// stack slot (instead of being passed in registers).  ArgOffset,
3691 /// AvailableFPRs, and AvailableVRs must hold the current argument
3692 /// position, and will be updated to account for this argument.
3693 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3694                                    unsigned PtrByteSize, unsigned LinkageSize,
3695                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3696                                    unsigned &AvailableFPRs,
3697                                    unsigned &AvailableVRs) {
3698   bool UseMemory = false;
3699 
3700   // Respect alignment of argument on the stack.
3701   Align Alignment =
3702       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3703   ArgOffset = alignTo(ArgOffset, Alignment);
3704   // If there's no space left in the argument save area, we must
3705   // use memory (this check also catches zero-sized arguments).
3706   if (ArgOffset >= LinkageSize + ParamAreaSize)
3707     UseMemory = true;
3708 
3709   // Allocate argument on the stack.
3710   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3711   if (Flags.isInConsecutiveRegsLast())
3712     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3713   // If we overran the argument save area, we must use memory
3714   // (this check catches arguments passed partially in memory)
3715   if (ArgOffset > LinkageSize + ParamAreaSize)
3716     UseMemory = true;
3717 
3718   // However, if the argument is actually passed in an FPR or a VR,
3719   // we don't use memory after all.
3720   if (!Flags.isByVal()) {
3721     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3722       if (AvailableFPRs > 0) {
3723         --AvailableFPRs;
3724         return false;
3725       }
3726     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3727         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3728         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3729         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3730       if (AvailableVRs > 0) {
3731         --AvailableVRs;
3732         return false;
3733       }
3734   }
3735 
3736   return UseMemory;
3737 }
3738 
3739 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3740 /// ensure minimum alignment required for target.
3741 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3742                                      unsigned NumBytes) {
3743   return alignTo(NumBytes, Lowering->getStackAlign());
3744 }
3745 
3746 SDValue PPCTargetLowering::LowerFormalArguments(
3747     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3748     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3749     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3750   if (Subtarget.isAIXABI())
3751     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3752                                     InVals);
3753   if (Subtarget.is64BitELFABI())
3754     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3755                                        InVals);
3756   assert(Subtarget.is32BitELFABI());
3757   return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3758                                      InVals);
3759 }
3760 
3761 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3762     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3763     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3764     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3765 
3766   // 32-bit SVR4 ABI Stack Frame Layout:
3767   //              +-----------------------------------+
3768   //        +-->  |            Back chain             |
3769   //        |     +-----------------------------------+
3770   //        |     | Floating-point register save area |
3771   //        |     +-----------------------------------+
3772   //        |     |    General register save area     |
3773   //        |     +-----------------------------------+
3774   //        |     |          CR save word             |
3775   //        |     +-----------------------------------+
3776   //        |     |         VRSAVE save word          |
3777   //        |     +-----------------------------------+
3778   //        |     |         Alignment padding         |
3779   //        |     +-----------------------------------+
3780   //        |     |     Vector register save area     |
3781   //        |     +-----------------------------------+
3782   //        |     |       Local variable space        |
3783   //        |     +-----------------------------------+
3784   //        |     |        Parameter list area        |
3785   //        |     +-----------------------------------+
3786   //        |     |           LR save word            |
3787   //        |     +-----------------------------------+
3788   // SP-->  +---  |            Back chain             |
3789   //              +-----------------------------------+
3790   //
3791   // Specifications:
3792   //   System V Application Binary Interface PowerPC Processor Supplement
3793   //   AltiVec Technology Programming Interface Manual
3794 
3795   MachineFunction &MF = DAG.getMachineFunction();
3796   MachineFrameInfo &MFI = MF.getFrameInfo();
3797   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3798 
3799   EVT PtrVT = getPointerTy(MF.getDataLayout());
3800   // Potential tail calls could cause overwriting of argument stack slots.
3801   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3802                        (CallConv == CallingConv::Fast));
3803   const Align PtrAlign(4);
3804 
3805   // Assign locations to all of the incoming arguments.
3806   SmallVector<CCValAssign, 16> ArgLocs;
3807   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3808                  *DAG.getContext());
3809 
3810   // Reserve space for the linkage area on the stack.
3811   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3812   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3813   if (useSoftFloat())
3814     CCInfo.PreAnalyzeFormalArguments(Ins);
3815 
3816   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3817   CCInfo.clearWasPPCF128();
3818 
3819   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3820     CCValAssign &VA = ArgLocs[i];
3821 
3822     // Arguments stored in registers.
3823     if (VA.isRegLoc()) {
3824       const TargetRegisterClass *RC;
3825       EVT ValVT = VA.getValVT();
3826 
3827       switch (ValVT.getSimpleVT().SimpleTy) {
3828         default:
3829           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3830         case MVT::i1:
3831         case MVT::i32:
3832           RC = &PPC::GPRCRegClass;
3833           break;
3834         case MVT::f32:
3835           if (Subtarget.hasP8Vector())
3836             RC = &PPC::VSSRCRegClass;
3837           else if (Subtarget.hasSPE())
3838             RC = &PPC::GPRCRegClass;
3839           else
3840             RC = &PPC::F4RCRegClass;
3841           break;
3842         case MVT::f64:
3843           if (Subtarget.hasVSX())
3844             RC = &PPC::VSFRCRegClass;
3845           else if (Subtarget.hasSPE())
3846             // SPE passes doubles in GPR pairs.
3847             RC = &PPC::GPRCRegClass;
3848           else
3849             RC = &PPC::F8RCRegClass;
3850           break;
3851         case MVT::v16i8:
3852         case MVT::v8i16:
3853         case MVT::v4i32:
3854           RC = &PPC::VRRCRegClass;
3855           break;
3856         case MVT::v4f32:
3857           RC = &PPC::VRRCRegClass;
3858           break;
3859         case MVT::v2f64:
3860         case MVT::v2i64:
3861           RC = &PPC::VRRCRegClass;
3862           break;
3863       }
3864 
3865       SDValue ArgValue;
3866       // Transform the arguments stored in physical registers into
3867       // virtual ones.
3868       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3869         assert(i + 1 < e && "No second half of double precision argument");
3870         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3871         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3872         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3873         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3874         if (!Subtarget.isLittleEndian())
3875           std::swap (ArgValueLo, ArgValueHi);
3876         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3877                                ArgValueHi);
3878       } else {
3879         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3880         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3881                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3882         if (ValVT == MVT::i1)
3883           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3884       }
3885 
3886       InVals.push_back(ArgValue);
3887     } else {
3888       // Argument stored in memory.
3889       assert(VA.isMemLoc());
3890 
3891       // Get the extended size of the argument type in stack
3892       unsigned ArgSize = VA.getLocVT().getStoreSize();
3893       // Get the actual size of the argument type
3894       unsigned ObjSize = VA.getValVT().getStoreSize();
3895       unsigned ArgOffset = VA.getLocMemOffset();
3896       // Stack objects in PPC32 are right justified.
3897       ArgOffset += ArgSize - ObjSize;
3898       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3899 
3900       // Create load nodes to retrieve arguments from the stack.
3901       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3902       InVals.push_back(
3903           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3904     }
3905   }
3906 
3907   // Assign locations to all of the incoming aggregate by value arguments.
3908   // Aggregates passed by value are stored in the local variable space of the
3909   // caller's stack frame, right above the parameter list area.
3910   SmallVector<CCValAssign, 16> ByValArgLocs;
3911   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3912                       ByValArgLocs, *DAG.getContext());
3913 
3914   // Reserve stack space for the allocations in CCInfo.
3915   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
3916 
3917   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3918 
3919   // Area that is at least reserved in the caller of this function.
3920   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3921   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3922 
3923   // Set the size that is at least reserved in caller of this function.  Tail
3924   // call optimized function's reserved stack space needs to be aligned so that
3925   // taking the difference between two stack areas will result in an aligned
3926   // stack.
3927   MinReservedArea =
3928       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3929   FuncInfo->setMinReservedArea(MinReservedArea);
3930 
3931   SmallVector<SDValue, 8> MemOps;
3932 
3933   // If the function takes variable number of arguments, make a frame index for
3934   // the start of the first vararg value... for expansion of llvm.va_start.
3935   if (isVarArg) {
3936     static const MCPhysReg GPArgRegs[] = {
3937       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3938       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3939     };
3940     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3941 
3942     static const MCPhysReg FPArgRegs[] = {
3943       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3944       PPC::F8
3945     };
3946     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3947 
3948     if (useSoftFloat() || hasSPE())
3949        NumFPArgRegs = 0;
3950 
3951     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3952     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3953 
3954     // Make room for NumGPArgRegs and NumFPArgRegs.
3955     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3956                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3957 
3958     FuncInfo->setVarArgsStackOffset(
3959       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3960                             CCInfo.getNextStackOffset(), true));
3961 
3962     FuncInfo->setVarArgsFrameIndex(
3963         MFI.CreateStackObject(Depth, Align(8), false));
3964     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3965 
3966     // The fixed integer arguments of a variadic function are stored to the
3967     // VarArgsFrameIndex on the stack so that they may be loaded by
3968     // dereferencing the result of va_next.
3969     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3970       // Get an existing live-in vreg, or add a new one.
3971       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3972       if (!VReg)
3973         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3974 
3975       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3976       SDValue Store =
3977           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3978       MemOps.push_back(Store);
3979       // Increment the address by four for the next argument to store
3980       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3981       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3982     }
3983 
3984     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3985     // is set.
3986     // The double arguments are stored to the VarArgsFrameIndex
3987     // on the stack.
3988     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3989       // Get an existing live-in vreg, or add a new one.
3990       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3991       if (!VReg)
3992         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3993 
3994       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3995       SDValue Store =
3996           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3997       MemOps.push_back(Store);
3998       // Increment the address by eight for the next argument to store
3999       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
4000                                          PtrVT);
4001       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4002     }
4003   }
4004 
4005   if (!MemOps.empty())
4006     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4007 
4008   return Chain;
4009 }
4010 
4011 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4012 // value to MVT::i64 and then truncate to the correct register size.
4013 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
4014                                              EVT ObjectVT, SelectionDAG &DAG,
4015                                              SDValue ArgVal,
4016                                              const SDLoc &dl) const {
4017   if (Flags.isSExt())
4018     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
4019                          DAG.getValueType(ObjectVT));
4020   else if (Flags.isZExt())
4021     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
4022                          DAG.getValueType(ObjectVT));
4023 
4024   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
4025 }
4026 
4027 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
4028     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4029     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4030     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4031   // TODO: add description of PPC stack frame format, or at least some docs.
4032   //
4033   bool isELFv2ABI = Subtarget.isELFv2ABI();
4034   bool isLittleEndian = Subtarget.isLittleEndian();
4035   MachineFunction &MF = DAG.getMachineFunction();
4036   MachineFrameInfo &MFI = MF.getFrameInfo();
4037   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4038 
4039   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4040          "fastcc not supported on varargs functions");
4041 
4042   EVT PtrVT = getPointerTy(MF.getDataLayout());
4043   // Potential tail calls could cause overwriting of argument stack slots.
4044   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4045                        (CallConv == CallingConv::Fast));
4046   unsigned PtrByteSize = 8;
4047   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4048 
4049   static const MCPhysReg GPR[] = {
4050     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4051     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4052   };
4053   static const MCPhysReg VR[] = {
4054     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4055     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4056   };
4057 
4058   const unsigned Num_GPR_Regs = array_lengthof(GPR);
4059   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4060   const unsigned Num_VR_Regs  = array_lengthof(VR);
4061 
4062   // Do a first pass over the arguments to determine whether the ABI
4063   // guarantees that our caller has allocated the parameter save area
4064   // on its stack frame.  In the ELFv1 ABI, this is always the case;
4065   // in the ELFv2 ABI, it is true if this is a vararg function or if
4066   // any parameter is located in a stack slot.
4067 
4068   bool HasParameterArea = !isELFv2ABI || isVarArg;
4069   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4070   unsigned NumBytes = LinkageSize;
4071   unsigned AvailableFPRs = Num_FPR_Regs;
4072   unsigned AvailableVRs = Num_VR_Regs;
4073   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4074     if (Ins[i].Flags.isNest())
4075       continue;
4076 
4077     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
4078                                PtrByteSize, LinkageSize, ParamAreaSize,
4079                                NumBytes, AvailableFPRs, AvailableVRs))
4080       HasParameterArea = true;
4081   }
4082 
4083   // Add DAG nodes to load the arguments or copy them out of registers.  On
4084   // entry to a function on PPC, the arguments start after the linkage area,
4085   // although the first ones are often in registers.
4086 
4087   unsigned ArgOffset = LinkageSize;
4088   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4089   SmallVector<SDValue, 8> MemOps;
4090   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4091   unsigned CurArgIdx = 0;
4092   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4093     SDValue ArgVal;
4094     bool needsLoad = false;
4095     EVT ObjectVT = Ins[ArgNo].VT;
4096     EVT OrigVT = Ins[ArgNo].ArgVT;
4097     unsigned ObjSize = ObjectVT.getStoreSize();
4098     unsigned ArgSize = ObjSize;
4099     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4100     if (Ins[ArgNo].isOrigArg()) {
4101       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4102       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4103     }
4104     // We re-align the argument offset for each argument, except when using the
4105     // fast calling convention, when we need to make sure we do that only when
4106     // we'll actually use a stack slot.
4107     unsigned CurArgOffset;
4108     Align Alignment;
4109     auto ComputeArgOffset = [&]() {
4110       /* Respect alignment of argument on the stack.  */
4111       Alignment =
4112           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4113       ArgOffset = alignTo(ArgOffset, Alignment);
4114       CurArgOffset = ArgOffset;
4115     };
4116 
4117     if (CallConv != CallingConv::Fast) {
4118       ComputeArgOffset();
4119 
4120       /* Compute GPR index associated with argument offset.  */
4121       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4122       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4123     }
4124 
4125     // FIXME the codegen can be much improved in some cases.
4126     // We do not have to keep everything in memory.
4127     if (Flags.isByVal()) {
4128       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4129 
4130       if (CallConv == CallingConv::Fast)
4131         ComputeArgOffset();
4132 
4133       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4134       ObjSize = Flags.getByValSize();
4135       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4136       // Empty aggregate parameters do not take up registers.  Examples:
4137       //   struct { } a;
4138       //   union  { } b;
4139       //   int c[0];
4140       // etc.  However, we have to provide a place-holder in InVals, so
4141       // pretend we have an 8-byte item at the current address for that
4142       // purpose.
4143       if (!ObjSize) {
4144         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4145         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4146         InVals.push_back(FIN);
4147         continue;
4148       }
4149 
4150       // Create a stack object covering all stack doublewords occupied
4151       // by the argument.  If the argument is (fully or partially) on
4152       // the stack, or if the argument is fully in registers but the
4153       // caller has allocated the parameter save anyway, we can refer
4154       // directly to the caller's stack frame.  Otherwise, create a
4155       // local copy in our own frame.
4156       int FI;
4157       if (HasParameterArea ||
4158           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4159         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4160       else
4161         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4162       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4163 
4164       // Handle aggregates smaller than 8 bytes.
4165       if (ObjSize < PtrByteSize) {
4166         // The value of the object is its address, which differs from the
4167         // address of the enclosing doubleword on big-endian systems.
4168         SDValue Arg = FIN;
4169         if (!isLittleEndian) {
4170           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4171           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4172         }
4173         InVals.push_back(Arg);
4174 
4175         if (GPR_idx != Num_GPR_Regs) {
4176           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4177           FuncInfo->addLiveInAttr(VReg, Flags);
4178           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4179           SDValue Store;
4180 
4181           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
4182             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
4183                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
4184             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4185                                       MachinePointerInfo(&*FuncArg), ObjType);
4186           } else {
4187             // For sizes that don't fit a truncating store (3, 5, 6, 7),
4188             // store the whole register as-is to the parameter save area
4189             // slot.
4190             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4191                                  MachinePointerInfo(&*FuncArg));
4192           }
4193 
4194           MemOps.push_back(Store);
4195         }
4196         // Whether we copied from a register or not, advance the offset
4197         // into the parameter save area by a full doubleword.
4198         ArgOffset += PtrByteSize;
4199         continue;
4200       }
4201 
4202       // The value of the object is its address, which is the address of
4203       // its first stack doubleword.
4204       InVals.push_back(FIN);
4205 
4206       // Store whatever pieces of the object are in registers to memory.
4207       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4208         if (GPR_idx == Num_GPR_Regs)
4209           break;
4210 
4211         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4212         FuncInfo->addLiveInAttr(VReg, Flags);
4213         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4214         SDValue Addr = FIN;
4215         if (j) {
4216           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4217           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4218         }
4219         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4220                                      MachinePointerInfo(&*FuncArg, j));
4221         MemOps.push_back(Store);
4222         ++GPR_idx;
4223       }
4224       ArgOffset += ArgSize;
4225       continue;
4226     }
4227 
4228     switch (ObjectVT.getSimpleVT().SimpleTy) {
4229     default: llvm_unreachable("Unhandled argument type!");
4230     case MVT::i1:
4231     case MVT::i32:
4232     case MVT::i64:
4233       if (Flags.isNest()) {
4234         // The 'nest' parameter, if any, is passed in R11.
4235         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4236         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4237 
4238         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4239           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4240 
4241         break;
4242       }
4243 
4244       // These can be scalar arguments or elements of an integer array type
4245       // passed directly.  Clang may use those instead of "byval" aggregate
4246       // types to avoid forcing arguments to memory unnecessarily.
4247       if (GPR_idx != Num_GPR_Regs) {
4248         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4249         FuncInfo->addLiveInAttr(VReg, Flags);
4250         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4251 
4252         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4253           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4254           // value to MVT::i64 and then truncate to the correct register size.
4255           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4256       } else {
4257         if (CallConv == CallingConv::Fast)
4258           ComputeArgOffset();
4259 
4260         needsLoad = true;
4261         ArgSize = PtrByteSize;
4262       }
4263       if (CallConv != CallingConv::Fast || needsLoad)
4264         ArgOffset += 8;
4265       break;
4266 
4267     case MVT::f32:
4268     case MVT::f64:
4269       // These can be scalar arguments or elements of a float array type
4270       // passed directly.  The latter are used to implement ELFv2 homogenous
4271       // float aggregates.
4272       if (FPR_idx != Num_FPR_Regs) {
4273         unsigned VReg;
4274 
4275         if (ObjectVT == MVT::f32)
4276           VReg = MF.addLiveIn(FPR[FPR_idx],
4277                               Subtarget.hasP8Vector()
4278                                   ? &PPC::VSSRCRegClass
4279                                   : &PPC::F4RCRegClass);
4280         else
4281           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4282                                                 ? &PPC::VSFRCRegClass
4283                                                 : &PPC::F8RCRegClass);
4284 
4285         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4286         ++FPR_idx;
4287       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4288         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4289         // once we support fp <-> gpr moves.
4290 
4291         // This can only ever happen in the presence of f32 array types,
4292         // since otherwise we never run out of FPRs before running out
4293         // of GPRs.
4294         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4295         FuncInfo->addLiveInAttr(VReg, Flags);
4296         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4297 
4298         if (ObjectVT == MVT::f32) {
4299           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4300             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4301                                  DAG.getConstant(32, dl, MVT::i32));
4302           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4303         }
4304 
4305         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4306       } else {
4307         if (CallConv == CallingConv::Fast)
4308           ComputeArgOffset();
4309 
4310         needsLoad = true;
4311       }
4312 
4313       // When passing an array of floats, the array occupies consecutive
4314       // space in the argument area; only round up to the next doubleword
4315       // at the end of the array.  Otherwise, each float takes 8 bytes.
4316       if (CallConv != CallingConv::Fast || needsLoad) {
4317         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4318         ArgOffset += ArgSize;
4319         if (Flags.isInConsecutiveRegsLast())
4320           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4321       }
4322       break;
4323     case MVT::v4f32:
4324     case MVT::v4i32:
4325     case MVT::v8i16:
4326     case MVT::v16i8:
4327     case MVT::v2f64:
4328     case MVT::v2i64:
4329     case MVT::v1i128:
4330     case MVT::f128:
4331       // These can be scalar arguments or elements of a vector array type
4332       // passed directly.  The latter are used to implement ELFv2 homogenous
4333       // vector aggregates.
4334       if (VR_idx != Num_VR_Regs) {
4335         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4336         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4337         ++VR_idx;
4338       } else {
4339         if (CallConv == CallingConv::Fast)
4340           ComputeArgOffset();
4341         needsLoad = true;
4342       }
4343       if (CallConv != CallingConv::Fast || needsLoad)
4344         ArgOffset += 16;
4345       break;
4346     }
4347 
4348     // We need to load the argument to a virtual register if we determined
4349     // above that we ran out of physical registers of the appropriate type.
4350     if (needsLoad) {
4351       if (ObjSize < ArgSize && !isLittleEndian)
4352         CurArgOffset += ArgSize - ObjSize;
4353       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4354       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4355       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4356     }
4357 
4358     InVals.push_back(ArgVal);
4359   }
4360 
4361   // Area that is at least reserved in the caller of this function.
4362   unsigned MinReservedArea;
4363   if (HasParameterArea)
4364     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4365   else
4366     MinReservedArea = LinkageSize;
4367 
4368   // Set the size that is at least reserved in caller of this function.  Tail
4369   // call optimized functions' reserved stack space needs to be aligned so that
4370   // taking the difference between two stack areas will result in an aligned
4371   // stack.
4372   MinReservedArea =
4373       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4374   FuncInfo->setMinReservedArea(MinReservedArea);
4375 
4376   // If the function takes variable number of arguments, make a frame index for
4377   // the start of the first vararg value... for expansion of llvm.va_start.
4378   // On ELFv2ABI spec, it writes:
4379   // C programs that are intended to be *portable* across different compilers
4380   // and architectures must use the header file <stdarg.h> to deal with variable
4381   // argument lists.
4382   if (isVarArg && MFI.hasVAStart()) {
4383     int Depth = ArgOffset;
4384 
4385     FuncInfo->setVarArgsFrameIndex(
4386       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4387     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4388 
4389     // If this function is vararg, store any remaining integer argument regs
4390     // to their spots on the stack so that they may be loaded by dereferencing
4391     // the result of va_next.
4392     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4393          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4394       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4395       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4396       SDValue Store =
4397           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4398       MemOps.push_back(Store);
4399       // Increment the address by four for the next argument to store
4400       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4401       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4402     }
4403   }
4404 
4405   if (!MemOps.empty())
4406     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4407 
4408   return Chain;
4409 }
4410 
4411 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4412 /// adjusted to accommodate the arguments for the tailcall.
4413 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4414                                    unsigned ParamSize) {
4415 
4416   if (!isTailCall) return 0;
4417 
4418   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4419   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4420   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4421   // Remember only if the new adjustment is bigger.
4422   if (SPDiff < FI->getTailCallSPDelta())
4423     FI->setTailCallSPDelta(SPDiff);
4424 
4425   return SPDiff;
4426 }
4427 
4428 static bool isFunctionGlobalAddress(SDValue Callee);
4429 
4430 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4431                               const TargetMachine &TM) {
4432   // It does not make sense to call callsShareTOCBase() with a caller that
4433   // is PC Relative since PC Relative callers do not have a TOC.
4434 #ifndef NDEBUG
4435   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4436   assert(!STICaller->isUsingPCRelativeCalls() &&
4437          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4438 #endif
4439 
4440   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4441   // don't have enough information to determine if the caller and callee share
4442   // the same  TOC base, so we have to pessimistically assume they don't for
4443   // correctness.
4444   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4445   if (!G)
4446     return false;
4447 
4448   const GlobalValue *GV = G->getGlobal();
4449 
4450   // If the callee is preemptable, then the static linker will use a plt-stub
4451   // which saves the toc to the stack, and needs a nop after the call
4452   // instruction to convert to a toc-restore.
4453   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4454     return false;
4455 
4456   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4457   // We may need a TOC restore in the situation where the caller requires a
4458   // valid TOC but the callee is PC Relative and does not.
4459   const Function *F = dyn_cast<Function>(GV);
4460   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4461 
4462   // If we have an Alias we can try to get the function from there.
4463   if (Alias) {
4464     const GlobalObject *GlobalObj = Alias->getBaseObject();
4465     F = dyn_cast<Function>(GlobalObj);
4466   }
4467 
4468   // If we still have no valid function pointer we do not have enough
4469   // information to determine if the callee uses PC Relative calls so we must
4470   // assume that it does.
4471   if (!F)
4472     return false;
4473 
4474   // If the callee uses PC Relative we cannot guarantee that the callee won't
4475   // clobber the TOC of the caller and so we must assume that the two
4476   // functions do not share a TOC base.
4477   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4478   if (STICallee->isUsingPCRelativeCalls())
4479     return false;
4480 
4481   // If the GV is not a strong definition then we need to assume it can be
4482   // replaced by another function at link time. The function that replaces
4483   // it may not share the same TOC as the caller since the callee may be
4484   // replaced by a PC Relative version of the same function.
4485   if (!GV->isStrongDefinitionForLinker())
4486     return false;
4487 
4488   // The medium and large code models are expected to provide a sufficiently
4489   // large TOC to provide all data addressing needs of a module with a
4490   // single TOC.
4491   if (CodeModel::Medium == TM.getCodeModel() ||
4492       CodeModel::Large == TM.getCodeModel())
4493     return true;
4494 
4495   // Any explicitly-specified sections and section prefixes must also match.
4496   // Also, if we're using -ffunction-sections, then each function is always in
4497   // a different section (the same is true for COMDAT functions).
4498   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4499       GV->getSection() != Caller->getSection())
4500     return false;
4501   if (const auto *F = dyn_cast<Function>(GV)) {
4502     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4503       return false;
4504   }
4505 
4506   return true;
4507 }
4508 
4509 static bool
4510 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4511                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4512   assert(Subtarget.is64BitELFABI());
4513 
4514   const unsigned PtrByteSize = 8;
4515   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4516 
4517   static const MCPhysReg GPR[] = {
4518     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4519     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4520   };
4521   static const MCPhysReg VR[] = {
4522     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4523     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4524   };
4525 
4526   const unsigned NumGPRs = array_lengthof(GPR);
4527   const unsigned NumFPRs = 13;
4528   const unsigned NumVRs = array_lengthof(VR);
4529   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4530 
4531   unsigned NumBytes = LinkageSize;
4532   unsigned AvailableFPRs = NumFPRs;
4533   unsigned AvailableVRs = NumVRs;
4534 
4535   for (const ISD::OutputArg& Param : Outs) {
4536     if (Param.Flags.isNest()) continue;
4537 
4538     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4539                                LinkageSize, ParamAreaSize, NumBytes,
4540                                AvailableFPRs, AvailableVRs))
4541       return true;
4542   }
4543   return false;
4544 }
4545 
4546 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4547   if (CB.arg_size() != CallerFn->arg_size())
4548     return false;
4549 
4550   auto CalleeArgIter = CB.arg_begin();
4551   auto CalleeArgEnd = CB.arg_end();
4552   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4553 
4554   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4555     const Value* CalleeArg = *CalleeArgIter;
4556     const Value* CallerArg = &(*CallerArgIter);
4557     if (CalleeArg == CallerArg)
4558       continue;
4559 
4560     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4561     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4562     //      }
4563     // 1st argument of callee is undef and has the same type as caller.
4564     if (CalleeArg->getType() == CallerArg->getType() &&
4565         isa<UndefValue>(CalleeArg))
4566       continue;
4567 
4568     return false;
4569   }
4570 
4571   return true;
4572 }
4573 
4574 // Returns true if TCO is possible between the callers and callees
4575 // calling conventions.
4576 static bool
4577 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4578                                     CallingConv::ID CalleeCC) {
4579   // Tail calls are possible with fastcc and ccc.
4580   auto isTailCallableCC  = [] (CallingConv::ID CC){
4581       return  CC == CallingConv::C || CC == CallingConv::Fast;
4582   };
4583   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4584     return false;
4585 
4586   // We can safely tail call both fastcc and ccc callees from a c calling
4587   // convention caller. If the caller is fastcc, we may have less stack space
4588   // than a non-fastcc caller with the same signature so disable tail-calls in
4589   // that case.
4590   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4591 }
4592 
4593 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4594     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4595     const SmallVectorImpl<ISD::OutputArg> &Outs,
4596     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4597   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4598 
4599   if (DisableSCO && !TailCallOpt) return false;
4600 
4601   // Variadic argument functions are not supported.
4602   if (isVarArg) return false;
4603 
4604   auto &Caller = DAG.getMachineFunction().getFunction();
4605   // Check that the calling conventions are compatible for tco.
4606   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4607     return false;
4608 
4609   // Caller contains any byval parameter is not supported.
4610   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4611     return false;
4612 
4613   // Callee contains any byval parameter is not supported, too.
4614   // Note: This is a quick work around, because in some cases, e.g.
4615   // caller's stack size > callee's stack size, we are still able to apply
4616   // sibling call optimization. For example, gcc is able to do SCO for caller1
4617   // in the following example, but not for caller2.
4618   //   struct test {
4619   //     long int a;
4620   //     char ary[56];
4621   //   } gTest;
4622   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4623   //     b->a = v.a;
4624   //     return 0;
4625   //   }
4626   //   void caller1(struct test a, struct test c, struct test *b) {
4627   //     callee(gTest, b); }
4628   //   void caller2(struct test *b) { callee(gTest, b); }
4629   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4630     return false;
4631 
4632   // If callee and caller use different calling conventions, we cannot pass
4633   // parameters on stack since offsets for the parameter area may be different.
4634   if (Caller.getCallingConv() != CalleeCC &&
4635       needStackSlotPassParameters(Subtarget, Outs))
4636     return false;
4637 
4638   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4639   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4640   // callee potentially have different TOC bases then we cannot tail call since
4641   // we need to restore the TOC pointer after the call.
4642   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4643   // We cannot guarantee this for indirect calls or calls to external functions.
4644   // When PC-Relative addressing is used, the concept of the TOC is no longer
4645   // applicable so this check is not required.
4646   // Check first for indirect calls.
4647   if (!Subtarget.isUsingPCRelativeCalls() &&
4648       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4649     return false;
4650 
4651   // Check if we share the TOC base.
4652   if (!Subtarget.isUsingPCRelativeCalls() &&
4653       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4654     return false;
4655 
4656   // TCO allows altering callee ABI, so we don't have to check further.
4657   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4658     return true;
4659 
4660   if (DisableSCO) return false;
4661 
4662   // If callee use the same argument list that caller is using, then we can
4663   // apply SCO on this case. If it is not, then we need to check if callee needs
4664   // stack for passing arguments.
4665   // PC Relative tail calls may not have a CallBase.
4666   // If there is no CallBase we cannot verify if we have the same argument
4667   // list so assume that we don't have the same argument list.
4668   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4669       needStackSlotPassParameters(Subtarget, Outs))
4670     return false;
4671   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4672     return false;
4673 
4674   return true;
4675 }
4676 
4677 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4678 /// for tail call optimization. Targets which want to do tail call
4679 /// optimization should implement this function.
4680 bool
4681 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4682                                                      CallingConv::ID CalleeCC,
4683                                                      bool isVarArg,
4684                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4685                                                      SelectionDAG& DAG) const {
4686   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4687     return false;
4688 
4689   // Variable argument functions are not supported.
4690   if (isVarArg)
4691     return false;
4692 
4693   MachineFunction &MF = DAG.getMachineFunction();
4694   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4695   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4696     // Functions containing by val parameters are not supported.
4697     for (unsigned i = 0; i != Ins.size(); i++) {
4698        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4699        if (Flags.isByVal()) return false;
4700     }
4701 
4702     // Non-PIC/GOT tail calls are supported.
4703     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4704       return true;
4705 
4706     // At the moment we can only do local tail calls (in same module, hidden
4707     // or protected) if we are generating PIC.
4708     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4709       return G->getGlobal()->hasHiddenVisibility()
4710           || G->getGlobal()->hasProtectedVisibility();
4711   }
4712 
4713   return false;
4714 }
4715 
4716 /// isCallCompatibleAddress - Return the immediate to use if the specified
4717 /// 32-bit value is representable in the immediate field of a BxA instruction.
4718 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4719   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4720   if (!C) return nullptr;
4721 
4722   int Addr = C->getZExtValue();
4723   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4724       SignExtend32<26>(Addr) != Addr)
4725     return nullptr;  // Top 6 bits have to be sext of immediate.
4726 
4727   return DAG
4728       .getConstant(
4729           (int)C->getZExtValue() >> 2, SDLoc(Op),
4730           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4731       .getNode();
4732 }
4733 
4734 namespace {
4735 
4736 struct TailCallArgumentInfo {
4737   SDValue Arg;
4738   SDValue FrameIdxOp;
4739   int FrameIdx = 0;
4740 
4741   TailCallArgumentInfo() = default;
4742 };
4743 
4744 } // end anonymous namespace
4745 
4746 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4747 static void StoreTailCallArgumentsToStackSlot(
4748     SelectionDAG &DAG, SDValue Chain,
4749     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4750     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4751   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4752     SDValue Arg = TailCallArgs[i].Arg;
4753     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4754     int FI = TailCallArgs[i].FrameIdx;
4755     // Store relative to framepointer.
4756     MemOpChains.push_back(DAG.getStore(
4757         Chain, dl, Arg, FIN,
4758         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4759   }
4760 }
4761 
4762 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4763 /// the appropriate stack slot for the tail call optimized function call.
4764 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4765                                              SDValue OldRetAddr, SDValue OldFP,
4766                                              int SPDiff, const SDLoc &dl) {
4767   if (SPDiff) {
4768     // Calculate the new stack slot for the return address.
4769     MachineFunction &MF = DAG.getMachineFunction();
4770     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4771     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4772     bool isPPC64 = Subtarget.isPPC64();
4773     int SlotSize = isPPC64 ? 8 : 4;
4774     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4775     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4776                                                          NewRetAddrLoc, true);
4777     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4778     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4779     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4780                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4781   }
4782   return Chain;
4783 }
4784 
4785 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4786 /// the position of the argument.
4787 static void
4788 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4789                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4790                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4791   int Offset = ArgOffset + SPDiff;
4792   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4793   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4794   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4795   SDValue FIN = DAG.getFrameIndex(FI, VT);
4796   TailCallArgumentInfo Info;
4797   Info.Arg = Arg;
4798   Info.FrameIdxOp = FIN;
4799   Info.FrameIdx = FI;
4800   TailCallArguments.push_back(Info);
4801 }
4802 
4803 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4804 /// stack slot. Returns the chain as result and the loaded frame pointers in
4805 /// LROpOut/FPOpout. Used when tail calling.
4806 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4807     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4808     SDValue &FPOpOut, const SDLoc &dl) const {
4809   if (SPDiff) {
4810     // Load the LR and FP stack slot for later adjusting.
4811     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4812     LROpOut = getReturnAddrFrameIndex(DAG);
4813     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4814     Chain = SDValue(LROpOut.getNode(), 1);
4815   }
4816   return Chain;
4817 }
4818 
4819 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4820 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4821 /// specified by the specific parameter attribute. The copy will be passed as
4822 /// a byval function parameter.
4823 /// Sometimes what we are copying is the end of a larger object, the part that
4824 /// does not fit in registers.
4825 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4826                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4827                                          SelectionDAG &DAG, const SDLoc &dl) {
4828   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4829   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
4830                        Flags.getNonZeroByValAlign(), false, false, false,
4831                        MachinePointerInfo(), MachinePointerInfo());
4832 }
4833 
4834 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4835 /// tail calls.
4836 static void LowerMemOpCallTo(
4837     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4838     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4839     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4840     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4841   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4842   if (!isTailCall) {
4843     if (isVector) {
4844       SDValue StackPtr;
4845       if (isPPC64)
4846         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4847       else
4848         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4849       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4850                            DAG.getConstant(ArgOffset, dl, PtrVT));
4851     }
4852     MemOpChains.push_back(
4853         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4854     // Calculate and remember argument location.
4855   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4856                                   TailCallArguments);
4857 }
4858 
4859 static void
4860 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4861                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4862                 SDValue FPOp,
4863                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4864   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4865   // might overwrite each other in case of tail call optimization.
4866   SmallVector<SDValue, 8> MemOpChains2;
4867   // Do not flag preceding copytoreg stuff together with the following stuff.
4868   InFlag = SDValue();
4869   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4870                                     MemOpChains2, dl);
4871   if (!MemOpChains2.empty())
4872     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4873 
4874   // Store the return address to the appropriate stack slot.
4875   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4876 
4877   // Emit callseq_end just before tailcall node.
4878   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4879                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4880   InFlag = Chain.getValue(1);
4881 }
4882 
4883 // Is this global address that of a function that can be called by name? (as
4884 // opposed to something that must hold a descriptor for an indirect call).
4885 static bool isFunctionGlobalAddress(SDValue Callee) {
4886   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4887     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4888         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4889       return false;
4890 
4891     return G->getGlobal()->getValueType()->isFunctionTy();
4892   }
4893 
4894   return false;
4895 }
4896 
4897 SDValue PPCTargetLowering::LowerCallResult(
4898     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4899     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4900     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4901   SmallVector<CCValAssign, 16> RVLocs;
4902   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4903                     *DAG.getContext());
4904 
4905   CCRetInfo.AnalyzeCallResult(
4906       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
4907                ? RetCC_PPC_Cold
4908                : RetCC_PPC);
4909 
4910   // Copy all of the result registers out of their specified physreg.
4911   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4912     CCValAssign &VA = RVLocs[i];
4913     assert(VA.isRegLoc() && "Can only return in registers!");
4914 
4915     SDValue Val;
4916 
4917     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
4918       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
4919                                       InFlag);
4920       Chain = Lo.getValue(1);
4921       InFlag = Lo.getValue(2);
4922       VA = RVLocs[++i]; // skip ahead to next loc
4923       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
4924                                       InFlag);
4925       Chain = Hi.getValue(1);
4926       InFlag = Hi.getValue(2);
4927       if (!Subtarget.isLittleEndian())
4928         std::swap (Lo, Hi);
4929       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
4930     } else {
4931       Val = DAG.getCopyFromReg(Chain, dl,
4932                                VA.getLocReg(), VA.getLocVT(), InFlag);
4933       Chain = Val.getValue(1);
4934       InFlag = Val.getValue(2);
4935     }
4936 
4937     switch (VA.getLocInfo()) {
4938     default: llvm_unreachable("Unknown loc info!");
4939     case CCValAssign::Full: break;
4940     case CCValAssign::AExt:
4941       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4942       break;
4943     case CCValAssign::ZExt:
4944       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4945                         DAG.getValueType(VA.getValVT()));
4946       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4947       break;
4948     case CCValAssign::SExt:
4949       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4950                         DAG.getValueType(VA.getValVT()));
4951       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4952       break;
4953     }
4954 
4955     InVals.push_back(Val);
4956   }
4957 
4958   return Chain;
4959 }
4960 
4961 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
4962                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
4963   // PatchPoint calls are not indirect.
4964   if (isPatchPoint)
4965     return false;
4966 
4967   if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee))
4968     return false;
4969 
4970   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
4971   // becuase the immediate function pointer points to a descriptor instead of
4972   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
4973   // pointer immediate points to the global entry point, while the BLA would
4974   // need to jump to the local entry point (see rL211174).
4975   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
4976       isBLACompatibleAddress(Callee, DAG))
4977     return false;
4978 
4979   return true;
4980 }
4981 
4982 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
4983 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
4984   return Subtarget.isAIXABI() ||
4985          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
4986 }
4987 
4988 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
4989                               const Function &Caller,
4990                               const SDValue &Callee,
4991                               const PPCSubtarget &Subtarget,
4992                               const TargetMachine &TM) {
4993   if (CFlags.IsTailCall)
4994     return PPCISD::TC_RETURN;
4995 
4996   // This is a call through a function pointer.
4997   if (CFlags.IsIndirect) {
4998     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
4999     // indirect calls. The save of the caller's TOC pointer to the stack will be
5000     // inserted into the DAG as part of call lowering. The restore of the TOC
5001     // pointer is modeled by using a pseudo instruction for the call opcode that
5002     // represents the 2 instruction sequence of an indirect branch and link,
5003     // immediately followed by a load of the TOC pointer from the the stack save
5004     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5005     // as it is not saved or used.
5006     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5007                                                : PPCISD::BCTRL;
5008   }
5009 
5010   if (Subtarget.isUsingPCRelativeCalls()) {
5011     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5012     return PPCISD::CALL_NOTOC;
5013   }
5014 
5015   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5016   // immediately following the call instruction if the caller and callee may
5017   // have different TOC bases. At link time if the linker determines the calls
5018   // may not share a TOC base, the call is redirected to a trampoline inserted
5019   // by the linker. The trampoline will (among other things) save the callers
5020   // TOC pointer at an ABI designated offset in the linkage area and the linker
5021   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5022   // into gpr2.
5023   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5024     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5025                                                   : PPCISD::CALL_NOP;
5026 
5027   return PPCISD::CALL;
5028 }
5029 
5030 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5031                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5032   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5033     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5034       return SDValue(Dest, 0);
5035 
5036   // Returns true if the callee is local, and false otherwise.
5037   auto isLocalCallee = [&]() {
5038     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5039     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5040     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5041 
5042     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5043            !dyn_cast_or_null<GlobalIFunc>(GV);
5044   };
5045 
5046   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5047   // a static relocation model causes some versions of GNU LD (2.17.50, at
5048   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5049   // built with secure-PLT.
5050   bool UsePlt =
5051       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5052       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5053 
5054   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5055     const TargetMachine &TM = Subtarget.getTargetMachine();
5056     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5057     MCSymbolXCOFF *S =
5058         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5059 
5060     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5061     return DAG.getMCSymbol(S, PtrVT);
5062   };
5063 
5064   if (isFunctionGlobalAddress(Callee)) {
5065     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5066 
5067     if (Subtarget.isAIXABI()) {
5068       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5069       return getAIXFuncEntryPointSymbolSDNode(GV);
5070     }
5071     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5072                                       UsePlt ? PPCII::MO_PLT : 0);
5073   }
5074 
5075   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5076     const char *SymName = S->getSymbol();
5077     if (Subtarget.isAIXABI()) {
5078       // If there exists a user-declared function whose name is the same as the
5079       // ExternalSymbol's, then we pick up the user-declared version.
5080       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5081       if (const Function *F =
5082               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5083         return getAIXFuncEntryPointSymbolSDNode(F);
5084 
5085       // On AIX, direct function calls reference the symbol for the function's
5086       // entry point, which is named by prepending a "." before the function's
5087       // C-linkage name. A Qualname is returned here because an external
5088       // function entry point is a csect with XTY_ER property.
5089       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5090         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5091         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5092             (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5093             XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER));
5094         return Sec->getQualNameSymbol();
5095       };
5096 
5097       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5098     }
5099     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5100                                        UsePlt ? PPCII::MO_PLT : 0);
5101   }
5102 
5103   // No transformation needed.
5104   assert(Callee.getNode() && "What no callee?");
5105   return Callee;
5106 }
5107 
5108 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5109   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5110          "Expected a CALLSEQ_STARTSDNode.");
5111 
5112   // The last operand is the chain, except when the node has glue. If the node
5113   // has glue, then the last operand is the glue, and the chain is the second
5114   // last operand.
5115   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5116   if (LastValue.getValueType() != MVT::Glue)
5117     return LastValue;
5118 
5119   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5120 }
5121 
5122 // Creates the node that moves a functions address into the count register
5123 // to prepare for an indirect call instruction.
5124 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5125                                 SDValue &Glue, SDValue &Chain,
5126                                 const SDLoc &dl) {
5127   SDValue MTCTROps[] = {Chain, Callee, Glue};
5128   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5129   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5130                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5131   // The glue is the second value produced.
5132   Glue = Chain.getValue(1);
5133 }
5134 
5135 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5136                                           SDValue &Glue, SDValue &Chain,
5137                                           SDValue CallSeqStart,
5138                                           const CallBase *CB, const SDLoc &dl,
5139                                           bool hasNest,
5140                                           const PPCSubtarget &Subtarget) {
5141   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5142   // entry point, but to the function descriptor (the function entry point
5143   // address is part of the function descriptor though).
5144   // The function descriptor is a three doubleword structure with the
5145   // following fields: function entry point, TOC base address and
5146   // environment pointer.
5147   // Thus for a call through a function pointer, the following actions need
5148   // to be performed:
5149   //   1. Save the TOC of the caller in the TOC save area of its stack
5150   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5151   //   2. Load the address of the function entry point from the function
5152   //      descriptor.
5153   //   3. Load the TOC of the callee from the function descriptor into r2.
5154   //   4. Load the environment pointer from the function descriptor into
5155   //      r11.
5156   //   5. Branch to the function entry point address.
5157   //   6. On return of the callee, the TOC of the caller needs to be
5158   //      restored (this is done in FinishCall()).
5159   //
5160   // The loads are scheduled at the beginning of the call sequence, and the
5161   // register copies are flagged together to ensure that no other
5162   // operations can be scheduled in between. E.g. without flagging the
5163   // copies together, a TOC access in the caller could be scheduled between
5164   // the assignment of the callee TOC and the branch to the callee, which leads
5165   // to incorrect code.
5166 
5167   // Start by loading the function address from the descriptor.
5168   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5169   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5170                       ? (MachineMemOperand::MODereferenceable |
5171                          MachineMemOperand::MOInvariant)
5172                       : MachineMemOperand::MONone;
5173 
5174   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5175 
5176   // Registers used in building the DAG.
5177   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5178   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5179 
5180   // Offsets of descriptor members.
5181   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5182   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5183 
5184   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5185   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5186 
5187   // One load for the functions entry point address.
5188   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5189                                     Alignment, MMOFlags);
5190 
5191   // One for loading the TOC anchor for the module that contains the called
5192   // function.
5193   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5194   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5195   SDValue TOCPtr =
5196       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5197                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5198 
5199   // One for loading the environment pointer.
5200   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5201   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5202   SDValue LoadEnvPtr =
5203       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5204                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5205 
5206 
5207   // Then copy the newly loaded TOC anchor to the TOC pointer.
5208   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5209   Chain = TOCVal.getValue(0);
5210   Glue = TOCVal.getValue(1);
5211 
5212   // If the function call has an explicit 'nest' parameter, it takes the
5213   // place of the environment pointer.
5214   assert((!hasNest || !Subtarget.isAIXABI()) &&
5215          "Nest parameter is not supported on AIX.");
5216   if (!hasNest) {
5217     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5218     Chain = EnvVal.getValue(0);
5219     Glue = EnvVal.getValue(1);
5220   }
5221 
5222   // The rest of the indirect call sequence is the same as the non-descriptor
5223   // DAG.
5224   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5225 }
5226 
5227 static void
5228 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5229                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5230                   SelectionDAG &DAG,
5231                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5232                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5233                   const PPCSubtarget &Subtarget) {
5234   const bool IsPPC64 = Subtarget.isPPC64();
5235   // MVT for a general purpose register.
5236   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5237 
5238   // First operand is always the chain.
5239   Ops.push_back(Chain);
5240 
5241   // If it's a direct call pass the callee as the second operand.
5242   if (!CFlags.IsIndirect)
5243     Ops.push_back(Callee);
5244   else {
5245     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5246 
5247     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5248     // on the stack (this would have been done in `LowerCall_64SVR4` or
5249     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5250     // represents both the indirect branch and a load that restores the TOC
5251     // pointer from the linkage area. The operand for the TOC restore is an add
5252     // of the TOC save offset to the stack pointer. This must be the second
5253     // operand: after the chain input but before any other variadic arguments.
5254     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5255     // saved or used.
5256     if (isTOCSaveRestoreRequired(Subtarget)) {
5257       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5258 
5259       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5260       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5261       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5262       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5263       Ops.push_back(AddTOC);
5264     }
5265 
5266     // Add the register used for the environment pointer.
5267     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5268       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5269                                     RegVT));
5270 
5271 
5272     // Add CTR register as callee so a bctr can be emitted later.
5273     if (CFlags.IsTailCall)
5274       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5275   }
5276 
5277   // If this is a tail call add stack pointer delta.
5278   if (CFlags.IsTailCall)
5279     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5280 
5281   // Add argument registers to the end of the list so that they are known live
5282   // into the call.
5283   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5284     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5285                                   RegsToPass[i].second.getValueType()));
5286 
5287   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5288   // no way to mark dependencies as implicit here.
5289   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5290   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5291        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5292     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5293 
5294   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5295   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5296     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5297 
5298   // Add a register mask operand representing the call-preserved registers.
5299   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5300   const uint32_t *Mask =
5301       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5302   assert(Mask && "Missing call preserved mask for calling convention");
5303   Ops.push_back(DAG.getRegisterMask(Mask));
5304 
5305   // If the glue is valid, it is the last operand.
5306   if (Glue.getNode())
5307     Ops.push_back(Glue);
5308 }
5309 
5310 SDValue PPCTargetLowering::FinishCall(
5311     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5312     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5313     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5314     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5315     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5316 
5317   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5318       Subtarget.isAIXABI())
5319     setUsesTOCBasePtr(DAG);
5320 
5321   unsigned CallOpc =
5322       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5323                     Subtarget, DAG.getTarget());
5324 
5325   if (!CFlags.IsIndirect)
5326     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5327   else if (Subtarget.usesFunctionDescriptors())
5328     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5329                                   dl, CFlags.HasNest, Subtarget);
5330   else
5331     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5332 
5333   // Build the operand list for the call instruction.
5334   SmallVector<SDValue, 8> Ops;
5335   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5336                     SPDiff, Subtarget);
5337 
5338   // Emit tail call.
5339   if (CFlags.IsTailCall) {
5340     // Indirect tail call when using PC Relative calls do not have the same
5341     // constraints.
5342     assert(((Callee.getOpcode() == ISD::Register &&
5343              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5344             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5345             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5346             isa<ConstantSDNode>(Callee) ||
5347             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5348            "Expecting a global address, external symbol, absolute value, "
5349            "register or an indirect tail call when PC Relative calls are "
5350            "used.");
5351     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5352     assert(CallOpc == PPCISD::TC_RETURN &&
5353            "Unexpected call opcode for a tail call.");
5354     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5355     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5356   }
5357 
5358   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5359   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5360   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5361   Glue = Chain.getValue(1);
5362 
5363   // When performing tail call optimization the callee pops its arguments off
5364   // the stack. Account for this here so these bytes can be pushed back on in
5365   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5366   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5367                          getTargetMachine().Options.GuaranteedTailCallOpt)
5368                             ? NumBytes
5369                             : 0;
5370 
5371   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5372                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5373                              Glue, dl);
5374   Glue = Chain.getValue(1);
5375 
5376   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5377                          DAG, InVals);
5378 }
5379 
5380 SDValue
5381 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5382                              SmallVectorImpl<SDValue> &InVals) const {
5383   SelectionDAG &DAG                     = CLI.DAG;
5384   SDLoc &dl                             = CLI.DL;
5385   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5386   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5387   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5388   SDValue Chain                         = CLI.Chain;
5389   SDValue Callee                        = CLI.Callee;
5390   bool &isTailCall                      = CLI.IsTailCall;
5391   CallingConv::ID CallConv              = CLI.CallConv;
5392   bool isVarArg                         = CLI.IsVarArg;
5393   bool isPatchPoint                     = CLI.IsPatchPoint;
5394   const CallBase *CB                    = CLI.CB;
5395 
5396   if (isTailCall) {
5397     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5398       isTailCall = false;
5399     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5400       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5401           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5402     else
5403       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5404                                                      Ins, DAG);
5405     if (isTailCall) {
5406       ++NumTailCalls;
5407       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5408         ++NumSiblingCalls;
5409 
5410       // PC Relative calls no longer guarantee that the callee is a Global
5411       // Address Node. The callee could be an indirect tail call in which
5412       // case the SDValue for the callee could be a load (to load the address
5413       // of a function pointer) or it may be a register copy (to move the
5414       // address of the callee from a function parameter into a virtual
5415       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5416       assert((Subtarget.isUsingPCRelativeCalls() ||
5417               isa<GlobalAddressSDNode>(Callee)) &&
5418              "Callee should be an llvm::Function object.");
5419 
5420       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5421                         << "\nTCO callee: ");
5422       LLVM_DEBUG(Callee.dump());
5423     }
5424   }
5425 
5426   if (!isTailCall && CB && CB->isMustTailCall())
5427     report_fatal_error("failed to perform tail call elimination on a call "
5428                        "site marked musttail");
5429 
5430   // When long calls (i.e. indirect calls) are always used, calls are always
5431   // made via function pointer. If we have a function name, first translate it
5432   // into a pointer.
5433   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5434       !isTailCall)
5435     Callee = LowerGlobalAddress(Callee, DAG);
5436 
5437   CallFlags CFlags(
5438       CallConv, isTailCall, isVarArg, isPatchPoint,
5439       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5440       // hasNest
5441       Subtarget.is64BitELFABI() &&
5442           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5443       CLI.NoMerge);
5444 
5445   if (Subtarget.isAIXABI())
5446     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5447                          InVals, CB);
5448 
5449   assert(Subtarget.isSVR4ABI());
5450   if (Subtarget.isPPC64())
5451     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5452                             InVals, CB);
5453   return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5454                           InVals, CB);
5455 }
5456 
5457 SDValue PPCTargetLowering::LowerCall_32SVR4(
5458     SDValue Chain, SDValue Callee, CallFlags CFlags,
5459     const SmallVectorImpl<ISD::OutputArg> &Outs,
5460     const SmallVectorImpl<SDValue> &OutVals,
5461     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5462     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5463     const CallBase *CB) const {
5464   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5465   // of the 32-bit SVR4 ABI stack frame layout.
5466 
5467   const CallingConv::ID CallConv = CFlags.CallConv;
5468   const bool IsVarArg = CFlags.IsVarArg;
5469   const bool IsTailCall = CFlags.IsTailCall;
5470 
5471   assert((CallConv == CallingConv::C ||
5472           CallConv == CallingConv::Cold ||
5473           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5474 
5475   const Align PtrAlign(4);
5476 
5477   MachineFunction &MF = DAG.getMachineFunction();
5478 
5479   // Mark this function as potentially containing a function that contains a
5480   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5481   // and restoring the callers stack pointer in this functions epilog. This is
5482   // done because by tail calling the called function might overwrite the value
5483   // in this function's (MF) stack pointer stack slot 0(SP).
5484   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5485       CallConv == CallingConv::Fast)
5486     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5487 
5488   // Count how many bytes are to be pushed on the stack, including the linkage
5489   // area, parameter list area and the part of the local variable space which
5490   // contains copies of aggregates which are passed by value.
5491 
5492   // Assign locations to all of the outgoing arguments.
5493   SmallVector<CCValAssign, 16> ArgLocs;
5494   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5495 
5496   // Reserve space for the linkage area on the stack.
5497   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5498                        PtrAlign);
5499   if (useSoftFloat())
5500     CCInfo.PreAnalyzeCallOperands(Outs);
5501 
5502   if (IsVarArg) {
5503     // Handle fixed and variable vector arguments differently.
5504     // Fixed vector arguments go into registers as long as registers are
5505     // available. Variable vector arguments always go into memory.
5506     unsigned NumArgs = Outs.size();
5507 
5508     for (unsigned i = 0; i != NumArgs; ++i) {
5509       MVT ArgVT = Outs[i].VT;
5510       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5511       bool Result;
5512 
5513       if (Outs[i].IsFixed) {
5514         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5515                                CCInfo);
5516       } else {
5517         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5518                                       ArgFlags, CCInfo);
5519       }
5520 
5521       if (Result) {
5522 #ifndef NDEBUG
5523         errs() << "Call operand #" << i << " has unhandled type "
5524              << EVT(ArgVT).getEVTString() << "\n";
5525 #endif
5526         llvm_unreachable(nullptr);
5527       }
5528     }
5529   } else {
5530     // All arguments are treated the same.
5531     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5532   }
5533   CCInfo.clearWasPPCF128();
5534 
5535   // Assign locations to all of the outgoing aggregate by value arguments.
5536   SmallVector<CCValAssign, 16> ByValArgLocs;
5537   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5538 
5539   // Reserve stack space for the allocations in CCInfo.
5540   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5541 
5542   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5543 
5544   // Size of the linkage area, parameter list area and the part of the local
5545   // space variable where copies of aggregates which are passed by value are
5546   // stored.
5547   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5548 
5549   // Calculate by how many bytes the stack has to be adjusted in case of tail
5550   // call optimization.
5551   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5552 
5553   // Adjust the stack pointer for the new arguments...
5554   // These operations are automatically eliminated by the prolog/epilog pass
5555   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5556   SDValue CallSeqStart = Chain;
5557 
5558   // Load the return address and frame pointer so it can be moved somewhere else
5559   // later.
5560   SDValue LROp, FPOp;
5561   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5562 
5563   // Set up a copy of the stack pointer for use loading and storing any
5564   // arguments that may not fit in the registers available for argument
5565   // passing.
5566   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5567 
5568   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5569   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5570   SmallVector<SDValue, 8> MemOpChains;
5571 
5572   bool seenFloatArg = false;
5573   // Walk the register/memloc assignments, inserting copies/loads.
5574   // i - Tracks the index into the list of registers allocated for the call
5575   // RealArgIdx - Tracks the index into the list of actual function arguments
5576   // j - Tracks the index into the list of byval arguments
5577   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5578        i != e;
5579        ++i, ++RealArgIdx) {
5580     CCValAssign &VA = ArgLocs[i];
5581     SDValue Arg = OutVals[RealArgIdx];
5582     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5583 
5584     if (Flags.isByVal()) {
5585       // Argument is an aggregate which is passed by value, thus we need to
5586       // create a copy of it in the local variable space of the current stack
5587       // frame (which is the stack frame of the caller) and pass the address of
5588       // this copy to the callee.
5589       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5590       CCValAssign &ByValVA = ByValArgLocs[j++];
5591       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5592 
5593       // Memory reserved in the local variable space of the callers stack frame.
5594       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5595 
5596       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5597       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5598                            StackPtr, PtrOff);
5599 
5600       // Create a copy of the argument in the local area of the current
5601       // stack frame.
5602       SDValue MemcpyCall =
5603         CreateCopyOfByValArgument(Arg, PtrOff,
5604                                   CallSeqStart.getNode()->getOperand(0),
5605                                   Flags, DAG, dl);
5606 
5607       // This must go outside the CALLSEQ_START..END.
5608       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5609                                                      SDLoc(MemcpyCall));
5610       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5611                              NewCallSeqStart.getNode());
5612       Chain = CallSeqStart = NewCallSeqStart;
5613 
5614       // Pass the address of the aggregate copy on the stack either in a
5615       // physical register or in the parameter list area of the current stack
5616       // frame to the callee.
5617       Arg = PtrOff;
5618     }
5619 
5620     // When useCRBits() is true, there can be i1 arguments.
5621     // It is because getRegisterType(MVT::i1) => MVT::i1,
5622     // and for other integer types getRegisterType() => MVT::i32.
5623     // Extend i1 and ensure callee will get i32.
5624     if (Arg.getValueType() == MVT::i1)
5625       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5626                         dl, MVT::i32, Arg);
5627 
5628     if (VA.isRegLoc()) {
5629       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5630       // Put argument in a physical register.
5631       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5632         bool IsLE = Subtarget.isLittleEndian();
5633         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5634                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5635         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5636         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5637                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5638         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5639                              SVal.getValue(0)));
5640       } else
5641         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5642     } else {
5643       // Put argument in the parameter list area of the current stack frame.
5644       assert(VA.isMemLoc());
5645       unsigned LocMemOffset = VA.getLocMemOffset();
5646 
5647       if (!IsTailCall) {
5648         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5649         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5650                              StackPtr, PtrOff);
5651 
5652         MemOpChains.push_back(
5653             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5654       } else {
5655         // Calculate and remember argument location.
5656         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5657                                  TailCallArguments);
5658       }
5659     }
5660   }
5661 
5662   if (!MemOpChains.empty())
5663     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5664 
5665   // Build a sequence of copy-to-reg nodes chained together with token chain
5666   // and flag operands which copy the outgoing args into the appropriate regs.
5667   SDValue InFlag;
5668   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5669     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5670                              RegsToPass[i].second, InFlag);
5671     InFlag = Chain.getValue(1);
5672   }
5673 
5674   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5675   // registers.
5676   if (IsVarArg) {
5677     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5678     SDValue Ops[] = { Chain, InFlag };
5679 
5680     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5681                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5682 
5683     InFlag = Chain.getValue(1);
5684   }
5685 
5686   if (IsTailCall)
5687     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5688                     TailCallArguments);
5689 
5690   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5691                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5692 }
5693 
5694 // Copy an argument into memory, being careful to do this outside the
5695 // call sequence for the call to which the argument belongs.
5696 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5697     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5698     SelectionDAG &DAG, const SDLoc &dl) const {
5699   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5700                         CallSeqStart.getNode()->getOperand(0),
5701                         Flags, DAG, dl);
5702   // The MEMCPY must go outside the CALLSEQ_START..END.
5703   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5704   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5705                                                  SDLoc(MemcpyCall));
5706   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5707                          NewCallSeqStart.getNode());
5708   return NewCallSeqStart;
5709 }
5710 
5711 SDValue PPCTargetLowering::LowerCall_64SVR4(
5712     SDValue Chain, SDValue Callee, CallFlags CFlags,
5713     const SmallVectorImpl<ISD::OutputArg> &Outs,
5714     const SmallVectorImpl<SDValue> &OutVals,
5715     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5716     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5717     const CallBase *CB) const {
5718   bool isELFv2ABI = Subtarget.isELFv2ABI();
5719   bool isLittleEndian = Subtarget.isLittleEndian();
5720   unsigned NumOps = Outs.size();
5721   bool IsSibCall = false;
5722   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5723 
5724   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5725   unsigned PtrByteSize = 8;
5726 
5727   MachineFunction &MF = DAG.getMachineFunction();
5728 
5729   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5730     IsSibCall = true;
5731 
5732   // Mark this function as potentially containing a function that contains a
5733   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5734   // and restoring the callers stack pointer in this functions epilog. This is
5735   // done because by tail calling the called function might overwrite the value
5736   // in this function's (MF) stack pointer stack slot 0(SP).
5737   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5738     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5739 
5740   assert(!(IsFastCall && CFlags.IsVarArg) &&
5741          "fastcc not supported on varargs functions");
5742 
5743   // Count how many bytes are to be pushed on the stack, including the linkage
5744   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5745   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5746   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5747   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5748   unsigned NumBytes = LinkageSize;
5749   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5750 
5751   static const MCPhysReg GPR[] = {
5752     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5753     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5754   };
5755   static const MCPhysReg VR[] = {
5756     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5757     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5758   };
5759 
5760   const unsigned NumGPRs = array_lengthof(GPR);
5761   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5762   const unsigned NumVRs  = array_lengthof(VR);
5763 
5764   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5765   // can be passed to the callee in registers.
5766   // For the fast calling convention, there is another check below.
5767   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5768   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5769   if (!HasParameterArea) {
5770     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5771     unsigned AvailableFPRs = NumFPRs;
5772     unsigned AvailableVRs = NumVRs;
5773     unsigned NumBytesTmp = NumBytes;
5774     for (unsigned i = 0; i != NumOps; ++i) {
5775       if (Outs[i].Flags.isNest()) continue;
5776       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5777                                  PtrByteSize, LinkageSize, ParamAreaSize,
5778                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
5779         HasParameterArea = true;
5780     }
5781   }
5782 
5783   // When using the fast calling convention, we don't provide backing for
5784   // arguments that will be in registers.
5785   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5786 
5787   // Avoid allocating parameter area for fastcc functions if all the arguments
5788   // can be passed in the registers.
5789   if (IsFastCall)
5790     HasParameterArea = false;
5791 
5792   // Add up all the space actually used.
5793   for (unsigned i = 0; i != NumOps; ++i) {
5794     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5795     EVT ArgVT = Outs[i].VT;
5796     EVT OrigVT = Outs[i].ArgVT;
5797 
5798     if (Flags.isNest())
5799       continue;
5800 
5801     if (IsFastCall) {
5802       if (Flags.isByVal()) {
5803         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5804         if (NumGPRsUsed > NumGPRs)
5805           HasParameterArea = true;
5806       } else {
5807         switch (ArgVT.getSimpleVT().SimpleTy) {
5808         default: llvm_unreachable("Unexpected ValueType for argument!");
5809         case MVT::i1:
5810         case MVT::i32:
5811         case MVT::i64:
5812           if (++NumGPRsUsed <= NumGPRs)
5813             continue;
5814           break;
5815         case MVT::v4i32:
5816         case MVT::v8i16:
5817         case MVT::v16i8:
5818         case MVT::v2f64:
5819         case MVT::v2i64:
5820         case MVT::v1i128:
5821         case MVT::f128:
5822           if (++NumVRsUsed <= NumVRs)
5823             continue;
5824           break;
5825         case MVT::v4f32:
5826           if (++NumVRsUsed <= NumVRs)
5827             continue;
5828           break;
5829         case MVT::f32:
5830         case MVT::f64:
5831           if (++NumFPRsUsed <= NumFPRs)
5832             continue;
5833           break;
5834         }
5835         HasParameterArea = true;
5836       }
5837     }
5838 
5839     /* Respect alignment of argument on the stack.  */
5840     auto Alignement =
5841         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5842     NumBytes = alignTo(NumBytes, Alignement);
5843 
5844     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5845     if (Flags.isInConsecutiveRegsLast())
5846       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5847   }
5848 
5849   unsigned NumBytesActuallyUsed = NumBytes;
5850 
5851   // In the old ELFv1 ABI,
5852   // the prolog code of the callee may store up to 8 GPR argument registers to
5853   // the stack, allowing va_start to index over them in memory if its varargs.
5854   // Because we cannot tell if this is needed on the caller side, we have to
5855   // conservatively assume that it is needed.  As such, make sure we have at
5856   // least enough stack space for the caller to store the 8 GPRs.
5857   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5858   // really requires memory operands, e.g. a vararg function.
5859   if (HasParameterArea)
5860     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5861   else
5862     NumBytes = LinkageSize;
5863 
5864   // Tail call needs the stack to be aligned.
5865   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5866     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5867 
5868   int SPDiff = 0;
5869 
5870   // Calculate by how many bytes the stack has to be adjusted in case of tail
5871   // call optimization.
5872   if (!IsSibCall)
5873     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
5874 
5875   // To protect arguments on the stack from being clobbered in a tail call,
5876   // force all the loads to happen before doing any other lowering.
5877   if (CFlags.IsTailCall)
5878     Chain = DAG.getStackArgumentTokenFactor(Chain);
5879 
5880   // Adjust the stack pointer for the new arguments...
5881   // These operations are automatically eliminated by the prolog/epilog pass
5882   if (!IsSibCall)
5883     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5884   SDValue CallSeqStart = Chain;
5885 
5886   // Load the return address and frame pointer so it can be move somewhere else
5887   // later.
5888   SDValue LROp, FPOp;
5889   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5890 
5891   // Set up a copy of the stack pointer for use loading and storing any
5892   // arguments that may not fit in the registers available for argument
5893   // passing.
5894   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5895 
5896   // Figure out which arguments are going to go in registers, and which in
5897   // memory.  Also, if this is a vararg function, floating point operations
5898   // must be stored to our stack, and loaded into integer regs as well, if
5899   // any integer regs are available for argument passing.
5900   unsigned ArgOffset = LinkageSize;
5901 
5902   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5903   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5904 
5905   SmallVector<SDValue, 8> MemOpChains;
5906   for (unsigned i = 0; i != NumOps; ++i) {
5907     SDValue Arg = OutVals[i];
5908     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5909     EVT ArgVT = Outs[i].VT;
5910     EVT OrigVT = Outs[i].ArgVT;
5911 
5912     // PtrOff will be used to store the current argument to the stack if a
5913     // register cannot be found for it.
5914     SDValue PtrOff;
5915 
5916     // We re-align the argument offset for each argument, except when using the
5917     // fast calling convention, when we need to make sure we do that only when
5918     // we'll actually use a stack slot.
5919     auto ComputePtrOff = [&]() {
5920       /* Respect alignment of argument on the stack.  */
5921       auto Alignment =
5922           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5923       ArgOffset = alignTo(ArgOffset, Alignment);
5924 
5925       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5926 
5927       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5928     };
5929 
5930     if (!IsFastCall) {
5931       ComputePtrOff();
5932 
5933       /* Compute GPR index associated with argument offset.  */
5934       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5935       GPR_idx = std::min(GPR_idx, NumGPRs);
5936     }
5937 
5938     // Promote integers to 64-bit values.
5939     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5940       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5941       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5942       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5943     }
5944 
5945     // FIXME memcpy is used way more than necessary.  Correctness first.
5946     // Note: "by value" is code for passing a structure by value, not
5947     // basic types.
5948     if (Flags.isByVal()) {
5949       // Note: Size includes alignment padding, so
5950       //   struct x { short a; char b; }
5951       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5952       // These are the proper values we need for right-justifying the
5953       // aggregate in a parameter register.
5954       unsigned Size = Flags.getByValSize();
5955 
5956       // An empty aggregate parameter takes up no storage and no
5957       // registers.
5958       if (Size == 0)
5959         continue;
5960 
5961       if (IsFastCall)
5962         ComputePtrOff();
5963 
5964       // All aggregates smaller than 8 bytes must be passed right-justified.
5965       if (Size==1 || Size==2 || Size==4) {
5966         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5967         if (GPR_idx != NumGPRs) {
5968           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5969                                         MachinePointerInfo(), VT);
5970           MemOpChains.push_back(Load.getValue(1));
5971           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5972 
5973           ArgOffset += PtrByteSize;
5974           continue;
5975         }
5976       }
5977 
5978       if (GPR_idx == NumGPRs && Size < 8) {
5979         SDValue AddPtr = PtrOff;
5980         if (!isLittleEndian) {
5981           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5982                                           PtrOff.getValueType());
5983           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5984         }
5985         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5986                                                           CallSeqStart,
5987                                                           Flags, DAG, dl);
5988         ArgOffset += PtrByteSize;
5989         continue;
5990       }
5991       // Copy entire object into memory.  There are cases where gcc-generated
5992       // code assumes it is there, even if it could be put entirely into
5993       // registers.  (This is not what the doc says.)
5994 
5995       // FIXME: The above statement is likely due to a misunderstanding of the
5996       // documents.  All arguments must be copied into the parameter area BY
5997       // THE CALLEE in the event that the callee takes the address of any
5998       // formal argument.  That has not yet been implemented.  However, it is
5999       // reasonable to use the stack area as a staging area for the register
6000       // load.
6001 
6002       // Skip this for small aggregates, as we will use the same slot for a
6003       // right-justified copy, below.
6004       if (Size >= 8)
6005         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6006                                                           CallSeqStart,
6007                                                           Flags, DAG, dl);
6008 
6009       // When a register is available, pass a small aggregate right-justified.
6010       if (Size < 8 && GPR_idx != NumGPRs) {
6011         // The easiest way to get this right-justified in a register
6012         // is to copy the structure into the rightmost portion of a
6013         // local variable slot, then load the whole slot into the
6014         // register.
6015         // FIXME: The memcpy seems to produce pretty awful code for
6016         // small aggregates, particularly for packed ones.
6017         // FIXME: It would be preferable to use the slot in the
6018         // parameter save area instead of a new local variable.
6019         SDValue AddPtr = PtrOff;
6020         if (!isLittleEndian) {
6021           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6022           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6023         }
6024         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6025                                                           CallSeqStart,
6026                                                           Flags, DAG, dl);
6027 
6028         // Load the slot into the register.
6029         SDValue Load =
6030             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6031         MemOpChains.push_back(Load.getValue(1));
6032         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6033 
6034         // Done with this argument.
6035         ArgOffset += PtrByteSize;
6036         continue;
6037       }
6038 
6039       // For aggregates larger than PtrByteSize, copy the pieces of the
6040       // object that fit into registers from the parameter save area.
6041       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6042         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6043         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6044         if (GPR_idx != NumGPRs) {
6045           SDValue Load =
6046               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6047           MemOpChains.push_back(Load.getValue(1));
6048           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6049           ArgOffset += PtrByteSize;
6050         } else {
6051           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6052           break;
6053         }
6054       }
6055       continue;
6056     }
6057 
6058     switch (Arg.getSimpleValueType().SimpleTy) {
6059     default: llvm_unreachable("Unexpected ValueType for argument!");
6060     case MVT::i1:
6061     case MVT::i32:
6062     case MVT::i64:
6063       if (Flags.isNest()) {
6064         // The 'nest' parameter, if any, is passed in R11.
6065         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6066         break;
6067       }
6068 
6069       // These can be scalar arguments or elements of an integer array type
6070       // passed directly.  Clang may use those instead of "byval" aggregate
6071       // types to avoid forcing arguments to memory unnecessarily.
6072       if (GPR_idx != NumGPRs) {
6073         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6074       } else {
6075         if (IsFastCall)
6076           ComputePtrOff();
6077 
6078         assert(HasParameterArea &&
6079                "Parameter area must exist to pass an argument in memory.");
6080         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6081                          true, CFlags.IsTailCall, false, MemOpChains,
6082                          TailCallArguments, dl);
6083         if (IsFastCall)
6084           ArgOffset += PtrByteSize;
6085       }
6086       if (!IsFastCall)
6087         ArgOffset += PtrByteSize;
6088       break;
6089     case MVT::f32:
6090     case MVT::f64: {
6091       // These can be scalar arguments or elements of a float array type
6092       // passed directly.  The latter are used to implement ELFv2 homogenous
6093       // float aggregates.
6094 
6095       // Named arguments go into FPRs first, and once they overflow, the
6096       // remaining arguments go into GPRs and then the parameter save area.
6097       // Unnamed arguments for vararg functions always go to GPRs and
6098       // then the parameter save area.  For now, put all arguments to vararg
6099       // routines always in both locations (FPR *and* GPR or stack slot).
6100       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6101       bool NeededLoad = false;
6102 
6103       // First load the argument into the next available FPR.
6104       if (FPR_idx != NumFPRs)
6105         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6106 
6107       // Next, load the argument into GPR or stack slot if needed.
6108       if (!NeedGPROrStack)
6109         ;
6110       else if (GPR_idx != NumGPRs && !IsFastCall) {
6111         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6112         // once we support fp <-> gpr moves.
6113 
6114         // In the non-vararg case, this can only ever happen in the
6115         // presence of f32 array types, since otherwise we never run
6116         // out of FPRs before running out of GPRs.
6117         SDValue ArgVal;
6118 
6119         // Double values are always passed in a single GPR.
6120         if (Arg.getValueType() != MVT::f32) {
6121           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6122 
6123         // Non-array float values are extended and passed in a GPR.
6124         } else if (!Flags.isInConsecutiveRegs()) {
6125           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6126           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6127 
6128         // If we have an array of floats, we collect every odd element
6129         // together with its predecessor into one GPR.
6130         } else if (ArgOffset % PtrByteSize != 0) {
6131           SDValue Lo, Hi;
6132           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6133           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6134           if (!isLittleEndian)
6135             std::swap(Lo, Hi);
6136           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6137 
6138         // The final element, if even, goes into the first half of a GPR.
6139         } else if (Flags.isInConsecutiveRegsLast()) {
6140           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6141           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6142           if (!isLittleEndian)
6143             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6144                                  DAG.getConstant(32, dl, MVT::i32));
6145 
6146         // Non-final even elements are skipped; they will be handled
6147         // together the with subsequent argument on the next go-around.
6148         } else
6149           ArgVal = SDValue();
6150 
6151         if (ArgVal.getNode())
6152           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6153       } else {
6154         if (IsFastCall)
6155           ComputePtrOff();
6156 
6157         // Single-precision floating-point values are mapped to the
6158         // second (rightmost) word of the stack doubleword.
6159         if (Arg.getValueType() == MVT::f32 &&
6160             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6161           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6162           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6163         }
6164 
6165         assert(HasParameterArea &&
6166                "Parameter area must exist to pass an argument in memory.");
6167         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6168                          true, CFlags.IsTailCall, false, MemOpChains,
6169                          TailCallArguments, dl);
6170 
6171         NeededLoad = true;
6172       }
6173       // When passing an array of floats, the array occupies consecutive
6174       // space in the argument area; only round up to the next doubleword
6175       // at the end of the array.  Otherwise, each float takes 8 bytes.
6176       if (!IsFastCall || NeededLoad) {
6177         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6178                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6179         if (Flags.isInConsecutiveRegsLast())
6180           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6181       }
6182       break;
6183     }
6184     case MVT::v4f32:
6185     case MVT::v4i32:
6186     case MVT::v8i16:
6187     case MVT::v16i8:
6188     case MVT::v2f64:
6189     case MVT::v2i64:
6190     case MVT::v1i128:
6191     case MVT::f128:
6192       // These can be scalar arguments or elements of a vector array type
6193       // passed directly.  The latter are used to implement ELFv2 homogenous
6194       // vector aggregates.
6195 
6196       // For a varargs call, named arguments go into VRs or on the stack as
6197       // usual; unnamed arguments always go to the stack or the corresponding
6198       // GPRs when within range.  For now, we always put the value in both
6199       // locations (or even all three).
6200       if (CFlags.IsVarArg) {
6201         assert(HasParameterArea &&
6202                "Parameter area must exist if we have a varargs call.");
6203         // We could elide this store in the case where the object fits
6204         // entirely in R registers.  Maybe later.
6205         SDValue Store =
6206             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6207         MemOpChains.push_back(Store);
6208         if (VR_idx != NumVRs) {
6209           SDValue Load =
6210               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6211           MemOpChains.push_back(Load.getValue(1));
6212           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6213         }
6214         ArgOffset += 16;
6215         for (unsigned i=0; i<16; i+=PtrByteSize) {
6216           if (GPR_idx == NumGPRs)
6217             break;
6218           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6219                                    DAG.getConstant(i, dl, PtrVT));
6220           SDValue Load =
6221               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6222           MemOpChains.push_back(Load.getValue(1));
6223           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6224         }
6225         break;
6226       }
6227 
6228       // Non-varargs Altivec params go into VRs or on the stack.
6229       if (VR_idx != NumVRs) {
6230         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6231       } else {
6232         if (IsFastCall)
6233           ComputePtrOff();
6234 
6235         assert(HasParameterArea &&
6236                "Parameter area must exist to pass an argument in memory.");
6237         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6238                          true, CFlags.IsTailCall, true, MemOpChains,
6239                          TailCallArguments, dl);
6240         if (IsFastCall)
6241           ArgOffset += 16;
6242       }
6243 
6244       if (!IsFastCall)
6245         ArgOffset += 16;
6246       break;
6247     }
6248   }
6249 
6250   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6251          "mismatch in size of parameter area");
6252   (void)NumBytesActuallyUsed;
6253 
6254   if (!MemOpChains.empty())
6255     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6256 
6257   // Check if this is an indirect call (MTCTR/BCTRL).
6258   // See prepareDescriptorIndirectCall and buildCallOperands for more
6259   // information about calls through function pointers in the 64-bit SVR4 ABI.
6260   if (CFlags.IsIndirect) {
6261     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6262     // caller in the TOC save area.
6263     if (isTOCSaveRestoreRequired(Subtarget)) {
6264       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6265       // Load r2 into a virtual register and store it to the TOC save area.
6266       setUsesTOCBasePtr(DAG);
6267       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6268       // TOC save area offset.
6269       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6270       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6271       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6272       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6273                            MachinePointerInfo::getStack(
6274                                DAG.getMachineFunction(), TOCSaveOffset));
6275     }
6276     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6277     // This does not mean the MTCTR instruction must use R12; it's easier
6278     // to model this as an extra parameter, so do that.
6279     if (isELFv2ABI && !CFlags.IsPatchPoint)
6280       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6281   }
6282 
6283   // Build a sequence of copy-to-reg nodes chained together with token chain
6284   // and flag operands which copy the outgoing args into the appropriate regs.
6285   SDValue InFlag;
6286   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6287     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6288                              RegsToPass[i].second, InFlag);
6289     InFlag = Chain.getValue(1);
6290   }
6291 
6292   if (CFlags.IsTailCall && !IsSibCall)
6293     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6294                     TailCallArguments);
6295 
6296   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6297                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6298 }
6299 
6300 // Returns true when the shadow of a general purpose argument register
6301 // in the parameter save area is aligned to at least 'RequiredAlign'.
6302 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
6303   assert(RequiredAlign.value() <= 16 &&
6304          "Required alignment greater than stack alignment.");
6305   switch (Reg) {
6306   default:
6307     report_fatal_error("called on invalid register.");
6308   case PPC::R5:
6309   case PPC::R9:
6310   case PPC::X3:
6311   case PPC::X5:
6312   case PPC::X7:
6313   case PPC::X9:
6314     // These registers are 16 byte aligned which is the most strict aligment
6315     // we can support.
6316     return true;
6317   case PPC::R3:
6318   case PPC::R7:
6319   case PPC::X4:
6320   case PPC::X6:
6321   case PPC::X8:
6322   case PPC::X10:
6323     // The shadow of these registers in the PSA is 8 byte aligned.
6324     return RequiredAlign <= 8;
6325   case PPC::R4:
6326   case PPC::R6:
6327   case PPC::R8:
6328   case PPC::R10:
6329     return RequiredAlign <= 4;
6330   }
6331 }
6332 
6333 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6334                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6335                    CCState &S) {
6336   AIXCCState &State = static_cast<AIXCCState &>(S);
6337   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6338       State.getMachineFunction().getSubtarget());
6339   const bool IsPPC64 = Subtarget.isPPC64();
6340   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6341   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6342 
6343   if (ValVT == MVT::f128)
6344     report_fatal_error("f128 is unimplemented on AIX.");
6345 
6346   if (ArgFlags.isNest())
6347     report_fatal_error("Nest arguments are unimplemented.");
6348 
6349   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6350                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6351                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6352   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6353                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6354                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6355 
6356   static const MCPhysReg VR[] = {// Vector registers.
6357                                  PPC::V2,  PPC::V3,  PPC::V4,  PPC::V5,
6358                                  PPC::V6,  PPC::V7,  PPC::V8,  PPC::V9,
6359                                  PPC::V10, PPC::V11, PPC::V12, PPC::V13};
6360 
6361   if (ArgFlags.isByVal()) {
6362     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6363       report_fatal_error("Pass-by-value arguments with alignment greater than "
6364                          "register width are not supported.");
6365 
6366     const unsigned ByValSize = ArgFlags.getByValSize();
6367 
6368     // An empty aggregate parameter takes up no storage and no registers,
6369     // but needs a MemLoc for a stack slot for the formal arguments side.
6370     if (ByValSize == 0) {
6371       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6372                                        State.getNextStackOffset(), RegVT,
6373                                        LocInfo));
6374       return false;
6375     }
6376 
6377     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6378     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6379     for (const unsigned E = Offset + StackSize; Offset < E;
6380          Offset += PtrAlign.value()) {
6381       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6382         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6383       else {
6384         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6385                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6386                                          LocInfo));
6387         break;
6388       }
6389     }
6390     return false;
6391   }
6392 
6393   // Arguments always reserve parameter save area.
6394   switch (ValVT.SimpleTy) {
6395   default:
6396     report_fatal_error("Unhandled value type for argument.");
6397   case MVT::i64:
6398     // i64 arguments should have been split to i32 for PPC32.
6399     assert(IsPPC64 && "PPC32 should have split i64 values.");
6400     LLVM_FALLTHROUGH;
6401   case MVT::i1:
6402   case MVT::i32: {
6403     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6404     // AIX integer arguments are always passed in register width.
6405     if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6406       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6407                                   : CCValAssign::LocInfo::ZExt;
6408     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6409       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6410     else
6411       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6412 
6413     return false;
6414   }
6415   case MVT::f32:
6416   case MVT::f64: {
6417     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6418     const unsigned StoreSize = LocVT.getStoreSize();
6419     // Floats are always 4-byte aligned in the PSA on AIX.
6420     // This includes f64 in 64-bit mode for ABI compatibility.
6421     const unsigned Offset =
6422         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6423     unsigned FReg = State.AllocateReg(FPR);
6424     if (FReg)
6425       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6426 
6427     // Reserve and initialize GPRs or initialize the PSA as required.
6428     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6429       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6430         assert(FReg && "An FPR should be available when a GPR is reserved.");
6431         if (State.isVarArg()) {
6432           // Successfully reserved GPRs are only initialized for vararg calls.
6433           // Custom handling is required for:
6434           //   f64 in PPC32 needs to be split into 2 GPRs.
6435           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6436           State.addLoc(
6437               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6438         }
6439       } else {
6440         // If there are insufficient GPRs, the PSA needs to be initialized.
6441         // Initialization occurs even if an FPR was initialized for
6442         // compatibility with the AIX XL compiler. The full memory for the
6443         // argument will be initialized even if a prior word is saved in GPR.
6444         // A custom memLoc is used when the argument also passes in FPR so
6445         // that the callee handling can skip over it easily.
6446         State.addLoc(
6447             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6448                                              LocInfo)
6449                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6450         break;
6451       }
6452     }
6453 
6454     return false;
6455   }
6456   case MVT::v4f32:
6457   case MVT::v4i32:
6458   case MVT::v8i16:
6459   case MVT::v16i8:
6460   case MVT::v2i64:
6461   case MVT::v2f64:
6462   case MVT::v1i128: {
6463     const unsigned VecSize = 16;
6464     const Align VecAlign(VecSize);
6465 
6466     if (!State.isVarArg()) {
6467       // If there are vector registers remaining we don't consume any stack
6468       // space.
6469       if (unsigned VReg = State.AllocateReg(VR)) {
6470         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6471         return false;
6472       }
6473       // Vectors passed on the stack do not shadow GPRs or FPRs even though they
6474       // might be allocated in the portion of the PSA that is shadowed by the
6475       // GPRs.
6476       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6477       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6478       return false;
6479     }
6480 
6481     const unsigned PtrSize = IsPPC64 ? 8 : 4;
6482     ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
6483 
6484     unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
6485     // Burn any underaligned registers and their shadowed stack space until
6486     // we reach the required alignment.
6487     while (NextRegIndex != GPRs.size() &&
6488            !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
6489       // Shadow allocate register and its stack shadow.
6490       unsigned Reg = State.AllocateReg(GPRs);
6491       State.AllocateStack(PtrSize, PtrAlign);
6492       assert(Reg && "Allocating register unexpectedly failed.");
6493       (void)Reg;
6494       NextRegIndex = State.getFirstUnallocated(GPRs);
6495     }
6496 
6497     // Vectors that are passed as fixed arguments are handled differently.
6498     // They are passed in VRs if any are available (unlike arguments passed
6499     // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
6500     // functions)
6501     if (State.isFixed(ValNo)) {
6502       if (unsigned VReg = State.AllocateReg(VR)) {
6503         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6504         // Shadow allocate GPRs and stack space even though we pass in a VR.
6505         for (unsigned I = 0; I != VecSize; I += PtrSize)
6506           State.AllocateReg(GPRs);
6507         State.AllocateStack(VecSize, VecAlign);
6508         return false;
6509       }
6510       // No vector registers remain so pass on the stack.
6511       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6512       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6513       return false;
6514     }
6515 
6516     // If all GPRS are consumed then we pass the argument fully on the stack.
6517     if (NextRegIndex == GPRs.size()) {
6518       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6519       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6520       return false;
6521     }
6522 
6523     // Corner case for 32-bit codegen. We have 2 registers to pass the first
6524     // half of the argument, and then need to pass the remaining half on the
6525     // stack.
6526     if (GPRs[NextRegIndex] == PPC::R9) {
6527       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6528       State.addLoc(
6529           CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6530 
6531       const unsigned FirstReg = State.AllocateReg(PPC::R9);
6532       const unsigned SecondReg = State.AllocateReg(PPC::R10);
6533       assert(FirstReg && SecondReg &&
6534              "Allocating R9 or R10 unexpectedly failed.");
6535       State.addLoc(
6536           CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
6537       State.addLoc(
6538           CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
6539       return false;
6540     }
6541 
6542     // We have enough GPRs to fully pass the vector argument, and we have
6543     // already consumed any underaligned registers. Start with the custom
6544     // MemLoc and then the custom RegLocs.
6545     const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6546     State.addLoc(
6547         CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6548     for (unsigned I = 0; I != VecSize; I += PtrSize) {
6549       const unsigned Reg = State.AllocateReg(GPRs);
6550       assert(Reg && "Failed to allocated register for vararg vector argument");
6551       State.addLoc(
6552           CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6553     }
6554     return false;
6555   }
6556   }
6557   return true;
6558 }
6559 
6560 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6561                                                     bool IsPPC64) {
6562   assert((IsPPC64 || SVT != MVT::i64) &&
6563          "i64 should have been split for 32-bit codegen.");
6564 
6565   switch (SVT) {
6566   default:
6567     report_fatal_error("Unexpected value type for formal argument");
6568   case MVT::i1:
6569   case MVT::i32:
6570   case MVT::i64:
6571     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6572   case MVT::f32:
6573     return &PPC::F4RCRegClass;
6574   case MVT::f64:
6575     return &PPC::F8RCRegClass;
6576   case MVT::v4f32:
6577   case MVT::v4i32:
6578   case MVT::v8i16:
6579   case MVT::v16i8:
6580   case MVT::v2i64:
6581   case MVT::v2f64:
6582   case MVT::v1i128:
6583     return &PPC::VRRCRegClass;
6584   }
6585 }
6586 
6587 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6588                                         SelectionDAG &DAG, SDValue ArgValue,
6589                                         MVT LocVT, const SDLoc &dl) {
6590   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6591   assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
6592 
6593   if (Flags.isSExt())
6594     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6595                            DAG.getValueType(ValVT));
6596   else if (Flags.isZExt())
6597     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6598                            DAG.getValueType(ValVT));
6599 
6600   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6601 }
6602 
6603 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6604   const unsigned LASize = FL->getLinkageSize();
6605 
6606   if (PPC::GPRCRegClass.contains(Reg)) {
6607     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6608            "Reg must be a valid argument register!");
6609     return LASize + 4 * (Reg - PPC::R3);
6610   }
6611 
6612   if (PPC::G8RCRegClass.contains(Reg)) {
6613     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6614            "Reg must be a valid argument register!");
6615     return LASize + 8 * (Reg - PPC::X3);
6616   }
6617 
6618   llvm_unreachable("Only general purpose registers expected.");
6619 }
6620 
6621 //   AIX ABI Stack Frame Layout:
6622 //
6623 //   Low Memory +--------------------------------------------+
6624 //   SP   +---> | Back chain                                 | ---+
6625 //        |     +--------------------------------------------+    |
6626 //        |     | Saved Condition Register                   |    |
6627 //        |     +--------------------------------------------+    |
6628 //        |     | Saved Linkage Register                     |    |
6629 //        |     +--------------------------------------------+    | Linkage Area
6630 //        |     | Reserved for compilers                     |    |
6631 //        |     +--------------------------------------------+    |
6632 //        |     | Reserved for binders                       |    |
6633 //        |     +--------------------------------------------+    |
6634 //        |     | Saved TOC pointer                          | ---+
6635 //        |     +--------------------------------------------+
6636 //        |     | Parameter save area                        |
6637 //        |     +--------------------------------------------+
6638 //        |     | Alloca space                               |
6639 //        |     +--------------------------------------------+
6640 //        |     | Local variable space                       |
6641 //        |     +--------------------------------------------+
6642 //        |     | Float/int conversion temporary             |
6643 //        |     +--------------------------------------------+
6644 //        |     | Save area for AltiVec registers            |
6645 //        |     +--------------------------------------------+
6646 //        |     | AltiVec alignment padding                  |
6647 //        |     +--------------------------------------------+
6648 //        |     | Save area for VRSAVE register              |
6649 //        |     +--------------------------------------------+
6650 //        |     | Save area for General Purpose registers    |
6651 //        |     +--------------------------------------------+
6652 //        |     | Save area for Floating Point registers     |
6653 //        |     +--------------------------------------------+
6654 //        +---- | Back chain                                 |
6655 // High Memory  +--------------------------------------------+
6656 //
6657 //  Specifications:
6658 //  AIX 7.2 Assembler Language Reference
6659 //  Subroutine linkage convention
6660 
6661 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6662     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6663     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6664     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6665 
6666   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6667           CallConv == CallingConv::Fast) &&
6668          "Unexpected calling convention!");
6669 
6670   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6671     report_fatal_error("Tail call support is unimplemented on AIX.");
6672 
6673   if (useSoftFloat())
6674     report_fatal_error("Soft float support is unimplemented on AIX.");
6675 
6676   const PPCSubtarget &Subtarget =
6677       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6678 
6679   const bool IsPPC64 = Subtarget.isPPC64();
6680   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6681 
6682   // Assign locations to all of the incoming arguments.
6683   SmallVector<CCValAssign, 16> ArgLocs;
6684   MachineFunction &MF = DAG.getMachineFunction();
6685   MachineFrameInfo &MFI = MF.getFrameInfo();
6686   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6687   AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6688 
6689   const EVT PtrVT = getPointerTy(MF.getDataLayout());
6690   // Reserve space for the linkage area on the stack.
6691   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6692   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
6693   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6694 
6695   SmallVector<SDValue, 8> MemOps;
6696 
6697   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
6698     CCValAssign &VA = ArgLocs[I++];
6699     MVT LocVT = VA.getLocVT();
6700     MVT ValVT = VA.getValVT();
6701     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
6702     // For compatibility with the AIX XL compiler, the float args in the
6703     // parameter save area are initialized even if the argument is available
6704     // in register.  The caller is required to initialize both the register
6705     // and memory, however, the callee can choose to expect it in either.
6706     // The memloc is dismissed here because the argument is retrieved from
6707     // the register.
6708     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
6709       continue;
6710 
6711     auto HandleMemLoc = [&]() {
6712       const unsigned LocSize = LocVT.getStoreSize();
6713       const unsigned ValSize = ValVT.getStoreSize();
6714       assert((ValSize <= LocSize) &&
6715              "Object size is larger than size of MemLoc");
6716       int CurArgOffset = VA.getLocMemOffset();
6717       // Objects are right-justified because AIX is big-endian.
6718       if (LocSize > ValSize)
6719         CurArgOffset += LocSize - ValSize;
6720       // Potential tail calls could cause overwriting of argument stack slots.
6721       const bool IsImmutable =
6722           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
6723             (CallConv == CallingConv::Fast));
6724       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
6725       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6726       SDValue ArgValue =
6727           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
6728       InVals.push_back(ArgValue);
6729     };
6730 
6731     // Vector arguments to VaArg functions are passed both on the stack, and
6732     // in any available GPRs. Load the value from the stack and add the GPRs
6733     // as live ins.
6734     if (VA.isMemLoc() && VA.needsCustom()) {
6735       assert(ValVT.isVector() && "Unexpected Custom MemLoc type.");
6736       assert(isVarArg && "Only use custom memloc for vararg.");
6737       // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
6738       // matching custom RegLocs.
6739       const unsigned OriginalValNo = VA.getValNo();
6740       (void)OriginalValNo;
6741 
6742       auto HandleCustomVecRegLoc = [&]() {
6743         assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
6744                "Missing custom RegLoc.");
6745         VA = ArgLocs[I++];
6746         assert(VA.getValVT().isVector() &&
6747                "Unexpected Val type for custom RegLoc.");
6748         assert(VA.getValNo() == OriginalValNo &&
6749                "ValNo mismatch between custom MemLoc and RegLoc.");
6750         MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy;
6751         MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
6752       };
6753 
6754       HandleMemLoc();
6755       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
6756       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
6757       // R10.
6758       HandleCustomVecRegLoc();
6759       HandleCustomVecRegLoc();
6760 
6761       // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
6762       // we passed the vector in R5, R6, R7 and R8.
6763       if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
6764         assert(!IsPPC64 &&
6765                "Only 2 custom RegLocs expected for 64-bit codegen.");
6766         HandleCustomVecRegLoc();
6767         HandleCustomVecRegLoc();
6768       }
6769 
6770       continue;
6771     }
6772 
6773     if (VA.isRegLoc()) {
6774       if (VA.getValVT().isScalarInteger())
6775         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
6776       else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector())
6777         FuncInfo->appendParameterType(VA.getValVT().SimpleTy == MVT::f32
6778                                           ? PPCFunctionInfo::ShortFloatPoint
6779                                           : PPCFunctionInfo::LongFloatPoint);
6780     }
6781 
6782     if (Flags.isByVal() && VA.isMemLoc()) {
6783       const unsigned Size =
6784           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
6785                   PtrByteSize);
6786       const int FI = MF.getFrameInfo().CreateFixedObject(
6787           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
6788           /* IsAliased */ true);
6789       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6790       InVals.push_back(FIN);
6791 
6792       continue;
6793     }
6794 
6795     if (Flags.isByVal()) {
6796       assert(VA.isRegLoc() && "MemLocs should already be handled.");
6797 
6798       const MCPhysReg ArgReg = VA.getLocReg();
6799       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
6800 
6801       if (Flags.getNonZeroByValAlign() > PtrByteSize)
6802         report_fatal_error("Over aligned byvals not supported yet.");
6803 
6804       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
6805       const int FI = MF.getFrameInfo().CreateFixedObject(
6806           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
6807           /* IsAliased */ true);
6808       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6809       InVals.push_back(FIN);
6810 
6811       // Add live ins for all the RegLocs for the same ByVal.
6812       const TargetRegisterClass *RegClass =
6813           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6814 
6815       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
6816                                                unsigned Offset) {
6817         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
6818         // Since the callers side has left justified the aggregate in the
6819         // register, we can simply store the entire register into the stack
6820         // slot.
6821         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
6822         // The store to the fixedstack object is needed becuase accessing a
6823         // field of the ByVal will use a gep and load. Ideally we will optimize
6824         // to extracting the value from the register directly, and elide the
6825         // stores when the arguments address is not taken, but that will need to
6826         // be future work.
6827         SDValue Store = DAG.getStore(
6828             CopyFrom.getValue(1), dl, CopyFrom,
6829             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
6830             MachinePointerInfo::getFixedStack(MF, FI, Offset));
6831 
6832         MemOps.push_back(Store);
6833       };
6834 
6835       unsigned Offset = 0;
6836       HandleRegLoc(VA.getLocReg(), Offset);
6837       Offset += PtrByteSize;
6838       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
6839            Offset += PtrByteSize) {
6840         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
6841                "RegLocs should be for ByVal argument.");
6842 
6843         const CCValAssign RL = ArgLocs[I++];
6844         HandleRegLoc(RL.getLocReg(), Offset);
6845         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
6846       }
6847 
6848       if (Offset != StackSize) {
6849         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
6850                "Expected MemLoc for remaining bytes.");
6851         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
6852         // Consume the MemLoc.The InVal has already been emitted, so nothing
6853         // more needs to be done.
6854         ++I;
6855       }
6856 
6857       continue;
6858     }
6859 
6860     if (VA.isRegLoc() && !VA.needsCustom()) {
6861       MVT::SimpleValueType SVT = ValVT.SimpleTy;
6862       unsigned VReg =
6863           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
6864       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
6865       if (ValVT.isScalarInteger() &&
6866           (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
6867         ArgValue =
6868             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
6869       }
6870       InVals.push_back(ArgValue);
6871       continue;
6872     }
6873     if (VA.isMemLoc()) {
6874       HandleMemLoc();
6875       continue;
6876     }
6877   }
6878 
6879   // On AIX a minimum of 8 words is saved to the parameter save area.
6880   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
6881   // Area that is at least reserved in the caller of this function.
6882   unsigned CallerReservedArea =
6883       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
6884 
6885   // Set the size that is at least reserved in caller of this function. Tail
6886   // call optimized function's reserved stack space needs to be aligned so
6887   // that taking the difference between two stack areas will result in an
6888   // aligned stack.
6889   CallerReservedArea =
6890       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
6891   FuncInfo->setMinReservedArea(CallerReservedArea);
6892 
6893   if (isVarArg) {
6894     FuncInfo->setVarArgsFrameIndex(
6895         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
6896     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
6897 
6898     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6899                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6900 
6901     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6902                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6903     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
6904 
6905     // The fixed integer arguments of a variadic function are stored to the
6906     // VarArgsFrameIndex on the stack so that they may be loaded by
6907     // dereferencing the result of va_next.
6908     for (unsigned GPRIndex =
6909              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
6910          GPRIndex < NumGPArgRegs; ++GPRIndex) {
6911 
6912       const unsigned VReg =
6913           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
6914                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
6915 
6916       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
6917       SDValue Store =
6918           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
6919       MemOps.push_back(Store);
6920       // Increment the address for the next argument to store.
6921       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
6922       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
6923     }
6924   }
6925 
6926   if (!MemOps.empty())
6927     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
6928 
6929   return Chain;
6930 }
6931 
6932 SDValue PPCTargetLowering::LowerCall_AIX(
6933     SDValue Chain, SDValue Callee, CallFlags CFlags,
6934     const SmallVectorImpl<ISD::OutputArg> &Outs,
6935     const SmallVectorImpl<SDValue> &OutVals,
6936     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6937     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6938     const CallBase *CB) const {
6939   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
6940   // AIX ABI stack frame layout.
6941 
6942   assert((CFlags.CallConv == CallingConv::C ||
6943           CFlags.CallConv == CallingConv::Cold ||
6944           CFlags.CallConv == CallingConv::Fast) &&
6945          "Unexpected calling convention!");
6946 
6947   if (CFlags.IsPatchPoint)
6948     report_fatal_error("This call type is unimplemented on AIX.");
6949 
6950   const PPCSubtarget& Subtarget =
6951       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
6952 
6953   MachineFunction &MF = DAG.getMachineFunction();
6954   SmallVector<CCValAssign, 16> ArgLocs;
6955   AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
6956                     *DAG.getContext());
6957 
6958   // Reserve space for the linkage save area (LSA) on the stack.
6959   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
6960   //   [SP][CR][LR][2 x reserved][TOC].
6961   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
6962   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6963   const bool IsPPC64 = Subtarget.isPPC64();
6964   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
6965   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6966   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
6967   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
6968 
6969   // The prolog code of the callee may store up to 8 GPR argument registers to
6970   // the stack, allowing va_start to index over them in memory if the callee
6971   // is variadic.
6972   // Because we cannot tell if this is needed on the caller side, we have to
6973   // conservatively assume that it is needed.  As such, make sure we have at
6974   // least enough stack space for the caller to store the 8 GPRs.
6975   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
6976   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
6977                                      CCInfo.getNextStackOffset());
6978 
6979   // Adjust the stack pointer for the new arguments...
6980   // These operations are automatically eliminated by the prolog/epilog pass.
6981   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6982   SDValue CallSeqStart = Chain;
6983 
6984   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6985   SmallVector<SDValue, 8> MemOpChains;
6986 
6987   // Set up a copy of the stack pointer for loading and storing any
6988   // arguments that may not fit in the registers available for argument
6989   // passing.
6990   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
6991                                    : DAG.getRegister(PPC::R1, MVT::i32);
6992 
6993   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
6994     const unsigned ValNo = ArgLocs[I].getValNo();
6995     SDValue Arg = OutVals[ValNo];
6996     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
6997 
6998     if (Flags.isByVal()) {
6999       const unsigned ByValSize = Flags.getByValSize();
7000 
7001       // Nothing to do for zero-sized ByVals on the caller side.
7002       if (!ByValSize) {
7003         ++I;
7004         continue;
7005       }
7006 
7007       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7008         return DAG.getExtLoad(
7009             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7010             (LoadOffset != 0)
7011                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7012                 : Arg,
7013             MachinePointerInfo(), VT);
7014       };
7015 
7016       unsigned LoadOffset = 0;
7017 
7018       // Initialize registers, which are fully occupied by the by-val argument.
7019       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7020         SDValue Load = GetLoad(PtrVT, LoadOffset);
7021         MemOpChains.push_back(Load.getValue(1));
7022         LoadOffset += PtrByteSize;
7023         const CCValAssign &ByValVA = ArgLocs[I++];
7024         assert(ByValVA.getValNo() == ValNo &&
7025                "Unexpected location for pass-by-value argument.");
7026         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7027       }
7028 
7029       if (LoadOffset == ByValSize)
7030         continue;
7031 
7032       // There must be one more loc to handle the remainder.
7033       assert(ArgLocs[I].getValNo() == ValNo &&
7034              "Expected additional location for by-value argument.");
7035 
7036       if (ArgLocs[I].isMemLoc()) {
7037         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7038         const CCValAssign &ByValVA = ArgLocs[I++];
7039         ISD::ArgFlagsTy MemcpyFlags = Flags;
7040         // Only memcpy the bytes that don't pass in register.
7041         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7042         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7043             (LoadOffset != 0)
7044                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7045                 : Arg,
7046             DAG.getObjectPtrOffset(dl, StackPtr,
7047                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7048             CallSeqStart, MemcpyFlags, DAG, dl);
7049         continue;
7050       }
7051 
7052       // Initialize the final register residue.
7053       // Any residue that occupies the final by-val arg register must be
7054       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7055       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7056       // 2 and 1 byte loads.
7057       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7058       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7059              "Unexpected register residue for by-value argument.");
7060       SDValue ResidueVal;
7061       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7062         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7063         const MVT VT =
7064             N == 1 ? MVT::i8
7065                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7066         SDValue Load = GetLoad(VT, LoadOffset);
7067         MemOpChains.push_back(Load.getValue(1));
7068         LoadOffset += N;
7069         Bytes += N;
7070 
7071         // By-val arguments are passed left-justfied in register.
7072         // Every load here needs to be shifted, otherwise a full register load
7073         // should have been used.
7074         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7075                "Unexpected load emitted during handling of pass-by-value "
7076                "argument.");
7077         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7078         EVT ShiftAmountTy =
7079             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7080         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7081         SDValue ShiftedLoad =
7082             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7083         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7084                                               ShiftedLoad)
7085                                 : ShiftedLoad;
7086       }
7087 
7088       const CCValAssign &ByValVA = ArgLocs[I++];
7089       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7090       continue;
7091     }
7092 
7093     CCValAssign &VA = ArgLocs[I++];
7094     const MVT LocVT = VA.getLocVT();
7095     const MVT ValVT = VA.getValVT();
7096 
7097     switch (VA.getLocInfo()) {
7098     default:
7099       report_fatal_error("Unexpected argument extension type.");
7100     case CCValAssign::Full:
7101       break;
7102     case CCValAssign::ZExt:
7103       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7104       break;
7105     case CCValAssign::SExt:
7106       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7107       break;
7108     }
7109 
7110     if (VA.isRegLoc() && !VA.needsCustom()) {
7111       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7112       continue;
7113     }
7114 
7115     // Vector arguments passed to VarArg functions need custom handling when
7116     // they are passed (at least partially) in GPRs.
7117     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
7118       assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.");
7119       // Store value to its stack slot.
7120       SDValue PtrOff =
7121           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7122       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7123       SDValue Store =
7124           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
7125       MemOpChains.push_back(Store);
7126       const unsigned OriginalValNo = VA.getValNo();
7127       // Then load the GPRs from the stack
7128       unsigned LoadOffset = 0;
7129       auto HandleCustomVecRegLoc = [&]() {
7130         assert(I != E && "Unexpected end of CCvalAssigns.");
7131         assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7132                "Expected custom RegLoc.");
7133         CCValAssign RegVA = ArgLocs[I++];
7134         assert(RegVA.getValNo() == OriginalValNo &&
7135                "Custom MemLoc ValNo and custom RegLoc ValNo must match.");
7136         SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
7137                                   DAG.getConstant(LoadOffset, dl, PtrVT));
7138         SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
7139         MemOpChains.push_back(Load.getValue(1));
7140         RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
7141         LoadOffset += PtrByteSize;
7142       };
7143 
7144       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7145       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7146       // R10.
7147       HandleCustomVecRegLoc();
7148       HandleCustomVecRegLoc();
7149 
7150       if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7151           ArgLocs[I].getValNo() == OriginalValNo) {
7152         assert(!IsPPC64 &&
7153                "Only 2 custom RegLocs expected for 64-bit codegen.");
7154         HandleCustomVecRegLoc();
7155         HandleCustomVecRegLoc();
7156       }
7157 
7158       continue;
7159     }
7160 
7161     if (VA.isMemLoc()) {
7162       SDValue PtrOff =
7163           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7164       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7165       MemOpChains.push_back(
7166           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7167 
7168       continue;
7169     }
7170 
7171     if (!ValVT.isFloatingPoint())
7172       report_fatal_error(
7173           "Unexpected register handling for calling convention.");
7174 
7175     // Custom handling is used for GPR initializations for vararg float
7176     // arguments.
7177     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7178            LocVT.isInteger() &&
7179            "Custom register handling only expected for VarArg.");
7180 
7181     SDValue ArgAsInt =
7182         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7183 
7184     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7185       // f32 in 32-bit GPR
7186       // f64 in 64-bit GPR
7187       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7188     else if (Arg.getValueType().getFixedSizeInBits() <
7189              LocVT.getFixedSizeInBits())
7190       // f32 in 64-bit GPR.
7191       RegsToPass.push_back(std::make_pair(
7192           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7193     else {
7194       // f64 in two 32-bit GPRs
7195       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7196       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7197              "Unexpected custom register for argument!");
7198       CCValAssign &GPR1 = VA;
7199       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7200                                      DAG.getConstant(32, dl, MVT::i8));
7201       RegsToPass.push_back(std::make_pair(
7202           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7203 
7204       if (I != E) {
7205         // If only 1 GPR was available, there will only be one custom GPR and
7206         // the argument will also pass in memory.
7207         CCValAssign &PeekArg = ArgLocs[I];
7208         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7209           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7210           CCValAssign &GPR2 = ArgLocs[I++];
7211           RegsToPass.push_back(std::make_pair(
7212               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7213         }
7214       }
7215     }
7216   }
7217 
7218   if (!MemOpChains.empty())
7219     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7220 
7221   // For indirect calls, we need to save the TOC base to the stack for
7222   // restoration after the call.
7223   if (CFlags.IsIndirect) {
7224     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7225     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7226     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7227     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7228     const unsigned TOCSaveOffset =
7229         Subtarget.getFrameLowering()->getTOCSaveOffset();
7230 
7231     setUsesTOCBasePtr(DAG);
7232     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7233     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7234     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7235     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7236     Chain = DAG.getStore(
7237         Val.getValue(1), dl, Val, AddPtr,
7238         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7239   }
7240 
7241   // Build a sequence of copy-to-reg nodes chained together with token chain
7242   // and flag operands which copy the outgoing args into the appropriate regs.
7243   SDValue InFlag;
7244   for (auto Reg : RegsToPass) {
7245     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7246     InFlag = Chain.getValue(1);
7247   }
7248 
7249   const int SPDiff = 0;
7250   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7251                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7252 }
7253 
7254 bool
7255 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7256                                   MachineFunction &MF, bool isVarArg,
7257                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7258                                   LLVMContext &Context) const {
7259   SmallVector<CCValAssign, 16> RVLocs;
7260   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7261   return CCInfo.CheckReturn(
7262       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7263                 ? RetCC_PPC_Cold
7264                 : RetCC_PPC);
7265 }
7266 
7267 SDValue
7268 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7269                                bool isVarArg,
7270                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7271                                const SmallVectorImpl<SDValue> &OutVals,
7272                                const SDLoc &dl, SelectionDAG &DAG) const {
7273   SmallVector<CCValAssign, 16> RVLocs;
7274   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7275                  *DAG.getContext());
7276   CCInfo.AnalyzeReturn(Outs,
7277                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7278                            ? RetCC_PPC_Cold
7279                            : RetCC_PPC);
7280 
7281   SDValue Flag;
7282   SmallVector<SDValue, 4> RetOps(1, Chain);
7283 
7284   // Copy the result values into the output registers.
7285   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7286     CCValAssign &VA = RVLocs[i];
7287     assert(VA.isRegLoc() && "Can only return in registers!");
7288 
7289     SDValue Arg = OutVals[RealResIdx];
7290 
7291     switch (VA.getLocInfo()) {
7292     default: llvm_unreachable("Unknown loc info!");
7293     case CCValAssign::Full: break;
7294     case CCValAssign::AExt:
7295       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7296       break;
7297     case CCValAssign::ZExt:
7298       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7299       break;
7300     case CCValAssign::SExt:
7301       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7302       break;
7303     }
7304     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7305       bool isLittleEndian = Subtarget.isLittleEndian();
7306       // Legalize ret f64 -> ret 2 x i32.
7307       SDValue SVal =
7308           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7309                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7310       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7311       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7312       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7313                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7314       Flag = Chain.getValue(1);
7315       VA = RVLocs[++i]; // skip ahead to next loc
7316       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7317     } else
7318       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7319     Flag = Chain.getValue(1);
7320     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7321   }
7322 
7323   RetOps[0] = Chain;  // Update chain.
7324 
7325   // Add the flag if we have it.
7326   if (Flag.getNode())
7327     RetOps.push_back(Flag);
7328 
7329   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7330 }
7331 
7332 SDValue
7333 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7334                                                 SelectionDAG &DAG) const {
7335   SDLoc dl(Op);
7336 
7337   // Get the correct type for integers.
7338   EVT IntVT = Op.getValueType();
7339 
7340   // Get the inputs.
7341   SDValue Chain = Op.getOperand(0);
7342   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7343   // Build a DYNAREAOFFSET node.
7344   SDValue Ops[2] = {Chain, FPSIdx};
7345   SDVTList VTs = DAG.getVTList(IntVT);
7346   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7347 }
7348 
7349 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7350                                              SelectionDAG &DAG) const {
7351   // When we pop the dynamic allocation we need to restore the SP link.
7352   SDLoc dl(Op);
7353 
7354   // Get the correct type for pointers.
7355   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7356 
7357   // Construct the stack pointer operand.
7358   bool isPPC64 = Subtarget.isPPC64();
7359   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7360   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7361 
7362   // Get the operands for the STACKRESTORE.
7363   SDValue Chain = Op.getOperand(0);
7364   SDValue SaveSP = Op.getOperand(1);
7365 
7366   // Load the old link SP.
7367   SDValue LoadLinkSP =
7368       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7369 
7370   // Restore the stack pointer.
7371   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7372 
7373   // Store the old link SP.
7374   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7375 }
7376 
7377 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7378   MachineFunction &MF = DAG.getMachineFunction();
7379   bool isPPC64 = Subtarget.isPPC64();
7380   EVT PtrVT = getPointerTy(MF.getDataLayout());
7381 
7382   // Get current frame pointer save index.  The users of this index will be
7383   // primarily DYNALLOC instructions.
7384   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7385   int RASI = FI->getReturnAddrSaveIndex();
7386 
7387   // If the frame pointer save index hasn't been defined yet.
7388   if (!RASI) {
7389     // Find out what the fix offset of the frame pointer save area.
7390     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7391     // Allocate the frame index for frame pointer save area.
7392     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7393     // Save the result.
7394     FI->setReturnAddrSaveIndex(RASI);
7395   }
7396   return DAG.getFrameIndex(RASI, PtrVT);
7397 }
7398 
7399 SDValue
7400 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7401   MachineFunction &MF = DAG.getMachineFunction();
7402   bool isPPC64 = Subtarget.isPPC64();
7403   EVT PtrVT = getPointerTy(MF.getDataLayout());
7404 
7405   // Get current frame pointer save index.  The users of this index will be
7406   // primarily DYNALLOC instructions.
7407   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7408   int FPSI = FI->getFramePointerSaveIndex();
7409 
7410   // If the frame pointer save index hasn't been defined yet.
7411   if (!FPSI) {
7412     // Find out what the fix offset of the frame pointer save area.
7413     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7414     // Allocate the frame index for frame pointer save area.
7415     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7416     // Save the result.
7417     FI->setFramePointerSaveIndex(FPSI);
7418   }
7419   return DAG.getFrameIndex(FPSI, PtrVT);
7420 }
7421 
7422 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7423                                                    SelectionDAG &DAG) const {
7424   MachineFunction &MF = DAG.getMachineFunction();
7425   // Get the inputs.
7426   SDValue Chain = Op.getOperand(0);
7427   SDValue Size  = Op.getOperand(1);
7428   SDLoc dl(Op);
7429 
7430   // Get the correct type for pointers.
7431   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7432   // Negate the size.
7433   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7434                                 DAG.getConstant(0, dl, PtrVT), Size);
7435   // Construct a node for the frame pointer save index.
7436   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7437   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7438   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7439   if (hasInlineStackProbe(MF))
7440     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7441   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7442 }
7443 
7444 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7445                                                      SelectionDAG &DAG) const {
7446   MachineFunction &MF = DAG.getMachineFunction();
7447 
7448   bool isPPC64 = Subtarget.isPPC64();
7449   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7450 
7451   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7452   return DAG.getFrameIndex(FI, PtrVT);
7453 }
7454 
7455 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7456                                                SelectionDAG &DAG) const {
7457   SDLoc DL(Op);
7458   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7459                      DAG.getVTList(MVT::i32, MVT::Other),
7460                      Op.getOperand(0), Op.getOperand(1));
7461 }
7462 
7463 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7464                                                 SelectionDAG &DAG) const {
7465   SDLoc DL(Op);
7466   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7467                      Op.getOperand(0), Op.getOperand(1));
7468 }
7469 
7470 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7471   if (Op.getValueType().isVector())
7472     return LowerVectorLoad(Op, DAG);
7473 
7474   assert(Op.getValueType() == MVT::i1 &&
7475          "Custom lowering only for i1 loads");
7476 
7477   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7478 
7479   SDLoc dl(Op);
7480   LoadSDNode *LD = cast<LoadSDNode>(Op);
7481 
7482   SDValue Chain = LD->getChain();
7483   SDValue BasePtr = LD->getBasePtr();
7484   MachineMemOperand *MMO = LD->getMemOperand();
7485 
7486   SDValue NewLD =
7487       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7488                      BasePtr, MVT::i8, MMO);
7489   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7490 
7491   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7492   return DAG.getMergeValues(Ops, dl);
7493 }
7494 
7495 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7496   if (Op.getOperand(1).getValueType().isVector())
7497     return LowerVectorStore(Op, DAG);
7498 
7499   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7500          "Custom lowering only for i1 stores");
7501 
7502   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7503 
7504   SDLoc dl(Op);
7505   StoreSDNode *ST = cast<StoreSDNode>(Op);
7506 
7507   SDValue Chain = ST->getChain();
7508   SDValue BasePtr = ST->getBasePtr();
7509   SDValue Value = ST->getValue();
7510   MachineMemOperand *MMO = ST->getMemOperand();
7511 
7512   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7513                       Value);
7514   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7515 }
7516 
7517 // FIXME: Remove this once the ANDI glue bug is fixed:
7518 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7519   assert(Op.getValueType() == MVT::i1 &&
7520          "Custom lowering only for i1 results");
7521 
7522   SDLoc DL(Op);
7523   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7524 }
7525 
7526 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7527                                                SelectionDAG &DAG) const {
7528 
7529   // Implements a vector truncate that fits in a vector register as a shuffle.
7530   // We want to legalize vector truncates down to where the source fits in
7531   // a vector register (and target is therefore smaller than vector register
7532   // size).  At that point legalization will try to custom lower the sub-legal
7533   // result and get here - where we can contain the truncate as a single target
7534   // operation.
7535 
7536   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7537   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7538   //
7539   // We will implement it for big-endian ordering as this (where x denotes
7540   // undefined):
7541   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7542   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7543   //
7544   // The same operation in little-endian ordering will be:
7545   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7546   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7547 
7548   EVT TrgVT = Op.getValueType();
7549   assert(TrgVT.isVector() && "Vector type expected.");
7550   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7551   EVT EltVT = TrgVT.getVectorElementType();
7552   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
7553       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
7554       !isPowerOf2_32(EltVT.getSizeInBits()))
7555     return SDValue();
7556 
7557   SDValue N1 = Op.getOperand(0);
7558   EVT SrcVT = N1.getValueType();
7559   unsigned SrcSize = SrcVT.getSizeInBits();
7560   if (SrcSize > 256 ||
7561       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
7562       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
7563     return SDValue();
7564   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
7565     return SDValue();
7566 
7567   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7568   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7569 
7570   SDLoc DL(Op);
7571   SDValue Op1, Op2;
7572   if (SrcSize == 256) {
7573     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
7574     EVT SplitVT =
7575         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
7576     unsigned SplitNumElts = SplitVT.getVectorNumElements();
7577     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7578                       DAG.getConstant(0, DL, VecIdxTy));
7579     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7580                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
7581   }
7582   else {
7583     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7584     Op2 = DAG.getUNDEF(WideVT);
7585   }
7586 
7587   // First list the elements we want to keep.
7588   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7589   SmallVector<int, 16> ShuffV;
7590   if (Subtarget.isLittleEndian())
7591     for (unsigned i = 0; i < TrgNumElts; ++i)
7592       ShuffV.push_back(i * SizeMult);
7593   else
7594     for (unsigned i = 1; i <= TrgNumElts; ++i)
7595       ShuffV.push_back(i * SizeMult - 1);
7596 
7597   // Populate the remaining elements with undefs.
7598   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7599     // ShuffV.push_back(i + WideNumElts);
7600     ShuffV.push_back(WideNumElts + 1);
7601 
7602   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
7603   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
7604   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
7605 }
7606 
7607 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7608 /// possible.
7609 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7610   // Not FP, or using SPE? Not a fsel.
7611   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7612       !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE())
7613     return Op;
7614 
7615   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7616 
7617   EVT ResVT = Op.getValueType();
7618   EVT CmpVT = Op.getOperand(0).getValueType();
7619   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7620   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7621   SDLoc dl(Op);
7622   SDNodeFlags Flags = Op.getNode()->getFlags();
7623 
7624   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7625   // presence of infinities.
7626   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7627     switch (CC) {
7628     default:
7629       break;
7630     case ISD::SETOGT:
7631     case ISD::SETGT:
7632       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7633     case ISD::SETOLT:
7634     case ISD::SETLT:
7635       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7636     }
7637   }
7638 
7639   // We might be able to do better than this under some circumstances, but in
7640   // general, fsel-based lowering of select is a finite-math-only optimization.
7641   // For more information, see section F.3 of the 2.06 ISA specification.
7642   // With ISA 3.0
7643   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7644       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7645     return Op;
7646 
7647   // If the RHS of the comparison is a 0.0, we don't need to do the
7648   // subtraction at all.
7649   SDValue Sel1;
7650   if (isFloatingPointZero(RHS))
7651     switch (CC) {
7652     default: break;       // SETUO etc aren't handled by fsel.
7653     case ISD::SETNE:
7654       std::swap(TV, FV);
7655       LLVM_FALLTHROUGH;
7656     case ISD::SETEQ:
7657       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7658         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7659       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7660       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7661         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7662       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7663                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7664     case ISD::SETULT:
7665     case ISD::SETLT:
7666       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7667       LLVM_FALLTHROUGH;
7668     case ISD::SETOGE:
7669     case ISD::SETGE:
7670       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7671         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7672       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7673     case ISD::SETUGT:
7674     case ISD::SETGT:
7675       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7676       LLVM_FALLTHROUGH;
7677     case ISD::SETOLE:
7678     case ISD::SETLE:
7679       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7680         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7681       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7682                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7683     }
7684 
7685   SDValue Cmp;
7686   switch (CC) {
7687   default: break;       // SETUO etc aren't handled by fsel.
7688   case ISD::SETNE:
7689     std::swap(TV, FV);
7690     LLVM_FALLTHROUGH;
7691   case ISD::SETEQ:
7692     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7693     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7694       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7695     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7696     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7697       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7698     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7699                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7700   case ISD::SETULT:
7701   case ISD::SETLT:
7702     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7703     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7704       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7705     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7706   case ISD::SETOGE:
7707   case ISD::SETGE:
7708     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7709     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7710       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7711     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7712   case ISD::SETUGT:
7713   case ISD::SETGT:
7714     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7715     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7716       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7717     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7718   case ISD::SETOLE:
7719   case ISD::SETLE:
7720     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7721     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7722       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7723     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7724   }
7725   return Op;
7726 }
7727 
7728 static unsigned getPPCStrictOpcode(unsigned Opc) {
7729   switch (Opc) {
7730   default:
7731     llvm_unreachable("No strict version of this opcode!");
7732   case PPCISD::FCTIDZ:
7733     return PPCISD::STRICT_FCTIDZ;
7734   case PPCISD::FCTIWZ:
7735     return PPCISD::STRICT_FCTIWZ;
7736   case PPCISD::FCTIDUZ:
7737     return PPCISD::STRICT_FCTIDUZ;
7738   case PPCISD::FCTIWUZ:
7739     return PPCISD::STRICT_FCTIWUZ;
7740   case PPCISD::FCFID:
7741     return PPCISD::STRICT_FCFID;
7742   case PPCISD::FCFIDU:
7743     return PPCISD::STRICT_FCFIDU;
7744   case PPCISD::FCFIDS:
7745     return PPCISD::STRICT_FCFIDS;
7746   case PPCISD::FCFIDUS:
7747     return PPCISD::STRICT_FCFIDUS;
7748   }
7749 }
7750 
7751 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
7752                               const PPCSubtarget &Subtarget) {
7753   SDLoc dl(Op);
7754   bool IsStrict = Op->isStrictFPOpcode();
7755   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
7756                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
7757 
7758   // TODO: Any other flags to propagate?
7759   SDNodeFlags Flags;
7760   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
7761 
7762   // For strict nodes, source is the second operand.
7763   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
7764   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
7765   assert(Src.getValueType().isFloatingPoint());
7766   if (Src.getValueType() == MVT::f32) {
7767     if (IsStrict) {
7768       Src =
7769           DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
7770                       DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
7771       Chain = Src.getValue(1);
7772     } else
7773       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7774   }
7775   SDValue Conv;
7776   unsigned Opc = ISD::DELETED_NODE;
7777   switch (Op.getSimpleValueType().SimpleTy) {
7778   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7779   case MVT::i32:
7780     Opc = IsSigned ? PPCISD::FCTIWZ
7781                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
7782     break;
7783   case MVT::i64:
7784     assert((IsSigned || Subtarget.hasFPCVT()) &&
7785            "i64 FP_TO_UINT is supported only with FPCVT");
7786     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
7787   }
7788   if (IsStrict) {
7789     Opc = getPPCStrictOpcode(Opc);
7790     Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
7791                        {Chain, Src}, Flags);
7792   } else {
7793     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
7794   }
7795   return Conv;
7796 }
7797 
7798 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7799                                                SelectionDAG &DAG,
7800                                                const SDLoc &dl) const {
7801   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
7802   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
7803                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
7804   bool IsStrict = Op->isStrictFPOpcode();
7805 
7806   // Convert the FP value to an int value through memory.
7807   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7808                   (IsSigned || Subtarget.hasFPCVT());
7809   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7810   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7811   MachinePointerInfo MPI =
7812       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7813 
7814   // Emit a store to the stack slot.
7815   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
7816   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
7817   if (i32Stack) {
7818     MachineFunction &MF = DAG.getMachineFunction();
7819     Alignment = Align(4);
7820     MachineMemOperand *MMO =
7821         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
7822     SDValue Ops[] = { Chain, Tmp, FIPtr };
7823     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7824               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7825   } else
7826     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
7827 
7828   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7829   // add in a bias on big endian.
7830   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7831     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7832                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7833     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7834   }
7835 
7836   RLI.Chain = Chain;
7837   RLI.Ptr = FIPtr;
7838   RLI.MPI = MPI;
7839   RLI.Alignment = Alignment;
7840 }
7841 
7842 /// Custom lowers floating point to integer conversions to use
7843 /// the direct move instructions available in ISA 2.07 to avoid the
7844 /// need for load/store combinations.
7845 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7846                                                     SelectionDAG &DAG,
7847                                                     const SDLoc &dl) const {
7848   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
7849   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
7850   if (Op->isStrictFPOpcode())
7851     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
7852   else
7853     return Mov;
7854 }
7855 
7856 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7857                                           const SDLoc &dl) const {
7858   bool IsStrict = Op->isStrictFPOpcode();
7859   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
7860                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
7861   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
7862   EVT SrcVT = Src.getValueType();
7863   EVT DstVT = Op.getValueType();
7864 
7865   // FP to INT conversions are legal for f128.
7866   if (SrcVT == MVT::f128)
7867     return Subtarget.hasP9Vector() ? Op : SDValue();
7868 
7869   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7870   // PPC (the libcall is not available).
7871   if (SrcVT == MVT::ppcf128) {
7872     if (DstVT == MVT::i32) {
7873       // TODO: Conservatively pass only nofpexcept flag here. Need to check and
7874       // set other fast-math flags to FP operations in both strict and
7875       // non-strict cases. (FP_TO_SINT, FSUB)
7876       SDNodeFlags Flags;
7877       Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
7878 
7879       if (IsSigned) {
7880         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
7881                                  DAG.getIntPtrConstant(0, dl));
7882         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
7883                                  DAG.getIntPtrConstant(1, dl));
7884 
7885         // Add the two halves of the long double in round-to-zero mode, and use
7886         // a smaller FP_TO_SINT.
7887         if (IsStrict) {
7888           SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
7889                                     DAG.getVTList(MVT::f64, MVT::Other),
7890                                     {Op.getOperand(0), Lo, Hi}, Flags);
7891           return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
7892                              DAG.getVTList(MVT::i32, MVT::Other),
7893                              {Res.getValue(1), Res}, Flags);
7894         } else {
7895           SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7896           return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7897         }
7898       } else {
7899         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7900         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7901         SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
7902         SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
7903         if (IsStrict) {
7904           // Sel = Src < 0x80000000
7905           // FltOfs = select Sel, 0.0, 0x80000000
7906           // IntOfs = select Sel, 0, 0x80000000
7907           // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
7908           SDValue Chain = Op.getOperand(0);
7909           EVT SetCCVT =
7910               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
7911           EVT DstSetCCVT =
7912               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
7913           SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
7914                                      Chain, true);
7915           Chain = Sel.getValue(1);
7916 
7917           SDValue FltOfs = DAG.getSelect(
7918               dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
7919           Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
7920 
7921           SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
7922                                     DAG.getVTList(SrcVT, MVT::Other),
7923                                     {Chain, Src, FltOfs}, Flags);
7924           Chain = Val.getValue(1);
7925           SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
7926                                      DAG.getVTList(DstVT, MVT::Other),
7927                                      {Chain, Val}, Flags);
7928           Chain = SInt.getValue(1);
7929           SDValue IntOfs = DAG.getSelect(
7930               dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
7931           SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
7932           return DAG.getMergeValues({Result, Chain}, dl);
7933         } else {
7934           // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7935           // FIXME: generated code sucks.
7936           SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
7937           True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7938           True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
7939           SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
7940           return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
7941         }
7942       }
7943     }
7944 
7945     return SDValue();
7946   }
7947 
7948   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
7949     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
7950 
7951   ReuseLoadInfo RLI;
7952   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7953 
7954   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7955                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7956 }
7957 
7958 // We're trying to insert a regular store, S, and then a load, L. If the
7959 // incoming value, O, is a load, we might just be able to have our load use the
7960 // address used by O. However, we don't know if anything else will store to
7961 // that address before we can load from it. To prevent this situation, we need
7962 // to insert our load, L, into the chain as a peer of O. To do this, we give L
7963 // the same chain operand as O, we create a token factor from the chain results
7964 // of O and L, and we replace all uses of O's chain result with that token
7965 // factor (see spliceIntoChain below for this last part).
7966 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
7967                                             ReuseLoadInfo &RLI,
7968                                             SelectionDAG &DAG,
7969                                             ISD::LoadExtType ET) const {
7970   // Conservatively skip reusing for constrained FP nodes.
7971   if (Op->isStrictFPOpcode())
7972     return false;
7973 
7974   SDLoc dl(Op);
7975   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
7976                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
7977   if (ET == ISD::NON_EXTLOAD &&
7978       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
7979       isOperationLegalOrCustom(Op.getOpcode(),
7980                                Op.getOperand(0).getValueType())) {
7981 
7982     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7983     return true;
7984   }
7985 
7986   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
7987   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
7988       LD->isNonTemporal())
7989     return false;
7990   if (LD->getMemoryVT() != MemVT)
7991     return false;
7992 
7993   // If the result of the load is an illegal type, then we can't build a
7994   // valid chain for reuse since the legalised loads and token factor node that
7995   // ties the legalised loads together uses a different output chain then the
7996   // illegal load.
7997   if (!isTypeLegal(LD->getValueType(0)))
7998     return false;
7999 
8000   RLI.Ptr = LD->getBasePtr();
8001   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8002     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8003            "Non-pre-inc AM on PPC?");
8004     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8005                           LD->getOffset());
8006   }
8007 
8008   RLI.Chain = LD->getChain();
8009   RLI.MPI = LD->getPointerInfo();
8010   RLI.IsDereferenceable = LD->isDereferenceable();
8011   RLI.IsInvariant = LD->isInvariant();
8012   RLI.Alignment = LD->getAlign();
8013   RLI.AAInfo = LD->getAAInfo();
8014   RLI.Ranges = LD->getRanges();
8015 
8016   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8017   return true;
8018 }
8019 
8020 // Given the head of the old chain, ResChain, insert a token factor containing
8021 // it and NewResChain, and make users of ResChain now be users of that token
8022 // factor.
8023 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8024 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8025                                         SDValue NewResChain,
8026                                         SelectionDAG &DAG) const {
8027   if (!ResChain)
8028     return;
8029 
8030   SDLoc dl(NewResChain);
8031 
8032   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8033                            NewResChain, DAG.getUNDEF(MVT::Other));
8034   assert(TF.getNode() != NewResChain.getNode() &&
8035          "A new TF really is required here");
8036 
8037   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8038   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8039 }
8040 
8041 /// Analyze profitability of direct move
8042 /// prefer float load to int load plus direct move
8043 /// when there is no integer use of int load
8044 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8045   SDNode *Origin = Op.getOperand(0).getNode();
8046   if (Origin->getOpcode() != ISD::LOAD)
8047     return true;
8048 
8049   // If there is no LXSIBZX/LXSIHZX, like Power8,
8050   // prefer direct move if the memory size is 1 or 2 bytes.
8051   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8052   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8053     return true;
8054 
8055   for (SDNode::use_iterator UI = Origin->use_begin(),
8056                             UE = Origin->use_end();
8057        UI != UE; ++UI) {
8058 
8059     // Only look at the users of the loaded value.
8060     if (UI.getUse().get().getResNo() != 0)
8061       continue;
8062 
8063     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8064         UI->getOpcode() != ISD::UINT_TO_FP &&
8065         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8066         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8067       return true;
8068   }
8069 
8070   return false;
8071 }
8072 
8073 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8074                               const PPCSubtarget &Subtarget,
8075                               SDValue Chain = SDValue()) {
8076   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8077                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8078   SDLoc dl(Op);
8079 
8080   // TODO: Any other flags to propagate?
8081   SDNodeFlags Flags;
8082   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8083 
8084   // If we have FCFIDS, then use it when converting to single-precision.
8085   // Otherwise, convert to double-precision and then round.
8086   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8087   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8088                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8089   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8090   if (Op->isStrictFPOpcode()) {
8091     if (!Chain)
8092       Chain = Op.getOperand(0);
8093     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8094                        DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8095   } else
8096     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8097 }
8098 
8099 /// Custom lowers integer to floating point conversions to use
8100 /// the direct move instructions available in ISA 2.07 to avoid the
8101 /// need for load/store combinations.
8102 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8103                                                     SelectionDAG &DAG,
8104                                                     const SDLoc &dl) const {
8105   assert((Op.getValueType() == MVT::f32 ||
8106           Op.getValueType() == MVT::f64) &&
8107          "Invalid floating point type as target of conversion");
8108   assert(Subtarget.hasFPCVT() &&
8109          "Int to FP conversions with direct moves require FPCVT");
8110   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8111   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8112   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8113                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8114   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8115   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8116   return convertIntToFP(Op, Mov, DAG, Subtarget);
8117 }
8118 
8119 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8120 
8121   EVT VecVT = Vec.getValueType();
8122   assert(VecVT.isVector() && "Expected a vector type.");
8123   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8124 
8125   EVT EltVT = VecVT.getVectorElementType();
8126   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8127   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8128 
8129   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8130   SmallVector<SDValue, 16> Ops(NumConcat);
8131   Ops[0] = Vec;
8132   SDValue UndefVec = DAG.getUNDEF(VecVT);
8133   for (unsigned i = 1; i < NumConcat; ++i)
8134     Ops[i] = UndefVec;
8135 
8136   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8137 }
8138 
8139 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8140                                                 const SDLoc &dl) const {
8141   bool IsStrict = Op->isStrictFPOpcode();
8142   unsigned Opc = Op.getOpcode();
8143   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8144   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8145           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8146          "Unexpected conversion type");
8147   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8148          "Supports conversions to v2f64/v4f32 only.");
8149 
8150   // TODO: Any other flags to propagate?
8151   SDNodeFlags Flags;
8152   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8153 
8154   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8155   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8156 
8157   SDValue Wide = widenVec(DAG, Src, dl);
8158   EVT WideVT = Wide.getValueType();
8159   unsigned WideNumElts = WideVT.getVectorNumElements();
8160   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8161 
8162   SmallVector<int, 16> ShuffV;
8163   for (unsigned i = 0; i < WideNumElts; ++i)
8164     ShuffV.push_back(i + WideNumElts);
8165 
8166   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8167   int SaveElts = FourEltRes ? 4 : 2;
8168   if (Subtarget.isLittleEndian())
8169     for (int i = 0; i < SaveElts; i++)
8170       ShuffV[i * Stride] = i;
8171   else
8172     for (int i = 1; i <= SaveElts; i++)
8173       ShuffV[i * Stride - 1] = i - 1;
8174 
8175   SDValue ShuffleSrc2 =
8176       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8177   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8178 
8179   SDValue Extend;
8180   if (SignedConv) {
8181     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8182     EVT ExtVT = Src.getValueType();
8183     if (Subtarget.hasP9Altivec())
8184       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8185                                IntermediateVT.getVectorNumElements());
8186 
8187     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8188                          DAG.getValueType(ExtVT));
8189   } else
8190     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8191 
8192   if (IsStrict)
8193     return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8194                        {Op.getOperand(0), Extend}, Flags);
8195 
8196   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8197 }
8198 
8199 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8200                                           SelectionDAG &DAG) const {
8201   SDLoc dl(Op);
8202   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8203                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8204   bool IsStrict = Op->isStrictFPOpcode();
8205   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8206   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8207 
8208   // TODO: Any other flags to propagate?
8209   SDNodeFlags Flags;
8210   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8211 
8212   EVT InVT = Src.getValueType();
8213   EVT OutVT = Op.getValueType();
8214   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8215       isOperationCustom(Op.getOpcode(), InVT))
8216     return LowerINT_TO_FPVector(Op, DAG, dl);
8217 
8218   // Conversions to f128 are legal.
8219   if (Op.getValueType() == MVT::f128)
8220     return Subtarget.hasP9Vector() ? Op : SDValue();
8221 
8222   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8223   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8224     return SDValue();
8225 
8226   if (Src.getValueType() == MVT::i1) {
8227     SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8228                               DAG.getConstantFP(1.0, dl, Op.getValueType()),
8229                               DAG.getConstantFP(0.0, dl, Op.getValueType()));
8230     if (IsStrict)
8231       return DAG.getMergeValues({Sel, Chain}, dl);
8232     else
8233       return Sel;
8234   }
8235 
8236   // If we have direct moves, we can do all the conversion, skip the store/load
8237   // however, without FPCVT we can't do most conversions.
8238   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8239       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8240     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8241 
8242   assert((IsSigned || Subtarget.hasFPCVT()) &&
8243          "UINT_TO_FP is supported only with FPCVT");
8244 
8245   if (Src.getValueType() == MVT::i64) {
8246     SDValue SINT = Src;
8247     // When converting to single-precision, we actually need to convert
8248     // to double-precision first and then round to single-precision.
8249     // To avoid double-rounding effects during that operation, we have
8250     // to prepare the input operand.  Bits that might be truncated when
8251     // converting to double-precision are replaced by a bit that won't
8252     // be lost at this stage, but is below the single-precision rounding
8253     // position.
8254     //
8255     // However, if -enable-unsafe-fp-math is in effect, accept double
8256     // rounding to avoid the extra overhead.
8257     if (Op.getValueType() == MVT::f32 &&
8258         !Subtarget.hasFPCVT() &&
8259         !DAG.getTarget().Options.UnsafeFPMath) {
8260 
8261       // Twiddle input to make sure the low 11 bits are zero.  (If this
8262       // is the case, we are guaranteed the value will fit into the 53 bit
8263       // mantissa of an IEEE double-precision value without rounding.)
8264       // If any of those low 11 bits were not zero originally, make sure
8265       // bit 12 (value 2048) is set instead, so that the final rounding
8266       // to single-precision gets the correct result.
8267       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8268                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8269       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8270                           Round, DAG.getConstant(2047, dl, MVT::i64));
8271       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8272       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8273                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8274 
8275       // However, we cannot use that value unconditionally: if the magnitude
8276       // of the input value is small, the bit-twiddling we did above might
8277       // end up visibly changing the output.  Fortunately, in that case, we
8278       // don't need to twiddle bits since the original input will convert
8279       // exactly to double-precision floating-point already.  Therefore,
8280       // construct a conditional to use the original value if the top 11
8281       // bits are all sign-bit copies, and use the rounded value computed
8282       // above otherwise.
8283       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8284                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8285       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8286                          Cond, DAG.getConstant(1, dl, MVT::i64));
8287       Cond = DAG.getSetCC(
8288           dl,
8289           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8290           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8291 
8292       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8293     }
8294 
8295     ReuseLoadInfo RLI;
8296     SDValue Bits;
8297 
8298     MachineFunction &MF = DAG.getMachineFunction();
8299     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8300       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8301                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8302       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8303     } else if (Subtarget.hasLFIWAX() &&
8304                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8305       MachineMemOperand *MMO =
8306         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8307                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8308       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8309       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8310                                      DAG.getVTList(MVT::f64, MVT::Other),
8311                                      Ops, MVT::i32, MMO);
8312       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8313     } else if (Subtarget.hasFPCVT() &&
8314                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8315       MachineMemOperand *MMO =
8316         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8317                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8318       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8319       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8320                                      DAG.getVTList(MVT::f64, MVT::Other),
8321                                      Ops, MVT::i32, MMO);
8322       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8323     } else if (((Subtarget.hasLFIWAX() &&
8324                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8325                 (Subtarget.hasFPCVT() &&
8326                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8327                SINT.getOperand(0).getValueType() == MVT::i32) {
8328       MachineFrameInfo &MFI = MF.getFrameInfo();
8329       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8330 
8331       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8332       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8333 
8334       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8335                                    MachinePointerInfo::getFixedStack(
8336                                        DAG.getMachineFunction(), FrameIdx));
8337       Chain = Store;
8338 
8339       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8340              "Expected an i32 store");
8341 
8342       RLI.Ptr = FIdx;
8343       RLI.Chain = Chain;
8344       RLI.MPI =
8345           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8346       RLI.Alignment = Align(4);
8347 
8348       MachineMemOperand *MMO =
8349         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8350                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8351       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8352       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8353                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8354                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8355                                      Ops, MVT::i32, MMO);
8356       Chain = Bits.getValue(1);
8357     } else
8358       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8359 
8360     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8361     if (IsStrict)
8362       Chain = FP.getValue(1);
8363 
8364     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8365       if (IsStrict)
8366         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8367                          DAG.getVTList(MVT::f32, MVT::Other),
8368                          {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8369       else
8370         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8371                          DAG.getIntPtrConstant(0, dl));
8372     }
8373     return FP;
8374   }
8375 
8376   assert(Src.getValueType() == MVT::i32 &&
8377          "Unhandled INT_TO_FP type in custom expander!");
8378   // Since we only generate this in 64-bit mode, we can take advantage of
8379   // 64-bit registers.  In particular, sign extend the input value into the
8380   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8381   // then lfd it and fcfid it.
8382   MachineFunction &MF = DAG.getMachineFunction();
8383   MachineFrameInfo &MFI = MF.getFrameInfo();
8384   EVT PtrVT = getPointerTy(MF.getDataLayout());
8385 
8386   SDValue Ld;
8387   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8388     ReuseLoadInfo RLI;
8389     bool ReusingLoad;
8390     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8391       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8392       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8393 
8394       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8395                                    MachinePointerInfo::getFixedStack(
8396                                        DAG.getMachineFunction(), FrameIdx));
8397       Chain = Store;
8398 
8399       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8400              "Expected an i32 store");
8401 
8402       RLI.Ptr = FIdx;
8403       RLI.Chain = Chain;
8404       RLI.MPI =
8405           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8406       RLI.Alignment = Align(4);
8407     }
8408 
8409     MachineMemOperand *MMO =
8410       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8411                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8412     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8413     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8414                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8415                                  MVT::i32, MMO);
8416     Chain = Ld.getValue(1);
8417     if (ReusingLoad)
8418       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8419   } else {
8420     assert(Subtarget.isPPC64() &&
8421            "i32->FP without LFIWAX supported only on PPC64");
8422 
8423     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8424     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8425 
8426     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8427 
8428     // STD the extended value into the stack slot.
8429     SDValue Store = DAG.getStore(
8430         Chain, dl, Ext64, FIdx,
8431         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8432     Chain = Store;
8433 
8434     // Load the value as a double.
8435     Ld = DAG.getLoad(
8436         MVT::f64, dl, Chain, FIdx,
8437         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8438     Chain = Ld.getValue(1);
8439   }
8440 
8441   // FCFID it and return it.
8442   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8443   if (IsStrict)
8444     Chain = FP.getValue(1);
8445   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8446     if (IsStrict)
8447       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8448                        DAG.getVTList(MVT::f32, MVT::Other),
8449                        {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8450     else
8451       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8452                        DAG.getIntPtrConstant(0, dl));
8453   }
8454   return FP;
8455 }
8456 
8457 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8458                                             SelectionDAG &DAG) const {
8459   SDLoc dl(Op);
8460   /*
8461    The rounding mode is in bits 30:31 of FPSR, and has the following
8462    settings:
8463      00 Round to nearest
8464      01 Round to 0
8465      10 Round to +inf
8466      11 Round to -inf
8467 
8468   FLT_ROUNDS, on the other hand, expects the following:
8469     -1 Undefined
8470      0 Round to 0
8471      1 Round to nearest
8472      2 Round to +inf
8473      3 Round to -inf
8474 
8475   To perform the conversion, we do:
8476     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8477   */
8478 
8479   MachineFunction &MF = DAG.getMachineFunction();
8480   EVT VT = Op.getValueType();
8481   EVT PtrVT = getPointerTy(MF.getDataLayout());
8482 
8483   // Save FP Control Word to register
8484   SDValue Chain = Op.getOperand(0);
8485   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8486   Chain = MFFS.getValue(1);
8487 
8488   SDValue CWD;
8489   if (isTypeLegal(MVT::i64)) {
8490     CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
8491                       DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
8492   } else {
8493     // Save FP register to stack slot
8494     int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8495     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8496     Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8497 
8498     // Load FP Control Word from low 32 bits of stack slot.
8499     assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) &&
8500            "Stack slot adjustment is valid only on big endian subtargets!");
8501     SDValue Four = DAG.getConstant(4, dl, PtrVT);
8502     SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8503     CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8504     Chain = CWD.getValue(1);
8505   }
8506 
8507   // Transform as necessary
8508   SDValue CWD1 =
8509     DAG.getNode(ISD::AND, dl, MVT::i32,
8510                 CWD, DAG.getConstant(3, dl, MVT::i32));
8511   SDValue CWD2 =
8512     DAG.getNode(ISD::SRL, dl, MVT::i32,
8513                 DAG.getNode(ISD::AND, dl, MVT::i32,
8514                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8515                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8516                             DAG.getConstant(3, dl, MVT::i32)),
8517                 DAG.getConstant(1, dl, MVT::i32));
8518 
8519   SDValue RetVal =
8520     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8521 
8522   RetVal =
8523       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8524                   dl, VT, RetVal);
8525 
8526   return DAG.getMergeValues({RetVal, Chain}, dl);
8527 }
8528 
8529 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8530   EVT VT = Op.getValueType();
8531   unsigned BitWidth = VT.getSizeInBits();
8532   SDLoc dl(Op);
8533   assert(Op.getNumOperands() == 3 &&
8534          VT == Op.getOperand(1).getValueType() &&
8535          "Unexpected SHL!");
8536 
8537   // Expand into a bunch of logical ops.  Note that these ops
8538   // depend on the PPC behavior for oversized shift amounts.
8539   SDValue Lo = Op.getOperand(0);
8540   SDValue Hi = Op.getOperand(1);
8541   SDValue Amt = Op.getOperand(2);
8542   EVT AmtVT = Amt.getValueType();
8543 
8544   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8545                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8546   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8547   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8548   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8549   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8550                              DAG.getConstant(-BitWidth, dl, AmtVT));
8551   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8552   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8553   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8554   SDValue OutOps[] = { OutLo, OutHi };
8555   return DAG.getMergeValues(OutOps, dl);
8556 }
8557 
8558 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8559   EVT VT = Op.getValueType();
8560   SDLoc dl(Op);
8561   unsigned BitWidth = VT.getSizeInBits();
8562   assert(Op.getNumOperands() == 3 &&
8563          VT == Op.getOperand(1).getValueType() &&
8564          "Unexpected SRL!");
8565 
8566   // Expand into a bunch of logical ops.  Note that these ops
8567   // depend on the PPC behavior for oversized shift amounts.
8568   SDValue Lo = Op.getOperand(0);
8569   SDValue Hi = Op.getOperand(1);
8570   SDValue Amt = Op.getOperand(2);
8571   EVT AmtVT = Amt.getValueType();
8572 
8573   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8574                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8575   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8576   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8577   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8578   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8579                              DAG.getConstant(-BitWidth, dl, AmtVT));
8580   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8581   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8582   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8583   SDValue OutOps[] = { OutLo, OutHi };
8584   return DAG.getMergeValues(OutOps, dl);
8585 }
8586 
8587 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8588   SDLoc dl(Op);
8589   EVT VT = Op.getValueType();
8590   unsigned BitWidth = VT.getSizeInBits();
8591   assert(Op.getNumOperands() == 3 &&
8592          VT == Op.getOperand(1).getValueType() &&
8593          "Unexpected SRA!");
8594 
8595   // Expand into a bunch of logical ops, followed by a select_cc.
8596   SDValue Lo = Op.getOperand(0);
8597   SDValue Hi = Op.getOperand(1);
8598   SDValue Amt = Op.getOperand(2);
8599   EVT AmtVT = Amt.getValueType();
8600 
8601   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8602                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8603   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8604   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8605   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8606   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8607                              DAG.getConstant(-BitWidth, dl, AmtVT));
8608   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8609   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8610   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8611                                   Tmp4, Tmp6, ISD::SETLE);
8612   SDValue OutOps[] = { OutLo, OutHi };
8613   return DAG.getMergeValues(OutOps, dl);
8614 }
8615 
8616 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8617                                             SelectionDAG &DAG) const {
8618   SDLoc dl(Op);
8619   EVT VT = Op.getValueType();
8620   unsigned BitWidth = VT.getSizeInBits();
8621 
8622   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8623   SDValue X = Op.getOperand(0);
8624   SDValue Y = Op.getOperand(1);
8625   SDValue Z = Op.getOperand(2);
8626   EVT AmtVT = Z.getValueType();
8627 
8628   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8629   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8630   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8631   // on PowerPC shift by BW being well defined.
8632   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8633                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8634   SDValue SubZ =
8635       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8636   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8637   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8638   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8639 }
8640 
8641 //===----------------------------------------------------------------------===//
8642 // Vector related lowering.
8643 //
8644 
8645 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8646 /// element size of SplatSize. Cast the result to VT.
8647 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8648                                       SelectionDAG &DAG, const SDLoc &dl) {
8649   static const MVT VTys[] = { // canonical VT to use for each size.
8650     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8651   };
8652 
8653   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8654 
8655   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8656   if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
8657     SplatSize = 1;
8658     Val = 0xFF;
8659   }
8660 
8661   EVT CanonicalVT = VTys[SplatSize-1];
8662 
8663   // Build a canonical splat for this value.
8664   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8665 }
8666 
8667 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8668 /// specified intrinsic ID.
8669 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8670                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8671   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8672   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8673                      DAG.getConstant(IID, dl, MVT::i32), Op);
8674 }
8675 
8676 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8677 /// specified intrinsic ID.
8678 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8679                                 SelectionDAG &DAG, const SDLoc &dl,
8680                                 EVT DestVT = MVT::Other) {
8681   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8682   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8683                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8684 }
8685 
8686 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8687 /// specified intrinsic ID.
8688 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8689                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8690                                 EVT DestVT = MVT::Other) {
8691   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8692   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8693                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8694 }
8695 
8696 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8697 /// amount.  The result has the specified value type.
8698 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8699                            SelectionDAG &DAG, const SDLoc &dl) {
8700   // Force LHS/RHS to be the right type.
8701   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8702   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8703 
8704   int Ops[16];
8705   for (unsigned i = 0; i != 16; ++i)
8706     Ops[i] = i + Amt;
8707   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8708   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8709 }
8710 
8711 /// Do we have an efficient pattern in a .td file for this node?
8712 ///
8713 /// \param V - pointer to the BuildVectorSDNode being matched
8714 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8715 ///
8716 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8717 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8718 /// the opposite is true (expansion is beneficial) are:
8719 /// - The node builds a vector out of integers that are not 32 or 64-bits
8720 /// - The node builds a vector out of constants
8721 /// - The node is a "load-and-splat"
8722 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8723 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8724                                             bool HasDirectMove,
8725                                             bool HasP8Vector) {
8726   EVT VecVT = V->getValueType(0);
8727   bool RightType = VecVT == MVT::v2f64 ||
8728     (HasP8Vector && VecVT == MVT::v4f32) ||
8729     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8730   if (!RightType)
8731     return false;
8732 
8733   bool IsSplat = true;
8734   bool IsLoad = false;
8735   SDValue Op0 = V->getOperand(0);
8736 
8737   // This function is called in a block that confirms the node is not a constant
8738   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8739   // different constants.
8740   if (V->isConstant())
8741     return false;
8742   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8743     if (V->getOperand(i).isUndef())
8744       return false;
8745     // We want to expand nodes that represent load-and-splat even if the
8746     // loaded value is a floating point truncation or conversion to int.
8747     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8748         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8749          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8750         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8751          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8752         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8753          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8754       IsLoad = true;
8755     // If the operands are different or the input is not a load and has more
8756     // uses than just this BV node, then it isn't a splat.
8757     if (V->getOperand(i) != Op0 ||
8758         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8759       IsSplat = false;
8760   }
8761   return !(IsSplat && IsLoad);
8762 }
8763 
8764 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8765 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8766 
8767   SDLoc dl(Op);
8768   SDValue Op0 = Op->getOperand(0);
8769 
8770   if ((Op.getValueType() != MVT::f128) ||
8771       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8772       (Op0.getOperand(0).getValueType() != MVT::i64) ||
8773       (Op0.getOperand(1).getValueType() != MVT::i64))
8774     return SDValue();
8775 
8776   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8777                      Op0.getOperand(1));
8778 }
8779 
8780 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
8781   const SDValue *InputLoad = &Op;
8782   if (InputLoad->getOpcode() == ISD::BITCAST)
8783     InputLoad = &InputLoad->getOperand(0);
8784   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
8785       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
8786     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
8787     InputLoad = &InputLoad->getOperand(0);
8788   }
8789   if (InputLoad->getOpcode() != ISD::LOAD)
8790     return nullptr;
8791   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8792   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8793 }
8794 
8795 // Convert the argument APFloat to a single precision APFloat if there is no
8796 // loss in information during the conversion to single precision APFloat and the
8797 // resulting number is not a denormal number. Return true if successful.
8798 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
8799   APFloat APFloatToConvert = ArgAPFloat;
8800   bool LosesInfo = true;
8801   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
8802                            &LosesInfo);
8803   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
8804   if (Success)
8805     ArgAPFloat = APFloatToConvert;
8806   return Success;
8807 }
8808 
8809 // Bitcast the argument APInt to a double and convert it to a single precision
8810 // APFloat, bitcast the APFloat to an APInt and assign it to the original
8811 // argument if there is no loss in information during the conversion from
8812 // double to single precision APFloat and the resulting number is not a denormal
8813 // number. Return true if successful.
8814 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
8815   double DpValue = ArgAPInt.bitsToDouble();
8816   APFloat APFloatDp(DpValue);
8817   bool Success = convertToNonDenormSingle(APFloatDp);
8818   if (Success)
8819     ArgAPInt = APFloatDp.bitcastToAPInt();
8820   return Success;
8821 }
8822 
8823 // If this is a case we can't handle, return null and let the default
8824 // expansion code take care of it.  If we CAN select this case, and if it
8825 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8826 // this case more efficiently than a constant pool load, lower it to the
8827 // sequence of ops that should be used.
8828 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8829                                              SelectionDAG &DAG) const {
8830   SDLoc dl(Op);
8831   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8832   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8833 
8834   // Check if this is a splat of a constant value.
8835   APInt APSplatBits, APSplatUndef;
8836   unsigned SplatBitSize;
8837   bool HasAnyUndefs;
8838   bool BVNIsConstantSplat =
8839       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8840                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
8841 
8842   // If it is a splat of a double, check if we can shrink it to a 32 bit
8843   // non-denormal float which when converted back to double gives us the same
8844   // double. This is to exploit the XXSPLTIDP instruction.
8845   // If we lose precision, we use XXSPLTI32DX.
8846   if (BVNIsConstantSplat && (SplatBitSize == 64) &&
8847       Subtarget.hasPrefixInstrs()) {
8848     // Check the type first to short-circuit so we don't modify APSplatBits if
8849     // this block isn't executed.
8850     if ((Op->getValueType(0) == MVT::v2f64) &&
8851         convertToNonDenormSingle(APSplatBits)) {
8852       SDValue SplatNode = DAG.getNode(
8853           PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
8854           DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
8855       return DAG.getBitcast(Op.getValueType(), SplatNode);
8856     } else {
8857       // We may lose precision, so we have to use XXSPLTI32DX.
8858 
8859       uint32_t Hi =
8860           (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32);
8861       uint32_t Lo =
8862           (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF);
8863       SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
8864 
8865       if (!Hi || !Lo)
8866         // If either load is 0, then we should generate XXLXOR to set to 0.
8867         SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
8868 
8869       if (Hi)
8870         SplatNode = DAG.getNode(
8871             PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
8872             DAG.getTargetConstant(0, dl, MVT::i32),
8873             DAG.getTargetConstant(Hi, dl, MVT::i32));
8874 
8875       if (Lo)
8876         SplatNode =
8877             DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
8878                         DAG.getTargetConstant(1, dl, MVT::i32),
8879                         DAG.getTargetConstant(Lo, dl, MVT::i32));
8880 
8881       return DAG.getBitcast(Op.getValueType(), SplatNode);
8882     }
8883   }
8884 
8885   if (!BVNIsConstantSplat || SplatBitSize > 32) {
8886 
8887     bool IsPermutedLoad = false;
8888     const SDValue *InputLoad =
8889         getNormalLoadInput(Op.getOperand(0), IsPermutedLoad);
8890     // Handle load-and-splat patterns as we have instructions that will do this
8891     // in one go.
8892     if (InputLoad && DAG.isSplatValue(Op, true)) {
8893       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8894 
8895       // We have handling for 4 and 8 byte elements.
8896       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
8897 
8898       // Checking for a single use of this load, we have to check for vector
8899       // width (128 bits) / ElementSize uses (since each operand of the
8900       // BUILD_VECTOR is a separate use of the value.
8901       unsigned NumUsesOfInputLD = 128 / ElementSize;
8902       for (SDValue BVInOp : Op->ops())
8903         if (BVInOp.isUndef())
8904           NumUsesOfInputLD--;
8905       assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
8906       if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
8907           ((Subtarget.hasVSX() && ElementSize == 64) ||
8908            (Subtarget.hasP9Vector() && ElementSize == 32))) {
8909         SDValue Ops[] = {
8910           LD->getChain(),    // Chain
8911           LD->getBasePtr(),  // Ptr
8912           DAG.getValueType(Op.getValueType()) // VT
8913         };
8914         SDValue LdSplt = DAG.getMemIntrinsicNode(
8915             PPCISD::LD_SPLAT, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8916             Ops, LD->getMemoryVT(), LD->getMemOperand());
8917         // Replace all uses of the output chain of the original load with the
8918         // output chain of the new load.
8919         DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
8920                                       LdSplt.getValue(1));
8921         return LdSplt;
8922       }
8923     }
8924 
8925     // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
8926     // 32-bits can be lowered to VSX instructions under certain conditions.
8927     // Without VSX, there is no pattern more efficient than expanding the node.
8928     if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
8929         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8930                                         Subtarget.hasP8Vector()))
8931       return Op;
8932     return SDValue();
8933   }
8934 
8935   uint64_t SplatBits = APSplatBits.getZExtValue();
8936   uint64_t SplatUndef = APSplatUndef.getZExtValue();
8937   unsigned SplatSize = SplatBitSize / 8;
8938 
8939   // First, handle single instruction cases.
8940 
8941   // All zeros?
8942   if (SplatBits == 0) {
8943     // Canonicalize all zero vectors to be v4i32.
8944     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8945       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8946       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8947     }
8948     return Op;
8949   }
8950 
8951   // We have XXSPLTIW for constant splats four bytes wide.
8952   // Given vector length is a multiple of 4, 2-byte splats can be replaced
8953   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
8954   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
8955   // turned into a 4-byte splat of 0xABABABAB.
8956   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
8957     return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
8958                                   Op.getValueType(), DAG, dl);
8959 
8960   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
8961     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
8962                                   dl);
8963 
8964   // We have XXSPLTIB for constant splats one byte wide.
8965   if (Subtarget.hasP9Vector() && SplatSize == 1)
8966     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
8967                                   dl);
8968 
8969   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8970   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8971                     (32-SplatBitSize));
8972   if (SextVal >= -16 && SextVal <= 15)
8973     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
8974                                   dl);
8975 
8976   // Two instruction sequences.
8977 
8978   // If this value is in the range [-32,30] and is even, use:
8979   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8980   // If this value is in the range [17,31] and is odd, use:
8981   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8982   // If this value is in the range [-31,-17] and is odd, use:
8983   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8984   // Note the last two are three-instruction sequences.
8985   if (SextVal >= -32 && SextVal <= 31) {
8986     // To avoid having these optimizations undone by constant folding,
8987     // we convert to a pseudo that will be expanded later into one of
8988     // the above forms.
8989     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8990     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8991               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8992     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8993     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8994     if (VT == Op.getValueType())
8995       return RetVal;
8996     else
8997       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8998   }
8999 
9000   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9001   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9002   // for fneg/fabs.
9003   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9004     // Make -1 and vspltisw -1:
9005     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9006 
9007     // Make the VSLW intrinsic, computing 0x8000_0000.
9008     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9009                                    OnesV, DAG, dl);
9010 
9011     // xor by OnesV to invert it.
9012     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9013     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9014   }
9015 
9016   // Check to see if this is a wide variety of vsplti*, binop self cases.
9017   static const signed char SplatCsts[] = {
9018     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9019     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9020   };
9021 
9022   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9023     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9024     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9025     int i = SplatCsts[idx];
9026 
9027     // Figure out what shift amount will be used by altivec if shifted by i in
9028     // this splat size.
9029     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9030 
9031     // vsplti + shl self.
9032     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9033       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9034       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9035         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9036         Intrinsic::ppc_altivec_vslw
9037       };
9038       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9039       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9040     }
9041 
9042     // vsplti + srl self.
9043     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9044       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9045       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9046         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9047         Intrinsic::ppc_altivec_vsrw
9048       };
9049       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9050       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9051     }
9052 
9053     // vsplti + rol self.
9054     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9055                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9056       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9057       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9058         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9059         Intrinsic::ppc_altivec_vrlw
9060       };
9061       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9062       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9063     }
9064 
9065     // t = vsplti c, result = vsldoi t, t, 1
9066     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9067       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9068       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9069       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9070     }
9071     // t = vsplti c, result = vsldoi t, t, 2
9072     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9073       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9074       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9075       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9076     }
9077     // t = vsplti c, result = vsldoi t, t, 3
9078     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9079       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9080       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9081       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9082     }
9083   }
9084 
9085   return SDValue();
9086 }
9087 
9088 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9089 /// the specified operations to build the shuffle.
9090 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9091                                       SDValue RHS, SelectionDAG &DAG,
9092                                       const SDLoc &dl) {
9093   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9094   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9095   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9096 
9097   enum {
9098     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9099     OP_VMRGHW,
9100     OP_VMRGLW,
9101     OP_VSPLTISW0,
9102     OP_VSPLTISW1,
9103     OP_VSPLTISW2,
9104     OP_VSPLTISW3,
9105     OP_VSLDOI4,
9106     OP_VSLDOI8,
9107     OP_VSLDOI12
9108   };
9109 
9110   if (OpNum == OP_COPY) {
9111     if (LHSID == (1*9+2)*9+3) return LHS;
9112     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9113     return RHS;
9114   }
9115 
9116   SDValue OpLHS, OpRHS;
9117   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9118   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9119 
9120   int ShufIdxs[16];
9121   switch (OpNum) {
9122   default: llvm_unreachable("Unknown i32 permute!");
9123   case OP_VMRGHW:
9124     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9125     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9126     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9127     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9128     break;
9129   case OP_VMRGLW:
9130     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9131     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9132     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9133     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9134     break;
9135   case OP_VSPLTISW0:
9136     for (unsigned i = 0; i != 16; ++i)
9137       ShufIdxs[i] = (i&3)+0;
9138     break;
9139   case OP_VSPLTISW1:
9140     for (unsigned i = 0; i != 16; ++i)
9141       ShufIdxs[i] = (i&3)+4;
9142     break;
9143   case OP_VSPLTISW2:
9144     for (unsigned i = 0; i != 16; ++i)
9145       ShufIdxs[i] = (i&3)+8;
9146     break;
9147   case OP_VSPLTISW3:
9148     for (unsigned i = 0; i != 16; ++i)
9149       ShufIdxs[i] = (i&3)+12;
9150     break;
9151   case OP_VSLDOI4:
9152     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9153   case OP_VSLDOI8:
9154     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9155   case OP_VSLDOI12:
9156     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9157   }
9158   EVT VT = OpLHS.getValueType();
9159   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9160   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9161   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9162   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9163 }
9164 
9165 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9166 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9167 /// SDValue.
9168 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9169                                            SelectionDAG &DAG) const {
9170   const unsigned BytesInVector = 16;
9171   bool IsLE = Subtarget.isLittleEndian();
9172   SDLoc dl(N);
9173   SDValue V1 = N->getOperand(0);
9174   SDValue V2 = N->getOperand(1);
9175   unsigned ShiftElts = 0, InsertAtByte = 0;
9176   bool Swap = false;
9177 
9178   // Shifts required to get the byte we want at element 7.
9179   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9180                                    0, 15, 14, 13, 12, 11, 10, 9};
9181   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9182                                 1, 2,  3,  4,  5,  6,  7,  8};
9183 
9184   ArrayRef<int> Mask = N->getMask();
9185   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9186 
9187   // For each mask element, find out if we're just inserting something
9188   // from V2 into V1 or vice versa.
9189   // Possible permutations inserting an element from V2 into V1:
9190   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9191   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9192   //   ...
9193   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9194   // Inserting from V1 into V2 will be similar, except mask range will be
9195   // [16,31].
9196 
9197   bool FoundCandidate = false;
9198   // If both vector operands for the shuffle are the same vector, the mask
9199   // will contain only elements from the first one and the second one will be
9200   // undef.
9201   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9202   // Go through the mask of half-words to find an element that's being moved
9203   // from one vector to the other.
9204   for (unsigned i = 0; i < BytesInVector; ++i) {
9205     unsigned CurrentElement = Mask[i];
9206     // If 2nd operand is undefined, we should only look for element 7 in the
9207     // Mask.
9208     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9209       continue;
9210 
9211     bool OtherElementsInOrder = true;
9212     // Examine the other elements in the Mask to see if they're in original
9213     // order.
9214     for (unsigned j = 0; j < BytesInVector; ++j) {
9215       if (j == i)
9216         continue;
9217       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9218       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9219       // in which we always assume we're always picking from the 1st operand.
9220       int MaskOffset =
9221           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9222       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9223         OtherElementsInOrder = false;
9224         break;
9225       }
9226     }
9227     // If other elements are in original order, we record the number of shifts
9228     // we need to get the element we want into element 7. Also record which byte
9229     // in the vector we should insert into.
9230     if (OtherElementsInOrder) {
9231       // If 2nd operand is undefined, we assume no shifts and no swapping.
9232       if (V2.isUndef()) {
9233         ShiftElts = 0;
9234         Swap = false;
9235       } else {
9236         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9237         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9238                          : BigEndianShifts[CurrentElement & 0xF];
9239         Swap = CurrentElement < BytesInVector;
9240       }
9241       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9242       FoundCandidate = true;
9243       break;
9244     }
9245   }
9246 
9247   if (!FoundCandidate)
9248     return SDValue();
9249 
9250   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9251   // optionally with VECSHL if shift is required.
9252   if (Swap)
9253     std::swap(V1, V2);
9254   if (V2.isUndef())
9255     V2 = V1;
9256   if (ShiftElts) {
9257     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9258                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9259     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9260                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9261   }
9262   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9263                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9264 }
9265 
9266 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9267 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9268 /// SDValue.
9269 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9270                                            SelectionDAG &DAG) const {
9271   const unsigned NumHalfWords = 8;
9272   const unsigned BytesInVector = NumHalfWords * 2;
9273   // Check that the shuffle is on half-words.
9274   if (!isNByteElemShuffleMask(N, 2, 1))
9275     return SDValue();
9276 
9277   bool IsLE = Subtarget.isLittleEndian();
9278   SDLoc dl(N);
9279   SDValue V1 = N->getOperand(0);
9280   SDValue V2 = N->getOperand(1);
9281   unsigned ShiftElts = 0, InsertAtByte = 0;
9282   bool Swap = false;
9283 
9284   // Shifts required to get the half-word we want at element 3.
9285   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9286   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9287 
9288   uint32_t Mask = 0;
9289   uint32_t OriginalOrderLow = 0x1234567;
9290   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9291   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9292   // 32-bit space, only need 4-bit nibbles per element.
9293   for (unsigned i = 0; i < NumHalfWords; ++i) {
9294     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9295     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9296   }
9297 
9298   // For each mask element, find out if we're just inserting something
9299   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9300   // from V2 into V1:
9301   //   X, 1, 2, 3, 4, 5, 6, 7
9302   //   0, X, 2, 3, 4, 5, 6, 7
9303   //   0, 1, X, 3, 4, 5, 6, 7
9304   //   0, 1, 2, X, 4, 5, 6, 7
9305   //   0, 1, 2, 3, X, 5, 6, 7
9306   //   0, 1, 2, 3, 4, X, 6, 7
9307   //   0, 1, 2, 3, 4, 5, X, 7
9308   //   0, 1, 2, 3, 4, 5, 6, X
9309   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9310 
9311   bool FoundCandidate = false;
9312   // Go through the mask of half-words to find an element that's being moved
9313   // from one vector to the other.
9314   for (unsigned i = 0; i < NumHalfWords; ++i) {
9315     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9316     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9317     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9318     uint32_t TargetOrder = 0x0;
9319 
9320     // If both vector operands for the shuffle are the same vector, the mask
9321     // will contain only elements from the first one and the second one will be
9322     // undef.
9323     if (V2.isUndef()) {
9324       ShiftElts = 0;
9325       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9326       TargetOrder = OriginalOrderLow;
9327       Swap = false;
9328       // Skip if not the correct element or mask of other elements don't equal
9329       // to our expected order.
9330       if (MaskOneElt == VINSERTHSrcElem &&
9331           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9332         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9333         FoundCandidate = true;
9334         break;
9335       }
9336     } else { // If both operands are defined.
9337       // Target order is [8,15] if the current mask is between [0,7].
9338       TargetOrder =
9339           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9340       // Skip if mask of other elements don't equal our expected order.
9341       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9342         // We only need the last 3 bits for the number of shifts.
9343         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9344                          : BigEndianShifts[MaskOneElt & 0x7];
9345         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9346         Swap = MaskOneElt < NumHalfWords;
9347         FoundCandidate = true;
9348         break;
9349       }
9350     }
9351   }
9352 
9353   if (!FoundCandidate)
9354     return SDValue();
9355 
9356   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9357   // optionally with VECSHL if shift is required.
9358   if (Swap)
9359     std::swap(V1, V2);
9360   if (V2.isUndef())
9361     V2 = V1;
9362   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9363   if (ShiftElts) {
9364     // Double ShiftElts because we're left shifting on v16i8 type.
9365     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9366                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9367     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9368     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9369                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9370     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9371   }
9372   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9373   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9374                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9375   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9376 }
9377 
9378 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9379 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9380 /// return the default SDValue.
9381 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9382                                               SelectionDAG &DAG) const {
9383   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9384   // to v16i8. Peek through the bitcasts to get the actual operands.
9385   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9386   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9387 
9388   auto ShuffleMask = SVN->getMask();
9389   SDValue VecShuffle(SVN, 0);
9390   SDLoc DL(SVN);
9391 
9392   // Check that we have a four byte shuffle.
9393   if (!isNByteElemShuffleMask(SVN, 4, 1))
9394     return SDValue();
9395 
9396   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9397   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9398     std::swap(LHS, RHS);
9399     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9400     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9401   }
9402 
9403   // Ensure that the RHS is a vector of constants.
9404   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9405   if (!BVN)
9406     return SDValue();
9407 
9408   // Check if RHS is a splat of 4-bytes (or smaller).
9409   APInt APSplatValue, APSplatUndef;
9410   unsigned SplatBitSize;
9411   bool HasAnyUndefs;
9412   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9413                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9414       SplatBitSize > 32)
9415     return SDValue();
9416 
9417   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9418   // The instruction splats a constant C into two words of the source vector
9419   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9420   // Thus we check that the shuffle mask is the equivalent  of
9421   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9422   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9423   // within each word are consecutive, so we only need to check the first byte.
9424   SDValue Index;
9425   bool IsLE = Subtarget.isLittleEndian();
9426   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9427       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9428        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9429     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9430   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9431            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9432             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9433     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9434   else
9435     return SDValue();
9436 
9437   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9438   // for XXSPLTI32DX.
9439   unsigned SplatVal = APSplatValue.getZExtValue();
9440   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9441     SplatVal |= (SplatVal << SplatBitSize);
9442 
9443   SDValue SplatNode = DAG.getNode(
9444       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9445       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9446   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9447 }
9448 
9449 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9450 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9451 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9452 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9453 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9454   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9455   assert(Op.getValueType() == MVT::v1i128 &&
9456          "Only set v1i128 as custom, other type shouldn't reach here!");
9457   SDLoc dl(Op);
9458   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9459   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9460   unsigned SHLAmt = N1.getConstantOperandVal(0);
9461   if (SHLAmt % 8 == 0) {
9462     SmallVector<int, 16> Mask(16, 0);
9463     std::iota(Mask.begin(), Mask.end(), 0);
9464     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9465     if (SDValue Shuffle =
9466             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9467                                  DAG.getUNDEF(MVT::v16i8), Mask))
9468       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9469   }
9470   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9471   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9472                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9473   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9474                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9475   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9476   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9477 }
9478 
9479 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9480 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9481 /// return the code it can be lowered into.  Worst case, it can always be
9482 /// lowered into a vperm.
9483 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9484                                                SelectionDAG &DAG) const {
9485   SDLoc dl(Op);
9486   SDValue V1 = Op.getOperand(0);
9487   SDValue V2 = Op.getOperand(1);
9488   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9489 
9490   // Any nodes that were combined in the target-independent combiner prior
9491   // to vector legalization will not be sent to the target combine. Try to
9492   // combine it here.
9493   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9494     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9495       return NewShuffle;
9496     Op = NewShuffle;
9497     SVOp = cast<ShuffleVectorSDNode>(Op);
9498     V1 = Op.getOperand(0);
9499     V2 = Op.getOperand(1);
9500   }
9501   EVT VT = Op.getValueType();
9502   bool isLittleEndian = Subtarget.isLittleEndian();
9503 
9504   unsigned ShiftElts, InsertAtByte;
9505   bool Swap = false;
9506 
9507   // If this is a load-and-splat, we can do that with a single instruction
9508   // in some cases. However if the load has multiple uses, we don't want to
9509   // combine it because that will just produce multiple loads.
9510   bool IsPermutedLoad = false;
9511   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9512   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9513       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9514       InputLoad->hasOneUse()) {
9515     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9516     int SplatIdx =
9517       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9518 
9519     // The splat index for permuted loads will be in the left half of the vector
9520     // which is strictly wider than the loaded value by 8 bytes. So we need to
9521     // adjust the splat index to point to the correct address in memory.
9522     if (IsPermutedLoad) {
9523       assert(isLittleEndian && "Unexpected permuted load on big endian target");
9524       SplatIdx += IsFourByte ? 2 : 1;
9525       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9526              "Splat of a value outside of the loaded memory");
9527     }
9528 
9529     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9530     // For 4-byte load-and-splat, we need Power9.
9531     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9532       uint64_t Offset = 0;
9533       if (IsFourByte)
9534         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9535       else
9536         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9537 
9538       SDValue BasePtr = LD->getBasePtr();
9539       if (Offset != 0)
9540         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9541                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9542       SDValue Ops[] = {
9543         LD->getChain(),    // Chain
9544         BasePtr,           // BasePtr
9545         DAG.getValueType(Op.getValueType()) // VT
9546       };
9547       SDVTList VTL =
9548         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9549       SDValue LdSplt =
9550         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9551                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9552       DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
9553       if (LdSplt.getValueType() != SVOp->getValueType(0))
9554         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9555       return LdSplt;
9556     }
9557   }
9558   if (Subtarget.hasP9Vector() &&
9559       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9560                            isLittleEndian)) {
9561     if (Swap)
9562       std::swap(V1, V2);
9563     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9564     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9565     if (ShiftElts) {
9566       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9567                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9568       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9569                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9570       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9571     }
9572     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9573                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9574     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9575   }
9576 
9577   if (Subtarget.hasPrefixInstrs()) {
9578     SDValue SplatInsertNode;
9579     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9580       return SplatInsertNode;
9581   }
9582 
9583   if (Subtarget.hasP9Altivec()) {
9584     SDValue NewISDNode;
9585     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9586       return NewISDNode;
9587 
9588     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9589       return NewISDNode;
9590   }
9591 
9592   if (Subtarget.hasVSX() &&
9593       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9594     if (Swap)
9595       std::swap(V1, V2);
9596     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9597     SDValue Conv2 =
9598         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9599 
9600     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9601                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9602     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9603   }
9604 
9605   if (Subtarget.hasVSX() &&
9606     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9607     if (Swap)
9608       std::swap(V1, V2);
9609     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9610     SDValue Conv2 =
9611         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9612 
9613     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9614                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9615     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9616   }
9617 
9618   if (Subtarget.hasP9Vector()) {
9619      if (PPC::isXXBRHShuffleMask(SVOp)) {
9620       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9621       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9622       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9623     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9624       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9625       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9626       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9627     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9628       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9629       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9630       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9631     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9632       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9633       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9634       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9635     }
9636   }
9637 
9638   if (Subtarget.hasVSX()) {
9639     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9640       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9641 
9642       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9643       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9644                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9645       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9646     }
9647 
9648     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9649     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9650       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9651       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9652       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9653     }
9654   }
9655 
9656   // Cases that are handled by instructions that take permute immediates
9657   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9658   // selected by the instruction selector.
9659   if (V2.isUndef()) {
9660     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9661         PPC::isSplatShuffleMask(SVOp, 2) ||
9662         PPC::isSplatShuffleMask(SVOp, 4) ||
9663         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9664         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9665         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9666         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9667         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9668         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9669         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9670         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9671         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9672         (Subtarget.hasP8Altivec() && (
9673          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9674          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9675          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9676       return Op;
9677     }
9678   }
9679 
9680   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9681   // and produce a fixed permutation.  If any of these match, do not lower to
9682   // VPERM.
9683   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9684   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9685       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9686       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9687       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9688       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9689       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9690       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9691       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9692       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9693       (Subtarget.hasP8Altivec() && (
9694        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9695        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9696        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9697     return Op;
9698 
9699   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9700   // perfect shuffle table to emit an optimal matching sequence.
9701   ArrayRef<int> PermMask = SVOp->getMask();
9702 
9703   unsigned PFIndexes[4];
9704   bool isFourElementShuffle = true;
9705   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9706     unsigned EltNo = 8;   // Start out undef.
9707     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9708       if (PermMask[i*4+j] < 0)
9709         continue;   // Undef, ignore it.
9710 
9711       unsigned ByteSource = PermMask[i*4+j];
9712       if ((ByteSource & 3) != j) {
9713         isFourElementShuffle = false;
9714         break;
9715       }
9716 
9717       if (EltNo == 8) {
9718         EltNo = ByteSource/4;
9719       } else if (EltNo != ByteSource/4) {
9720         isFourElementShuffle = false;
9721         break;
9722       }
9723     }
9724     PFIndexes[i] = EltNo;
9725   }
9726 
9727   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9728   // perfect shuffle vector to determine if it is cost effective to do this as
9729   // discrete instructions, or whether we should use a vperm.
9730   // For now, we skip this for little endian until such time as we have a
9731   // little-endian perfect shuffle table.
9732   if (isFourElementShuffle && !isLittleEndian) {
9733     // Compute the index in the perfect shuffle table.
9734     unsigned PFTableIndex =
9735       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9736 
9737     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9738     unsigned Cost  = (PFEntry >> 30);
9739 
9740     // Determining when to avoid vperm is tricky.  Many things affect the cost
9741     // of vperm, particularly how many times the perm mask needs to be computed.
9742     // For example, if the perm mask can be hoisted out of a loop or is already
9743     // used (perhaps because there are multiple permutes with the same shuffle
9744     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9745     // the loop requires an extra register.
9746     //
9747     // As a compromise, we only emit discrete instructions if the shuffle can be
9748     // generated in 3 or fewer operations.  When we have loop information
9749     // available, if this block is within a loop, we should avoid using vperm
9750     // for 3-operation perms and use a constant pool load instead.
9751     if (Cost < 3)
9752       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9753   }
9754 
9755   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9756   // vector that will get spilled to the constant pool.
9757   if (V2.isUndef()) V2 = V1;
9758 
9759   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9760   // that it is in input element units, not in bytes.  Convert now.
9761 
9762   // For little endian, the order of the input vectors is reversed, and
9763   // the permutation mask is complemented with respect to 31.  This is
9764   // necessary to produce proper semantics with the big-endian-biased vperm
9765   // instruction.
9766   EVT EltVT = V1.getValueType().getVectorElementType();
9767   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9768 
9769   SmallVector<SDValue, 16> ResultMask;
9770   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9771     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9772 
9773     for (unsigned j = 0; j != BytesPerElement; ++j)
9774       if (isLittleEndian)
9775         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9776                                              dl, MVT::i32));
9777       else
9778         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9779                                              MVT::i32));
9780   }
9781 
9782   ShufflesHandledWithVPERM++;
9783   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9784   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
9785   LLVM_DEBUG(SVOp->dump());
9786   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
9787   LLVM_DEBUG(VPermMask.dump());
9788 
9789   if (isLittleEndian)
9790     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9791                        V2, V1, VPermMask);
9792   else
9793     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9794                        V1, V2, VPermMask);
9795 }
9796 
9797 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9798 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9799 /// information about the intrinsic.
9800 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9801                                  bool &isDot, const PPCSubtarget &Subtarget) {
9802   unsigned IntrinsicID =
9803       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9804   CompareOpc = -1;
9805   isDot = false;
9806   switch (IntrinsicID) {
9807   default:
9808     return false;
9809   // Comparison predicates.
9810   case Intrinsic::ppc_altivec_vcmpbfp_p:
9811     CompareOpc = 966;
9812     isDot = true;
9813     break;
9814   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9815     CompareOpc = 198;
9816     isDot = true;
9817     break;
9818   case Intrinsic::ppc_altivec_vcmpequb_p:
9819     CompareOpc = 6;
9820     isDot = true;
9821     break;
9822   case Intrinsic::ppc_altivec_vcmpequh_p:
9823     CompareOpc = 70;
9824     isDot = true;
9825     break;
9826   case Intrinsic::ppc_altivec_vcmpequw_p:
9827     CompareOpc = 134;
9828     isDot = true;
9829     break;
9830   case Intrinsic::ppc_altivec_vcmpequd_p:
9831     if (Subtarget.hasP8Altivec()) {
9832       CompareOpc = 199;
9833       isDot = true;
9834     } else
9835       return false;
9836     break;
9837   case Intrinsic::ppc_altivec_vcmpneb_p:
9838   case Intrinsic::ppc_altivec_vcmpneh_p:
9839   case Intrinsic::ppc_altivec_vcmpnew_p:
9840   case Intrinsic::ppc_altivec_vcmpnezb_p:
9841   case Intrinsic::ppc_altivec_vcmpnezh_p:
9842   case Intrinsic::ppc_altivec_vcmpnezw_p:
9843     if (Subtarget.hasP9Altivec()) {
9844       switch (IntrinsicID) {
9845       default:
9846         llvm_unreachable("Unknown comparison intrinsic.");
9847       case Intrinsic::ppc_altivec_vcmpneb_p:
9848         CompareOpc = 7;
9849         break;
9850       case Intrinsic::ppc_altivec_vcmpneh_p:
9851         CompareOpc = 71;
9852         break;
9853       case Intrinsic::ppc_altivec_vcmpnew_p:
9854         CompareOpc = 135;
9855         break;
9856       case Intrinsic::ppc_altivec_vcmpnezb_p:
9857         CompareOpc = 263;
9858         break;
9859       case Intrinsic::ppc_altivec_vcmpnezh_p:
9860         CompareOpc = 327;
9861         break;
9862       case Intrinsic::ppc_altivec_vcmpnezw_p:
9863         CompareOpc = 391;
9864         break;
9865       }
9866       isDot = true;
9867     } else
9868       return false;
9869     break;
9870   case Intrinsic::ppc_altivec_vcmpgefp_p:
9871     CompareOpc = 454;
9872     isDot = true;
9873     break;
9874   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9875     CompareOpc = 710;
9876     isDot = true;
9877     break;
9878   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9879     CompareOpc = 774;
9880     isDot = true;
9881     break;
9882   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9883     CompareOpc = 838;
9884     isDot = true;
9885     break;
9886   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9887     CompareOpc = 902;
9888     isDot = true;
9889     break;
9890   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9891     if (Subtarget.hasP8Altivec()) {
9892       CompareOpc = 967;
9893       isDot = true;
9894     } else
9895       return false;
9896     break;
9897   case Intrinsic::ppc_altivec_vcmpgtub_p:
9898     CompareOpc = 518;
9899     isDot = true;
9900     break;
9901   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9902     CompareOpc = 582;
9903     isDot = true;
9904     break;
9905   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9906     CompareOpc = 646;
9907     isDot = true;
9908     break;
9909   case Intrinsic::ppc_altivec_vcmpgtud_p:
9910     if (Subtarget.hasP8Altivec()) {
9911       CompareOpc = 711;
9912       isDot = true;
9913     } else
9914       return false;
9915     break;
9916 
9917   case Intrinsic::ppc_altivec_vcmpequq:
9918   case Intrinsic::ppc_altivec_vcmpgtsq:
9919   case Intrinsic::ppc_altivec_vcmpgtuq:
9920     if (!Subtarget.isISA3_1())
9921       return false;
9922     switch (IntrinsicID) {
9923     default:
9924       llvm_unreachable("Unknown comparison intrinsic.");
9925     case Intrinsic::ppc_altivec_vcmpequq:
9926       CompareOpc = 455;
9927       break;
9928     case Intrinsic::ppc_altivec_vcmpgtsq:
9929       CompareOpc = 903;
9930       break;
9931     case Intrinsic::ppc_altivec_vcmpgtuq:
9932       CompareOpc = 647;
9933       break;
9934     }
9935     break;
9936 
9937   // VSX predicate comparisons use the same infrastructure
9938   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9939   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9940   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9941   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9942   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9943   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9944     if (Subtarget.hasVSX()) {
9945       switch (IntrinsicID) {
9946       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9947         CompareOpc = 99;
9948         break;
9949       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9950         CompareOpc = 115;
9951         break;
9952       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9953         CompareOpc = 107;
9954         break;
9955       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9956         CompareOpc = 67;
9957         break;
9958       case Intrinsic::ppc_vsx_xvcmpgesp_p:
9959         CompareOpc = 83;
9960         break;
9961       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9962         CompareOpc = 75;
9963         break;
9964       }
9965       isDot = true;
9966     } else
9967       return false;
9968     break;
9969 
9970   // Normal Comparisons.
9971   case Intrinsic::ppc_altivec_vcmpbfp:
9972     CompareOpc = 966;
9973     break;
9974   case Intrinsic::ppc_altivec_vcmpeqfp:
9975     CompareOpc = 198;
9976     break;
9977   case Intrinsic::ppc_altivec_vcmpequb:
9978     CompareOpc = 6;
9979     break;
9980   case Intrinsic::ppc_altivec_vcmpequh:
9981     CompareOpc = 70;
9982     break;
9983   case Intrinsic::ppc_altivec_vcmpequw:
9984     CompareOpc = 134;
9985     break;
9986   case Intrinsic::ppc_altivec_vcmpequd:
9987     if (Subtarget.hasP8Altivec())
9988       CompareOpc = 199;
9989     else
9990       return false;
9991     break;
9992   case Intrinsic::ppc_altivec_vcmpneb:
9993   case Intrinsic::ppc_altivec_vcmpneh:
9994   case Intrinsic::ppc_altivec_vcmpnew:
9995   case Intrinsic::ppc_altivec_vcmpnezb:
9996   case Intrinsic::ppc_altivec_vcmpnezh:
9997   case Intrinsic::ppc_altivec_vcmpnezw:
9998     if (Subtarget.hasP9Altivec())
9999       switch (IntrinsicID) {
10000       default:
10001         llvm_unreachable("Unknown comparison intrinsic.");
10002       case Intrinsic::ppc_altivec_vcmpneb:
10003         CompareOpc = 7;
10004         break;
10005       case Intrinsic::ppc_altivec_vcmpneh:
10006         CompareOpc = 71;
10007         break;
10008       case Intrinsic::ppc_altivec_vcmpnew:
10009         CompareOpc = 135;
10010         break;
10011       case Intrinsic::ppc_altivec_vcmpnezb:
10012         CompareOpc = 263;
10013         break;
10014       case Intrinsic::ppc_altivec_vcmpnezh:
10015         CompareOpc = 327;
10016         break;
10017       case Intrinsic::ppc_altivec_vcmpnezw:
10018         CompareOpc = 391;
10019         break;
10020       }
10021     else
10022       return false;
10023     break;
10024   case Intrinsic::ppc_altivec_vcmpgefp:
10025     CompareOpc = 454;
10026     break;
10027   case Intrinsic::ppc_altivec_vcmpgtfp:
10028     CompareOpc = 710;
10029     break;
10030   case Intrinsic::ppc_altivec_vcmpgtsb:
10031     CompareOpc = 774;
10032     break;
10033   case Intrinsic::ppc_altivec_vcmpgtsh:
10034     CompareOpc = 838;
10035     break;
10036   case Intrinsic::ppc_altivec_vcmpgtsw:
10037     CompareOpc = 902;
10038     break;
10039   case Intrinsic::ppc_altivec_vcmpgtsd:
10040     if (Subtarget.hasP8Altivec())
10041       CompareOpc = 967;
10042     else
10043       return false;
10044     break;
10045   case Intrinsic::ppc_altivec_vcmpgtub:
10046     CompareOpc = 518;
10047     break;
10048   case Intrinsic::ppc_altivec_vcmpgtuh:
10049     CompareOpc = 582;
10050     break;
10051   case Intrinsic::ppc_altivec_vcmpgtuw:
10052     CompareOpc = 646;
10053     break;
10054   case Intrinsic::ppc_altivec_vcmpgtud:
10055     if (Subtarget.hasP8Altivec())
10056       CompareOpc = 711;
10057     else
10058       return false;
10059     break;
10060   case Intrinsic::ppc_altivec_vcmpequq_p:
10061   case Intrinsic::ppc_altivec_vcmpgtsq_p:
10062   case Intrinsic::ppc_altivec_vcmpgtuq_p:
10063     if (!Subtarget.isISA3_1())
10064       return false;
10065     switch (IntrinsicID) {
10066     default:
10067       llvm_unreachable("Unknown comparison intrinsic.");
10068     case Intrinsic::ppc_altivec_vcmpequq_p:
10069       CompareOpc = 455;
10070       break;
10071     case Intrinsic::ppc_altivec_vcmpgtsq_p:
10072       CompareOpc = 903;
10073       break;
10074     case Intrinsic::ppc_altivec_vcmpgtuq_p:
10075       CompareOpc = 647;
10076       break;
10077     }
10078     isDot = true;
10079     break;
10080   }
10081   return true;
10082 }
10083 
10084 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10085 /// lower, do it, otherwise return null.
10086 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10087                                                    SelectionDAG &DAG) const {
10088   unsigned IntrinsicID =
10089     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10090 
10091   SDLoc dl(Op);
10092 
10093   switch (IntrinsicID) {
10094   case Intrinsic::thread_pointer:
10095     // Reads the thread pointer register, used for __builtin_thread_pointer.
10096     if (Subtarget.isPPC64())
10097       return DAG.getRegister(PPC::X13, MVT::i64);
10098     return DAG.getRegister(PPC::R2, MVT::i32);
10099 
10100   case Intrinsic::ppc_mma_disassemble_acc:
10101   case Intrinsic::ppc_vsx_disassemble_pair: {
10102     int NumVecs = 2;
10103     SDValue WideVec = Op.getOperand(1);
10104     if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
10105       NumVecs = 4;
10106       WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
10107     }
10108     SmallVector<SDValue, 4> RetOps;
10109     for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
10110       SDValue Extract = DAG.getNode(
10111           PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
10112           DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
10113                                                      : VecNo,
10114                           dl, MVT::i64));
10115       RetOps.push_back(Extract);
10116     }
10117     return DAG.getMergeValues(RetOps, dl);
10118   }
10119   }
10120 
10121   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10122   // opcode number of the comparison.
10123   int CompareOpc;
10124   bool isDot;
10125   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10126     return SDValue();    // Don't custom lower most intrinsics.
10127 
10128   // If this is a non-dot comparison, make the VCMP node and we are done.
10129   if (!isDot) {
10130     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10131                               Op.getOperand(1), Op.getOperand(2),
10132                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10133     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10134   }
10135 
10136   // Create the PPCISD altivec 'dot' comparison node.
10137   SDValue Ops[] = {
10138     Op.getOperand(2),  // LHS
10139     Op.getOperand(3),  // RHS
10140     DAG.getConstant(CompareOpc, dl, MVT::i32)
10141   };
10142   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10143   SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
10144 
10145   // Now that we have the comparison, emit a copy from the CR to a GPR.
10146   // This is flagged to the above dot comparison.
10147   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10148                                 DAG.getRegister(PPC::CR6, MVT::i32),
10149                                 CompNode.getValue(1));
10150 
10151   // Unpack the result based on how the target uses it.
10152   unsigned BitNo;   // Bit # of CR6.
10153   bool InvertBit;   // Invert result?
10154   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10155   default:  // Can't happen, don't crash on invalid number though.
10156   case 0:   // Return the value of the EQ bit of CR6.
10157     BitNo = 0; InvertBit = false;
10158     break;
10159   case 1:   // Return the inverted value of the EQ bit of CR6.
10160     BitNo = 0; InvertBit = true;
10161     break;
10162   case 2:   // Return the value of the LT bit of CR6.
10163     BitNo = 2; InvertBit = false;
10164     break;
10165   case 3:   // Return the inverted value of the LT bit of CR6.
10166     BitNo = 2; InvertBit = true;
10167     break;
10168   }
10169 
10170   // Shift the bit into the low position.
10171   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10172                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10173   // Isolate the bit.
10174   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10175                       DAG.getConstant(1, dl, MVT::i32));
10176 
10177   // If we are supposed to, toggle the bit.
10178   if (InvertBit)
10179     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10180                         DAG.getConstant(1, dl, MVT::i32));
10181   return Flags;
10182 }
10183 
10184 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10185                                                SelectionDAG &DAG) const {
10186   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10187   // the beginning of the argument list.
10188   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10189   SDLoc DL(Op);
10190   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10191   case Intrinsic::ppc_cfence: {
10192     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10193     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10194     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10195                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10196                                                   Op.getOperand(ArgStart + 1)),
10197                                       Op.getOperand(0)),
10198                    0);
10199   }
10200   default:
10201     break;
10202   }
10203   return SDValue();
10204 }
10205 
10206 // Lower scalar BSWAP64 to xxbrd.
10207 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10208   SDLoc dl(Op);
10209   // MTVSRDD
10210   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10211                    Op.getOperand(0));
10212   // XXBRD
10213   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10214   // MFVSRD
10215   int VectorIndex = 0;
10216   if (Subtarget.isLittleEndian())
10217     VectorIndex = 1;
10218   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10219                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10220   return Op;
10221 }
10222 
10223 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10224 // compared to a value that is atomically loaded (atomic loads zero-extend).
10225 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10226                                                 SelectionDAG &DAG) const {
10227   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10228          "Expecting an atomic compare-and-swap here.");
10229   SDLoc dl(Op);
10230   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10231   EVT MemVT = AtomicNode->getMemoryVT();
10232   if (MemVT.getSizeInBits() >= 32)
10233     return Op;
10234 
10235   SDValue CmpOp = Op.getOperand(2);
10236   // If this is already correctly zero-extended, leave it alone.
10237   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10238   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10239     return Op;
10240 
10241   // Clear the high bits of the compare operand.
10242   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10243   SDValue NewCmpOp =
10244     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10245                 DAG.getConstant(MaskVal, dl, MVT::i32));
10246 
10247   // Replace the existing compare operand with the properly zero-extended one.
10248   SmallVector<SDValue, 4> Ops;
10249   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10250     Ops.push_back(AtomicNode->getOperand(i));
10251   Ops[2] = NewCmpOp;
10252   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10253   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10254   auto NodeTy =
10255     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10256   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10257 }
10258 
10259 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10260                                                  SelectionDAG &DAG) const {
10261   SDLoc dl(Op);
10262   // Create a stack slot that is 16-byte aligned.
10263   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10264   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10265   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10266   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10267 
10268   // Store the input value into Value#0 of the stack slot.
10269   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10270                                MachinePointerInfo());
10271   // Load it out.
10272   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10273 }
10274 
10275 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10276                                                   SelectionDAG &DAG) const {
10277   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10278          "Should only be called for ISD::INSERT_VECTOR_ELT");
10279 
10280   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10281 
10282   EVT VT = Op.getValueType();
10283   SDLoc dl(Op);
10284   SDValue V1 = Op.getOperand(0);
10285   SDValue V2 = Op.getOperand(1);
10286   SDValue V3 = Op.getOperand(2);
10287 
10288   if (Subtarget.isISA3_1()) {
10289     // On P10, we have legal lowering for constant and variable indices for
10290     // integer vectors.
10291     if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
10292         VT == MVT::v2i64)
10293       return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3);
10294     // For f32 and f64 vectors, we have legal lowering for variable indices.
10295     // For f32 we also have legal lowering when the element is loaded from
10296     // memory.
10297     if (VT == MVT::v4f32 || VT == MVT::v2f64) {
10298       if (!C || (VT == MVT::v4f32 && dyn_cast<LoadSDNode>(V2)))
10299         return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3);
10300       return SDValue();
10301     }
10302   }
10303 
10304   // Before P10, we have legal lowering for constant indices but not for
10305   // variable ones.
10306   if (!C)
10307     return SDValue();
10308 
10309   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10310   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10311     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10312     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10313     unsigned InsertAtElement = C->getZExtValue();
10314     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10315     if (Subtarget.isLittleEndian()) {
10316       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10317     }
10318     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10319                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10320   }
10321   return Op;
10322 }
10323 
10324 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10325                                            SelectionDAG &DAG) const {
10326   SDLoc dl(Op);
10327   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10328   SDValue LoadChain = LN->getChain();
10329   SDValue BasePtr = LN->getBasePtr();
10330   EVT VT = Op.getValueType();
10331 
10332   if (VT != MVT::v256i1 && VT != MVT::v512i1)
10333     return Op;
10334 
10335   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10336   // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
10337   // 2 or 4 vsx registers.
10338   assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
10339          "Type unsupported without MMA");
10340   assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10341          "Type unsupported without paired vector support");
10342   Align Alignment = LN->getAlign();
10343   SmallVector<SDValue, 4> Loads;
10344   SmallVector<SDValue, 4> LoadChains;
10345   unsigned NumVecs = VT.getSizeInBits() / 128;
10346   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10347     SDValue Load =
10348         DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
10349                     LN->getPointerInfo().getWithOffset(Idx * 16),
10350                     commonAlignment(Alignment, Idx * 16),
10351                     LN->getMemOperand()->getFlags(), LN->getAAInfo());
10352     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10353                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10354     Loads.push_back(Load);
10355     LoadChains.push_back(Load.getValue(1));
10356   }
10357   if (Subtarget.isLittleEndian()) {
10358     std::reverse(Loads.begin(), Loads.end());
10359     std::reverse(LoadChains.begin(), LoadChains.end());
10360   }
10361   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10362   SDValue Value =
10363       DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
10364                   dl, VT, Loads);
10365   SDValue RetOps[] = {Value, TF};
10366   return DAG.getMergeValues(RetOps, dl);
10367 }
10368 
10369 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10370                                             SelectionDAG &DAG) const {
10371   SDLoc dl(Op);
10372   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10373   SDValue StoreChain = SN->getChain();
10374   SDValue BasePtr = SN->getBasePtr();
10375   SDValue Value = SN->getValue();
10376   EVT StoreVT = Value.getValueType();
10377 
10378   if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
10379     return Op;
10380 
10381   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10382   // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
10383   // underlying registers individually.
10384   assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
10385          "Type unsupported without MMA");
10386   assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10387          "Type unsupported without paired vector support");
10388   Align Alignment = SN->getAlign();
10389   SmallVector<SDValue, 4> Stores;
10390   unsigned NumVecs = 2;
10391   if (StoreVT == MVT::v512i1) {
10392     Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
10393     NumVecs = 4;
10394   }
10395   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10396     unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
10397     SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
10398                               DAG.getConstant(VecNum, dl, MVT::i64));
10399     SDValue Store =
10400         DAG.getStore(StoreChain, dl, Elt, BasePtr,
10401                      SN->getPointerInfo().getWithOffset(Idx * 16),
10402                      commonAlignment(Alignment, Idx * 16),
10403                      SN->getMemOperand()->getFlags(), SN->getAAInfo());
10404     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10405                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10406     Stores.push_back(Store);
10407   }
10408   SDValue TF = DAG.getTokenFactor(dl, Stores);
10409   return TF;
10410 }
10411 
10412 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10413   SDLoc dl(Op);
10414   if (Op.getValueType() == MVT::v4i32) {
10415     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10416 
10417     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10418     // +16 as shift amt.
10419     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10420     SDValue RHSSwap =   // = vrlw RHS, 16
10421       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10422 
10423     // Shrinkify inputs to v8i16.
10424     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10425     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10426     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10427 
10428     // Low parts multiplied together, generating 32-bit results (we ignore the
10429     // top parts).
10430     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10431                                         LHS, RHS, DAG, dl, MVT::v4i32);
10432 
10433     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10434                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10435     // Shift the high parts up 16 bits.
10436     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10437                               Neg16, DAG, dl);
10438     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10439   } else if (Op.getValueType() == MVT::v16i8) {
10440     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10441     bool isLittleEndian = Subtarget.isLittleEndian();
10442 
10443     // Multiply the even 8-bit parts, producing 16-bit sums.
10444     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10445                                            LHS, RHS, DAG, dl, MVT::v8i16);
10446     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10447 
10448     // Multiply the odd 8-bit parts, producing 16-bit sums.
10449     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10450                                           LHS, RHS, DAG, dl, MVT::v8i16);
10451     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10452 
10453     // Merge the results together.  Because vmuleub and vmuloub are
10454     // instructions with a big-endian bias, we must reverse the
10455     // element numbering and reverse the meaning of "odd" and "even"
10456     // when generating little endian code.
10457     int Ops[16];
10458     for (unsigned i = 0; i != 8; ++i) {
10459       if (isLittleEndian) {
10460         Ops[i*2  ] = 2*i;
10461         Ops[i*2+1] = 2*i+16;
10462       } else {
10463         Ops[i*2  ] = 2*i+1;
10464         Ops[i*2+1] = 2*i+1+16;
10465       }
10466     }
10467     if (isLittleEndian)
10468       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10469     else
10470       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10471   } else {
10472     llvm_unreachable("Unknown mul to lower!");
10473   }
10474 }
10475 
10476 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10477   bool IsStrict = Op->isStrictFPOpcode();
10478   if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
10479       !Subtarget.hasP9Vector())
10480     return SDValue();
10481 
10482   return Op;
10483 }
10484 
10485 // Custom lowering for fpext vf32 to v2f64
10486 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10487 
10488   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10489          "Should only be called for ISD::FP_EXTEND");
10490 
10491   // FIXME: handle extends from half precision float vectors on P9.
10492   // We only want to custom lower an extend from v2f32 to v2f64.
10493   if (Op.getValueType() != MVT::v2f64 ||
10494       Op.getOperand(0).getValueType() != MVT::v2f32)
10495     return SDValue();
10496 
10497   SDLoc dl(Op);
10498   SDValue Op0 = Op.getOperand(0);
10499 
10500   switch (Op0.getOpcode()) {
10501   default:
10502     return SDValue();
10503   case ISD::EXTRACT_SUBVECTOR: {
10504     assert(Op0.getNumOperands() == 2 &&
10505            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10506            "Node should have 2 operands with second one being a constant!");
10507 
10508     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10509       return SDValue();
10510 
10511     // Custom lower is only done for high or low doubleword.
10512     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10513     if (Idx % 2 != 0)
10514       return SDValue();
10515 
10516     // Since input is v4f32, at this point Idx is either 0 or 2.
10517     // Shift to get the doubleword position we want.
10518     int DWord = Idx >> 1;
10519 
10520     // High and low word positions are different on little endian.
10521     if (Subtarget.isLittleEndian())
10522       DWord ^= 0x1;
10523 
10524     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10525                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10526   }
10527   case ISD::FADD:
10528   case ISD::FMUL:
10529   case ISD::FSUB: {
10530     SDValue NewLoad[2];
10531     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10532       // Ensure both input are loads.
10533       SDValue LdOp = Op0.getOperand(i);
10534       if (LdOp.getOpcode() != ISD::LOAD)
10535         return SDValue();
10536       // Generate new load node.
10537       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10538       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10539       NewLoad[i] = DAG.getMemIntrinsicNode(
10540           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10541           LD->getMemoryVT(), LD->getMemOperand());
10542     }
10543     SDValue NewOp =
10544         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10545                     NewLoad[1], Op0.getNode()->getFlags());
10546     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10547                        DAG.getConstant(0, dl, MVT::i32));
10548   }
10549   case ISD::LOAD: {
10550     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10551     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10552     SDValue NewLd = DAG.getMemIntrinsicNode(
10553         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10554         LD->getMemoryVT(), LD->getMemOperand());
10555     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10556                        DAG.getConstant(0, dl, MVT::i32));
10557   }
10558   }
10559   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10560 }
10561 
10562 /// LowerOperation - Provide custom lowering hooks for some operations.
10563 ///
10564 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10565   switch (Op.getOpcode()) {
10566   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10567   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10568   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10569   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10570   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10571   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10572   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10573   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10574   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10575 
10576   // Variable argument lowering.
10577   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10578   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10579   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10580 
10581   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10582   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10583   case ISD::GET_DYNAMIC_AREA_OFFSET:
10584     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10585 
10586   // Exception handling lowering.
10587   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10588   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10589   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10590 
10591   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10592   case ISD::STORE:              return LowerSTORE(Op, DAG);
10593   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10594   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10595   case ISD::STRICT_FP_TO_UINT:
10596   case ISD::STRICT_FP_TO_SINT:
10597   case ISD::FP_TO_UINT:
10598   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10599   case ISD::STRICT_UINT_TO_FP:
10600   case ISD::STRICT_SINT_TO_FP:
10601   case ISD::UINT_TO_FP:
10602   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10603   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10604 
10605   // Lower 64-bit shifts.
10606   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10607   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10608   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10609 
10610   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
10611   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
10612 
10613   // Vector-related lowering.
10614   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10615   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10616   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10617   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10618   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10619   case ISD::MUL:                return LowerMUL(Op, DAG);
10620   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10621   case ISD::STRICT_FP_ROUND:
10622   case ISD::FP_ROUND:
10623     return LowerFP_ROUND(Op, DAG);
10624   case ISD::ROTL:               return LowerROTL(Op, DAG);
10625 
10626   // For counter-based loop handling.
10627   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10628 
10629   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10630 
10631   // Frame & Return address.
10632   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10633   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10634 
10635   case ISD::INTRINSIC_VOID:
10636     return LowerINTRINSIC_VOID(Op, DAG);
10637   case ISD::BSWAP:
10638     return LowerBSWAP(Op, DAG);
10639   case ISD::ATOMIC_CMP_SWAP:
10640     return LowerATOMIC_CMP_SWAP(Op, DAG);
10641   }
10642 }
10643 
10644 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10645                                            SmallVectorImpl<SDValue>&Results,
10646                                            SelectionDAG &DAG) const {
10647   SDLoc dl(N);
10648   switch (N->getOpcode()) {
10649   default:
10650     llvm_unreachable("Do not know how to custom type legalize this operation!");
10651   case ISD::READCYCLECOUNTER: {
10652     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10653     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10654 
10655     Results.push_back(
10656         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10657     Results.push_back(RTB.getValue(2));
10658     break;
10659   }
10660   case ISD::INTRINSIC_W_CHAIN: {
10661     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10662         Intrinsic::loop_decrement)
10663       break;
10664 
10665     assert(N->getValueType(0) == MVT::i1 &&
10666            "Unexpected result type for CTR decrement intrinsic");
10667     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10668                                  N->getValueType(0));
10669     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10670     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10671                                  N->getOperand(1));
10672 
10673     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10674     Results.push_back(NewInt.getValue(1));
10675     break;
10676   }
10677   case ISD::VAARG: {
10678     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10679       return;
10680 
10681     EVT VT = N->getValueType(0);
10682 
10683     if (VT == MVT::i64) {
10684       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10685 
10686       Results.push_back(NewNode);
10687       Results.push_back(NewNode.getValue(1));
10688     }
10689     return;
10690   }
10691   case ISD::STRICT_FP_TO_SINT:
10692   case ISD::STRICT_FP_TO_UINT:
10693   case ISD::FP_TO_SINT:
10694   case ISD::FP_TO_UINT:
10695     // LowerFP_TO_INT() can only handle f32 and f64.
10696     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
10697         MVT::ppcf128)
10698       return;
10699     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10700     return;
10701   case ISD::TRUNCATE: {
10702     if (!N->getValueType(0).isVector())
10703       return;
10704     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
10705     if (Lowered)
10706       Results.push_back(Lowered);
10707     return;
10708   }
10709   case ISD::FSHL:
10710   case ISD::FSHR:
10711     // Don't handle funnel shifts here.
10712     return;
10713   case ISD::BITCAST:
10714     // Don't handle bitcast here.
10715     return;
10716   case ISD::FP_EXTEND:
10717     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
10718     if (Lowered)
10719       Results.push_back(Lowered);
10720     return;
10721   }
10722 }
10723 
10724 //===----------------------------------------------------------------------===//
10725 //  Other Lowering Code
10726 //===----------------------------------------------------------------------===//
10727 
10728 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10729   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10730   Function *Func = Intrinsic::getDeclaration(M, Id);
10731   return Builder.CreateCall(Func, {});
10732 }
10733 
10734 // The mappings for emitLeading/TrailingFence is taken from
10735 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10736 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10737                                                  Instruction *Inst,
10738                                                  AtomicOrdering Ord) const {
10739   if (Ord == AtomicOrdering::SequentiallyConsistent)
10740     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10741   if (isReleaseOrStronger(Ord))
10742     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10743   return nullptr;
10744 }
10745 
10746 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10747                                                   Instruction *Inst,
10748                                                   AtomicOrdering Ord) const {
10749   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10750     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10751     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10752     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10753     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10754       return Builder.CreateCall(
10755           Intrinsic::getDeclaration(
10756               Builder.GetInsertBlock()->getParent()->getParent(),
10757               Intrinsic::ppc_cfence, {Inst->getType()}),
10758           {Inst});
10759     // FIXME: Can use isync for rmw operation.
10760     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10761   }
10762   return nullptr;
10763 }
10764 
10765 MachineBasicBlock *
10766 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10767                                     unsigned AtomicSize,
10768                                     unsigned BinOpcode,
10769                                     unsigned CmpOpcode,
10770                                     unsigned CmpPred) const {
10771   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10772   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10773 
10774   auto LoadMnemonic = PPC::LDARX;
10775   auto StoreMnemonic = PPC::STDCX;
10776   switch (AtomicSize) {
10777   default:
10778     llvm_unreachable("Unexpected size of atomic entity");
10779   case 1:
10780     LoadMnemonic = PPC::LBARX;
10781     StoreMnemonic = PPC::STBCX;
10782     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10783     break;
10784   case 2:
10785     LoadMnemonic = PPC::LHARX;
10786     StoreMnemonic = PPC::STHCX;
10787     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10788     break;
10789   case 4:
10790     LoadMnemonic = PPC::LWARX;
10791     StoreMnemonic = PPC::STWCX;
10792     break;
10793   case 8:
10794     LoadMnemonic = PPC::LDARX;
10795     StoreMnemonic = PPC::STDCX;
10796     break;
10797   }
10798 
10799   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10800   MachineFunction *F = BB->getParent();
10801   MachineFunction::iterator It = ++BB->getIterator();
10802 
10803   Register dest = MI.getOperand(0).getReg();
10804   Register ptrA = MI.getOperand(1).getReg();
10805   Register ptrB = MI.getOperand(2).getReg();
10806   Register incr = MI.getOperand(3).getReg();
10807   DebugLoc dl = MI.getDebugLoc();
10808 
10809   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10810   MachineBasicBlock *loop2MBB =
10811     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10812   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10813   F->insert(It, loopMBB);
10814   if (CmpOpcode)
10815     F->insert(It, loop2MBB);
10816   F->insert(It, exitMBB);
10817   exitMBB->splice(exitMBB->begin(), BB,
10818                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10819   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10820 
10821   MachineRegisterInfo &RegInfo = F->getRegInfo();
10822   Register TmpReg = (!BinOpcode) ? incr :
10823     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10824                                            : &PPC::GPRCRegClass);
10825 
10826   //  thisMBB:
10827   //   ...
10828   //   fallthrough --> loopMBB
10829   BB->addSuccessor(loopMBB);
10830 
10831   //  loopMBB:
10832   //   l[wd]arx dest, ptr
10833   //   add r0, dest, incr
10834   //   st[wd]cx. r0, ptr
10835   //   bne- loopMBB
10836   //   fallthrough --> exitMBB
10837 
10838   // For max/min...
10839   //  loopMBB:
10840   //   l[wd]arx dest, ptr
10841   //   cmpl?[wd] incr, dest
10842   //   bgt exitMBB
10843   //  loop2MBB:
10844   //   st[wd]cx. dest, ptr
10845   //   bne- loopMBB
10846   //   fallthrough --> exitMBB
10847 
10848   BB = loopMBB;
10849   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10850     .addReg(ptrA).addReg(ptrB);
10851   if (BinOpcode)
10852     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10853   if (CmpOpcode) {
10854     // Signed comparisons of byte or halfword values must be sign-extended.
10855     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10856       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10857       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10858               ExtReg).addReg(dest);
10859       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10860         .addReg(incr).addReg(ExtReg);
10861     } else
10862       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10863         .addReg(incr).addReg(dest);
10864 
10865     BuildMI(BB, dl, TII->get(PPC::BCC))
10866       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10867     BB->addSuccessor(loop2MBB);
10868     BB->addSuccessor(exitMBB);
10869     BB = loop2MBB;
10870   }
10871   BuildMI(BB, dl, TII->get(StoreMnemonic))
10872     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10873   BuildMI(BB, dl, TII->get(PPC::BCC))
10874     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10875   BB->addSuccessor(loopMBB);
10876   BB->addSuccessor(exitMBB);
10877 
10878   //  exitMBB:
10879   //   ...
10880   BB = exitMBB;
10881   return BB;
10882 }
10883 
10884 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) {
10885   switch(MI.getOpcode()) {
10886   default:
10887     return false;
10888   case PPC::COPY:
10889     return TII->isSignExtended(MI);
10890   case PPC::LHA:
10891   case PPC::LHA8:
10892   case PPC::LHAU:
10893   case PPC::LHAU8:
10894   case PPC::LHAUX:
10895   case PPC::LHAUX8:
10896   case PPC::LHAX:
10897   case PPC::LHAX8:
10898   case PPC::LWA:
10899   case PPC::LWAUX:
10900   case PPC::LWAX:
10901   case PPC::LWAX_32:
10902   case PPC::LWA_32:
10903   case PPC::PLHA:
10904   case PPC::PLHA8:
10905   case PPC::PLHA8pc:
10906   case PPC::PLHApc:
10907   case PPC::PLWA:
10908   case PPC::PLWA8:
10909   case PPC::PLWA8pc:
10910   case PPC::PLWApc:
10911   case PPC::EXTSB:
10912   case PPC::EXTSB8:
10913   case PPC::EXTSB8_32_64:
10914   case PPC::EXTSB8_rec:
10915   case PPC::EXTSB_rec:
10916   case PPC::EXTSH:
10917   case PPC::EXTSH8:
10918   case PPC::EXTSH8_32_64:
10919   case PPC::EXTSH8_rec:
10920   case PPC::EXTSH_rec:
10921   case PPC::EXTSW:
10922   case PPC::EXTSWSLI:
10923   case PPC::EXTSWSLI_32_64:
10924   case PPC::EXTSWSLI_32_64_rec:
10925   case PPC::EXTSWSLI_rec:
10926   case PPC::EXTSW_32:
10927   case PPC::EXTSW_32_64:
10928   case PPC::EXTSW_32_64_rec:
10929   case PPC::EXTSW_rec:
10930   case PPC::SRAW:
10931   case PPC::SRAWI:
10932   case PPC::SRAWI_rec:
10933   case PPC::SRAW_rec:
10934     return true;
10935   }
10936   return false;
10937 }
10938 
10939 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10940     MachineInstr &MI, MachineBasicBlock *BB,
10941     bool is8bit, // operation
10942     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10943   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10944   const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10945 
10946   // If this is a signed comparison and the value being compared is not known
10947   // to be sign extended, sign extend it here.
10948   DebugLoc dl = MI.getDebugLoc();
10949   MachineFunction *F = BB->getParent();
10950   MachineRegisterInfo &RegInfo = F->getRegInfo();
10951   Register incr = MI.getOperand(3).getReg();
10952   bool IsSignExtended = Register::isVirtualRegister(incr) &&
10953     isSignExtended(*RegInfo.getVRegDef(incr), TII);
10954 
10955   if (CmpOpcode == PPC::CMPW && !IsSignExtended) {
10956     Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10957     BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg)
10958         .addReg(MI.getOperand(3).getReg());
10959     MI.getOperand(3).setReg(ValueReg);
10960   }
10961   // If we support part-word atomic mnemonics, just use them
10962   if (Subtarget.hasPartwordAtomics())
10963     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10964                             CmpPred);
10965 
10966   // In 64 bit mode we have to use 64 bits for addresses, even though the
10967   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10968   // registers without caring whether they're 32 or 64, but here we're
10969   // doing actual arithmetic on the addresses.
10970   bool is64bit = Subtarget.isPPC64();
10971   bool isLittleEndian = Subtarget.isLittleEndian();
10972   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10973 
10974   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10975   MachineFunction::iterator It = ++BB->getIterator();
10976 
10977   Register dest = MI.getOperand(0).getReg();
10978   Register ptrA = MI.getOperand(1).getReg();
10979   Register ptrB = MI.getOperand(2).getReg();
10980 
10981   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10982   MachineBasicBlock *loop2MBB =
10983       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10984   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10985   F->insert(It, loopMBB);
10986   if (CmpOpcode)
10987     F->insert(It, loop2MBB);
10988   F->insert(It, exitMBB);
10989   exitMBB->splice(exitMBB->begin(), BB,
10990                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10991   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10992 
10993   const TargetRegisterClass *RC =
10994       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10995   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10996 
10997   Register PtrReg = RegInfo.createVirtualRegister(RC);
10998   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10999   Register ShiftReg =
11000       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11001   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11002   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11003   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11004   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11005   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11006   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11007   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11008   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11009   Register Ptr1Reg;
11010   Register TmpReg =
11011       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11012 
11013   //  thisMBB:
11014   //   ...
11015   //   fallthrough --> loopMBB
11016   BB->addSuccessor(loopMBB);
11017 
11018   // The 4-byte load must be aligned, while a char or short may be
11019   // anywhere in the word.  Hence all this nasty bookkeeping code.
11020   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11021   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11022   //   xori shift, shift1, 24 [16]
11023   //   rlwinm ptr, ptr1, 0, 0, 29
11024   //   slw incr2, incr, shift
11025   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11026   //   slw mask, mask2, shift
11027   //  loopMBB:
11028   //   lwarx tmpDest, ptr
11029   //   add tmp, tmpDest, incr2
11030   //   andc tmp2, tmpDest, mask
11031   //   and tmp3, tmp, mask
11032   //   or tmp4, tmp3, tmp2
11033   //   stwcx. tmp4, ptr
11034   //   bne- loopMBB
11035   //   fallthrough --> exitMBB
11036   //   srw dest, tmpDest, shift
11037   if (ptrA != ZeroReg) {
11038     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11039     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11040         .addReg(ptrA)
11041         .addReg(ptrB);
11042   } else {
11043     Ptr1Reg = ptrB;
11044   }
11045   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11046   // mode.
11047   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11048       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11049       .addImm(3)
11050       .addImm(27)
11051       .addImm(is8bit ? 28 : 27);
11052   if (!isLittleEndian)
11053     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11054         .addReg(Shift1Reg)
11055         .addImm(is8bit ? 24 : 16);
11056   if (is64bit)
11057     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11058         .addReg(Ptr1Reg)
11059         .addImm(0)
11060         .addImm(61);
11061   else
11062     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11063         .addReg(Ptr1Reg)
11064         .addImm(0)
11065         .addImm(0)
11066         .addImm(29);
11067   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11068   if (is8bit)
11069     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11070   else {
11071     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11072     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11073         .addReg(Mask3Reg)
11074         .addImm(65535);
11075   }
11076   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11077       .addReg(Mask2Reg)
11078       .addReg(ShiftReg);
11079 
11080   BB = loopMBB;
11081   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11082       .addReg(ZeroReg)
11083       .addReg(PtrReg);
11084   if (BinOpcode)
11085     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11086         .addReg(Incr2Reg)
11087         .addReg(TmpDestReg);
11088   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11089       .addReg(TmpDestReg)
11090       .addReg(MaskReg);
11091   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11092   if (CmpOpcode) {
11093     // For unsigned comparisons, we can directly compare the shifted values.
11094     // For signed comparisons we shift and sign extend.
11095     Register SReg = RegInfo.createVirtualRegister(GPRC);
11096     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11097         .addReg(TmpDestReg)
11098         .addReg(MaskReg);
11099     unsigned ValueReg = SReg;
11100     unsigned CmpReg = Incr2Reg;
11101     if (CmpOpcode == PPC::CMPW) {
11102       ValueReg = RegInfo.createVirtualRegister(GPRC);
11103       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11104           .addReg(SReg)
11105           .addReg(ShiftReg);
11106       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11107       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11108           .addReg(ValueReg);
11109       ValueReg = ValueSReg;
11110       CmpReg = incr;
11111     }
11112     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11113         .addReg(CmpReg)
11114         .addReg(ValueReg);
11115     BuildMI(BB, dl, TII->get(PPC::BCC))
11116         .addImm(CmpPred)
11117         .addReg(PPC::CR0)
11118         .addMBB(exitMBB);
11119     BB->addSuccessor(loop2MBB);
11120     BB->addSuccessor(exitMBB);
11121     BB = loop2MBB;
11122   }
11123   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11124   BuildMI(BB, dl, TII->get(PPC::STWCX))
11125       .addReg(Tmp4Reg)
11126       .addReg(ZeroReg)
11127       .addReg(PtrReg);
11128   BuildMI(BB, dl, TII->get(PPC::BCC))
11129       .addImm(PPC::PRED_NE)
11130       .addReg(PPC::CR0)
11131       .addMBB(loopMBB);
11132   BB->addSuccessor(loopMBB);
11133   BB->addSuccessor(exitMBB);
11134 
11135   //  exitMBB:
11136   //   ...
11137   BB = exitMBB;
11138   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11139       .addReg(TmpDestReg)
11140       .addReg(ShiftReg);
11141   return BB;
11142 }
11143 
11144 llvm::MachineBasicBlock *
11145 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11146                                     MachineBasicBlock *MBB) const {
11147   DebugLoc DL = MI.getDebugLoc();
11148   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11149   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11150 
11151   MachineFunction *MF = MBB->getParent();
11152   MachineRegisterInfo &MRI = MF->getRegInfo();
11153 
11154   const BasicBlock *BB = MBB->getBasicBlock();
11155   MachineFunction::iterator I = ++MBB->getIterator();
11156 
11157   Register DstReg = MI.getOperand(0).getReg();
11158   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11159   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11160   Register mainDstReg = MRI.createVirtualRegister(RC);
11161   Register restoreDstReg = MRI.createVirtualRegister(RC);
11162 
11163   MVT PVT = getPointerTy(MF->getDataLayout());
11164   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11165          "Invalid Pointer Size!");
11166   // For v = setjmp(buf), we generate
11167   //
11168   // thisMBB:
11169   //  SjLjSetup mainMBB
11170   //  bl mainMBB
11171   //  v_restore = 1
11172   //  b sinkMBB
11173   //
11174   // mainMBB:
11175   //  buf[LabelOffset] = LR
11176   //  v_main = 0
11177   //
11178   // sinkMBB:
11179   //  v = phi(main, restore)
11180   //
11181 
11182   MachineBasicBlock *thisMBB = MBB;
11183   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11184   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11185   MF->insert(I, mainMBB);
11186   MF->insert(I, sinkMBB);
11187 
11188   MachineInstrBuilder MIB;
11189 
11190   // Transfer the remainder of BB and its successor edges to sinkMBB.
11191   sinkMBB->splice(sinkMBB->begin(), MBB,
11192                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11193   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11194 
11195   // Note that the structure of the jmp_buf used here is not compatible
11196   // with that used by libc, and is not designed to be. Specifically, it
11197   // stores only those 'reserved' registers that LLVM does not otherwise
11198   // understand how to spill. Also, by convention, by the time this
11199   // intrinsic is called, Clang has already stored the frame address in the
11200   // first slot of the buffer and stack address in the third. Following the
11201   // X86 target code, we'll store the jump address in the second slot. We also
11202   // need to save the TOC pointer (R2) to handle jumps between shared
11203   // libraries, and that will be stored in the fourth slot. The thread
11204   // identifier (R13) is not affected.
11205 
11206   // thisMBB:
11207   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11208   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11209   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11210 
11211   // Prepare IP either in reg.
11212   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11213   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11214   Register BufReg = MI.getOperand(1).getReg();
11215 
11216   if (Subtarget.is64BitELFABI()) {
11217     setUsesTOCBasePtr(*MBB->getParent());
11218     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11219               .addReg(PPC::X2)
11220               .addImm(TOCOffset)
11221               .addReg(BufReg)
11222               .cloneMemRefs(MI);
11223   }
11224 
11225   // Naked functions never have a base pointer, and so we use r1. For all
11226   // other functions, this decision must be delayed until during PEI.
11227   unsigned BaseReg;
11228   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11229     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11230   else
11231     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11232 
11233   MIB = BuildMI(*thisMBB, MI, DL,
11234                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11235             .addReg(BaseReg)
11236             .addImm(BPOffset)
11237             .addReg(BufReg)
11238             .cloneMemRefs(MI);
11239 
11240   // Setup
11241   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11242   MIB.addRegMask(TRI->getNoPreservedMask());
11243 
11244   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11245 
11246   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11247           .addMBB(mainMBB);
11248   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11249 
11250   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11251   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11252 
11253   // mainMBB:
11254   //  mainDstReg = 0
11255   MIB =
11256       BuildMI(mainMBB, DL,
11257               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11258 
11259   // Store IP
11260   if (Subtarget.isPPC64()) {
11261     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11262             .addReg(LabelReg)
11263             .addImm(LabelOffset)
11264             .addReg(BufReg);
11265   } else {
11266     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11267             .addReg(LabelReg)
11268             .addImm(LabelOffset)
11269             .addReg(BufReg);
11270   }
11271   MIB.cloneMemRefs(MI);
11272 
11273   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11274   mainMBB->addSuccessor(sinkMBB);
11275 
11276   // sinkMBB:
11277   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11278           TII->get(PPC::PHI), DstReg)
11279     .addReg(mainDstReg).addMBB(mainMBB)
11280     .addReg(restoreDstReg).addMBB(thisMBB);
11281 
11282   MI.eraseFromParent();
11283   return sinkMBB;
11284 }
11285 
11286 MachineBasicBlock *
11287 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11288                                      MachineBasicBlock *MBB) const {
11289   DebugLoc DL = MI.getDebugLoc();
11290   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11291 
11292   MachineFunction *MF = MBB->getParent();
11293   MachineRegisterInfo &MRI = MF->getRegInfo();
11294 
11295   MVT PVT = getPointerTy(MF->getDataLayout());
11296   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11297          "Invalid Pointer Size!");
11298 
11299   const TargetRegisterClass *RC =
11300     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11301   Register Tmp = MRI.createVirtualRegister(RC);
11302   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11303   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11304   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11305   unsigned BP =
11306       (PVT == MVT::i64)
11307           ? PPC::X30
11308           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11309                                                               : PPC::R30);
11310 
11311   MachineInstrBuilder MIB;
11312 
11313   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11314   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11315   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11316   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11317 
11318   Register BufReg = MI.getOperand(0).getReg();
11319 
11320   // Reload FP (the jumped-to function may not have had a
11321   // frame pointer, and if so, then its r31 will be restored
11322   // as necessary).
11323   if (PVT == MVT::i64) {
11324     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11325             .addImm(0)
11326             .addReg(BufReg);
11327   } else {
11328     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11329             .addImm(0)
11330             .addReg(BufReg);
11331   }
11332   MIB.cloneMemRefs(MI);
11333 
11334   // Reload IP
11335   if (PVT == MVT::i64) {
11336     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11337             .addImm(LabelOffset)
11338             .addReg(BufReg);
11339   } else {
11340     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11341             .addImm(LabelOffset)
11342             .addReg(BufReg);
11343   }
11344   MIB.cloneMemRefs(MI);
11345 
11346   // Reload SP
11347   if (PVT == MVT::i64) {
11348     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11349             .addImm(SPOffset)
11350             .addReg(BufReg);
11351   } else {
11352     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11353             .addImm(SPOffset)
11354             .addReg(BufReg);
11355   }
11356   MIB.cloneMemRefs(MI);
11357 
11358   // Reload BP
11359   if (PVT == MVT::i64) {
11360     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11361             .addImm(BPOffset)
11362             .addReg(BufReg);
11363   } else {
11364     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11365             .addImm(BPOffset)
11366             .addReg(BufReg);
11367   }
11368   MIB.cloneMemRefs(MI);
11369 
11370   // Reload TOC
11371   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11372     setUsesTOCBasePtr(*MBB->getParent());
11373     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11374               .addImm(TOCOffset)
11375               .addReg(BufReg)
11376               .cloneMemRefs(MI);
11377   }
11378 
11379   // Jump
11380   BuildMI(*MBB, MI, DL,
11381           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11382   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11383 
11384   MI.eraseFromParent();
11385   return MBB;
11386 }
11387 
11388 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11389   // If the function specifically requests inline stack probes, emit them.
11390   if (MF.getFunction().hasFnAttribute("probe-stack"))
11391     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11392            "inline-asm";
11393   return false;
11394 }
11395 
11396 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11397   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11398   unsigned StackAlign = TFI->getStackAlignment();
11399   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11400          "Unexpected stack alignment");
11401   // The default stack probe size is 4096 if the function has no
11402   // stack-probe-size attribute.
11403   unsigned StackProbeSize = 4096;
11404   const Function &Fn = MF.getFunction();
11405   if (Fn.hasFnAttribute("stack-probe-size"))
11406     Fn.getFnAttribute("stack-probe-size")
11407         .getValueAsString()
11408         .getAsInteger(0, StackProbeSize);
11409   // Round down to the stack alignment.
11410   StackProbeSize &= ~(StackAlign - 1);
11411   return StackProbeSize ? StackProbeSize : StackAlign;
11412 }
11413 
11414 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11415 // into three phases. In the first phase, it uses pseudo instruction
11416 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11417 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11418 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11419 // MaxCallFrameSize so that it can calculate correct data area pointer.
11420 MachineBasicBlock *
11421 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11422                                     MachineBasicBlock *MBB) const {
11423   const bool isPPC64 = Subtarget.isPPC64();
11424   MachineFunction *MF = MBB->getParent();
11425   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11426   DebugLoc DL = MI.getDebugLoc();
11427   const unsigned ProbeSize = getStackProbeSize(*MF);
11428   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11429   MachineRegisterInfo &MRI = MF->getRegInfo();
11430   // The CFG of probing stack looks as
11431   //         +-----+
11432   //         | MBB |
11433   //         +--+--+
11434   //            |
11435   //       +----v----+
11436   //  +--->+ TestMBB +---+
11437   //  |    +----+----+   |
11438   //  |         |        |
11439   //  |   +-----v----+   |
11440   //  +---+ BlockMBB |   |
11441   //      +----------+   |
11442   //                     |
11443   //       +---------+   |
11444   //       | TailMBB +<--+
11445   //       +---------+
11446   // In MBB, calculate previous frame pointer and final stack pointer.
11447   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11448   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11449   // TailMBB is spliced via \p MI.
11450   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11451   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11452   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11453 
11454   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11455   MF->insert(MBBIter, TestMBB);
11456   MF->insert(MBBIter, BlockMBB);
11457   MF->insert(MBBIter, TailMBB);
11458 
11459   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11460   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11461 
11462   Register DstReg = MI.getOperand(0).getReg();
11463   Register NegSizeReg = MI.getOperand(1).getReg();
11464   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11465   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11466   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11467   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11468 
11469   // Since value of NegSizeReg might be realigned in prologepilog, insert a
11470   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
11471   // NegSize.
11472   unsigned ProbeOpc;
11473   if (!MRI.hasOneNonDBGUse(NegSizeReg))
11474     ProbeOpc =
11475         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
11476   else
11477     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
11478     // and NegSizeReg will be allocated in the same phyreg to avoid
11479     // redundant copy when NegSizeReg has only one use which is current MI and
11480     // will be replaced by PREPARE_PROBED_ALLOCA then.
11481     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
11482                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
11483   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
11484       .addDef(ActualNegSizeReg)
11485       .addReg(NegSizeReg)
11486       .add(MI.getOperand(2))
11487       .add(MI.getOperand(3));
11488 
11489   // Calculate final stack pointer, which equals to SP + ActualNegSize.
11490   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
11491           FinalStackPtr)
11492       .addReg(SPReg)
11493       .addReg(ActualNegSizeReg);
11494 
11495   // Materialize a scratch register for update.
11496   int64_t NegProbeSize = -(int64_t)ProbeSize;
11497   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
11498   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11499   if (!isInt<16>(NegProbeSize)) {
11500     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11501     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
11502         .addImm(NegProbeSize >> 16);
11503     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
11504             ScratchReg)
11505         .addReg(TempReg)
11506         .addImm(NegProbeSize & 0xFFFF);
11507   } else
11508     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
11509         .addImm(NegProbeSize);
11510 
11511   {
11512     // Probing leading residual part.
11513     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11514     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
11515         .addReg(ActualNegSizeReg)
11516         .addReg(ScratchReg);
11517     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11518     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
11519         .addReg(Div)
11520         .addReg(ScratchReg);
11521     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11522     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
11523         .addReg(Mul)
11524         .addReg(ActualNegSizeReg);
11525     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11526         .addReg(FramePointer)
11527         .addReg(SPReg)
11528         .addReg(NegMod);
11529   }
11530 
11531   {
11532     // Remaining part should be multiple of ProbeSize.
11533     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
11534     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
11535         .addReg(SPReg)
11536         .addReg(FinalStackPtr);
11537     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
11538         .addImm(PPC::PRED_EQ)
11539         .addReg(CmpResult)
11540         .addMBB(TailMBB);
11541     TestMBB->addSuccessor(BlockMBB);
11542     TestMBB->addSuccessor(TailMBB);
11543   }
11544 
11545   {
11546     // Touch the block.
11547     // |P...|P...|P...
11548     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11549         .addReg(FramePointer)
11550         .addReg(SPReg)
11551         .addReg(ScratchReg);
11552     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
11553     BlockMBB->addSuccessor(TestMBB);
11554   }
11555 
11556   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
11557   // DYNAREAOFFSET pseudo instruction to get the future result.
11558   Register MaxCallFrameSizeReg =
11559       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11560   BuildMI(TailMBB, DL,
11561           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
11562           MaxCallFrameSizeReg)
11563       .add(MI.getOperand(2))
11564       .add(MI.getOperand(3));
11565   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
11566       .addReg(SPReg)
11567       .addReg(MaxCallFrameSizeReg);
11568 
11569   // Splice instructions after MI to TailMBB.
11570   TailMBB->splice(TailMBB->end(), MBB,
11571                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11572   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
11573   MBB->addSuccessor(TestMBB);
11574 
11575   // Delete the pseudo instruction.
11576   MI.eraseFromParent();
11577 
11578   ++NumDynamicAllocaProbed;
11579   return TailMBB;
11580 }
11581 
11582 MachineBasicBlock *
11583 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11584                                                MachineBasicBlock *BB) const {
11585   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11586       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11587     if (Subtarget.is64BitELFABI() &&
11588         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11589         !Subtarget.isUsingPCRelativeCalls()) {
11590       // Call lowering should have added an r2 operand to indicate a dependence
11591       // on the TOC base pointer value. It can't however, because there is no
11592       // way to mark the dependence as implicit there, and so the stackmap code
11593       // will confuse it with a regular operand. Instead, add the dependence
11594       // here.
11595       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11596     }
11597 
11598     return emitPatchPoint(MI, BB);
11599   }
11600 
11601   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11602       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11603     return emitEHSjLjSetJmp(MI, BB);
11604   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11605              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11606     return emitEHSjLjLongJmp(MI, BB);
11607   }
11608 
11609   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11610 
11611   // To "insert" these instructions we actually have to insert their
11612   // control-flow patterns.
11613   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11614   MachineFunction::iterator It = ++BB->getIterator();
11615 
11616   MachineFunction *F = BB->getParent();
11617 
11618   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11619       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11620       MI.getOpcode() == PPC::SELECT_I8) {
11621     SmallVector<MachineOperand, 2> Cond;
11622     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11623         MI.getOpcode() == PPC::SELECT_CC_I8)
11624       Cond.push_back(MI.getOperand(4));
11625     else
11626       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11627     Cond.push_back(MI.getOperand(1));
11628 
11629     DebugLoc dl = MI.getDebugLoc();
11630     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11631                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11632   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11633              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11634              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11635              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11636              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11637              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11638              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11639              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11640              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11641              MI.getOpcode() == PPC::SELECT_F4 ||
11642              MI.getOpcode() == PPC::SELECT_F8 ||
11643              MI.getOpcode() == PPC::SELECT_F16 ||
11644              MI.getOpcode() == PPC::SELECT_SPE ||
11645              MI.getOpcode() == PPC::SELECT_SPE4 ||
11646              MI.getOpcode() == PPC::SELECT_VRRC ||
11647              MI.getOpcode() == PPC::SELECT_VSFRC ||
11648              MI.getOpcode() == PPC::SELECT_VSSRC ||
11649              MI.getOpcode() == PPC::SELECT_VSRC) {
11650     // The incoming instruction knows the destination vreg to set, the
11651     // condition code register to branch on, the true/false values to
11652     // select between, and a branch opcode to use.
11653 
11654     //  thisMBB:
11655     //  ...
11656     //   TrueVal = ...
11657     //   cmpTY ccX, r1, r2
11658     //   bCC copy1MBB
11659     //   fallthrough --> copy0MBB
11660     MachineBasicBlock *thisMBB = BB;
11661     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11662     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11663     DebugLoc dl = MI.getDebugLoc();
11664     F->insert(It, copy0MBB);
11665     F->insert(It, sinkMBB);
11666 
11667     // Transfer the remainder of BB and its successor edges to sinkMBB.
11668     sinkMBB->splice(sinkMBB->begin(), BB,
11669                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11670     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11671 
11672     // Next, add the true and fallthrough blocks as its successors.
11673     BB->addSuccessor(copy0MBB);
11674     BB->addSuccessor(sinkMBB);
11675 
11676     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11677         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11678         MI.getOpcode() == PPC::SELECT_F16 ||
11679         MI.getOpcode() == PPC::SELECT_SPE4 ||
11680         MI.getOpcode() == PPC::SELECT_SPE ||
11681         MI.getOpcode() == PPC::SELECT_VRRC ||
11682         MI.getOpcode() == PPC::SELECT_VSFRC ||
11683         MI.getOpcode() == PPC::SELECT_VSSRC ||
11684         MI.getOpcode() == PPC::SELECT_VSRC) {
11685       BuildMI(BB, dl, TII->get(PPC::BC))
11686           .addReg(MI.getOperand(1).getReg())
11687           .addMBB(sinkMBB);
11688     } else {
11689       unsigned SelectPred = MI.getOperand(4).getImm();
11690       BuildMI(BB, dl, TII->get(PPC::BCC))
11691           .addImm(SelectPred)
11692           .addReg(MI.getOperand(1).getReg())
11693           .addMBB(sinkMBB);
11694     }
11695 
11696     //  copy0MBB:
11697     //   %FalseValue = ...
11698     //   # fallthrough to sinkMBB
11699     BB = copy0MBB;
11700 
11701     // Update machine-CFG edges
11702     BB->addSuccessor(sinkMBB);
11703 
11704     //  sinkMBB:
11705     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11706     //  ...
11707     BB = sinkMBB;
11708     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11709         .addReg(MI.getOperand(3).getReg())
11710         .addMBB(copy0MBB)
11711         .addReg(MI.getOperand(2).getReg())
11712         .addMBB(thisMBB);
11713   } else if (MI.getOpcode() == PPC::ReadTB) {
11714     // To read the 64-bit time-base register on a 32-bit target, we read the
11715     // two halves. Should the counter have wrapped while it was being read, we
11716     // need to try again.
11717     // ...
11718     // readLoop:
11719     // mfspr Rx,TBU # load from TBU
11720     // mfspr Ry,TB  # load from TB
11721     // mfspr Rz,TBU # load from TBU
11722     // cmpw crX,Rx,Rz # check if 'old'='new'
11723     // bne readLoop   # branch if they're not equal
11724     // ...
11725 
11726     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11727     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11728     DebugLoc dl = MI.getDebugLoc();
11729     F->insert(It, readMBB);
11730     F->insert(It, sinkMBB);
11731 
11732     // Transfer the remainder of BB and its successor edges to sinkMBB.
11733     sinkMBB->splice(sinkMBB->begin(), BB,
11734                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11735     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11736 
11737     BB->addSuccessor(readMBB);
11738     BB = readMBB;
11739 
11740     MachineRegisterInfo &RegInfo = F->getRegInfo();
11741     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11742     Register LoReg = MI.getOperand(0).getReg();
11743     Register HiReg = MI.getOperand(1).getReg();
11744 
11745     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11746     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11747     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11748 
11749     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11750 
11751     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11752         .addReg(HiReg)
11753         .addReg(ReadAgainReg);
11754     BuildMI(BB, dl, TII->get(PPC::BCC))
11755         .addImm(PPC::PRED_NE)
11756         .addReg(CmpReg)
11757         .addMBB(readMBB);
11758 
11759     BB->addSuccessor(readMBB);
11760     BB->addSuccessor(sinkMBB);
11761   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11762     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11763   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11764     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11765   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11766     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11767   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11768     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11769 
11770   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11771     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11772   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11773     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11774   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11775     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11776   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11777     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11778 
11779   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11780     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11781   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11782     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11783   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11784     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11785   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11786     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11787 
11788   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11789     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11790   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11791     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11792   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11793     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11794   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11795     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11796 
11797   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11798     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11799   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11800     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11801   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11802     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11803   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11804     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11805 
11806   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11807     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11808   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11809     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11810   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11811     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11812   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11813     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11814 
11815   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11816     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11817   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11818     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11819   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11820     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11821   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11822     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11823 
11824   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11825     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11826   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11827     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11828   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11829     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11830   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11831     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11832 
11833   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11834     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11835   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11836     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11837   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11838     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11839   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11840     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11841 
11842   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11843     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11844   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11845     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11846   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11847     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11848   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11849     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11850 
11851   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11852     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11853   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11854     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11855   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11856     BB = EmitAtomicBinary(MI, BB, 4, 0);
11857   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11858     BB = EmitAtomicBinary(MI, BB, 8, 0);
11859   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11860            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11861            (Subtarget.hasPartwordAtomics() &&
11862             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11863            (Subtarget.hasPartwordAtomics() &&
11864             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11865     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11866 
11867     auto LoadMnemonic = PPC::LDARX;
11868     auto StoreMnemonic = PPC::STDCX;
11869     switch (MI.getOpcode()) {
11870     default:
11871       llvm_unreachable("Compare and swap of unknown size");
11872     case PPC::ATOMIC_CMP_SWAP_I8:
11873       LoadMnemonic = PPC::LBARX;
11874       StoreMnemonic = PPC::STBCX;
11875       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11876       break;
11877     case PPC::ATOMIC_CMP_SWAP_I16:
11878       LoadMnemonic = PPC::LHARX;
11879       StoreMnemonic = PPC::STHCX;
11880       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11881       break;
11882     case PPC::ATOMIC_CMP_SWAP_I32:
11883       LoadMnemonic = PPC::LWARX;
11884       StoreMnemonic = PPC::STWCX;
11885       break;
11886     case PPC::ATOMIC_CMP_SWAP_I64:
11887       LoadMnemonic = PPC::LDARX;
11888       StoreMnemonic = PPC::STDCX;
11889       break;
11890     }
11891     Register dest = MI.getOperand(0).getReg();
11892     Register ptrA = MI.getOperand(1).getReg();
11893     Register ptrB = MI.getOperand(2).getReg();
11894     Register oldval = MI.getOperand(3).getReg();
11895     Register newval = MI.getOperand(4).getReg();
11896     DebugLoc dl = MI.getDebugLoc();
11897 
11898     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11899     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11900     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11901     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11902     F->insert(It, loop1MBB);
11903     F->insert(It, loop2MBB);
11904     F->insert(It, midMBB);
11905     F->insert(It, exitMBB);
11906     exitMBB->splice(exitMBB->begin(), BB,
11907                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11908     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11909 
11910     //  thisMBB:
11911     //   ...
11912     //   fallthrough --> loopMBB
11913     BB->addSuccessor(loop1MBB);
11914 
11915     // loop1MBB:
11916     //   l[bhwd]arx dest, ptr
11917     //   cmp[wd] dest, oldval
11918     //   bne- midMBB
11919     // loop2MBB:
11920     //   st[bhwd]cx. newval, ptr
11921     //   bne- loopMBB
11922     //   b exitBB
11923     // midMBB:
11924     //   st[bhwd]cx. dest, ptr
11925     // exitBB:
11926     BB = loop1MBB;
11927     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11928     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11929         .addReg(oldval)
11930         .addReg(dest);
11931     BuildMI(BB, dl, TII->get(PPC::BCC))
11932         .addImm(PPC::PRED_NE)
11933         .addReg(PPC::CR0)
11934         .addMBB(midMBB);
11935     BB->addSuccessor(loop2MBB);
11936     BB->addSuccessor(midMBB);
11937 
11938     BB = loop2MBB;
11939     BuildMI(BB, dl, TII->get(StoreMnemonic))
11940         .addReg(newval)
11941         .addReg(ptrA)
11942         .addReg(ptrB);
11943     BuildMI(BB, dl, TII->get(PPC::BCC))
11944         .addImm(PPC::PRED_NE)
11945         .addReg(PPC::CR0)
11946         .addMBB(loop1MBB);
11947     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11948     BB->addSuccessor(loop1MBB);
11949     BB->addSuccessor(exitMBB);
11950 
11951     BB = midMBB;
11952     BuildMI(BB, dl, TII->get(StoreMnemonic))
11953         .addReg(dest)
11954         .addReg(ptrA)
11955         .addReg(ptrB);
11956     BB->addSuccessor(exitMBB);
11957 
11958     //  exitMBB:
11959     //   ...
11960     BB = exitMBB;
11961   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11962              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11963     // We must use 64-bit registers for addresses when targeting 64-bit,
11964     // since we're actually doing arithmetic on them.  Other registers
11965     // can be 32-bit.
11966     bool is64bit = Subtarget.isPPC64();
11967     bool isLittleEndian = Subtarget.isLittleEndian();
11968     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11969 
11970     Register dest = MI.getOperand(0).getReg();
11971     Register ptrA = MI.getOperand(1).getReg();
11972     Register ptrB = MI.getOperand(2).getReg();
11973     Register oldval = MI.getOperand(3).getReg();
11974     Register newval = MI.getOperand(4).getReg();
11975     DebugLoc dl = MI.getDebugLoc();
11976 
11977     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11978     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11979     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11980     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11981     F->insert(It, loop1MBB);
11982     F->insert(It, loop2MBB);
11983     F->insert(It, midMBB);
11984     F->insert(It, exitMBB);
11985     exitMBB->splice(exitMBB->begin(), BB,
11986                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11987     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11988 
11989     MachineRegisterInfo &RegInfo = F->getRegInfo();
11990     const TargetRegisterClass *RC =
11991         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11992     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11993 
11994     Register PtrReg = RegInfo.createVirtualRegister(RC);
11995     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11996     Register ShiftReg =
11997         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11998     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11999     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12000     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12001     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12002     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12003     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12004     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12005     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12006     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12007     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12008     Register Ptr1Reg;
12009     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12010     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12011     //  thisMBB:
12012     //   ...
12013     //   fallthrough --> loopMBB
12014     BB->addSuccessor(loop1MBB);
12015 
12016     // The 4-byte load must be aligned, while a char or short may be
12017     // anywhere in the word.  Hence all this nasty bookkeeping code.
12018     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12019     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12020     //   xori shift, shift1, 24 [16]
12021     //   rlwinm ptr, ptr1, 0, 0, 29
12022     //   slw newval2, newval, shift
12023     //   slw oldval2, oldval,shift
12024     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12025     //   slw mask, mask2, shift
12026     //   and newval3, newval2, mask
12027     //   and oldval3, oldval2, mask
12028     // loop1MBB:
12029     //   lwarx tmpDest, ptr
12030     //   and tmp, tmpDest, mask
12031     //   cmpw tmp, oldval3
12032     //   bne- midMBB
12033     // loop2MBB:
12034     //   andc tmp2, tmpDest, mask
12035     //   or tmp4, tmp2, newval3
12036     //   stwcx. tmp4, ptr
12037     //   bne- loop1MBB
12038     //   b exitBB
12039     // midMBB:
12040     //   stwcx. tmpDest, ptr
12041     // exitBB:
12042     //   srw dest, tmpDest, shift
12043     if (ptrA != ZeroReg) {
12044       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12045       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12046           .addReg(ptrA)
12047           .addReg(ptrB);
12048     } else {
12049       Ptr1Reg = ptrB;
12050     }
12051 
12052     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12053     // mode.
12054     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12055         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12056         .addImm(3)
12057         .addImm(27)
12058         .addImm(is8bit ? 28 : 27);
12059     if (!isLittleEndian)
12060       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12061           .addReg(Shift1Reg)
12062           .addImm(is8bit ? 24 : 16);
12063     if (is64bit)
12064       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12065           .addReg(Ptr1Reg)
12066           .addImm(0)
12067           .addImm(61);
12068     else
12069       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12070           .addReg(Ptr1Reg)
12071           .addImm(0)
12072           .addImm(0)
12073           .addImm(29);
12074     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12075         .addReg(newval)
12076         .addReg(ShiftReg);
12077     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12078         .addReg(oldval)
12079         .addReg(ShiftReg);
12080     if (is8bit)
12081       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12082     else {
12083       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12084       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12085           .addReg(Mask3Reg)
12086           .addImm(65535);
12087     }
12088     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12089         .addReg(Mask2Reg)
12090         .addReg(ShiftReg);
12091     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12092         .addReg(NewVal2Reg)
12093         .addReg(MaskReg);
12094     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12095         .addReg(OldVal2Reg)
12096         .addReg(MaskReg);
12097 
12098     BB = loop1MBB;
12099     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12100         .addReg(ZeroReg)
12101         .addReg(PtrReg);
12102     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12103         .addReg(TmpDestReg)
12104         .addReg(MaskReg);
12105     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12106         .addReg(TmpReg)
12107         .addReg(OldVal3Reg);
12108     BuildMI(BB, dl, TII->get(PPC::BCC))
12109         .addImm(PPC::PRED_NE)
12110         .addReg(PPC::CR0)
12111         .addMBB(midMBB);
12112     BB->addSuccessor(loop2MBB);
12113     BB->addSuccessor(midMBB);
12114 
12115     BB = loop2MBB;
12116     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12117         .addReg(TmpDestReg)
12118         .addReg(MaskReg);
12119     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12120         .addReg(Tmp2Reg)
12121         .addReg(NewVal3Reg);
12122     BuildMI(BB, dl, TII->get(PPC::STWCX))
12123         .addReg(Tmp4Reg)
12124         .addReg(ZeroReg)
12125         .addReg(PtrReg);
12126     BuildMI(BB, dl, TII->get(PPC::BCC))
12127         .addImm(PPC::PRED_NE)
12128         .addReg(PPC::CR0)
12129         .addMBB(loop1MBB);
12130     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12131     BB->addSuccessor(loop1MBB);
12132     BB->addSuccessor(exitMBB);
12133 
12134     BB = midMBB;
12135     BuildMI(BB, dl, TII->get(PPC::STWCX))
12136         .addReg(TmpDestReg)
12137         .addReg(ZeroReg)
12138         .addReg(PtrReg);
12139     BB->addSuccessor(exitMBB);
12140 
12141     //  exitMBB:
12142     //   ...
12143     BB = exitMBB;
12144     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12145         .addReg(TmpReg)
12146         .addReg(ShiftReg);
12147   } else if (MI.getOpcode() == PPC::FADDrtz) {
12148     // This pseudo performs an FADD with rounding mode temporarily forced
12149     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12150     // is not modeled at the SelectionDAG level.
12151     Register Dest = MI.getOperand(0).getReg();
12152     Register Src1 = MI.getOperand(1).getReg();
12153     Register Src2 = MI.getOperand(2).getReg();
12154     DebugLoc dl = MI.getDebugLoc();
12155 
12156     MachineRegisterInfo &RegInfo = F->getRegInfo();
12157     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12158 
12159     // Save FPSCR value.
12160     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12161 
12162     // Set rounding mode to round-to-zero.
12163     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12164         .addImm(31)
12165         .addReg(PPC::RM, RegState::ImplicitDefine);
12166 
12167     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12168         .addImm(30)
12169         .addReg(PPC::RM, RegState::ImplicitDefine);
12170 
12171     // Perform addition.
12172     auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
12173                    .addReg(Src1)
12174                    .addReg(Src2);
12175     if (MI.getFlag(MachineInstr::NoFPExcept))
12176       MIB.setMIFlag(MachineInstr::NoFPExcept);
12177 
12178     // Restore FPSCR value.
12179     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12180   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12181              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12182              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12183              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12184     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12185                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12186                           ? PPC::ANDI8_rec
12187                           : PPC::ANDI_rec;
12188     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12189                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12190 
12191     MachineRegisterInfo &RegInfo = F->getRegInfo();
12192     Register Dest = RegInfo.createVirtualRegister(
12193         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12194 
12195     DebugLoc Dl = MI.getDebugLoc();
12196     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12197         .addReg(MI.getOperand(1).getReg())
12198         .addImm(1);
12199     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12200             MI.getOperand(0).getReg())
12201         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12202   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12203     DebugLoc Dl = MI.getDebugLoc();
12204     MachineRegisterInfo &RegInfo = F->getRegInfo();
12205     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12206     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12207     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12208             MI.getOperand(0).getReg())
12209         .addReg(CRReg);
12210   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12211     DebugLoc Dl = MI.getDebugLoc();
12212     unsigned Imm = MI.getOperand(1).getImm();
12213     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12214     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12215             MI.getOperand(0).getReg())
12216         .addReg(PPC::CR0EQ);
12217   } else if (MI.getOpcode() == PPC::SETRNDi) {
12218     DebugLoc dl = MI.getDebugLoc();
12219     Register OldFPSCRReg = MI.getOperand(0).getReg();
12220 
12221     // Save FPSCR value.
12222     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12223 
12224     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12225     // the following settings:
12226     //   00 Round to nearest
12227     //   01 Round to 0
12228     //   10 Round to +inf
12229     //   11 Round to -inf
12230 
12231     // When the operand is immediate, using the two least significant bits of
12232     // the immediate to set the bits 62:63 of FPSCR.
12233     unsigned Mode = MI.getOperand(1).getImm();
12234     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12235         .addImm(31)
12236         .addReg(PPC::RM, RegState::ImplicitDefine);
12237 
12238     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12239         .addImm(30)
12240         .addReg(PPC::RM, RegState::ImplicitDefine);
12241   } else if (MI.getOpcode() == PPC::SETRND) {
12242     DebugLoc dl = MI.getDebugLoc();
12243 
12244     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12245     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12246     // If the target doesn't have DirectMove, we should use stack to do the
12247     // conversion, because the target doesn't have the instructions like mtvsrd
12248     // or mfvsrd to do this conversion directly.
12249     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12250       if (Subtarget.hasDirectMove()) {
12251         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12252           .addReg(SrcReg);
12253       } else {
12254         // Use stack to do the register copy.
12255         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12256         MachineRegisterInfo &RegInfo = F->getRegInfo();
12257         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12258         if (RC == &PPC::F8RCRegClass) {
12259           // Copy register from F8RCRegClass to G8RCRegclass.
12260           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12261                  "Unsupported RegClass.");
12262 
12263           StoreOp = PPC::STFD;
12264           LoadOp = PPC::LD;
12265         } else {
12266           // Copy register from G8RCRegClass to F8RCRegclass.
12267           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12268                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12269                  "Unsupported RegClass.");
12270         }
12271 
12272         MachineFrameInfo &MFI = F->getFrameInfo();
12273         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12274 
12275         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12276             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12277             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12278             MFI.getObjectAlign(FrameIdx));
12279 
12280         // Store the SrcReg into the stack.
12281         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12282           .addReg(SrcReg)
12283           .addImm(0)
12284           .addFrameIndex(FrameIdx)
12285           .addMemOperand(MMOStore);
12286 
12287         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12288             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12289             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12290             MFI.getObjectAlign(FrameIdx));
12291 
12292         // Load from the stack where SrcReg is stored, and save to DestReg,
12293         // so we have done the RegClass conversion from RegClass::SrcReg to
12294         // RegClass::DestReg.
12295         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12296           .addImm(0)
12297           .addFrameIndex(FrameIdx)
12298           .addMemOperand(MMOLoad);
12299       }
12300     };
12301 
12302     Register OldFPSCRReg = MI.getOperand(0).getReg();
12303 
12304     // Save FPSCR value.
12305     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12306 
12307     // When the operand is gprc register, use two least significant bits of the
12308     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12309     //
12310     // copy OldFPSCRTmpReg, OldFPSCRReg
12311     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12312     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12313     // copy NewFPSCRReg, NewFPSCRTmpReg
12314     // mtfsf 255, NewFPSCRReg
12315     MachineOperand SrcOp = MI.getOperand(1);
12316     MachineRegisterInfo &RegInfo = F->getRegInfo();
12317     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12318 
12319     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12320 
12321     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12322     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12323 
12324     // The first operand of INSERT_SUBREG should be a register which has
12325     // subregisters, we only care about its RegClass, so we should use an
12326     // IMPLICIT_DEF register.
12327     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12328     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12329       .addReg(ImDefReg)
12330       .add(SrcOp)
12331       .addImm(1);
12332 
12333     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12334     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12335       .addReg(OldFPSCRTmpReg)
12336       .addReg(ExtSrcReg)
12337       .addImm(0)
12338       .addImm(62);
12339 
12340     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12341     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12342 
12343     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12344     // bits of FPSCR.
12345     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12346       .addImm(255)
12347       .addReg(NewFPSCRReg)
12348       .addImm(0)
12349       .addImm(0);
12350   } else if (MI.getOpcode() == PPC::SETFLM) {
12351     DebugLoc Dl = MI.getDebugLoc();
12352 
12353     // Result of setflm is previous FPSCR content, so we need to save it first.
12354     Register OldFPSCRReg = MI.getOperand(0).getReg();
12355     BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12356 
12357     // Put bits in 32:63 to FPSCR.
12358     Register NewFPSCRReg = MI.getOperand(1).getReg();
12359     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12360         .addImm(255)
12361         .addReg(NewFPSCRReg)
12362         .addImm(0)
12363         .addImm(0);
12364   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12365              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12366     return emitProbedAlloca(MI, BB);
12367   } else {
12368     llvm_unreachable("Unexpected instr type to insert");
12369   }
12370 
12371   MI.eraseFromParent(); // The pseudo instruction is gone now.
12372   return BB;
12373 }
12374 
12375 //===----------------------------------------------------------------------===//
12376 // Target Optimization Hooks
12377 //===----------------------------------------------------------------------===//
12378 
12379 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12380   // For the estimates, convergence is quadratic, so we essentially double the
12381   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12382   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12383   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12384   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12385   if (VT.getScalarType() == MVT::f64)
12386     RefinementSteps++;
12387   return RefinementSteps;
12388 }
12389 
12390 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
12391                                             const DenormalMode &Mode) const {
12392   // We only have VSX Vector Test for software Square Root.
12393   EVT VT = Op.getValueType();
12394   if (!isTypeLegal(MVT::i1) ||
12395       (VT != MVT::f64 &&
12396        ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
12397     return TargetLowering::getSqrtInputTest(Op, DAG, Mode);
12398 
12399   SDLoc DL(Op);
12400   // The output register of FTSQRT is CR field.
12401   SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
12402   // ftsqrt BF,FRB
12403   // Let e_b be the unbiased exponent of the double-precision
12404   // floating-point operand in register FRB.
12405   // fe_flag is set to 1 if either of the following conditions occurs.
12406   //   - The double-precision floating-point operand in register FRB is a zero,
12407   //     a NaN, or an infinity, or a negative value.
12408   //   - e_b is less than or equal to -970.
12409   // Otherwise fe_flag is set to 0.
12410   // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
12411   // not eligible for iteration. (zero/negative/infinity/nan or unbiased
12412   // exponent is less than -970)
12413   SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
12414   return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
12415                                     FTSQRT, SRIdxVal),
12416                  0);
12417 }
12418 
12419 SDValue
12420 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
12421                                                SelectionDAG &DAG) const {
12422   // We only have VSX Vector Square Root.
12423   EVT VT = Op.getValueType();
12424   if (VT != MVT::f64 &&
12425       ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
12426     return TargetLowering::getSqrtResultForDenormInput(Op, DAG);
12427 
12428   return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
12429 }
12430 
12431 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12432                                            int Enabled, int &RefinementSteps,
12433                                            bool &UseOneConstNR,
12434                                            bool Reciprocal) const {
12435   EVT VT = Operand.getValueType();
12436   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12437       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12438       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12439       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12440     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12441       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12442 
12443     // The Newton-Raphson computation with a single constant does not provide
12444     // enough accuracy on some CPUs.
12445     UseOneConstNR = !Subtarget.needsTwoConstNR();
12446     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12447   }
12448   return SDValue();
12449 }
12450 
12451 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12452                                             int Enabled,
12453                                             int &RefinementSteps) const {
12454   EVT VT = Operand.getValueType();
12455   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12456       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12457       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12458       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12459     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12460       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12461     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12462   }
12463   return SDValue();
12464 }
12465 
12466 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12467   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12468   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12469   // enabled for division), this functionality is redundant with the default
12470   // combiner logic (once the division -> reciprocal/multiply transformation
12471   // has taken place). As a result, this matters more for older cores than for
12472   // newer ones.
12473 
12474   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12475   // reciprocal if there are two or more FDIVs (for embedded cores with only
12476   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12477   switch (Subtarget.getCPUDirective()) {
12478   default:
12479     return 3;
12480   case PPC::DIR_440:
12481   case PPC::DIR_A2:
12482   case PPC::DIR_E500:
12483   case PPC::DIR_E500mc:
12484   case PPC::DIR_E5500:
12485     return 2;
12486   }
12487 }
12488 
12489 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12490 // collapsed, and so we need to look through chains of them.
12491 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12492                                      int64_t& Offset, SelectionDAG &DAG) {
12493   if (DAG.isBaseWithConstantOffset(Loc)) {
12494     Base = Loc.getOperand(0);
12495     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12496 
12497     // The base might itself be a base plus an offset, and if so, accumulate
12498     // that as well.
12499     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12500   }
12501 }
12502 
12503 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12504                             unsigned Bytes, int Dist,
12505                             SelectionDAG &DAG) {
12506   if (VT.getSizeInBits() / 8 != Bytes)
12507     return false;
12508 
12509   SDValue BaseLoc = Base->getBasePtr();
12510   if (Loc.getOpcode() == ISD::FrameIndex) {
12511     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12512       return false;
12513     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12514     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12515     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12516     int FS  = MFI.getObjectSize(FI);
12517     int BFS = MFI.getObjectSize(BFI);
12518     if (FS != BFS || FS != (int)Bytes) return false;
12519     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12520   }
12521 
12522   SDValue Base1 = Loc, Base2 = BaseLoc;
12523   int64_t Offset1 = 0, Offset2 = 0;
12524   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12525   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12526   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12527     return true;
12528 
12529   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12530   const GlobalValue *GV1 = nullptr;
12531   const GlobalValue *GV2 = nullptr;
12532   Offset1 = 0;
12533   Offset2 = 0;
12534   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12535   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12536   if (isGA1 && isGA2 && GV1 == GV2)
12537     return Offset1 == (Offset2 + Dist*Bytes);
12538   return false;
12539 }
12540 
12541 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12542 // not enforce equality of the chain operands.
12543 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12544                             unsigned Bytes, int Dist,
12545                             SelectionDAG &DAG) {
12546   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12547     EVT VT = LS->getMemoryVT();
12548     SDValue Loc = LS->getBasePtr();
12549     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12550   }
12551 
12552   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12553     EVT VT;
12554     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12555     default: return false;
12556     case Intrinsic::ppc_altivec_lvx:
12557     case Intrinsic::ppc_altivec_lvxl:
12558     case Intrinsic::ppc_vsx_lxvw4x:
12559     case Intrinsic::ppc_vsx_lxvw4x_be:
12560       VT = MVT::v4i32;
12561       break;
12562     case Intrinsic::ppc_vsx_lxvd2x:
12563     case Intrinsic::ppc_vsx_lxvd2x_be:
12564       VT = MVT::v2f64;
12565       break;
12566     case Intrinsic::ppc_altivec_lvebx:
12567       VT = MVT::i8;
12568       break;
12569     case Intrinsic::ppc_altivec_lvehx:
12570       VT = MVT::i16;
12571       break;
12572     case Intrinsic::ppc_altivec_lvewx:
12573       VT = MVT::i32;
12574       break;
12575     }
12576 
12577     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12578   }
12579 
12580   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12581     EVT VT;
12582     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12583     default: return false;
12584     case Intrinsic::ppc_altivec_stvx:
12585     case Intrinsic::ppc_altivec_stvxl:
12586     case Intrinsic::ppc_vsx_stxvw4x:
12587       VT = MVT::v4i32;
12588       break;
12589     case Intrinsic::ppc_vsx_stxvd2x:
12590       VT = MVT::v2f64;
12591       break;
12592     case Intrinsic::ppc_vsx_stxvw4x_be:
12593       VT = MVT::v4i32;
12594       break;
12595     case Intrinsic::ppc_vsx_stxvd2x_be:
12596       VT = MVT::v2f64;
12597       break;
12598     case Intrinsic::ppc_altivec_stvebx:
12599       VT = MVT::i8;
12600       break;
12601     case Intrinsic::ppc_altivec_stvehx:
12602       VT = MVT::i16;
12603       break;
12604     case Intrinsic::ppc_altivec_stvewx:
12605       VT = MVT::i32;
12606       break;
12607     }
12608 
12609     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12610   }
12611 
12612   return false;
12613 }
12614 
12615 // Return true is there is a nearyby consecutive load to the one provided
12616 // (regardless of alignment). We search up and down the chain, looking though
12617 // token factors and other loads (but nothing else). As a result, a true result
12618 // indicates that it is safe to create a new consecutive load adjacent to the
12619 // load provided.
12620 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12621   SDValue Chain = LD->getChain();
12622   EVT VT = LD->getMemoryVT();
12623 
12624   SmallSet<SDNode *, 16> LoadRoots;
12625   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12626   SmallSet<SDNode *, 16> Visited;
12627 
12628   // First, search up the chain, branching to follow all token-factor operands.
12629   // If we find a consecutive load, then we're done, otherwise, record all
12630   // nodes just above the top-level loads and token factors.
12631   while (!Queue.empty()) {
12632     SDNode *ChainNext = Queue.pop_back_val();
12633     if (!Visited.insert(ChainNext).second)
12634       continue;
12635 
12636     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12637       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12638         return true;
12639 
12640       if (!Visited.count(ChainLD->getChain().getNode()))
12641         Queue.push_back(ChainLD->getChain().getNode());
12642     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12643       for (const SDUse &O : ChainNext->ops())
12644         if (!Visited.count(O.getNode()))
12645           Queue.push_back(O.getNode());
12646     } else
12647       LoadRoots.insert(ChainNext);
12648   }
12649 
12650   // Second, search down the chain, starting from the top-level nodes recorded
12651   // in the first phase. These top-level nodes are the nodes just above all
12652   // loads and token factors. Starting with their uses, recursively look though
12653   // all loads (just the chain uses) and token factors to find a consecutive
12654   // load.
12655   Visited.clear();
12656   Queue.clear();
12657 
12658   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12659        IE = LoadRoots.end(); I != IE; ++I) {
12660     Queue.push_back(*I);
12661 
12662     while (!Queue.empty()) {
12663       SDNode *LoadRoot = Queue.pop_back_val();
12664       if (!Visited.insert(LoadRoot).second)
12665         continue;
12666 
12667       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12668         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12669           return true;
12670 
12671       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12672            UE = LoadRoot->use_end(); UI != UE; ++UI)
12673         if (((isa<MemSDNode>(*UI) &&
12674             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12675             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12676           Queue.push_back(*UI);
12677     }
12678   }
12679 
12680   return false;
12681 }
12682 
12683 /// This function is called when we have proved that a SETCC node can be replaced
12684 /// by subtraction (and other supporting instructions) so that the result of
12685 /// comparison is kept in a GPR instead of CR. This function is purely for
12686 /// codegen purposes and has some flags to guide the codegen process.
12687 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12688                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12689   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12690 
12691   // Zero extend the operands to the largest legal integer. Originally, they
12692   // must be of a strictly smaller size.
12693   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12694                          DAG.getConstant(Size, DL, MVT::i32));
12695   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12696                          DAG.getConstant(Size, DL, MVT::i32));
12697 
12698   // Swap if needed. Depends on the condition code.
12699   if (Swap)
12700     std::swap(Op0, Op1);
12701 
12702   // Subtract extended integers.
12703   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12704 
12705   // Move the sign bit to the least significant position and zero out the rest.
12706   // Now the least significant bit carries the result of original comparison.
12707   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12708                              DAG.getConstant(Size - 1, DL, MVT::i32));
12709   auto Final = Shifted;
12710 
12711   // Complement the result if needed. Based on the condition code.
12712   if (Complement)
12713     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12714                         DAG.getConstant(1, DL, MVT::i64));
12715 
12716   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12717 }
12718 
12719 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12720                                                   DAGCombinerInfo &DCI) const {
12721   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12722 
12723   SelectionDAG &DAG = DCI.DAG;
12724   SDLoc DL(N);
12725 
12726   // Size of integers being compared has a critical role in the following
12727   // analysis, so we prefer to do this when all types are legal.
12728   if (!DCI.isAfterLegalizeDAG())
12729     return SDValue();
12730 
12731   // If all users of SETCC extend its value to a legal integer type
12732   // then we replace SETCC with a subtraction
12733   for (SDNode::use_iterator UI = N->use_begin(),
12734        UE = N->use_end(); UI != UE; ++UI) {
12735     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12736       return SDValue();
12737   }
12738 
12739   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12740   auto OpSize = N->getOperand(0).getValueSizeInBits();
12741 
12742   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12743 
12744   if (OpSize < Size) {
12745     switch (CC) {
12746     default: break;
12747     case ISD::SETULT:
12748       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12749     case ISD::SETULE:
12750       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12751     case ISD::SETUGT:
12752       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12753     case ISD::SETUGE:
12754       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12755     }
12756   }
12757 
12758   return SDValue();
12759 }
12760 
12761 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12762                                                   DAGCombinerInfo &DCI) const {
12763   SelectionDAG &DAG = DCI.DAG;
12764   SDLoc dl(N);
12765 
12766   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12767   // If we're tracking CR bits, we need to be careful that we don't have:
12768   //   trunc(binary-ops(zext(x), zext(y)))
12769   // or
12770   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12771   // such that we're unnecessarily moving things into GPRs when it would be
12772   // better to keep them in CR bits.
12773 
12774   // Note that trunc here can be an actual i1 trunc, or can be the effective
12775   // truncation that comes from a setcc or select_cc.
12776   if (N->getOpcode() == ISD::TRUNCATE &&
12777       N->getValueType(0) != MVT::i1)
12778     return SDValue();
12779 
12780   if (N->getOperand(0).getValueType() != MVT::i32 &&
12781       N->getOperand(0).getValueType() != MVT::i64)
12782     return SDValue();
12783 
12784   if (N->getOpcode() == ISD::SETCC ||
12785       N->getOpcode() == ISD::SELECT_CC) {
12786     // If we're looking at a comparison, then we need to make sure that the
12787     // high bits (all except for the first) don't matter the result.
12788     ISD::CondCode CC =
12789       cast<CondCodeSDNode>(N->getOperand(
12790         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12791     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12792 
12793     if (ISD::isSignedIntSetCC(CC)) {
12794       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12795           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12796         return SDValue();
12797     } else if (ISD::isUnsignedIntSetCC(CC)) {
12798       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12799                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12800           !DAG.MaskedValueIsZero(N->getOperand(1),
12801                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12802         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12803                                              : SDValue());
12804     } else {
12805       // This is neither a signed nor an unsigned comparison, just make sure
12806       // that the high bits are equal.
12807       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12808       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12809 
12810       // We don't really care about what is known about the first bit (if
12811       // anything), so pretend that it is known zero for both to ensure they can
12812       // be compared as constants.
12813       Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
12814       Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
12815 
12816       if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
12817           Op1Known.getConstant() != Op2Known.getConstant())
12818         return SDValue();
12819     }
12820   }
12821 
12822   // We now know that the higher-order bits are irrelevant, we just need to
12823   // make sure that all of the intermediate operations are bit operations, and
12824   // all inputs are extensions.
12825   if (N->getOperand(0).getOpcode() != ISD::AND &&
12826       N->getOperand(0).getOpcode() != ISD::OR  &&
12827       N->getOperand(0).getOpcode() != ISD::XOR &&
12828       N->getOperand(0).getOpcode() != ISD::SELECT &&
12829       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12830       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12831       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12832       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12833       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12834     return SDValue();
12835 
12836   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12837       N->getOperand(1).getOpcode() != ISD::AND &&
12838       N->getOperand(1).getOpcode() != ISD::OR  &&
12839       N->getOperand(1).getOpcode() != ISD::XOR &&
12840       N->getOperand(1).getOpcode() != ISD::SELECT &&
12841       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12842       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12843       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12844       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12845       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12846     return SDValue();
12847 
12848   SmallVector<SDValue, 4> Inputs;
12849   SmallVector<SDValue, 8> BinOps, PromOps;
12850   SmallPtrSet<SDNode *, 16> Visited;
12851 
12852   for (unsigned i = 0; i < 2; ++i) {
12853     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12854           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12855           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12856           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12857         isa<ConstantSDNode>(N->getOperand(i)))
12858       Inputs.push_back(N->getOperand(i));
12859     else
12860       BinOps.push_back(N->getOperand(i));
12861 
12862     if (N->getOpcode() == ISD::TRUNCATE)
12863       break;
12864   }
12865 
12866   // Visit all inputs, collect all binary operations (and, or, xor and
12867   // select) that are all fed by extensions.
12868   while (!BinOps.empty()) {
12869     SDValue BinOp = BinOps.pop_back_val();
12870 
12871     if (!Visited.insert(BinOp.getNode()).second)
12872       continue;
12873 
12874     PromOps.push_back(BinOp);
12875 
12876     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12877       // The condition of the select is not promoted.
12878       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12879         continue;
12880       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12881         continue;
12882 
12883       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12884             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12885             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12886            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12887           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12888         Inputs.push_back(BinOp.getOperand(i));
12889       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12890                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12891                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12892                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12893                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12894                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12895                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12896                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12897                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12898         BinOps.push_back(BinOp.getOperand(i));
12899       } else {
12900         // We have an input that is not an extension or another binary
12901         // operation; we'll abort this transformation.
12902         return SDValue();
12903       }
12904     }
12905   }
12906 
12907   // Make sure that this is a self-contained cluster of operations (which
12908   // is not quite the same thing as saying that everything has only one
12909   // use).
12910   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12911     if (isa<ConstantSDNode>(Inputs[i]))
12912       continue;
12913 
12914     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12915                               UE = Inputs[i].getNode()->use_end();
12916          UI != UE; ++UI) {
12917       SDNode *User = *UI;
12918       if (User != N && !Visited.count(User))
12919         return SDValue();
12920 
12921       // Make sure that we're not going to promote the non-output-value
12922       // operand(s) or SELECT or SELECT_CC.
12923       // FIXME: Although we could sometimes handle this, and it does occur in
12924       // practice that one of the condition inputs to the select is also one of
12925       // the outputs, we currently can't deal with this.
12926       if (User->getOpcode() == ISD::SELECT) {
12927         if (User->getOperand(0) == Inputs[i])
12928           return SDValue();
12929       } else if (User->getOpcode() == ISD::SELECT_CC) {
12930         if (User->getOperand(0) == Inputs[i] ||
12931             User->getOperand(1) == Inputs[i])
12932           return SDValue();
12933       }
12934     }
12935   }
12936 
12937   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12938     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12939                               UE = PromOps[i].getNode()->use_end();
12940          UI != UE; ++UI) {
12941       SDNode *User = *UI;
12942       if (User != N && !Visited.count(User))
12943         return SDValue();
12944 
12945       // Make sure that we're not going to promote the non-output-value
12946       // operand(s) or SELECT or SELECT_CC.
12947       // FIXME: Although we could sometimes handle this, and it does occur in
12948       // practice that one of the condition inputs to the select is also one of
12949       // the outputs, we currently can't deal with this.
12950       if (User->getOpcode() == ISD::SELECT) {
12951         if (User->getOperand(0) == PromOps[i])
12952           return SDValue();
12953       } else if (User->getOpcode() == ISD::SELECT_CC) {
12954         if (User->getOperand(0) == PromOps[i] ||
12955             User->getOperand(1) == PromOps[i])
12956           return SDValue();
12957       }
12958     }
12959   }
12960 
12961   // Replace all inputs with the extension operand.
12962   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12963     // Constants may have users outside the cluster of to-be-promoted nodes,
12964     // and so we need to replace those as we do the promotions.
12965     if (isa<ConstantSDNode>(Inputs[i]))
12966       continue;
12967     else
12968       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12969   }
12970 
12971   std::list<HandleSDNode> PromOpHandles;
12972   for (auto &PromOp : PromOps)
12973     PromOpHandles.emplace_back(PromOp);
12974 
12975   // Replace all operations (these are all the same, but have a different
12976   // (i1) return type). DAG.getNode will validate that the types of
12977   // a binary operator match, so go through the list in reverse so that
12978   // we've likely promoted both operands first. Any intermediate truncations or
12979   // extensions disappear.
12980   while (!PromOpHandles.empty()) {
12981     SDValue PromOp = PromOpHandles.back().getValue();
12982     PromOpHandles.pop_back();
12983 
12984     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12985         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12986         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12987         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12988       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12989           PromOp.getOperand(0).getValueType() != MVT::i1) {
12990         // The operand is not yet ready (see comment below).
12991         PromOpHandles.emplace_front(PromOp);
12992         continue;
12993       }
12994 
12995       SDValue RepValue = PromOp.getOperand(0);
12996       if (isa<ConstantSDNode>(RepValue))
12997         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12998 
12999       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13000       continue;
13001     }
13002 
13003     unsigned C;
13004     switch (PromOp.getOpcode()) {
13005     default:             C = 0; break;
13006     case ISD::SELECT:    C = 1; break;
13007     case ISD::SELECT_CC: C = 2; break;
13008     }
13009 
13010     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13011          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13012         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13013          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13014       // The to-be-promoted operands of this node have not yet been
13015       // promoted (this should be rare because we're going through the
13016       // list backward, but if one of the operands has several users in
13017       // this cluster of to-be-promoted nodes, it is possible).
13018       PromOpHandles.emplace_front(PromOp);
13019       continue;
13020     }
13021 
13022     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13023                                 PromOp.getNode()->op_end());
13024 
13025     // If there are any constant inputs, make sure they're replaced now.
13026     for (unsigned i = 0; i < 2; ++i)
13027       if (isa<ConstantSDNode>(Ops[C+i]))
13028         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13029 
13030     DAG.ReplaceAllUsesOfValueWith(PromOp,
13031       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13032   }
13033 
13034   // Now we're left with the initial truncation itself.
13035   if (N->getOpcode() == ISD::TRUNCATE)
13036     return N->getOperand(0);
13037 
13038   // Otherwise, this is a comparison. The operands to be compared have just
13039   // changed type (to i1), but everything else is the same.
13040   return SDValue(N, 0);
13041 }
13042 
13043 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13044                                                   DAGCombinerInfo &DCI) const {
13045   SelectionDAG &DAG = DCI.DAG;
13046   SDLoc dl(N);
13047 
13048   // If we're tracking CR bits, we need to be careful that we don't have:
13049   //   zext(binary-ops(trunc(x), trunc(y)))
13050   // or
13051   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13052   // such that we're unnecessarily moving things into CR bits that can more
13053   // efficiently stay in GPRs. Note that if we're not certain that the high
13054   // bits are set as required by the final extension, we still may need to do
13055   // some masking to get the proper behavior.
13056 
13057   // This same functionality is important on PPC64 when dealing with
13058   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13059   // the return values of functions. Because it is so similar, it is handled
13060   // here as well.
13061 
13062   if (N->getValueType(0) != MVT::i32 &&
13063       N->getValueType(0) != MVT::i64)
13064     return SDValue();
13065 
13066   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13067         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13068     return SDValue();
13069 
13070   if (N->getOperand(0).getOpcode() != ISD::AND &&
13071       N->getOperand(0).getOpcode() != ISD::OR  &&
13072       N->getOperand(0).getOpcode() != ISD::XOR &&
13073       N->getOperand(0).getOpcode() != ISD::SELECT &&
13074       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13075     return SDValue();
13076 
13077   SmallVector<SDValue, 4> Inputs;
13078   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13079   SmallPtrSet<SDNode *, 16> Visited;
13080 
13081   // Visit all inputs, collect all binary operations (and, or, xor and
13082   // select) that are all fed by truncations.
13083   while (!BinOps.empty()) {
13084     SDValue BinOp = BinOps.pop_back_val();
13085 
13086     if (!Visited.insert(BinOp.getNode()).second)
13087       continue;
13088 
13089     PromOps.push_back(BinOp);
13090 
13091     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13092       // The condition of the select is not promoted.
13093       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13094         continue;
13095       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13096         continue;
13097 
13098       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13099           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13100         Inputs.push_back(BinOp.getOperand(i));
13101       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13102                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13103                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13104                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13105                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13106         BinOps.push_back(BinOp.getOperand(i));
13107       } else {
13108         // We have an input that is not a truncation or another binary
13109         // operation; we'll abort this transformation.
13110         return SDValue();
13111       }
13112     }
13113   }
13114 
13115   // The operands of a select that must be truncated when the select is
13116   // promoted because the operand is actually part of the to-be-promoted set.
13117   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13118 
13119   // Make sure that this is a self-contained cluster of operations (which
13120   // is not quite the same thing as saying that everything has only one
13121   // use).
13122   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13123     if (isa<ConstantSDNode>(Inputs[i]))
13124       continue;
13125 
13126     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13127                               UE = Inputs[i].getNode()->use_end();
13128          UI != UE; ++UI) {
13129       SDNode *User = *UI;
13130       if (User != N && !Visited.count(User))
13131         return SDValue();
13132 
13133       // If we're going to promote the non-output-value operand(s) or SELECT or
13134       // SELECT_CC, record them for truncation.
13135       if (User->getOpcode() == ISD::SELECT) {
13136         if (User->getOperand(0) == Inputs[i])
13137           SelectTruncOp[0].insert(std::make_pair(User,
13138                                     User->getOperand(0).getValueType()));
13139       } else if (User->getOpcode() == ISD::SELECT_CC) {
13140         if (User->getOperand(0) == Inputs[i])
13141           SelectTruncOp[0].insert(std::make_pair(User,
13142                                     User->getOperand(0).getValueType()));
13143         if (User->getOperand(1) == Inputs[i])
13144           SelectTruncOp[1].insert(std::make_pair(User,
13145                                     User->getOperand(1).getValueType()));
13146       }
13147     }
13148   }
13149 
13150   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13151     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13152                               UE = PromOps[i].getNode()->use_end();
13153          UI != UE; ++UI) {
13154       SDNode *User = *UI;
13155       if (User != N && !Visited.count(User))
13156         return SDValue();
13157 
13158       // If we're going to promote the non-output-value operand(s) or SELECT or
13159       // SELECT_CC, record them for truncation.
13160       if (User->getOpcode() == ISD::SELECT) {
13161         if (User->getOperand(0) == PromOps[i])
13162           SelectTruncOp[0].insert(std::make_pair(User,
13163                                     User->getOperand(0).getValueType()));
13164       } else if (User->getOpcode() == ISD::SELECT_CC) {
13165         if (User->getOperand(0) == PromOps[i])
13166           SelectTruncOp[0].insert(std::make_pair(User,
13167                                     User->getOperand(0).getValueType()));
13168         if (User->getOperand(1) == PromOps[i])
13169           SelectTruncOp[1].insert(std::make_pair(User,
13170                                     User->getOperand(1).getValueType()));
13171       }
13172     }
13173   }
13174 
13175   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13176   bool ReallyNeedsExt = false;
13177   if (N->getOpcode() != ISD::ANY_EXTEND) {
13178     // If all of the inputs are not already sign/zero extended, then
13179     // we'll still need to do that at the end.
13180     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13181       if (isa<ConstantSDNode>(Inputs[i]))
13182         continue;
13183 
13184       unsigned OpBits =
13185         Inputs[i].getOperand(0).getValueSizeInBits();
13186       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13187 
13188       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13189            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13190                                   APInt::getHighBitsSet(OpBits,
13191                                                         OpBits-PromBits))) ||
13192           (N->getOpcode() == ISD::SIGN_EXTEND &&
13193            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13194              (OpBits-(PromBits-1)))) {
13195         ReallyNeedsExt = true;
13196         break;
13197       }
13198     }
13199   }
13200 
13201   // Replace all inputs, either with the truncation operand, or a
13202   // truncation or extension to the final output type.
13203   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13204     // Constant inputs need to be replaced with the to-be-promoted nodes that
13205     // use them because they might have users outside of the cluster of
13206     // promoted nodes.
13207     if (isa<ConstantSDNode>(Inputs[i]))
13208       continue;
13209 
13210     SDValue InSrc = Inputs[i].getOperand(0);
13211     if (Inputs[i].getValueType() == N->getValueType(0))
13212       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13213     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13214       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13215         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13216     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13217       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13218         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13219     else
13220       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13221         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13222   }
13223 
13224   std::list<HandleSDNode> PromOpHandles;
13225   for (auto &PromOp : PromOps)
13226     PromOpHandles.emplace_back(PromOp);
13227 
13228   // Replace all operations (these are all the same, but have a different
13229   // (promoted) return type). DAG.getNode will validate that the types of
13230   // a binary operator match, so go through the list in reverse so that
13231   // we've likely promoted both operands first.
13232   while (!PromOpHandles.empty()) {
13233     SDValue PromOp = PromOpHandles.back().getValue();
13234     PromOpHandles.pop_back();
13235 
13236     unsigned C;
13237     switch (PromOp.getOpcode()) {
13238     default:             C = 0; break;
13239     case ISD::SELECT:    C = 1; break;
13240     case ISD::SELECT_CC: C = 2; break;
13241     }
13242 
13243     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13244          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13245         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13246          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13247       // The to-be-promoted operands of this node have not yet been
13248       // promoted (this should be rare because we're going through the
13249       // list backward, but if one of the operands has several users in
13250       // this cluster of to-be-promoted nodes, it is possible).
13251       PromOpHandles.emplace_front(PromOp);
13252       continue;
13253     }
13254 
13255     // For SELECT and SELECT_CC nodes, we do a similar check for any
13256     // to-be-promoted comparison inputs.
13257     if (PromOp.getOpcode() == ISD::SELECT ||
13258         PromOp.getOpcode() == ISD::SELECT_CC) {
13259       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13260            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13261           (SelectTruncOp[1].count(PromOp.getNode()) &&
13262            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13263         PromOpHandles.emplace_front(PromOp);
13264         continue;
13265       }
13266     }
13267 
13268     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13269                                 PromOp.getNode()->op_end());
13270 
13271     // If this node has constant inputs, then they'll need to be promoted here.
13272     for (unsigned i = 0; i < 2; ++i) {
13273       if (!isa<ConstantSDNode>(Ops[C+i]))
13274         continue;
13275       if (Ops[C+i].getValueType() == N->getValueType(0))
13276         continue;
13277 
13278       if (N->getOpcode() == ISD::SIGN_EXTEND)
13279         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13280       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13281         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13282       else
13283         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13284     }
13285 
13286     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13287     // truncate them again to the original value type.
13288     if (PromOp.getOpcode() == ISD::SELECT ||
13289         PromOp.getOpcode() == ISD::SELECT_CC) {
13290       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13291       if (SI0 != SelectTruncOp[0].end())
13292         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13293       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13294       if (SI1 != SelectTruncOp[1].end())
13295         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13296     }
13297 
13298     DAG.ReplaceAllUsesOfValueWith(PromOp,
13299       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13300   }
13301 
13302   // Now we're left with the initial extension itself.
13303   if (!ReallyNeedsExt)
13304     return N->getOperand(0);
13305 
13306   // To zero extend, just mask off everything except for the first bit (in the
13307   // i1 case).
13308   if (N->getOpcode() == ISD::ZERO_EXTEND)
13309     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13310                        DAG.getConstant(APInt::getLowBitsSet(
13311                                          N->getValueSizeInBits(0), PromBits),
13312                                        dl, N->getValueType(0)));
13313 
13314   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13315          "Invalid extension type");
13316   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13317   SDValue ShiftCst =
13318       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13319   return DAG.getNode(
13320       ISD::SRA, dl, N->getValueType(0),
13321       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13322       ShiftCst);
13323 }
13324 
13325 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13326                                         DAGCombinerInfo &DCI) const {
13327   assert(N->getOpcode() == ISD::SETCC &&
13328          "Should be called with a SETCC node");
13329 
13330   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13331   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13332     SDValue LHS = N->getOperand(0);
13333     SDValue RHS = N->getOperand(1);
13334 
13335     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13336     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13337         LHS.hasOneUse())
13338       std::swap(LHS, RHS);
13339 
13340     // x == 0-y --> x+y == 0
13341     // x != 0-y --> x+y != 0
13342     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13343         RHS.hasOneUse()) {
13344       SDLoc DL(N);
13345       SelectionDAG &DAG = DCI.DAG;
13346       EVT VT = N->getValueType(0);
13347       EVT OpVT = LHS.getValueType();
13348       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13349       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13350     }
13351   }
13352 
13353   return DAGCombineTruncBoolExt(N, DCI);
13354 }
13355 
13356 // Is this an extending load from an f32 to an f64?
13357 static bool isFPExtLoad(SDValue Op) {
13358   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13359     return LD->getExtensionType() == ISD::EXTLOAD &&
13360       Op.getValueType() == MVT::f64;
13361   return false;
13362 }
13363 
13364 /// Reduces the number of fp-to-int conversion when building a vector.
13365 ///
13366 /// If this vector is built out of floating to integer conversions,
13367 /// transform it to a vector built out of floating point values followed by a
13368 /// single floating to integer conversion of the vector.
13369 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13370 /// becomes (fptosi (build_vector ($A, $B, ...)))
13371 SDValue PPCTargetLowering::
13372 combineElementTruncationToVectorTruncation(SDNode *N,
13373                                            DAGCombinerInfo &DCI) const {
13374   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13375          "Should be called with a BUILD_VECTOR node");
13376 
13377   SelectionDAG &DAG = DCI.DAG;
13378   SDLoc dl(N);
13379 
13380   SDValue FirstInput = N->getOperand(0);
13381   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13382          "The input operand must be an fp-to-int conversion.");
13383 
13384   // This combine happens after legalization so the fp_to_[su]i nodes are
13385   // already converted to PPCSISD nodes.
13386   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13387   if (FirstConversion == PPCISD::FCTIDZ ||
13388       FirstConversion == PPCISD::FCTIDUZ ||
13389       FirstConversion == PPCISD::FCTIWZ ||
13390       FirstConversion == PPCISD::FCTIWUZ) {
13391     bool IsSplat = true;
13392     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13393       FirstConversion == PPCISD::FCTIWUZ;
13394     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13395     SmallVector<SDValue, 4> Ops;
13396     EVT TargetVT = N->getValueType(0);
13397     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13398       SDValue NextOp = N->getOperand(i);
13399       if (NextOp.getOpcode() != PPCISD::MFVSR)
13400         return SDValue();
13401       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13402       if (NextConversion != FirstConversion)
13403         return SDValue();
13404       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13405       // This is not valid if the input was originally double precision. It is
13406       // also not profitable to do unless this is an extending load in which
13407       // case doing this combine will allow us to combine consecutive loads.
13408       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13409         return SDValue();
13410       if (N->getOperand(i) != FirstInput)
13411         IsSplat = false;
13412     }
13413 
13414     // If this is a splat, we leave it as-is since there will be only a single
13415     // fp-to-int conversion followed by a splat of the integer. This is better
13416     // for 32-bit and smaller ints and neutral for 64-bit ints.
13417     if (IsSplat)
13418       return SDValue();
13419 
13420     // Now that we know we have the right type of node, get its operands
13421     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13422       SDValue In = N->getOperand(i).getOperand(0);
13423       if (Is32Bit) {
13424         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13425         // here, we know that all inputs are extending loads so this is safe).
13426         if (In.isUndef())
13427           Ops.push_back(DAG.getUNDEF(SrcVT));
13428         else {
13429           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13430                                       MVT::f32, In.getOperand(0),
13431                                       DAG.getIntPtrConstant(1, dl));
13432           Ops.push_back(Trunc);
13433         }
13434       } else
13435         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13436     }
13437 
13438     unsigned Opcode;
13439     if (FirstConversion == PPCISD::FCTIDZ ||
13440         FirstConversion == PPCISD::FCTIWZ)
13441       Opcode = ISD::FP_TO_SINT;
13442     else
13443       Opcode = ISD::FP_TO_UINT;
13444 
13445     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13446     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13447     return DAG.getNode(Opcode, dl, TargetVT, BV);
13448   }
13449   return SDValue();
13450 }
13451 
13452 /// Reduce the number of loads when building a vector.
13453 ///
13454 /// Building a vector out of multiple loads can be converted to a load
13455 /// of the vector type if the loads are consecutive. If the loads are
13456 /// consecutive but in descending order, a shuffle is added at the end
13457 /// to reorder the vector.
13458 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13459   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13460          "Should be called with a BUILD_VECTOR node");
13461 
13462   SDLoc dl(N);
13463 
13464   // Return early for non byte-sized type, as they can't be consecutive.
13465   if (!N->getValueType(0).getVectorElementType().isByteSized())
13466     return SDValue();
13467 
13468   bool InputsAreConsecutiveLoads = true;
13469   bool InputsAreReverseConsecutive = true;
13470   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13471   SDValue FirstInput = N->getOperand(0);
13472   bool IsRoundOfExtLoad = false;
13473 
13474   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13475       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13476     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13477     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13478   }
13479   // Not a build vector of (possibly fp_rounded) loads.
13480   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13481       N->getNumOperands() == 1)
13482     return SDValue();
13483 
13484   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13485     // If any inputs are fp_round(extload), they all must be.
13486     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13487       return SDValue();
13488 
13489     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13490       N->getOperand(i);
13491     if (NextInput.getOpcode() != ISD::LOAD)
13492       return SDValue();
13493 
13494     SDValue PreviousInput =
13495       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13496     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13497     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13498 
13499     // If any inputs are fp_round(extload), they all must be.
13500     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13501       return SDValue();
13502 
13503     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13504       InputsAreConsecutiveLoads = false;
13505     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13506       InputsAreReverseConsecutive = false;
13507 
13508     // Exit early if the loads are neither consecutive nor reverse consecutive.
13509     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13510       return SDValue();
13511   }
13512 
13513   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13514          "The loads cannot be both consecutive and reverse consecutive.");
13515 
13516   SDValue FirstLoadOp =
13517     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13518   SDValue LastLoadOp =
13519     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13520                        N->getOperand(N->getNumOperands()-1);
13521 
13522   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13523   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13524   if (InputsAreConsecutiveLoads) {
13525     assert(LD1 && "Input needs to be a LoadSDNode.");
13526     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13527                        LD1->getBasePtr(), LD1->getPointerInfo(),
13528                        LD1->getAlignment());
13529   }
13530   if (InputsAreReverseConsecutive) {
13531     assert(LDL && "Input needs to be a LoadSDNode.");
13532     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13533                                LDL->getBasePtr(), LDL->getPointerInfo(),
13534                                LDL->getAlignment());
13535     SmallVector<int, 16> Ops;
13536     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13537       Ops.push_back(i);
13538 
13539     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13540                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13541   }
13542   return SDValue();
13543 }
13544 
13545 // This function adds the required vector_shuffle needed to get
13546 // the elements of the vector extract in the correct position
13547 // as specified by the CorrectElems encoding.
13548 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13549                                       SDValue Input, uint64_t Elems,
13550                                       uint64_t CorrectElems) {
13551   SDLoc dl(N);
13552 
13553   unsigned NumElems = Input.getValueType().getVectorNumElements();
13554   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13555 
13556   // Knowing the element indices being extracted from the original
13557   // vector and the order in which they're being inserted, just put
13558   // them at element indices required for the instruction.
13559   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13560     if (DAG.getDataLayout().isLittleEndian())
13561       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13562     else
13563       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13564     CorrectElems = CorrectElems >> 8;
13565     Elems = Elems >> 8;
13566   }
13567 
13568   SDValue Shuffle =
13569       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13570                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13571 
13572   EVT VT = N->getValueType(0);
13573   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13574 
13575   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13576                                Input.getValueType().getVectorElementType(),
13577                                VT.getVectorNumElements());
13578   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13579                      DAG.getValueType(ExtVT));
13580 }
13581 
13582 // Look for build vector patterns where input operands come from sign
13583 // extended vector_extract elements of specific indices. If the correct indices
13584 // aren't used, add a vector shuffle to fix up the indices and create
13585 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13586 // during instruction selection.
13587 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13588   // This array encodes the indices that the vector sign extend instructions
13589   // extract from when extending from one type to another for both BE and LE.
13590   // The right nibble of each byte corresponds to the LE incides.
13591   // and the left nibble of each byte corresponds to the BE incides.
13592   // For example: 0x3074B8FC  byte->word
13593   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13594   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13595   // For example: 0x000070F8  byte->double word
13596   // For LE: the allowed indices are: 0x0,0x8
13597   // For BE: the allowed indices are: 0x7,0xF
13598   uint64_t TargetElems[] = {
13599       0x3074B8FC, // b->w
13600       0x000070F8, // b->d
13601       0x10325476, // h->w
13602       0x00003074, // h->d
13603       0x00001032, // w->d
13604   };
13605 
13606   uint64_t Elems = 0;
13607   int Index;
13608   SDValue Input;
13609 
13610   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13611     if (!Op)
13612       return false;
13613     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13614         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13615       return false;
13616 
13617     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13618     // of the right width.
13619     SDValue Extract = Op.getOperand(0);
13620     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13621       Extract = Extract.getOperand(0);
13622     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13623       return false;
13624 
13625     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13626     if (!ExtOp)
13627       return false;
13628 
13629     Index = ExtOp->getZExtValue();
13630     if (Input && Input != Extract.getOperand(0))
13631       return false;
13632 
13633     if (!Input)
13634       Input = Extract.getOperand(0);
13635 
13636     Elems = Elems << 8;
13637     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13638     Elems |= Index;
13639 
13640     return true;
13641   };
13642 
13643   // If the build vector operands aren't sign extended vector extracts,
13644   // of the same input vector, then return.
13645   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13646     if (!isSExtOfVecExtract(N->getOperand(i))) {
13647       return SDValue();
13648     }
13649   }
13650 
13651   // If the vector extract indicies are not correct, add the appropriate
13652   // vector_shuffle.
13653   int TgtElemArrayIdx;
13654   int InputSize = Input.getValueType().getScalarSizeInBits();
13655   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13656   if (InputSize + OutputSize == 40)
13657     TgtElemArrayIdx = 0;
13658   else if (InputSize + OutputSize == 72)
13659     TgtElemArrayIdx = 1;
13660   else if (InputSize + OutputSize == 48)
13661     TgtElemArrayIdx = 2;
13662   else if (InputSize + OutputSize == 80)
13663     TgtElemArrayIdx = 3;
13664   else if (InputSize + OutputSize == 96)
13665     TgtElemArrayIdx = 4;
13666   else
13667     return SDValue();
13668 
13669   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13670   CorrectElems = DAG.getDataLayout().isLittleEndian()
13671                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13672                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13673   if (Elems != CorrectElems) {
13674     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13675   }
13676 
13677   // Regular lowering will catch cases where a shuffle is not needed.
13678   return SDValue();
13679 }
13680 
13681 // Look for the pattern of a load from a narrow width to i128, feeding
13682 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
13683 // (LXVRZX). This node represents a zero extending load that will be matched
13684 // to the Load VSX Vector Rightmost instructions.
13685 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
13686   SDLoc DL(N);
13687 
13688   // This combine is only eligible for a BUILD_VECTOR of v1i128.
13689   if (N->getValueType(0) != MVT::v1i128)
13690     return SDValue();
13691 
13692   SDValue Operand = N->getOperand(0);
13693   // Proceed with the transformation if the operand to the BUILD_VECTOR
13694   // is a load instruction.
13695   if (Operand.getOpcode() != ISD::LOAD)
13696     return SDValue();
13697 
13698   LoadSDNode *LD = dyn_cast<LoadSDNode>(Operand);
13699   EVT MemoryType = LD->getMemoryVT();
13700 
13701   // This transformation is only valid if the we are loading either a byte,
13702   // halfword, word, or doubleword.
13703   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
13704                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
13705 
13706   // Ensure that the load from the narrow width is being zero extended to i128.
13707   if (!ValidLDType ||
13708       (LD->getExtensionType() != ISD::ZEXTLOAD &&
13709        LD->getExtensionType() != ISD::EXTLOAD))
13710     return SDValue();
13711 
13712   SDValue LoadOps[] = {
13713       LD->getChain(), LD->getBasePtr(),
13714       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
13715 
13716   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
13717                                  DAG.getVTList(MVT::v1i128, MVT::Other),
13718                                  LoadOps, MemoryType, LD->getMemOperand());
13719 }
13720 
13721 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13722                                                  DAGCombinerInfo &DCI) const {
13723   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13724          "Should be called with a BUILD_VECTOR node");
13725 
13726   SelectionDAG &DAG = DCI.DAG;
13727   SDLoc dl(N);
13728 
13729   if (!Subtarget.hasVSX())
13730     return SDValue();
13731 
13732   // The target independent DAG combiner will leave a build_vector of
13733   // float-to-int conversions intact. We can generate MUCH better code for
13734   // a float-to-int conversion of a vector of floats.
13735   SDValue FirstInput = N->getOperand(0);
13736   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13737     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13738     if (Reduced)
13739       return Reduced;
13740   }
13741 
13742   // If we're building a vector out of consecutive loads, just load that
13743   // vector type.
13744   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13745   if (Reduced)
13746     return Reduced;
13747 
13748   // If we're building a vector out of extended elements from another vector
13749   // we have P9 vector integer extend instructions. The code assumes legal
13750   // input types (i.e. it can't handle things like v4i16) so do not run before
13751   // legalization.
13752   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13753     Reduced = combineBVOfVecSExt(N, DAG);
13754     if (Reduced)
13755       return Reduced;
13756   }
13757 
13758   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
13759   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
13760   // is a load from <valid narrow width> to i128.
13761   if (Subtarget.isISA3_1()) {
13762     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
13763     if (BVOfZLoad)
13764       return BVOfZLoad;
13765   }
13766 
13767   if (N->getValueType(0) != MVT::v2f64)
13768     return SDValue();
13769 
13770   // Looking for:
13771   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13772   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13773       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13774     return SDValue();
13775   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13776       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13777     return SDValue();
13778   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13779     return SDValue();
13780 
13781   SDValue Ext1 = FirstInput.getOperand(0);
13782   SDValue Ext2 = N->getOperand(1).getOperand(0);
13783   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13784      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13785     return SDValue();
13786 
13787   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13788   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13789   if (!Ext1Op || !Ext2Op)
13790     return SDValue();
13791   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13792       Ext1.getOperand(0) != Ext2.getOperand(0))
13793     return SDValue();
13794 
13795   int FirstElem = Ext1Op->getZExtValue();
13796   int SecondElem = Ext2Op->getZExtValue();
13797   int SubvecIdx;
13798   if (FirstElem == 0 && SecondElem == 1)
13799     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13800   else if (FirstElem == 2 && SecondElem == 3)
13801     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13802   else
13803     return SDValue();
13804 
13805   SDValue SrcVec = Ext1.getOperand(0);
13806   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13807     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13808   return DAG.getNode(NodeType, dl, MVT::v2f64,
13809                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13810 }
13811 
13812 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13813                                               DAGCombinerInfo &DCI) const {
13814   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13815           N->getOpcode() == ISD::UINT_TO_FP) &&
13816          "Need an int -> FP conversion node here");
13817 
13818   if (useSoftFloat() || !Subtarget.has64BitSupport())
13819     return SDValue();
13820 
13821   SelectionDAG &DAG = DCI.DAG;
13822   SDLoc dl(N);
13823   SDValue Op(N, 0);
13824 
13825   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13826   // from the hardware.
13827   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13828     return SDValue();
13829   if (!Op.getOperand(0).getValueType().isSimple())
13830     return SDValue();
13831   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13832       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13833     return SDValue();
13834 
13835   SDValue FirstOperand(Op.getOperand(0));
13836   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13837     (FirstOperand.getValueType() == MVT::i8 ||
13838      FirstOperand.getValueType() == MVT::i16);
13839   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13840     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13841     bool DstDouble = Op.getValueType() == MVT::f64;
13842     unsigned ConvOp = Signed ?
13843       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13844       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13845     SDValue WidthConst =
13846       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13847                             dl, false);
13848     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13849     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13850     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13851                                          DAG.getVTList(MVT::f64, MVT::Other),
13852                                          Ops, MVT::i8, LDN->getMemOperand());
13853 
13854     // For signed conversion, we need to sign-extend the value in the VSR
13855     if (Signed) {
13856       SDValue ExtOps[] = { Ld, WidthConst };
13857       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13858       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13859     } else
13860       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13861   }
13862 
13863 
13864   // For i32 intermediate values, unfortunately, the conversion functions
13865   // leave the upper 32 bits of the value are undefined. Within the set of
13866   // scalar instructions, we have no method for zero- or sign-extending the
13867   // value. Thus, we cannot handle i32 intermediate values here.
13868   if (Op.getOperand(0).getValueType() == MVT::i32)
13869     return SDValue();
13870 
13871   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13872          "UINT_TO_FP is supported only with FPCVT");
13873 
13874   // If we have FCFIDS, then use it when converting to single-precision.
13875   // Otherwise, convert to double-precision and then round.
13876   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13877                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13878                                                             : PPCISD::FCFIDS)
13879                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13880                                                             : PPCISD::FCFID);
13881   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13882                   ? MVT::f32
13883                   : MVT::f64;
13884 
13885   // If we're converting from a float, to an int, and back to a float again,
13886   // then we don't need the store/load pair at all.
13887   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13888        Subtarget.hasFPCVT()) ||
13889       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13890     SDValue Src = Op.getOperand(0).getOperand(0);
13891     if (Src.getValueType() == MVT::f32) {
13892       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13893       DCI.AddToWorklist(Src.getNode());
13894     } else if (Src.getValueType() != MVT::f64) {
13895       // Make sure that we don't pick up a ppc_fp128 source value.
13896       return SDValue();
13897     }
13898 
13899     unsigned FCTOp =
13900       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13901                                                         PPCISD::FCTIDUZ;
13902 
13903     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13904     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13905 
13906     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13907       FP = DAG.getNode(ISD::FP_ROUND, dl,
13908                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13909       DCI.AddToWorklist(FP.getNode());
13910     }
13911 
13912     return FP;
13913   }
13914 
13915   return SDValue();
13916 }
13917 
13918 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13919 // builtins) into loads with swaps.
13920 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13921                                               DAGCombinerInfo &DCI) const {
13922   SelectionDAG &DAG = DCI.DAG;
13923   SDLoc dl(N);
13924   SDValue Chain;
13925   SDValue Base;
13926   MachineMemOperand *MMO;
13927 
13928   switch (N->getOpcode()) {
13929   default:
13930     llvm_unreachable("Unexpected opcode for little endian VSX load");
13931   case ISD::LOAD: {
13932     LoadSDNode *LD = cast<LoadSDNode>(N);
13933     Chain = LD->getChain();
13934     Base = LD->getBasePtr();
13935     MMO = LD->getMemOperand();
13936     // If the MMO suggests this isn't a load of a full vector, leave
13937     // things alone.  For a built-in, we have to make the change for
13938     // correctness, so if there is a size problem that will be a bug.
13939     if (MMO->getSize() < 16)
13940       return SDValue();
13941     break;
13942   }
13943   case ISD::INTRINSIC_W_CHAIN: {
13944     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13945     Chain = Intrin->getChain();
13946     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13947     // us what we want. Get operand 2 instead.
13948     Base = Intrin->getOperand(2);
13949     MMO = Intrin->getMemOperand();
13950     break;
13951   }
13952   }
13953 
13954   MVT VecTy = N->getValueType(0).getSimpleVT();
13955 
13956   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13957   // aligned and the type is a vector with elements up to 4 bytes
13958   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13959       VecTy.getScalarSizeInBits() <= 32) {
13960     return SDValue();
13961   }
13962 
13963   SDValue LoadOps[] = { Chain, Base };
13964   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13965                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13966                                          LoadOps, MVT::v2f64, MMO);
13967 
13968   DCI.AddToWorklist(Load.getNode());
13969   Chain = Load.getValue(1);
13970   SDValue Swap = DAG.getNode(
13971       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13972   DCI.AddToWorklist(Swap.getNode());
13973 
13974   // Add a bitcast if the resulting load type doesn't match v2f64.
13975   if (VecTy != MVT::v2f64) {
13976     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13977     DCI.AddToWorklist(N.getNode());
13978     // Package {bitcast value, swap's chain} to match Load's shape.
13979     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13980                        N, Swap.getValue(1));
13981   }
13982 
13983   return Swap;
13984 }
13985 
13986 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13987 // builtins) into stores with swaps.
13988 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13989                                                DAGCombinerInfo &DCI) const {
13990   SelectionDAG &DAG = DCI.DAG;
13991   SDLoc dl(N);
13992   SDValue Chain;
13993   SDValue Base;
13994   unsigned SrcOpnd;
13995   MachineMemOperand *MMO;
13996 
13997   switch (N->getOpcode()) {
13998   default:
13999     llvm_unreachable("Unexpected opcode for little endian VSX store");
14000   case ISD::STORE: {
14001     StoreSDNode *ST = cast<StoreSDNode>(N);
14002     Chain = ST->getChain();
14003     Base = ST->getBasePtr();
14004     MMO = ST->getMemOperand();
14005     SrcOpnd = 1;
14006     // If the MMO suggests this isn't a store of a full vector, leave
14007     // things alone.  For a built-in, we have to make the change for
14008     // correctness, so if there is a size problem that will be a bug.
14009     if (MMO->getSize() < 16)
14010       return SDValue();
14011     break;
14012   }
14013   case ISD::INTRINSIC_VOID: {
14014     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14015     Chain = Intrin->getChain();
14016     // Intrin->getBasePtr() oddly does not get what we want.
14017     Base = Intrin->getOperand(3);
14018     MMO = Intrin->getMemOperand();
14019     SrcOpnd = 2;
14020     break;
14021   }
14022   }
14023 
14024   SDValue Src = N->getOperand(SrcOpnd);
14025   MVT VecTy = Src.getValueType().getSimpleVT();
14026 
14027   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14028   // aligned and the type is a vector with elements up to 4 bytes
14029   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14030       VecTy.getScalarSizeInBits() <= 32) {
14031     return SDValue();
14032   }
14033 
14034   // All stores are done as v2f64 and possible bit cast.
14035   if (VecTy != MVT::v2f64) {
14036     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14037     DCI.AddToWorklist(Src.getNode());
14038   }
14039 
14040   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14041                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14042   DCI.AddToWorklist(Swap.getNode());
14043   Chain = Swap.getValue(1);
14044   SDValue StoreOps[] = { Chain, Swap, Base };
14045   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14046                                           DAG.getVTList(MVT::Other),
14047                                           StoreOps, VecTy, MMO);
14048   DCI.AddToWorklist(Store.getNode());
14049   return Store;
14050 }
14051 
14052 // Handle DAG combine for STORE (FP_TO_INT F).
14053 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14054                                                DAGCombinerInfo &DCI) const {
14055 
14056   SelectionDAG &DAG = DCI.DAG;
14057   SDLoc dl(N);
14058   unsigned Opcode = N->getOperand(1).getOpcode();
14059 
14060   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14061          && "Not a FP_TO_INT Instruction!");
14062 
14063   SDValue Val = N->getOperand(1).getOperand(0);
14064   EVT Op1VT = N->getOperand(1).getValueType();
14065   EVT ResVT = Val.getValueType();
14066 
14067   if (!isTypeLegal(ResVT))
14068     return SDValue();
14069 
14070   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14071   bool ValidTypeForStoreFltAsInt =
14072         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14073          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14074 
14075   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14076       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14077     return SDValue();
14078 
14079   // Extend f32 values to f64
14080   if (ResVT.getScalarSizeInBits() == 32) {
14081     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14082     DCI.AddToWorklist(Val.getNode());
14083   }
14084 
14085   // Set signed or unsigned conversion opcode.
14086   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14087                           PPCISD::FP_TO_SINT_IN_VSR :
14088                           PPCISD::FP_TO_UINT_IN_VSR;
14089 
14090   Val = DAG.getNode(ConvOpcode,
14091                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14092   DCI.AddToWorklist(Val.getNode());
14093 
14094   // Set number of bytes being converted.
14095   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14096   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14097                     DAG.getIntPtrConstant(ByteSize, dl, false),
14098                     DAG.getValueType(Op1VT) };
14099 
14100   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14101           DAG.getVTList(MVT::Other), Ops,
14102           cast<StoreSDNode>(N)->getMemoryVT(),
14103           cast<StoreSDNode>(N)->getMemOperand());
14104 
14105   DCI.AddToWorklist(Val.getNode());
14106   return Val;
14107 }
14108 
14109 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14110   // Check that the source of the element keeps flipping
14111   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14112   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14113   for (int i = 1, e = Mask.size(); i < e; i++) {
14114     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14115       return false;
14116     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14117       return false;
14118     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14119   }
14120   return true;
14121 }
14122 
14123 static bool isSplatBV(SDValue Op) {
14124   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14125     return false;
14126   SDValue FirstOp;
14127 
14128   // Find first non-undef input.
14129   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14130     FirstOp = Op.getOperand(i);
14131     if (!FirstOp.isUndef())
14132       break;
14133   }
14134 
14135   // All inputs are undef or the same as the first non-undef input.
14136   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14137     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14138       return false;
14139   return true;
14140 }
14141 
14142 static SDValue isScalarToVec(SDValue Op) {
14143   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14144     return Op;
14145   if (Op.getOpcode() != ISD::BITCAST)
14146     return SDValue();
14147   Op = Op.getOperand(0);
14148   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14149     return Op;
14150   return SDValue();
14151 }
14152 
14153 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14154                                             int LHSMaxIdx, int RHSMinIdx,
14155                                             int RHSMaxIdx, int HalfVec) {
14156   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14157     int Idx = ShuffV[i];
14158     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14159       ShuffV[i] += HalfVec;
14160   }
14161 }
14162 
14163 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14164 // the original is:
14165 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14166 // In such a case, just change the shuffle mask to extract the element
14167 // from the permuted index.
14168 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) {
14169   SDLoc dl(OrigSToV);
14170   EVT VT = OrigSToV.getValueType();
14171   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14172          "Expecting a SCALAR_TO_VECTOR here");
14173   SDValue Input = OrigSToV.getOperand(0);
14174 
14175   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14176     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14177     SDValue OrigVector = Input.getOperand(0);
14178 
14179     // Can't handle non-const element indices or different vector types
14180     // for the input to the extract and the output of the scalar_to_vector.
14181     if (Idx && VT == OrigVector.getValueType()) {
14182       SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1);
14183       NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue();
14184       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14185     }
14186   }
14187   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14188                      OrigSToV.getOperand(0));
14189 }
14190 
14191 // On little endian subtargets, combine shuffles such as:
14192 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14193 // into:
14194 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14195 // because the latter can be matched to a single instruction merge.
14196 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14197 // to put the value into element zero. Adjust the shuffle mask so that the
14198 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14199 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14200                                                 SelectionDAG &DAG) const {
14201   SDValue LHS = SVN->getOperand(0);
14202   SDValue RHS = SVN->getOperand(1);
14203   auto Mask = SVN->getMask();
14204   int NumElts = LHS.getValueType().getVectorNumElements();
14205   SDValue Res(SVN, 0);
14206   SDLoc dl(SVN);
14207 
14208   // None of these combines are useful on big endian systems since the ISA
14209   // already has a big endian bias.
14210   if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14211     return Res;
14212 
14213   // If this is not a shuffle of a shuffle and the first element comes from
14214   // the second vector, canonicalize to the commuted form. This will make it
14215   // more likely to match one of the single instruction patterns.
14216   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14217       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14218     std::swap(LHS, RHS);
14219     Res = DAG.getCommutedVectorShuffle(*SVN);
14220     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14221   }
14222 
14223   // Adjust the shuffle mask if either input vector comes from a
14224   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14225   // form (to prevent the need for a swap).
14226   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14227   SDValue SToVLHS = isScalarToVec(LHS);
14228   SDValue SToVRHS = isScalarToVec(RHS);
14229   if (SToVLHS || SToVRHS) {
14230     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14231                             : SToVRHS.getValueType().getVectorNumElements();
14232     int NumEltsOut = ShuffV.size();
14233 
14234     // Initially assume that neither input is permuted. These will be adjusted
14235     // accordingly if either input is.
14236     int LHSMaxIdx = -1;
14237     int RHSMinIdx = -1;
14238     int RHSMaxIdx = -1;
14239     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14240 
14241     // Get the permuted scalar to vector nodes for the source(s) that come from
14242     // ISD::SCALAR_TO_VECTOR.
14243     if (SToVLHS) {
14244       // Set up the values for the shuffle vector fixup.
14245       LHSMaxIdx = NumEltsOut / NumEltsIn;
14246       SToVLHS = getSToVPermuted(SToVLHS, DAG);
14247       if (SToVLHS.getValueType() != LHS.getValueType())
14248         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14249       LHS = SToVLHS;
14250     }
14251     if (SToVRHS) {
14252       RHSMinIdx = NumEltsOut;
14253       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14254       SToVRHS = getSToVPermuted(SToVRHS, DAG);
14255       if (SToVRHS.getValueType() != RHS.getValueType())
14256         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14257       RHS = SToVRHS;
14258     }
14259 
14260     // Fix up the shuffle mask to reflect where the desired element actually is.
14261     // The minimum and maximum indices that correspond to element zero for both
14262     // the LHS and RHS are computed and will control which shuffle mask entries
14263     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14264     // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by
14265     // HalfVec to refer to the corresponding element in the permuted vector.
14266     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14267                                     HalfVec);
14268     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14269 
14270     // We may have simplified away the shuffle. We won't be able to do anything
14271     // further with it here.
14272     if (!isa<ShuffleVectorSDNode>(Res))
14273       return Res;
14274     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14275   }
14276 
14277   // The common case after we commuted the shuffle is that the RHS is a splat
14278   // and we have elements coming in from the splat at indices that are not
14279   // conducive to using a merge.
14280   // Example:
14281   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14282   if (!isSplatBV(RHS))
14283     return Res;
14284 
14285   // We are looking for a mask such that all even elements are from
14286   // one vector and all odd elements from the other.
14287   if (!isAlternatingShuffMask(Mask, NumElts))
14288     return Res;
14289 
14290   // Adjust the mask so we are pulling in the same index from the splat
14291   // as the index from the interesting vector in consecutive elements.
14292   // Example (even elements from first vector):
14293   // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14294   if (Mask[0] < NumElts)
14295     for (int i = 1, e = Mask.size(); i < e; i += 2)
14296       ShuffV[i] = (ShuffV[i - 1] + NumElts);
14297   // Example (odd elements from first vector):
14298   // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14299   else
14300     for (int i = 0, e = Mask.size(); i < e; i += 2)
14301       ShuffV[i] = (ShuffV[i + 1] + NumElts);
14302 
14303   // If the RHS has undefs, we need to remove them since we may have created
14304   // a shuffle that adds those instead of the splat value.
14305   SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue();
14306   RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal);
14307 
14308   Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14309   return Res;
14310 }
14311 
14312 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14313                                                 LSBaseSDNode *LSBase,
14314                                                 DAGCombinerInfo &DCI) const {
14315   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14316         "Not a reverse memop pattern!");
14317 
14318   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14319     auto Mask = SVN->getMask();
14320     int i = 0;
14321     auto I = Mask.rbegin();
14322     auto E = Mask.rend();
14323 
14324     for (; I != E; ++I) {
14325       if (*I != i)
14326         return false;
14327       i++;
14328     }
14329     return true;
14330   };
14331 
14332   SelectionDAG &DAG = DCI.DAG;
14333   EVT VT = SVN->getValueType(0);
14334 
14335   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14336     return SDValue();
14337 
14338   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14339   // See comment in PPCVSXSwapRemoval.cpp.
14340   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14341   if (!Subtarget.hasP9Vector())
14342     return SDValue();
14343 
14344   if(!IsElementReverse(SVN))
14345     return SDValue();
14346 
14347   if (LSBase->getOpcode() == ISD::LOAD) {
14348     SDLoc dl(SVN);
14349     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14350     return DAG.getMemIntrinsicNode(
14351         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14352         LSBase->getMemoryVT(), LSBase->getMemOperand());
14353   }
14354 
14355   if (LSBase->getOpcode() == ISD::STORE) {
14356     SDLoc dl(LSBase);
14357     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14358                           LSBase->getBasePtr()};
14359     return DAG.getMemIntrinsicNode(
14360         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14361         LSBase->getMemoryVT(), LSBase->getMemOperand());
14362   }
14363 
14364   llvm_unreachable("Expected a load or store node here");
14365 }
14366 
14367 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14368                                              DAGCombinerInfo &DCI) const {
14369   SelectionDAG &DAG = DCI.DAG;
14370   SDLoc dl(N);
14371   switch (N->getOpcode()) {
14372   default: break;
14373   case ISD::ADD:
14374     return combineADD(N, DCI);
14375   case ISD::SHL:
14376     return combineSHL(N, DCI);
14377   case ISD::SRA:
14378     return combineSRA(N, DCI);
14379   case ISD::SRL:
14380     return combineSRL(N, DCI);
14381   case ISD::MUL:
14382     return combineMUL(N, DCI);
14383   case ISD::FMA:
14384   case PPCISD::FNMSUB:
14385     return combineFMALike(N, DCI);
14386   case PPCISD::SHL:
14387     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14388         return N->getOperand(0);
14389     break;
14390   case PPCISD::SRL:
14391     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14392         return N->getOperand(0);
14393     break;
14394   case PPCISD::SRA:
14395     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14396       if (C->isNullValue() ||   //  0 >>s V -> 0.
14397           C->isAllOnesValue())    // -1 >>s V -> -1.
14398         return N->getOperand(0);
14399     }
14400     break;
14401   case ISD::SIGN_EXTEND:
14402   case ISD::ZERO_EXTEND:
14403   case ISD::ANY_EXTEND:
14404     return DAGCombineExtBoolTrunc(N, DCI);
14405   case ISD::TRUNCATE:
14406     return combineTRUNCATE(N, DCI);
14407   case ISD::SETCC:
14408     if (SDValue CSCC = combineSetCC(N, DCI))
14409       return CSCC;
14410     LLVM_FALLTHROUGH;
14411   case ISD::SELECT_CC:
14412     return DAGCombineTruncBoolExt(N, DCI);
14413   case ISD::SINT_TO_FP:
14414   case ISD::UINT_TO_FP:
14415     return combineFPToIntToFP(N, DCI);
14416   case ISD::VECTOR_SHUFFLE:
14417     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14418       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14419       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14420     }
14421     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14422   case ISD::STORE: {
14423 
14424     EVT Op1VT = N->getOperand(1).getValueType();
14425     unsigned Opcode = N->getOperand(1).getOpcode();
14426 
14427     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14428       SDValue Val= combineStoreFPToInt(N, DCI);
14429       if (Val)
14430         return Val;
14431     }
14432 
14433     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14434       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14435       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14436       if (Val)
14437         return Val;
14438     }
14439 
14440     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14441     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14442         N->getOperand(1).getNode()->hasOneUse() &&
14443         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14444          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14445 
14446       // STBRX can only handle simple types and it makes no sense to store less
14447       // two bytes in byte-reversed order.
14448       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14449       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14450         break;
14451 
14452       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14453       // Do an any-extend to 32-bits if this is a half-word input.
14454       if (BSwapOp.getValueType() == MVT::i16)
14455         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14456 
14457       // If the type of BSWAP operand is wider than stored memory width
14458       // it need to be shifted to the right side before STBRX.
14459       if (Op1VT.bitsGT(mVT)) {
14460         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14461         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14462                               DAG.getConstant(Shift, dl, MVT::i32));
14463         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14464         if (Op1VT == MVT::i64)
14465           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14466       }
14467 
14468       SDValue Ops[] = {
14469         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14470       };
14471       return
14472         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14473                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14474                                 cast<StoreSDNode>(N)->getMemOperand());
14475     }
14476 
14477     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14478     // So it can increase the chance of CSE constant construction.
14479     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14480         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14481       // Need to sign-extended to 64-bits to handle negative values.
14482       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14483       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14484                                     MemVT.getSizeInBits());
14485       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14486 
14487       // DAG.getTruncStore() can't be used here because it doesn't accept
14488       // the general (base + offset) addressing mode.
14489       // So we use UpdateNodeOperands and setTruncatingStore instead.
14490       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14491                              N->getOperand(3));
14492       cast<StoreSDNode>(N)->setTruncatingStore(true);
14493       return SDValue(N, 0);
14494     }
14495 
14496     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14497     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14498     if (Op1VT.isSimple()) {
14499       MVT StoreVT = Op1VT.getSimpleVT();
14500       if (Subtarget.needsSwapsForVSXMemOps() &&
14501           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14502            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14503         return expandVSXStoreForLE(N, DCI);
14504     }
14505     break;
14506   }
14507   case ISD::LOAD: {
14508     LoadSDNode *LD = cast<LoadSDNode>(N);
14509     EVT VT = LD->getValueType(0);
14510 
14511     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14512     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14513     if (VT.isSimple()) {
14514       MVT LoadVT = VT.getSimpleVT();
14515       if (Subtarget.needsSwapsForVSXMemOps() &&
14516           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14517            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14518         return expandVSXLoadForLE(N, DCI);
14519     }
14520 
14521     // We sometimes end up with a 64-bit integer load, from which we extract
14522     // two single-precision floating-point numbers. This happens with
14523     // std::complex<float>, and other similar structures, because of the way we
14524     // canonicalize structure copies. However, if we lack direct moves,
14525     // then the final bitcasts from the extracted integer values to the
14526     // floating-point numbers turn into store/load pairs. Even with direct moves,
14527     // just loading the two floating-point numbers is likely better.
14528     auto ReplaceTwoFloatLoad = [&]() {
14529       if (VT != MVT::i64)
14530         return false;
14531 
14532       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14533           LD->isVolatile())
14534         return false;
14535 
14536       //  We're looking for a sequence like this:
14537       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14538       //      t16: i64 = srl t13, Constant:i32<32>
14539       //    t17: i32 = truncate t16
14540       //  t18: f32 = bitcast t17
14541       //    t19: i32 = truncate t13
14542       //  t20: f32 = bitcast t19
14543 
14544       if (!LD->hasNUsesOfValue(2, 0))
14545         return false;
14546 
14547       auto UI = LD->use_begin();
14548       while (UI.getUse().getResNo() != 0) ++UI;
14549       SDNode *Trunc = *UI++;
14550       while (UI.getUse().getResNo() != 0) ++UI;
14551       SDNode *RightShift = *UI;
14552       if (Trunc->getOpcode() != ISD::TRUNCATE)
14553         std::swap(Trunc, RightShift);
14554 
14555       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14556           Trunc->getValueType(0) != MVT::i32 ||
14557           !Trunc->hasOneUse())
14558         return false;
14559       if (RightShift->getOpcode() != ISD::SRL ||
14560           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14561           RightShift->getConstantOperandVal(1) != 32 ||
14562           !RightShift->hasOneUse())
14563         return false;
14564 
14565       SDNode *Trunc2 = *RightShift->use_begin();
14566       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14567           Trunc2->getValueType(0) != MVT::i32 ||
14568           !Trunc2->hasOneUse())
14569         return false;
14570 
14571       SDNode *Bitcast = *Trunc->use_begin();
14572       SDNode *Bitcast2 = *Trunc2->use_begin();
14573 
14574       if (Bitcast->getOpcode() != ISD::BITCAST ||
14575           Bitcast->getValueType(0) != MVT::f32)
14576         return false;
14577       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14578           Bitcast2->getValueType(0) != MVT::f32)
14579         return false;
14580 
14581       if (Subtarget.isLittleEndian())
14582         std::swap(Bitcast, Bitcast2);
14583 
14584       // Bitcast has the second float (in memory-layout order) and Bitcast2
14585       // has the first one.
14586 
14587       SDValue BasePtr = LD->getBasePtr();
14588       if (LD->isIndexed()) {
14589         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14590                "Non-pre-inc AM on PPC?");
14591         BasePtr =
14592           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14593                       LD->getOffset());
14594       }
14595 
14596       auto MMOFlags =
14597           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14598       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14599                                       LD->getPointerInfo(), LD->getAlignment(),
14600                                       MMOFlags, LD->getAAInfo());
14601       SDValue AddPtr =
14602         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14603                     BasePtr, DAG.getIntPtrConstant(4, dl));
14604       SDValue FloatLoad2 = DAG.getLoad(
14605           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14606           LD->getPointerInfo().getWithOffset(4),
14607           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14608 
14609       if (LD->isIndexed()) {
14610         // Note that DAGCombine should re-form any pre-increment load(s) from
14611         // what is produced here if that makes sense.
14612         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14613       }
14614 
14615       DCI.CombineTo(Bitcast2, FloatLoad);
14616       DCI.CombineTo(Bitcast, FloatLoad2);
14617 
14618       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14619                                     SDValue(FloatLoad2.getNode(), 1));
14620       return true;
14621     };
14622 
14623     if (ReplaceTwoFloatLoad())
14624       return SDValue(N, 0);
14625 
14626     EVT MemVT = LD->getMemoryVT();
14627     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14628     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
14629     if (LD->isUnindexed() && VT.isVector() &&
14630         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14631           // P8 and later hardware should just use LOAD.
14632           !Subtarget.hasP8Vector() &&
14633           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
14634            VT == MVT::v4f32))) &&
14635         LD->getAlign() < ABIAlignment) {
14636       // This is a type-legal unaligned Altivec load.
14637       SDValue Chain = LD->getChain();
14638       SDValue Ptr = LD->getBasePtr();
14639       bool isLittleEndian = Subtarget.isLittleEndian();
14640 
14641       // This implements the loading of unaligned vectors as described in
14642       // the venerable Apple Velocity Engine overview. Specifically:
14643       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14644       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14645       //
14646       // The general idea is to expand a sequence of one or more unaligned
14647       // loads into an alignment-based permutation-control instruction (lvsl
14648       // or lvsr), a series of regular vector loads (which always truncate
14649       // their input address to an aligned address), and a series of
14650       // permutations.  The results of these permutations are the requested
14651       // loaded values.  The trick is that the last "extra" load is not taken
14652       // from the address you might suspect (sizeof(vector) bytes after the
14653       // last requested load), but rather sizeof(vector) - 1 bytes after the
14654       // last requested vector. The point of this is to avoid a page fault if
14655       // the base address happened to be aligned. This works because if the
14656       // base address is aligned, then adding less than a full vector length
14657       // will cause the last vector in the sequence to be (re)loaded.
14658       // Otherwise, the next vector will be fetched as you might suspect was
14659       // necessary.
14660 
14661       // We might be able to reuse the permutation generation from
14662       // a different base address offset from this one by an aligned amount.
14663       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14664       // optimization later.
14665       Intrinsic::ID Intr, IntrLD, IntrPerm;
14666       MVT PermCntlTy, PermTy, LDTy;
14667       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14668                             : Intrinsic::ppc_altivec_lvsl;
14669       IntrLD = Intrinsic::ppc_altivec_lvx;
14670       IntrPerm = Intrinsic::ppc_altivec_vperm;
14671       PermCntlTy = MVT::v16i8;
14672       PermTy = MVT::v4i32;
14673       LDTy = MVT::v4i32;
14674 
14675       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14676 
14677       // Create the new MMO for the new base load. It is like the original MMO,
14678       // but represents an area in memory almost twice the vector size centered
14679       // on the original address. If the address is unaligned, we might start
14680       // reading up to (sizeof(vector)-1) bytes below the address of the
14681       // original unaligned load.
14682       MachineFunction &MF = DAG.getMachineFunction();
14683       MachineMemOperand *BaseMMO =
14684         MF.getMachineMemOperand(LD->getMemOperand(),
14685                                 -(long)MemVT.getStoreSize()+1,
14686                                 2*MemVT.getStoreSize()-1);
14687 
14688       // Create the new base load.
14689       SDValue LDXIntID =
14690           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14691       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14692       SDValue BaseLoad =
14693         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14694                                 DAG.getVTList(PermTy, MVT::Other),
14695                                 BaseLoadOps, LDTy, BaseMMO);
14696 
14697       // Note that the value of IncOffset (which is provided to the next
14698       // load's pointer info offset value, and thus used to calculate the
14699       // alignment), and the value of IncValue (which is actually used to
14700       // increment the pointer value) are different! This is because we
14701       // require the next load to appear to be aligned, even though it
14702       // is actually offset from the base pointer by a lesser amount.
14703       int IncOffset = VT.getSizeInBits() / 8;
14704       int IncValue = IncOffset;
14705 
14706       // Walk (both up and down) the chain looking for another load at the real
14707       // (aligned) offset (the alignment of the other load does not matter in
14708       // this case). If found, then do not use the offset reduction trick, as
14709       // that will prevent the loads from being later combined (as they would
14710       // otherwise be duplicates).
14711       if (!findConsecutiveLoad(LD, DAG))
14712         --IncValue;
14713 
14714       SDValue Increment =
14715           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14716       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14717 
14718       MachineMemOperand *ExtraMMO =
14719         MF.getMachineMemOperand(LD->getMemOperand(),
14720                                 1, 2*MemVT.getStoreSize()-1);
14721       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14722       SDValue ExtraLoad =
14723         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14724                                 DAG.getVTList(PermTy, MVT::Other),
14725                                 ExtraLoadOps, LDTy, ExtraMMO);
14726 
14727       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14728         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14729 
14730       // Because vperm has a big-endian bias, we must reverse the order
14731       // of the input vectors and complement the permute control vector
14732       // when generating little endian code.  We have already handled the
14733       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14734       // and ExtraLoad here.
14735       SDValue Perm;
14736       if (isLittleEndian)
14737         Perm = BuildIntrinsicOp(IntrPerm,
14738                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14739       else
14740         Perm = BuildIntrinsicOp(IntrPerm,
14741                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14742 
14743       if (VT != PermTy)
14744         Perm = Subtarget.hasAltivec()
14745                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
14746                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
14747                                  DAG.getTargetConstant(1, dl, MVT::i64));
14748                                // second argument is 1 because this rounding
14749                                // is always exact.
14750 
14751       // The output of the permutation is our loaded result, the TokenFactor is
14752       // our new chain.
14753       DCI.CombineTo(N, Perm, TF);
14754       return SDValue(N, 0);
14755     }
14756     }
14757     break;
14758     case ISD::INTRINSIC_WO_CHAIN: {
14759       bool isLittleEndian = Subtarget.isLittleEndian();
14760       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14761       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14762                                            : Intrinsic::ppc_altivec_lvsl);
14763       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
14764         SDValue Add = N->getOperand(1);
14765 
14766         int Bits = 4 /* 16 byte alignment */;
14767 
14768         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14769                                   APInt::getAllOnesValue(Bits /* alignment */)
14770                                       .zext(Add.getScalarValueSizeInBits()))) {
14771           SDNode *BasePtr = Add->getOperand(0).getNode();
14772           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14773                                     UE = BasePtr->use_end();
14774                UI != UE; ++UI) {
14775             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14776                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
14777                     IID) {
14778               // We've found another LVSL/LVSR, and this address is an aligned
14779               // multiple of that one. The results will be the same, so use the
14780               // one we've just found instead.
14781 
14782               return SDValue(*UI, 0);
14783             }
14784           }
14785         }
14786 
14787         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14788           SDNode *BasePtr = Add->getOperand(0).getNode();
14789           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14790                UE = BasePtr->use_end(); UI != UE; ++UI) {
14791             if (UI->getOpcode() == ISD::ADD &&
14792                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14793                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14794                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14795                 (1ULL << Bits) == 0) {
14796               SDNode *OtherAdd = *UI;
14797               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14798                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14799                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14800                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14801                   return SDValue(*VI, 0);
14802                 }
14803               }
14804             }
14805           }
14806         }
14807       }
14808 
14809       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14810       // Expose the vabsduw/h/b opportunity for down stream
14811       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14812           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14813            IID == Intrinsic::ppc_altivec_vmaxsh ||
14814            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14815         SDValue V1 = N->getOperand(1);
14816         SDValue V2 = N->getOperand(2);
14817         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14818              V1.getSimpleValueType() == MVT::v8i16 ||
14819              V1.getSimpleValueType() == MVT::v16i8) &&
14820             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14821           // (0-a, a)
14822           if (V1.getOpcode() == ISD::SUB &&
14823               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14824               V1.getOperand(1) == V2) {
14825             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14826           }
14827           // (a, 0-a)
14828           if (V2.getOpcode() == ISD::SUB &&
14829               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14830               V2.getOperand(1) == V1) {
14831             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14832           }
14833           // (x-y, y-x)
14834           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14835               V1.getOperand(0) == V2.getOperand(1) &&
14836               V1.getOperand(1) == V2.getOperand(0)) {
14837             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14838           }
14839         }
14840       }
14841     }
14842 
14843     break;
14844   case ISD::INTRINSIC_W_CHAIN:
14845     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14846     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14847     if (Subtarget.needsSwapsForVSXMemOps()) {
14848       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14849       default:
14850         break;
14851       case Intrinsic::ppc_vsx_lxvw4x:
14852       case Intrinsic::ppc_vsx_lxvd2x:
14853         return expandVSXLoadForLE(N, DCI);
14854       }
14855     }
14856     break;
14857   case ISD::INTRINSIC_VOID:
14858     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14859     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14860     if (Subtarget.needsSwapsForVSXMemOps()) {
14861       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14862       default:
14863         break;
14864       case Intrinsic::ppc_vsx_stxvw4x:
14865       case Intrinsic::ppc_vsx_stxvd2x:
14866         return expandVSXStoreForLE(N, DCI);
14867       }
14868     }
14869     break;
14870   case ISD::BSWAP:
14871     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14872     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14873         N->getOperand(0).hasOneUse() &&
14874         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14875          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14876           N->getValueType(0) == MVT::i64))) {
14877       SDValue Load = N->getOperand(0);
14878       LoadSDNode *LD = cast<LoadSDNode>(Load);
14879       // Create the byte-swapping load.
14880       SDValue Ops[] = {
14881         LD->getChain(),    // Chain
14882         LD->getBasePtr(),  // Ptr
14883         DAG.getValueType(N->getValueType(0)) // VT
14884       };
14885       SDValue BSLoad =
14886         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14887                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14888                                               MVT::i64 : MVT::i32, MVT::Other),
14889                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14890 
14891       // If this is an i16 load, insert the truncate.
14892       SDValue ResVal = BSLoad;
14893       if (N->getValueType(0) == MVT::i16)
14894         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14895 
14896       // First, combine the bswap away.  This makes the value produced by the
14897       // load dead.
14898       DCI.CombineTo(N, ResVal);
14899 
14900       // Next, combine the load away, we give it a bogus result value but a real
14901       // chain result.  The result value is dead because the bswap is dead.
14902       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14903 
14904       // Return N so it doesn't get rechecked!
14905       return SDValue(N, 0);
14906     }
14907     break;
14908   case PPCISD::VCMP:
14909     // If a VCMP_rec node already exists with exactly the same operands as this
14910     // node, use its result instead of this node (VCMP_rec computes both a CR6
14911     // and a normal output).
14912     //
14913     if (!N->getOperand(0).hasOneUse() &&
14914         !N->getOperand(1).hasOneUse() &&
14915         !N->getOperand(2).hasOneUse()) {
14916 
14917       // Scan all of the users of the LHS, looking for VCMP_rec's that match.
14918       SDNode *VCMPrecNode = nullptr;
14919 
14920       SDNode *LHSN = N->getOperand(0).getNode();
14921       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14922            UI != E; ++UI)
14923         if (UI->getOpcode() == PPCISD::VCMP_rec &&
14924             UI->getOperand(1) == N->getOperand(1) &&
14925             UI->getOperand(2) == N->getOperand(2) &&
14926             UI->getOperand(0) == N->getOperand(0)) {
14927           VCMPrecNode = *UI;
14928           break;
14929         }
14930 
14931       // If there is no VCMP_rec node, or if the flag value has a single use,
14932       // don't transform this.
14933       if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
14934         break;
14935 
14936       // Look at the (necessarily single) use of the flag value.  If it has a
14937       // chain, this transformation is more complex.  Note that multiple things
14938       // could use the value result, which we should ignore.
14939       SDNode *FlagUser = nullptr;
14940       for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
14941            FlagUser == nullptr; ++UI) {
14942         assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
14943         SDNode *User = *UI;
14944         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14945           if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
14946             FlagUser = User;
14947             break;
14948           }
14949         }
14950       }
14951 
14952       // If the user is a MFOCRF instruction, we know this is safe.
14953       // Otherwise we give up for right now.
14954       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14955         return SDValue(VCMPrecNode, 0);
14956     }
14957     break;
14958   case ISD::BRCOND: {
14959     SDValue Cond = N->getOperand(1);
14960     SDValue Target = N->getOperand(2);
14961 
14962     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14963         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14964           Intrinsic::loop_decrement) {
14965 
14966       // We now need to make the intrinsic dead (it cannot be instruction
14967       // selected).
14968       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14969       assert(Cond.getNode()->hasOneUse() &&
14970              "Counter decrement has more than one use");
14971 
14972       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14973                          N->getOperand(0), Target);
14974     }
14975   }
14976   break;
14977   case ISD::BR_CC: {
14978     // If this is a branch on an altivec predicate comparison, lower this so
14979     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14980     // lowering is done pre-legalize, because the legalizer lowers the predicate
14981     // compare down to code that is difficult to reassemble.
14982     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14983     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14984 
14985     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14986     // value. If so, pass-through the AND to get to the intrinsic.
14987     if (LHS.getOpcode() == ISD::AND &&
14988         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14989         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14990           Intrinsic::loop_decrement &&
14991         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14992         !isNullConstant(LHS.getOperand(1)))
14993       LHS = LHS.getOperand(0);
14994 
14995     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14996         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14997           Intrinsic::loop_decrement &&
14998         isa<ConstantSDNode>(RHS)) {
14999       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15000              "Counter decrement comparison is not EQ or NE");
15001 
15002       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15003       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15004                     (CC == ISD::SETNE && !Val);
15005 
15006       // We now need to make the intrinsic dead (it cannot be instruction
15007       // selected).
15008       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15009       assert(LHS.getNode()->hasOneUse() &&
15010              "Counter decrement has more than one use");
15011 
15012       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15013                          N->getOperand(0), N->getOperand(4));
15014     }
15015 
15016     int CompareOpc;
15017     bool isDot;
15018 
15019     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15020         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15021         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15022       assert(isDot && "Can't compare against a vector result!");
15023 
15024       // If this is a comparison against something other than 0/1, then we know
15025       // that the condition is never/always true.
15026       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15027       if (Val != 0 && Val != 1) {
15028         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15029           return N->getOperand(0);
15030         // Always !=, turn it into an unconditional branch.
15031         return DAG.getNode(ISD::BR, dl, MVT::Other,
15032                            N->getOperand(0), N->getOperand(4));
15033       }
15034 
15035       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15036 
15037       // Create the PPCISD altivec 'dot' comparison node.
15038       SDValue Ops[] = {
15039         LHS.getOperand(2),  // LHS of compare
15040         LHS.getOperand(3),  // RHS of compare
15041         DAG.getConstant(CompareOpc, dl, MVT::i32)
15042       };
15043       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15044       SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
15045 
15046       // Unpack the result based on how the target uses it.
15047       PPC::Predicate CompOpc;
15048       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15049       default:  // Can't happen, don't crash on invalid number though.
15050       case 0:   // Branch on the value of the EQ bit of CR6.
15051         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15052         break;
15053       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15054         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15055         break;
15056       case 2:   // Branch on the value of the LT bit of CR6.
15057         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15058         break;
15059       case 3:   // Branch on the inverted value of the LT bit of CR6.
15060         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15061         break;
15062       }
15063 
15064       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15065                          DAG.getConstant(CompOpc, dl, MVT::i32),
15066                          DAG.getRegister(PPC::CR6, MVT::i32),
15067                          N->getOperand(4), CompNode.getValue(1));
15068     }
15069     break;
15070   }
15071   case ISD::BUILD_VECTOR:
15072     return DAGCombineBuildVector(N, DCI);
15073   case ISD::ABS:
15074     return combineABS(N, DCI);
15075   case ISD::VSELECT:
15076     return combineVSelect(N, DCI);
15077   }
15078 
15079   return SDValue();
15080 }
15081 
15082 SDValue
15083 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15084                                  SelectionDAG &DAG,
15085                                  SmallVectorImpl<SDNode *> &Created) const {
15086   // fold (sdiv X, pow2)
15087   EVT VT = N->getValueType(0);
15088   if (VT == MVT::i64 && !Subtarget.isPPC64())
15089     return SDValue();
15090   if ((VT != MVT::i32 && VT != MVT::i64) ||
15091       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
15092     return SDValue();
15093 
15094   SDLoc DL(N);
15095   SDValue N0 = N->getOperand(0);
15096 
15097   bool IsNegPow2 = (-Divisor).isPowerOf2();
15098   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15099   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15100 
15101   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15102   Created.push_back(Op.getNode());
15103 
15104   if (IsNegPow2) {
15105     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15106     Created.push_back(Op.getNode());
15107   }
15108 
15109   return Op;
15110 }
15111 
15112 //===----------------------------------------------------------------------===//
15113 // Inline Assembly Support
15114 //===----------------------------------------------------------------------===//
15115 
15116 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15117                                                       KnownBits &Known,
15118                                                       const APInt &DemandedElts,
15119                                                       const SelectionDAG &DAG,
15120                                                       unsigned Depth) const {
15121   Known.resetAll();
15122   switch (Op.getOpcode()) {
15123   default: break;
15124   case PPCISD::LBRX: {
15125     // lhbrx is known to have the top bits cleared out.
15126     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15127       Known.Zero = 0xFFFF0000;
15128     break;
15129   }
15130   case ISD::INTRINSIC_WO_CHAIN: {
15131     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15132     default: break;
15133     case Intrinsic::ppc_altivec_vcmpbfp_p:
15134     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15135     case Intrinsic::ppc_altivec_vcmpequb_p:
15136     case Intrinsic::ppc_altivec_vcmpequh_p:
15137     case Intrinsic::ppc_altivec_vcmpequw_p:
15138     case Intrinsic::ppc_altivec_vcmpequd_p:
15139     case Intrinsic::ppc_altivec_vcmpequq_p:
15140     case Intrinsic::ppc_altivec_vcmpgefp_p:
15141     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15142     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15143     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15144     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15145     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15146     case Intrinsic::ppc_altivec_vcmpgtsq_p:
15147     case Intrinsic::ppc_altivec_vcmpgtub_p:
15148     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15149     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15150     case Intrinsic::ppc_altivec_vcmpgtud_p:
15151     case Intrinsic::ppc_altivec_vcmpgtuq_p:
15152       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15153       break;
15154     }
15155   }
15156   }
15157 }
15158 
15159 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15160   switch (Subtarget.getCPUDirective()) {
15161   default: break;
15162   case PPC::DIR_970:
15163   case PPC::DIR_PWR4:
15164   case PPC::DIR_PWR5:
15165   case PPC::DIR_PWR5X:
15166   case PPC::DIR_PWR6:
15167   case PPC::DIR_PWR6X:
15168   case PPC::DIR_PWR7:
15169   case PPC::DIR_PWR8:
15170   case PPC::DIR_PWR9:
15171   case PPC::DIR_PWR10:
15172   case PPC::DIR_PWR_FUTURE: {
15173     if (!ML)
15174       break;
15175 
15176     if (!DisableInnermostLoopAlign32) {
15177       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15178       // so that we can decrease cache misses and branch-prediction misses.
15179       // Actual alignment of the loop will depend on the hotness check and other
15180       // logic in alignBlocks.
15181       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15182         return Align(32);
15183     }
15184 
15185     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15186 
15187     // For small loops (between 5 and 8 instructions), align to a 32-byte
15188     // boundary so that the entire loop fits in one instruction-cache line.
15189     uint64_t LoopSize = 0;
15190     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15191       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15192         LoopSize += TII->getInstSizeInBytes(*J);
15193         if (LoopSize > 32)
15194           break;
15195       }
15196 
15197     if (LoopSize > 16 && LoopSize <= 32)
15198       return Align(32);
15199 
15200     break;
15201   }
15202   }
15203 
15204   return TargetLowering::getPrefLoopAlignment(ML);
15205 }
15206 
15207 /// getConstraintType - Given a constraint, return the type of
15208 /// constraint it is for this target.
15209 PPCTargetLowering::ConstraintType
15210 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15211   if (Constraint.size() == 1) {
15212     switch (Constraint[0]) {
15213     default: break;
15214     case 'b':
15215     case 'r':
15216     case 'f':
15217     case 'd':
15218     case 'v':
15219     case 'y':
15220       return C_RegisterClass;
15221     case 'Z':
15222       // FIXME: While Z does indicate a memory constraint, it specifically
15223       // indicates an r+r address (used in conjunction with the 'y' modifier
15224       // in the replacement string). Currently, we're forcing the base
15225       // register to be r0 in the asm printer (which is interpreted as zero)
15226       // and forming the complete address in the second register. This is
15227       // suboptimal.
15228       return C_Memory;
15229     }
15230   } else if (Constraint == "wc") { // individual CR bits.
15231     return C_RegisterClass;
15232   } else if (Constraint == "wa" || Constraint == "wd" ||
15233              Constraint == "wf" || Constraint == "ws" ||
15234              Constraint == "wi" || Constraint == "ww") {
15235     return C_RegisterClass; // VSX registers.
15236   }
15237   return TargetLowering::getConstraintType(Constraint);
15238 }
15239 
15240 /// Examine constraint type and operand type and determine a weight value.
15241 /// This object must already have been set up with the operand type
15242 /// and the current alternative constraint selected.
15243 TargetLowering::ConstraintWeight
15244 PPCTargetLowering::getSingleConstraintMatchWeight(
15245     AsmOperandInfo &info, const char *constraint) const {
15246   ConstraintWeight weight = CW_Invalid;
15247   Value *CallOperandVal = info.CallOperandVal;
15248     // If we don't have a value, we can't do a match,
15249     // but allow it at the lowest weight.
15250   if (!CallOperandVal)
15251     return CW_Default;
15252   Type *type = CallOperandVal->getType();
15253 
15254   // Look at the constraint type.
15255   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15256     return CW_Register; // an individual CR bit.
15257   else if ((StringRef(constraint) == "wa" ||
15258             StringRef(constraint) == "wd" ||
15259             StringRef(constraint) == "wf") &&
15260            type->isVectorTy())
15261     return CW_Register;
15262   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15263     return CW_Register; // just hold 64-bit integers data.
15264   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15265     return CW_Register;
15266   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15267     return CW_Register;
15268 
15269   switch (*constraint) {
15270   default:
15271     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15272     break;
15273   case 'b':
15274     if (type->isIntegerTy())
15275       weight = CW_Register;
15276     break;
15277   case 'f':
15278     if (type->isFloatTy())
15279       weight = CW_Register;
15280     break;
15281   case 'd':
15282     if (type->isDoubleTy())
15283       weight = CW_Register;
15284     break;
15285   case 'v':
15286     if (type->isVectorTy())
15287       weight = CW_Register;
15288     break;
15289   case 'y':
15290     weight = CW_Register;
15291     break;
15292   case 'Z':
15293     weight = CW_Memory;
15294     break;
15295   }
15296   return weight;
15297 }
15298 
15299 std::pair<unsigned, const TargetRegisterClass *>
15300 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15301                                                 StringRef Constraint,
15302                                                 MVT VT) const {
15303   if (Constraint.size() == 1) {
15304     // GCC RS6000 Constraint Letters
15305     switch (Constraint[0]) {
15306     case 'b':   // R1-R31
15307       if (VT == MVT::i64 && Subtarget.isPPC64())
15308         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15309       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15310     case 'r':   // R0-R31
15311       if (VT == MVT::i64 && Subtarget.isPPC64())
15312         return std::make_pair(0U, &PPC::G8RCRegClass);
15313       return std::make_pair(0U, &PPC::GPRCRegClass);
15314     // 'd' and 'f' constraints are both defined to be "the floating point
15315     // registers", where one is for 32-bit and the other for 64-bit. We don't
15316     // really care overly much here so just give them all the same reg classes.
15317     case 'd':
15318     case 'f':
15319       if (Subtarget.hasSPE()) {
15320         if (VT == MVT::f32 || VT == MVT::i32)
15321           return std::make_pair(0U, &PPC::GPRCRegClass);
15322         if (VT == MVT::f64 || VT == MVT::i64)
15323           return std::make_pair(0U, &PPC::SPERCRegClass);
15324       } else {
15325         if (VT == MVT::f32 || VT == MVT::i32)
15326           return std::make_pair(0U, &PPC::F4RCRegClass);
15327         if (VT == MVT::f64 || VT == MVT::i64)
15328           return std::make_pair(0U, &PPC::F8RCRegClass);
15329       }
15330       break;
15331     case 'v':
15332       if (Subtarget.hasAltivec())
15333         return std::make_pair(0U, &PPC::VRRCRegClass);
15334       break;
15335     case 'y':   // crrc
15336       return std::make_pair(0U, &PPC::CRRCRegClass);
15337     }
15338   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15339     // An individual CR bit.
15340     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15341   } else if ((Constraint == "wa" || Constraint == "wd" ||
15342              Constraint == "wf" || Constraint == "wi") &&
15343              Subtarget.hasVSX()) {
15344     return std::make_pair(0U, &PPC::VSRCRegClass);
15345   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15346     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15347       return std::make_pair(0U, &PPC::VSSRCRegClass);
15348     else
15349       return std::make_pair(0U, &PPC::VSFRCRegClass);
15350   }
15351 
15352   // Handle special cases of physical registers that are not properly handled
15353   // by the base class.
15354   if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
15355     // If we name a VSX register, we can't defer to the base class because it
15356     // will not recognize the correct register (their names will be VSL{0-31}
15357     // and V{0-31} so they won't match). So we match them here.
15358     if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15359       int VSNum = atoi(Constraint.data() + 3);
15360       assert(VSNum >= 0 && VSNum <= 63 &&
15361              "Attempted to access a vsr out of range");
15362       if (VSNum < 32)
15363         return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15364       return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15365     }
15366 
15367     // For float registers, we can't defer to the base class as it will match
15368     // the SPILLTOVSRRC class.
15369     if (Constraint.size() > 3 && Constraint[1] == 'f') {
15370       int RegNum = atoi(Constraint.data() + 2);
15371       if (RegNum > 31 || RegNum < 0)
15372         report_fatal_error("Invalid floating point register number");
15373       if (VT == MVT::f32 || VT == MVT::i32)
15374         return Subtarget.hasSPE()
15375                    ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
15376                    : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
15377       if (VT == MVT::f64 || VT == MVT::i64)
15378         return Subtarget.hasSPE()
15379                    ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
15380                    : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
15381     }
15382   }
15383 
15384   std::pair<unsigned, const TargetRegisterClass *> R =
15385       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15386 
15387   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15388   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15389   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15390   // register.
15391   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15392   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15393   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15394       PPC::GPRCRegClass.contains(R.first))
15395     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15396                             PPC::sub_32, &PPC::G8RCRegClass),
15397                           &PPC::G8RCRegClass);
15398 
15399   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15400   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15401     R.first = PPC::CR0;
15402     R.second = &PPC::CRRCRegClass;
15403   }
15404   // FIXME: This warning should ideally be emitted in the front end.
15405   const auto &TM = getTargetMachine();
15406   if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) {
15407     if (((R.first >= PPC::V20 && R.first <= PPC::V31) ||
15408          (R.first >= PPC::VF20 && R.first <= PPC::VF31)) &&
15409         (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass))
15410       errs() << "warning: vector registers 20 to 32 are reserved in the "
15411                 "default AIX AltiVec ABI and cannot be used\n";
15412   }
15413 
15414   return R;
15415 }
15416 
15417 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15418 /// vector.  If it is invalid, don't add anything to Ops.
15419 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15420                                                      std::string &Constraint,
15421                                                      std::vector<SDValue>&Ops,
15422                                                      SelectionDAG &DAG) const {
15423   SDValue Result;
15424 
15425   // Only support length 1 constraints.
15426   if (Constraint.length() > 1) return;
15427 
15428   char Letter = Constraint[0];
15429   switch (Letter) {
15430   default: break;
15431   case 'I':
15432   case 'J':
15433   case 'K':
15434   case 'L':
15435   case 'M':
15436   case 'N':
15437   case 'O':
15438   case 'P': {
15439     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15440     if (!CST) return; // Must be an immediate to match.
15441     SDLoc dl(Op);
15442     int64_t Value = CST->getSExtValue();
15443     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15444                          // numbers are printed as such.
15445     switch (Letter) {
15446     default: llvm_unreachable("Unknown constraint letter!");
15447     case 'I':  // "I" is a signed 16-bit constant.
15448       if (isInt<16>(Value))
15449         Result = DAG.getTargetConstant(Value, dl, TCVT);
15450       break;
15451     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15452       if (isShiftedUInt<16, 16>(Value))
15453         Result = DAG.getTargetConstant(Value, dl, TCVT);
15454       break;
15455     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15456       if (isShiftedInt<16, 16>(Value))
15457         Result = DAG.getTargetConstant(Value, dl, TCVT);
15458       break;
15459     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15460       if (isUInt<16>(Value))
15461         Result = DAG.getTargetConstant(Value, dl, TCVT);
15462       break;
15463     case 'M':  // "M" is a constant that is greater than 31.
15464       if (Value > 31)
15465         Result = DAG.getTargetConstant(Value, dl, TCVT);
15466       break;
15467     case 'N':  // "N" is a positive constant that is an exact power of two.
15468       if (Value > 0 && isPowerOf2_64(Value))
15469         Result = DAG.getTargetConstant(Value, dl, TCVT);
15470       break;
15471     case 'O':  // "O" is the constant zero.
15472       if (Value == 0)
15473         Result = DAG.getTargetConstant(Value, dl, TCVT);
15474       break;
15475     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15476       if (isInt<16>(-Value))
15477         Result = DAG.getTargetConstant(Value, dl, TCVT);
15478       break;
15479     }
15480     break;
15481   }
15482   }
15483 
15484   if (Result.getNode()) {
15485     Ops.push_back(Result);
15486     return;
15487   }
15488 
15489   // Handle standard constraint letters.
15490   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15491 }
15492 
15493 // isLegalAddressingMode - Return true if the addressing mode represented
15494 // by AM is legal for this target, for a load/store of the specified type.
15495 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15496                                               const AddrMode &AM, Type *Ty,
15497                                               unsigned AS,
15498                                               Instruction *I) const {
15499   // Vector type r+i form is supported since power9 as DQ form. We don't check
15500   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
15501   // imm form is preferred and the offset can be adjusted to use imm form later
15502   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
15503   // max offset to check legal addressing mode, we should be a little aggressive
15504   // to contain other offsets for that LSRUse.
15505   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
15506     return false;
15507 
15508   // PPC allows a sign-extended 16-bit immediate field.
15509   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15510     return false;
15511 
15512   // No global is ever allowed as a base.
15513   if (AM.BaseGV)
15514     return false;
15515 
15516   // PPC only support r+r,
15517   switch (AM.Scale) {
15518   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15519     break;
15520   case 1:
15521     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15522       return false;
15523     // Otherwise we have r+r or r+i.
15524     break;
15525   case 2:
15526     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15527       return false;
15528     // Allow 2*r as r+r.
15529     break;
15530   default:
15531     // No other scales are supported.
15532     return false;
15533   }
15534 
15535   return true;
15536 }
15537 
15538 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15539                                            SelectionDAG &DAG) const {
15540   MachineFunction &MF = DAG.getMachineFunction();
15541   MachineFrameInfo &MFI = MF.getFrameInfo();
15542   MFI.setReturnAddressIsTaken(true);
15543 
15544   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15545     return SDValue();
15546 
15547   SDLoc dl(Op);
15548   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15549 
15550   // Make sure the function does not optimize away the store of the RA to
15551   // the stack.
15552   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15553   FuncInfo->setLRStoreRequired();
15554   bool isPPC64 = Subtarget.isPPC64();
15555   auto PtrVT = getPointerTy(MF.getDataLayout());
15556 
15557   if (Depth > 0) {
15558     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15559     SDValue Offset =
15560         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15561                         isPPC64 ? MVT::i64 : MVT::i32);
15562     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15563                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15564                        MachinePointerInfo());
15565   }
15566 
15567   // Just load the return address off the stack.
15568   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15569   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15570                      MachinePointerInfo());
15571 }
15572 
15573 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15574                                           SelectionDAG &DAG) const {
15575   SDLoc dl(Op);
15576   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15577 
15578   MachineFunction &MF = DAG.getMachineFunction();
15579   MachineFrameInfo &MFI = MF.getFrameInfo();
15580   MFI.setFrameAddressIsTaken(true);
15581 
15582   EVT PtrVT = getPointerTy(MF.getDataLayout());
15583   bool isPPC64 = PtrVT == MVT::i64;
15584 
15585   // Naked functions never have a frame pointer, and so we use r1. For all
15586   // other functions, this decision must be delayed until during PEI.
15587   unsigned FrameReg;
15588   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15589     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15590   else
15591     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15592 
15593   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15594                                          PtrVT);
15595   while (Depth--)
15596     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15597                             FrameAddr, MachinePointerInfo());
15598   return FrameAddr;
15599 }
15600 
15601 // FIXME? Maybe this could be a TableGen attribute on some registers and
15602 // this table could be generated automatically from RegInfo.
15603 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15604                                               const MachineFunction &MF) const {
15605   bool isPPC64 = Subtarget.isPPC64();
15606 
15607   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15608   if (!is64Bit && VT != LLT::scalar(32))
15609     report_fatal_error("Invalid register global variable type");
15610 
15611   Register Reg = StringSwitch<Register>(RegName)
15612                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15613                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15614                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15615                      .Default(Register());
15616 
15617   if (Reg)
15618     return Reg;
15619   report_fatal_error("Invalid register name global variable");
15620 }
15621 
15622 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15623   // 32-bit SVR4 ABI access everything as got-indirect.
15624   if (Subtarget.is32BitELFABI())
15625     return true;
15626 
15627   // AIX accesses everything indirectly through the TOC, which is similar to
15628   // the GOT.
15629   if (Subtarget.isAIXABI())
15630     return true;
15631 
15632   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15633   // If it is small or large code model, module locals are accessed
15634   // indirectly by loading their address from .toc/.got.
15635   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15636     return true;
15637 
15638   // JumpTable and BlockAddress are accessed as got-indirect.
15639   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15640     return true;
15641 
15642   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15643     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15644 
15645   return false;
15646 }
15647 
15648 bool
15649 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15650   // The PowerPC target isn't yet aware of offsets.
15651   return false;
15652 }
15653 
15654 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15655                                            const CallInst &I,
15656                                            MachineFunction &MF,
15657                                            unsigned Intrinsic) const {
15658   switch (Intrinsic) {
15659   case Intrinsic::ppc_altivec_lvx:
15660   case Intrinsic::ppc_altivec_lvxl:
15661   case Intrinsic::ppc_altivec_lvebx:
15662   case Intrinsic::ppc_altivec_lvehx:
15663   case Intrinsic::ppc_altivec_lvewx:
15664   case Intrinsic::ppc_vsx_lxvd2x:
15665   case Intrinsic::ppc_vsx_lxvw4x:
15666   case Intrinsic::ppc_vsx_lxvd2x_be:
15667   case Intrinsic::ppc_vsx_lxvw4x_be:
15668   case Intrinsic::ppc_vsx_lxvl:
15669   case Intrinsic::ppc_vsx_lxvll: {
15670     EVT VT;
15671     switch (Intrinsic) {
15672     case Intrinsic::ppc_altivec_lvebx:
15673       VT = MVT::i8;
15674       break;
15675     case Intrinsic::ppc_altivec_lvehx:
15676       VT = MVT::i16;
15677       break;
15678     case Intrinsic::ppc_altivec_lvewx:
15679       VT = MVT::i32;
15680       break;
15681     case Intrinsic::ppc_vsx_lxvd2x:
15682     case Intrinsic::ppc_vsx_lxvd2x_be:
15683       VT = MVT::v2f64;
15684       break;
15685     default:
15686       VT = MVT::v4i32;
15687       break;
15688     }
15689 
15690     Info.opc = ISD::INTRINSIC_W_CHAIN;
15691     Info.memVT = VT;
15692     Info.ptrVal = I.getArgOperand(0);
15693     Info.offset = -VT.getStoreSize()+1;
15694     Info.size = 2*VT.getStoreSize()-1;
15695     Info.align = Align(1);
15696     Info.flags = MachineMemOperand::MOLoad;
15697     return true;
15698   }
15699   case Intrinsic::ppc_altivec_stvx:
15700   case Intrinsic::ppc_altivec_stvxl:
15701   case Intrinsic::ppc_altivec_stvebx:
15702   case Intrinsic::ppc_altivec_stvehx:
15703   case Intrinsic::ppc_altivec_stvewx:
15704   case Intrinsic::ppc_vsx_stxvd2x:
15705   case Intrinsic::ppc_vsx_stxvw4x:
15706   case Intrinsic::ppc_vsx_stxvd2x_be:
15707   case Intrinsic::ppc_vsx_stxvw4x_be:
15708   case Intrinsic::ppc_vsx_stxvl:
15709   case Intrinsic::ppc_vsx_stxvll: {
15710     EVT VT;
15711     switch (Intrinsic) {
15712     case Intrinsic::ppc_altivec_stvebx:
15713       VT = MVT::i8;
15714       break;
15715     case Intrinsic::ppc_altivec_stvehx:
15716       VT = MVT::i16;
15717       break;
15718     case Intrinsic::ppc_altivec_stvewx:
15719       VT = MVT::i32;
15720       break;
15721     case Intrinsic::ppc_vsx_stxvd2x:
15722     case Intrinsic::ppc_vsx_stxvd2x_be:
15723       VT = MVT::v2f64;
15724       break;
15725     default:
15726       VT = MVT::v4i32;
15727       break;
15728     }
15729 
15730     Info.opc = ISD::INTRINSIC_VOID;
15731     Info.memVT = VT;
15732     Info.ptrVal = I.getArgOperand(1);
15733     Info.offset = -VT.getStoreSize()+1;
15734     Info.size = 2*VT.getStoreSize()-1;
15735     Info.align = Align(1);
15736     Info.flags = MachineMemOperand::MOStore;
15737     return true;
15738   }
15739   default:
15740     break;
15741   }
15742 
15743   return false;
15744 }
15745 
15746 /// It returns EVT::Other if the type should be determined using generic
15747 /// target-independent logic.
15748 EVT PPCTargetLowering::getOptimalMemOpType(
15749     const MemOp &Op, const AttributeList &FuncAttributes) const {
15750   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15751     // We should use Altivec/VSX loads and stores when available. For unaligned
15752     // addresses, unaligned VSX loads are only fast starting with the P8.
15753     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15754         (Op.isAligned(Align(16)) ||
15755          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15756       return MVT::v4i32;
15757   }
15758 
15759   if (Subtarget.isPPC64()) {
15760     return MVT::i64;
15761   }
15762 
15763   return MVT::i32;
15764 }
15765 
15766 /// Returns true if it is beneficial to convert a load of a constant
15767 /// to just the constant itself.
15768 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15769                                                           Type *Ty) const {
15770   assert(Ty->isIntegerTy());
15771 
15772   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15773   return !(BitSize == 0 || BitSize > 64);
15774 }
15775 
15776 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15777   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15778     return false;
15779   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15780   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15781   return NumBits1 == 64 && NumBits2 == 32;
15782 }
15783 
15784 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15785   if (!VT1.isInteger() || !VT2.isInteger())
15786     return false;
15787   unsigned NumBits1 = VT1.getSizeInBits();
15788   unsigned NumBits2 = VT2.getSizeInBits();
15789   return NumBits1 == 64 && NumBits2 == 32;
15790 }
15791 
15792 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15793   // Generally speaking, zexts are not free, but they are free when they can be
15794   // folded with other operations.
15795   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15796     EVT MemVT = LD->getMemoryVT();
15797     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15798          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15799         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15800          LD->getExtensionType() == ISD::ZEXTLOAD))
15801       return true;
15802   }
15803 
15804   // FIXME: Add other cases...
15805   //  - 32-bit shifts with a zext to i64
15806   //  - zext after ctlz, bswap, etc.
15807   //  - zext after and by a constant mask
15808 
15809   return TargetLowering::isZExtFree(Val, VT2);
15810 }
15811 
15812 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15813   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15814          "invalid fpext types");
15815   // Extending to float128 is not free.
15816   if (DestVT == MVT::f128)
15817     return false;
15818   return true;
15819 }
15820 
15821 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15822   return isInt<16>(Imm) || isUInt<16>(Imm);
15823 }
15824 
15825 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15826   return isInt<16>(Imm) || isUInt<16>(Imm);
15827 }
15828 
15829 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align,
15830                                                        MachineMemOperand::Flags,
15831                                                        bool *Fast) const {
15832   if (DisablePPCUnaligned)
15833     return false;
15834 
15835   // PowerPC supports unaligned memory access for simple non-vector types.
15836   // Although accessing unaligned addresses is not as efficient as accessing
15837   // aligned addresses, it is generally more efficient than manual expansion,
15838   // and generally only traps for software emulation when crossing page
15839   // boundaries.
15840 
15841   if (!VT.isSimple())
15842     return false;
15843 
15844   if (VT.isFloatingPoint() && !VT.isVector() &&
15845       !Subtarget.allowsUnalignedFPAccess())
15846     return false;
15847 
15848   if (VT.getSimpleVT().isVector()) {
15849     if (Subtarget.hasVSX()) {
15850       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15851           VT != MVT::v4f32 && VT != MVT::v4i32)
15852         return false;
15853     } else {
15854       return false;
15855     }
15856   }
15857 
15858   if (VT == MVT::ppcf128)
15859     return false;
15860 
15861   if (Fast)
15862     *Fast = true;
15863 
15864   return true;
15865 }
15866 
15867 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
15868                                                SDValue C) const {
15869   // Check integral scalar types.
15870   if (!VT.isScalarInteger())
15871     return false;
15872   if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
15873     if (!ConstNode->getAPIntValue().isSignedIntN(64))
15874       return false;
15875     // This transformation will generate >= 2 operations. But the following
15876     // cases will generate <= 2 instructions during ISEL. So exclude them.
15877     // 1. If the constant multiplier fits 16 bits, it can be handled by one
15878     // HW instruction, ie. MULLI
15879     // 2. If the multiplier after shifted fits 16 bits, an extra shift
15880     // instruction is needed than case 1, ie. MULLI and RLDICR
15881     int64_t Imm = ConstNode->getSExtValue();
15882     unsigned Shift = countTrailingZeros<uint64_t>(Imm);
15883     Imm >>= Shift;
15884     if (isInt<16>(Imm))
15885       return false;
15886     uint64_t UImm = static_cast<uint64_t>(Imm);
15887     if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
15888         isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
15889       return true;
15890   }
15891   return false;
15892 }
15893 
15894 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15895                                                    EVT VT) const {
15896   return isFMAFasterThanFMulAndFAdd(
15897       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15898 }
15899 
15900 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15901                                                    Type *Ty) const {
15902   switch (Ty->getScalarType()->getTypeID()) {
15903   case Type::FloatTyID:
15904   case Type::DoubleTyID:
15905     return true;
15906   case Type::FP128TyID:
15907     return Subtarget.hasP9Vector();
15908   default:
15909     return false;
15910   }
15911 }
15912 
15913 // FIXME: add more patterns which are not profitable to hoist.
15914 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
15915   if (!I->hasOneUse())
15916     return true;
15917 
15918   Instruction *User = I->user_back();
15919   assert(User && "A single use instruction with no uses.");
15920 
15921   switch (I->getOpcode()) {
15922   case Instruction::FMul: {
15923     // Don't break FMA, PowerPC prefers FMA.
15924     if (User->getOpcode() != Instruction::FSub &&
15925         User->getOpcode() != Instruction::FAdd)
15926       return true;
15927 
15928     const TargetOptions &Options = getTargetMachine().Options;
15929     const Function *F = I->getFunction();
15930     const DataLayout &DL = F->getParent()->getDataLayout();
15931     Type *Ty = User->getOperand(0)->getType();
15932 
15933     return !(
15934         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
15935         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
15936         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
15937   }
15938   case Instruction::Load: {
15939     // Don't break "store (load float*)" pattern, this pattern will be combined
15940     // to "store (load int32)" in later InstCombine pass. See function
15941     // combineLoadToOperationType. On PowerPC, loading a float point takes more
15942     // cycles than loading a 32 bit integer.
15943     LoadInst *LI = cast<LoadInst>(I);
15944     // For the loads that combineLoadToOperationType does nothing, like
15945     // ordered load, it should be profitable to hoist them.
15946     // For swifterror load, it can only be used for pointer to pointer type, so
15947     // later type check should get rid of this case.
15948     if (!LI->isUnordered())
15949       return true;
15950 
15951     if (User->getOpcode() != Instruction::Store)
15952       return true;
15953 
15954     if (I->getType()->getTypeID() != Type::FloatTyID)
15955       return true;
15956 
15957     return false;
15958   }
15959   default:
15960     return true;
15961   }
15962   return true;
15963 }
15964 
15965 const MCPhysReg *
15966 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15967   // LR is a callee-save register, but we must treat it as clobbered by any call
15968   // site. Hence we include LR in the scratch registers, which are in turn added
15969   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15970   // to CTR, which is used by any indirect call.
15971   static const MCPhysReg ScratchRegs[] = {
15972     PPC::X12, PPC::LR8, PPC::CTR8, 0
15973   };
15974 
15975   return ScratchRegs;
15976 }
15977 
15978 Register PPCTargetLowering::getExceptionPointerRegister(
15979     const Constant *PersonalityFn) const {
15980   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15981 }
15982 
15983 Register PPCTargetLowering::getExceptionSelectorRegister(
15984     const Constant *PersonalityFn) const {
15985   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15986 }
15987 
15988 bool
15989 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15990                      EVT VT , unsigned DefinedValues) const {
15991   if (VT == MVT::v2i64)
15992     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15993 
15994   if (Subtarget.hasVSX())
15995     return true;
15996 
15997   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15998 }
15999 
16000 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16001   if (DisableILPPref || Subtarget.enableMachineScheduler())
16002     return TargetLowering::getSchedulingPreference(N);
16003 
16004   return Sched::ILP;
16005 }
16006 
16007 // Create a fast isel object.
16008 FastISel *
16009 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16010                                   const TargetLibraryInfo *LibInfo) const {
16011   return PPC::createFastISel(FuncInfo, LibInfo);
16012 }
16013 
16014 // 'Inverted' means the FMA opcode after negating one multiplicand.
16015 // For example, (fma -a b c) = (fnmsub a b c)
16016 static unsigned invertFMAOpcode(unsigned Opc) {
16017   switch (Opc) {
16018   default:
16019     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16020   case ISD::FMA:
16021     return PPCISD::FNMSUB;
16022   case PPCISD::FNMSUB:
16023     return ISD::FMA;
16024   }
16025 }
16026 
16027 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16028                                                 bool LegalOps, bool OptForSize,
16029                                                 NegatibleCost &Cost,
16030                                                 unsigned Depth) const {
16031   if (Depth > SelectionDAG::MaxRecursionDepth)
16032     return SDValue();
16033 
16034   unsigned Opc = Op.getOpcode();
16035   EVT VT = Op.getValueType();
16036   SDNodeFlags Flags = Op.getNode()->getFlags();
16037 
16038   switch (Opc) {
16039   case PPCISD::FNMSUB:
16040     if (!Op.hasOneUse() || !isTypeLegal(VT))
16041       break;
16042 
16043     const TargetOptions &Options = getTargetMachine().Options;
16044     SDValue N0 = Op.getOperand(0);
16045     SDValue N1 = Op.getOperand(1);
16046     SDValue N2 = Op.getOperand(2);
16047     SDLoc Loc(Op);
16048 
16049     NegatibleCost N2Cost = NegatibleCost::Expensive;
16050     SDValue NegN2 =
16051         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16052 
16053     if (!NegN2)
16054       return SDValue();
16055 
16056     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16057     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16058     // These transformations may change sign of zeroes. For example,
16059     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16060     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16061       // Try and choose the cheaper one to negate.
16062       NegatibleCost N0Cost = NegatibleCost::Expensive;
16063       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16064                                            N0Cost, Depth + 1);
16065 
16066       NegatibleCost N1Cost = NegatibleCost::Expensive;
16067       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16068                                            N1Cost, Depth + 1);
16069 
16070       if (NegN0 && N0Cost <= N1Cost) {
16071         Cost = std::min(N0Cost, N2Cost);
16072         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16073       } else if (NegN1) {
16074         Cost = std::min(N1Cost, N2Cost);
16075         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16076       }
16077     }
16078 
16079     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16080     if (isOperationLegal(ISD::FMA, VT)) {
16081       Cost = N2Cost;
16082       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16083     }
16084 
16085     break;
16086   }
16087 
16088   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16089                                               Cost, Depth);
16090 }
16091 
16092 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16093 bool PPCTargetLowering::useLoadStackGuardNode() const {
16094   if (!Subtarget.isTargetLinux())
16095     return TargetLowering::useLoadStackGuardNode();
16096   return true;
16097 }
16098 
16099 // Override to disable global variable loading on Linux.
16100 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16101   if (!Subtarget.isTargetLinux())
16102     return TargetLowering::insertSSPDeclarations(M);
16103 }
16104 
16105 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16106                                      bool ForCodeSize) const {
16107   if (!VT.isSimple() || !Subtarget.hasVSX())
16108     return false;
16109 
16110   switch(VT.getSimpleVT().SimpleTy) {
16111   default:
16112     // For FP types that are currently not supported by PPC backend, return
16113     // false. Examples: f16, f80.
16114     return false;
16115   case MVT::f32:
16116   case MVT::f64:
16117     if (Subtarget.hasPrefixInstrs()) {
16118       // With prefixed instructions, we can materialize anything that can be
16119       // represented with a 32-bit immediate, not just positive zero.
16120       APFloat APFloatOfImm = Imm;
16121       return convertToNonDenormSingle(APFloatOfImm);
16122     }
16123     LLVM_FALLTHROUGH;
16124   case MVT::ppcf128:
16125     return Imm.isPosZero();
16126   }
16127 }
16128 
16129 // For vector shift operation op, fold
16130 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16131 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16132                                   SelectionDAG &DAG) {
16133   SDValue N0 = N->getOperand(0);
16134   SDValue N1 = N->getOperand(1);
16135   EVT VT = N0.getValueType();
16136   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16137   unsigned Opcode = N->getOpcode();
16138   unsigned TargetOpcode;
16139 
16140   switch (Opcode) {
16141   default:
16142     llvm_unreachable("Unexpected shift operation");
16143   case ISD::SHL:
16144     TargetOpcode = PPCISD::SHL;
16145     break;
16146   case ISD::SRL:
16147     TargetOpcode = PPCISD::SRL;
16148     break;
16149   case ISD::SRA:
16150     TargetOpcode = PPCISD::SRA;
16151     break;
16152   }
16153 
16154   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16155       N1->getOpcode() == ISD::AND)
16156     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16157       if (Mask->getZExtValue() == OpSizeInBits - 1)
16158         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16159 
16160   return SDValue();
16161 }
16162 
16163 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16164   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16165     return Value;
16166 
16167   SDValue N0 = N->getOperand(0);
16168   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16169   if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
16170       N0.getOpcode() != ISD::SIGN_EXTEND ||
16171       N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
16172       N->getValueType(0) != MVT::i64)
16173     return SDValue();
16174 
16175   // We can't save an operation here if the value is already extended, and
16176   // the existing shift is easier to combine.
16177   SDValue ExtsSrc = N0.getOperand(0);
16178   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16179       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16180     return SDValue();
16181 
16182   SDLoc DL(N0);
16183   SDValue ShiftBy = SDValue(CN1, 0);
16184   // We want the shift amount to be i32 on the extswli, but the shift could
16185   // have an i64.
16186   if (ShiftBy.getValueType() == MVT::i64)
16187     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16188 
16189   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16190                          ShiftBy);
16191 }
16192 
16193 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16194   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16195     return Value;
16196 
16197   return SDValue();
16198 }
16199 
16200 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16201   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16202     return Value;
16203 
16204   return SDValue();
16205 }
16206 
16207 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16208 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16209 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16210 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16211 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16212                                  const PPCSubtarget &Subtarget) {
16213   if (!Subtarget.isPPC64())
16214     return SDValue();
16215 
16216   SDValue LHS = N->getOperand(0);
16217   SDValue RHS = N->getOperand(1);
16218 
16219   auto isZextOfCompareWithConstant = [](SDValue Op) {
16220     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16221         Op.getValueType() != MVT::i64)
16222       return false;
16223 
16224     SDValue Cmp = Op.getOperand(0);
16225     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16226         Cmp.getOperand(0).getValueType() != MVT::i64)
16227       return false;
16228 
16229     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
16230       int64_t NegConstant = 0 - Constant->getSExtValue();
16231       // Due to the limitations of the addi instruction,
16232       // -C is required to be [-32768, 32767].
16233       return isInt<16>(NegConstant);
16234     }
16235 
16236     return false;
16237   };
16238 
16239   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
16240   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16241 
16242   // If there is a pattern, canonicalize a zext operand to the RHS.
16243   if (LHSHasPattern && !RHSHasPattern)
16244     std::swap(LHS, RHS);
16245   else if (!LHSHasPattern && !RHSHasPattern)
16246     return SDValue();
16247 
16248   SDLoc DL(N);
16249   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16250   SDValue Cmp = RHS.getOperand(0);
16251   SDValue Z = Cmp.getOperand(0);
16252   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
16253 
16254   assert(Constant && "Constant Should not be a null pointer.");
16255   int64_t NegConstant = 0 - Constant->getSExtValue();
16256 
16257   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16258   default: break;
16259   case ISD::SETNE: {
16260     //                                 when C == 0
16261     //                             --> addze X, (addic Z, -1).carry
16262     //                            /
16263     // add X, (zext(setne Z, C))--
16264     //                            \    when -32768 <= -C <= 32767 && C != 0
16265     //                             --> addze X, (addic (addi Z, -C), -1).carry
16266     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16267                               DAG.getConstant(NegConstant, DL, MVT::i64));
16268     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16269     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16270                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16271     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16272                        SDValue(Addc.getNode(), 1));
16273     }
16274   case ISD::SETEQ: {
16275     //                                 when C == 0
16276     //                             --> addze X, (subfic Z, 0).carry
16277     //                            /
16278     // add X, (zext(sete  Z, C))--
16279     //                            \    when -32768 <= -C <= 32767 && C != 0
16280     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16281     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16282                               DAG.getConstant(NegConstant, DL, MVT::i64));
16283     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16284     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16285                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16286     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16287                        SDValue(Subc.getNode(), 1));
16288     }
16289   }
16290 
16291   return SDValue();
16292 }
16293 
16294 // Transform
16295 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16296 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16297 // In this case both C1 and C2 must be known constants.
16298 // C1+C2 must fit into a 34 bit signed integer.
16299 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16300                                           const PPCSubtarget &Subtarget) {
16301   if (!Subtarget.isUsingPCRelativeCalls())
16302     return SDValue();
16303 
16304   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16305   // If we find that node try to cast the Global Address and the Constant.
16306   SDValue LHS = N->getOperand(0);
16307   SDValue RHS = N->getOperand(1);
16308 
16309   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16310     std::swap(LHS, RHS);
16311 
16312   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16313     return SDValue();
16314 
16315   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16316   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16317   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16318 
16319   // Check that both casts succeeded.
16320   if (!GSDN || !ConstNode)
16321     return SDValue();
16322 
16323   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16324   SDLoc DL(GSDN);
16325 
16326   // The signed int offset needs to fit in 34 bits.
16327   if (!isInt<34>(NewOffset))
16328     return SDValue();
16329 
16330   // The new global address is a copy of the old global address except
16331   // that it has the updated Offset.
16332   SDValue GA =
16333       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16334                                  NewOffset, GSDN->getTargetFlags());
16335   SDValue MatPCRel =
16336       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16337   return MatPCRel;
16338 }
16339 
16340 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16341   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16342     return Value;
16343 
16344   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16345     return Value;
16346 
16347   return SDValue();
16348 }
16349 
16350 // Detect TRUNCATE operations on bitcasts of float128 values.
16351 // What we are looking for here is the situtation where we extract a subset
16352 // of bits from a 128 bit float.
16353 // This can be of two forms:
16354 // 1) BITCAST of f128 feeding TRUNCATE
16355 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16356 // The reason this is required is because we do not have a legal i128 type
16357 // and so we want to prevent having to store the f128 and then reload part
16358 // of it.
16359 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16360                                            DAGCombinerInfo &DCI) const {
16361   // If we are using CRBits then try that first.
16362   if (Subtarget.useCRBits()) {
16363     // Check if CRBits did anything and return that if it did.
16364     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16365       return CRTruncValue;
16366   }
16367 
16368   SDLoc dl(N);
16369   SDValue Op0 = N->getOperand(0);
16370 
16371   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
16372   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
16373     EVT VT = N->getValueType(0);
16374     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16375       return SDValue();
16376     SDValue Sub = Op0.getOperand(0);
16377     if (Sub.getOpcode() == ISD::SUB) {
16378       SDValue SubOp0 = Sub.getOperand(0);
16379       SDValue SubOp1 = Sub.getOperand(1);
16380       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16381           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16382         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16383                                SubOp1.getOperand(0),
16384                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16385       }
16386     }
16387   }
16388 
16389   // Looking for a truncate of i128 to i64.
16390   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16391     return SDValue();
16392 
16393   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16394 
16395   // SRL feeding TRUNCATE.
16396   if (Op0.getOpcode() == ISD::SRL) {
16397     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16398     // The right shift has to be by 64 bits.
16399     if (!ConstNode || ConstNode->getZExtValue() != 64)
16400       return SDValue();
16401 
16402     // Switch the element number to extract.
16403     EltToExtract = EltToExtract ? 0 : 1;
16404     // Update Op0 past the SRL.
16405     Op0 = Op0.getOperand(0);
16406   }
16407 
16408   // BITCAST feeding a TRUNCATE possibly via SRL.
16409   if (Op0.getOpcode() == ISD::BITCAST &&
16410       Op0.getValueType() == MVT::i128 &&
16411       Op0.getOperand(0).getValueType() == MVT::f128) {
16412     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16413     return DCI.DAG.getNode(
16414         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16415         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16416   }
16417   return SDValue();
16418 }
16419 
16420 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16421   SelectionDAG &DAG = DCI.DAG;
16422 
16423   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16424   if (!ConstOpOrElement)
16425     return SDValue();
16426 
16427   // An imul is usually smaller than the alternative sequence for legal type.
16428   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16429       isOperationLegal(ISD::MUL, N->getValueType(0)))
16430     return SDValue();
16431 
16432   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16433     switch (this->Subtarget.getCPUDirective()) {
16434     default:
16435       // TODO: enhance the condition for subtarget before pwr8
16436       return false;
16437     case PPC::DIR_PWR8:
16438       //  type        mul     add    shl
16439       // scalar        4       1      1
16440       // vector        7       2      2
16441       return true;
16442     case PPC::DIR_PWR9:
16443     case PPC::DIR_PWR10:
16444     case PPC::DIR_PWR_FUTURE:
16445       //  type        mul     add    shl
16446       // scalar        5       2      2
16447       // vector        7       2      2
16448 
16449       // The cycle RATIO of related operations are showed as a table above.
16450       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16451       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16452       // are 4, it is always profitable; but for 3 instrs patterns
16453       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16454       // So we should only do it for vector type.
16455       return IsAddOne && IsNeg ? VT.isVector() : true;
16456     }
16457   };
16458 
16459   EVT VT = N->getValueType(0);
16460   SDLoc DL(N);
16461 
16462   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16463   bool IsNeg = MulAmt.isNegative();
16464   APInt MulAmtAbs = MulAmt.abs();
16465 
16466   if ((MulAmtAbs - 1).isPowerOf2()) {
16467     // (mul x, 2^N + 1) => (add (shl x, N), x)
16468     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16469 
16470     if (!IsProfitable(IsNeg, true, VT))
16471       return SDValue();
16472 
16473     SDValue Op0 = N->getOperand(0);
16474     SDValue Op1 =
16475         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16476                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16477     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16478 
16479     if (!IsNeg)
16480       return Res;
16481 
16482     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16483   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16484     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16485     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16486 
16487     if (!IsProfitable(IsNeg, false, VT))
16488       return SDValue();
16489 
16490     SDValue Op0 = N->getOperand(0);
16491     SDValue Op1 =
16492         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16493                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16494 
16495     if (!IsNeg)
16496       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16497     else
16498       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16499 
16500   } else {
16501     return SDValue();
16502   }
16503 }
16504 
16505 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16506 // in combiner since we need to check SD flags and other subtarget features.
16507 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16508                                           DAGCombinerInfo &DCI) const {
16509   SDValue N0 = N->getOperand(0);
16510   SDValue N1 = N->getOperand(1);
16511   SDValue N2 = N->getOperand(2);
16512   SDNodeFlags Flags = N->getFlags();
16513   EVT VT = N->getValueType(0);
16514   SelectionDAG &DAG = DCI.DAG;
16515   const TargetOptions &Options = getTargetMachine().Options;
16516   unsigned Opc = N->getOpcode();
16517   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16518   bool LegalOps = !DCI.isBeforeLegalizeOps();
16519   SDLoc Loc(N);
16520 
16521   if (!isOperationLegal(ISD::FMA, VT))
16522     return SDValue();
16523 
16524   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16525   // since (fnmsub a b c)=-0 while c-ab=+0.
16526   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16527     return SDValue();
16528 
16529   // (fma (fneg a) b c) => (fnmsub a b c)
16530   // (fnmsub (fneg a) b c) => (fma a b c)
16531   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16532     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16533 
16534   // (fma a (fneg b) c) => (fnmsub a b c)
16535   // (fnmsub a (fneg b) c) => (fma a b c)
16536   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16537     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16538 
16539   return SDValue();
16540 }
16541 
16542 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16543   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16544   if (!Subtarget.is64BitELFABI())
16545     return false;
16546 
16547   // If not a tail call then no need to proceed.
16548   if (!CI->isTailCall())
16549     return false;
16550 
16551   // If sibling calls have been disabled and tail-calls aren't guaranteed
16552   // there is no reason to duplicate.
16553   auto &TM = getTargetMachine();
16554   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16555     return false;
16556 
16557   // Can't tail call a function called indirectly, or if it has variadic args.
16558   const Function *Callee = CI->getCalledFunction();
16559   if (!Callee || Callee->isVarArg())
16560     return false;
16561 
16562   // Make sure the callee and caller calling conventions are eligible for tco.
16563   const Function *Caller = CI->getParent()->getParent();
16564   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16565                                            CI->getCallingConv()))
16566       return false;
16567 
16568   // If the function is local then we have a good chance at tail-calling it
16569   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16570 }
16571 
16572 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16573   if (!Subtarget.hasVSX())
16574     return false;
16575   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16576     return true;
16577   return VT == MVT::f32 || VT == MVT::f64 ||
16578     VT == MVT::v4f32 || VT == MVT::v2f64;
16579 }
16580 
16581 bool PPCTargetLowering::
16582 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16583   const Value *Mask = AndI.getOperand(1);
16584   // If the mask is suitable for andi. or andis. we should sink the and.
16585   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16586     // Can't handle constants wider than 64-bits.
16587     if (CI->getBitWidth() > 64)
16588       return false;
16589     int64_t ConstVal = CI->getZExtValue();
16590     return isUInt<16>(ConstVal) ||
16591       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16592   }
16593 
16594   // For non-constant masks, we can always use the record-form and.
16595   return true;
16596 }
16597 
16598 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16599 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16600 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16601 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16602 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16603 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16604   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16605   assert(Subtarget.hasP9Altivec() &&
16606          "Only combine this when P9 altivec supported!");
16607   EVT VT = N->getValueType(0);
16608   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16609     return SDValue();
16610 
16611   SelectionDAG &DAG = DCI.DAG;
16612   SDLoc dl(N);
16613   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16614     // Even for signed integers, if it's known to be positive (as signed
16615     // integer) due to zero-extended inputs.
16616     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16617     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16618     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16619          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16620         (SubOpcd1 == ISD::ZERO_EXTEND ||
16621          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16622       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16623                          N->getOperand(0)->getOperand(0),
16624                          N->getOperand(0)->getOperand(1),
16625                          DAG.getTargetConstant(0, dl, MVT::i32));
16626     }
16627 
16628     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16629     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16630         N->getOperand(0).hasOneUse()) {
16631       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16632                          N->getOperand(0)->getOperand(0),
16633                          N->getOperand(0)->getOperand(1),
16634                          DAG.getTargetConstant(1, dl, MVT::i32));
16635     }
16636   }
16637 
16638   return SDValue();
16639 }
16640 
16641 // For type v4i32/v8ii16/v16i8, transform
16642 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16643 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16644 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16645 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16646 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16647                                           DAGCombinerInfo &DCI) const {
16648   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16649   assert(Subtarget.hasP9Altivec() &&
16650          "Only combine this when P9 altivec supported!");
16651 
16652   SelectionDAG &DAG = DCI.DAG;
16653   SDLoc dl(N);
16654   SDValue Cond = N->getOperand(0);
16655   SDValue TrueOpnd = N->getOperand(1);
16656   SDValue FalseOpnd = N->getOperand(2);
16657   EVT VT = N->getOperand(1).getValueType();
16658 
16659   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16660       FalseOpnd.getOpcode() != ISD::SUB)
16661     return SDValue();
16662 
16663   // ABSD only available for type v4i32/v8i16/v16i8
16664   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16665     return SDValue();
16666 
16667   // At least to save one more dependent computation
16668   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16669     return SDValue();
16670 
16671   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16672 
16673   // Can only handle unsigned comparison here
16674   switch (CC) {
16675   default:
16676     return SDValue();
16677   case ISD::SETUGT:
16678   case ISD::SETUGE:
16679     break;
16680   case ISD::SETULT:
16681   case ISD::SETULE:
16682     std::swap(TrueOpnd, FalseOpnd);
16683     break;
16684   }
16685 
16686   SDValue CmpOpnd1 = Cond.getOperand(0);
16687   SDValue CmpOpnd2 = Cond.getOperand(1);
16688 
16689   // SETCC CmpOpnd1 CmpOpnd2 cond
16690   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16691   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16692   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16693       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16694       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16695       FalseOpnd.getOperand(1) == CmpOpnd1) {
16696     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16697                        CmpOpnd1, CmpOpnd2,
16698                        DAG.getTargetConstant(0, dl, MVT::i32));
16699   }
16700 
16701   return SDValue();
16702 }
16703