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       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
155     } else {
156       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
157       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
158     }
159   }
160 
161   // Match BITREVERSE to customized fast code sequence in the td file.
162   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
163   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
164 
165   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
166   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
167 
168   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
169   for (MVT VT : MVT::integer_valuetypes()) {
170     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
171     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
172   }
173 
174   if (Subtarget.isISA3_0()) {
175     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
176     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
177     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
178     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
179   } else {
180     // No extending loads from f16 or HW conversions back and forth.
181     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
182     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
183     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
184     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
185     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
186     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
187     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
188     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
189   }
190 
191   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
192 
193   // PowerPC has pre-inc load and store's.
194   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
195   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
196   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
197   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
198   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
199   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
200   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
201   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
202   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
203   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
204   if (!Subtarget.hasSPE()) {
205     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
206     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
207     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
208     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
209   }
210 
211   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
212   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
213   for (MVT VT : ScalarIntVTs) {
214     setOperationAction(ISD::ADDC, VT, Legal);
215     setOperationAction(ISD::ADDE, VT, Legal);
216     setOperationAction(ISD::SUBC, VT, Legal);
217     setOperationAction(ISD::SUBE, VT, Legal);
218   }
219 
220   if (Subtarget.useCRBits()) {
221     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
222 
223     if (isPPC64 || Subtarget.hasFPCVT()) {
224       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote);
225       AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1,
226                         isPPC64 ? MVT::i64 : MVT::i32);
227       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote);
228       AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1,
229                         isPPC64 ? MVT::i64 : MVT::i32);
230 
231       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
232       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
233                          isPPC64 ? MVT::i64 : MVT::i32);
234       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
235       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
236                         isPPC64 ? MVT::i64 : MVT::i32);
237 
238       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote);
239       AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1,
240                         isPPC64 ? MVT::i64 : MVT::i32);
241       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote);
242       AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1,
243                         isPPC64 ? MVT::i64 : MVT::i32);
244 
245       setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
246       AddPromotedToType(ISD::FP_TO_SINT, MVT::i1,
247                         isPPC64 ? MVT::i64 : MVT::i32);
248       setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
249       AddPromotedToType(ISD::FP_TO_UINT, MVT::i1,
250                         isPPC64 ? MVT::i64 : MVT::i32);
251     } else {
252       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom);
253       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom);
254       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
255       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
256     }
257 
258     // PowerPC does not support direct load/store of condition registers.
259     setOperationAction(ISD::LOAD, MVT::i1, Custom);
260     setOperationAction(ISD::STORE, MVT::i1, Custom);
261 
262     // FIXME: Remove this once the ANDI glue bug is fixed:
263     if (ANDIGlueBug)
264       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
265 
266     for (MVT VT : MVT::integer_valuetypes()) {
267       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
268       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
269       setTruncStoreAction(VT, MVT::i1, Expand);
270     }
271 
272     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
273   }
274 
275   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
276   // PPC (the libcall is not available).
277   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
278   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
279   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom);
280   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom);
281 
282   // We do not currently implement these libm ops for PowerPC.
283   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
284   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
285   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
286   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
287   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
288   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
289 
290   // PowerPC has no SREM/UREM instructions unless we are on P9
291   // On P9 we may use a hardware instruction to compute the remainder.
292   // When the result of both the remainder and the division is required it is
293   // more efficient to compute the remainder from the result of the division
294   // rather than use the remainder instruction. The instructions are legalized
295   // directly because the DivRemPairsPass performs the transformation at the IR
296   // level.
297   if (Subtarget.isISA3_0()) {
298     setOperationAction(ISD::SREM, MVT::i32, Legal);
299     setOperationAction(ISD::UREM, MVT::i32, Legal);
300     setOperationAction(ISD::SREM, MVT::i64, Legal);
301     setOperationAction(ISD::UREM, MVT::i64, Legal);
302   } else {
303     setOperationAction(ISD::SREM, MVT::i32, Expand);
304     setOperationAction(ISD::UREM, MVT::i32, Expand);
305     setOperationAction(ISD::SREM, MVT::i64, Expand);
306     setOperationAction(ISD::UREM, MVT::i64, Expand);
307   }
308 
309   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
310   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
311   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
312   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
313   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
314   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
315   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
316   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
317   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
318 
319   // Handle constrained floating-point operations of scalar.
320   // TODO: Handle SPE specific operation.
321   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
322   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
323   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
324   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
325   setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
326   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
327 
328   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
329   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
330   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
331   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
332   setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
333   if (Subtarget.hasVSX()) {
334     setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal);
335     setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal);
336   }
337 
338   if (Subtarget.hasFSQRT()) {
339     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
340     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
341   }
342 
343   if (Subtarget.hasFPRND()) {
344     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
345     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
346     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
347     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
348 
349     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
350     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
351     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
352     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
353   }
354 
355   // We don't support sin/cos/sqrt/fmod/pow
356   setOperationAction(ISD::FSIN , MVT::f64, Expand);
357   setOperationAction(ISD::FCOS , MVT::f64, Expand);
358   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
359   setOperationAction(ISD::FREM , MVT::f64, Expand);
360   setOperationAction(ISD::FPOW , MVT::f64, Expand);
361   setOperationAction(ISD::FSIN , MVT::f32, Expand);
362   setOperationAction(ISD::FCOS , MVT::f32, Expand);
363   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
364   setOperationAction(ISD::FREM , MVT::f32, Expand);
365   setOperationAction(ISD::FPOW , MVT::f32, Expand);
366   if (Subtarget.hasSPE()) {
367     setOperationAction(ISD::FMA  , MVT::f64, Expand);
368     setOperationAction(ISD::FMA  , MVT::f32, Expand);
369   } else {
370     setOperationAction(ISD::FMA  , MVT::f64, Legal);
371     setOperationAction(ISD::FMA  , MVT::f32, Legal);
372   }
373 
374   if (Subtarget.hasSPE())
375     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
376 
377   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
378 
379   // If we're enabling GP optimizations, use hardware square root
380   if (!Subtarget.hasFSQRT() &&
381       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
382         Subtarget.hasFRE()))
383     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
384 
385   if (!Subtarget.hasFSQRT() &&
386       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
387         Subtarget.hasFRES()))
388     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
389 
390   if (Subtarget.hasFCPSGN()) {
391     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
392     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
393   } else {
394     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
395     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
396   }
397 
398   if (Subtarget.hasFPRND()) {
399     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
400     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
401     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
402     setOperationAction(ISD::FROUND, MVT::f64, Legal);
403 
404     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
405     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
406     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
407     setOperationAction(ISD::FROUND, MVT::f32, Legal);
408   }
409 
410   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
411   // to speed up scalar BSWAP64.
412   // CTPOP or CTTZ were introduced in P8/P9 respectively
413   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
414   if (Subtarget.hasP9Vector())
415     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
416   else
417     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
418   if (Subtarget.isISA3_0()) {
419     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
420     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
421   } else {
422     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
423     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
424   }
425 
426   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
427     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
428     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
429   } else {
430     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
431     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
432   }
433 
434   // PowerPC does not have ROTR
435   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
436   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
437 
438   if (!Subtarget.useCRBits()) {
439     // PowerPC does not have Select
440     setOperationAction(ISD::SELECT, MVT::i32, Expand);
441     setOperationAction(ISD::SELECT, MVT::i64, Expand);
442     setOperationAction(ISD::SELECT, MVT::f32, Expand);
443     setOperationAction(ISD::SELECT, MVT::f64, Expand);
444   }
445 
446   // PowerPC wants to turn select_cc of FP into fsel when possible.
447   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
448   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
449 
450   // PowerPC wants to optimize integer setcc a bit
451   if (!Subtarget.useCRBits())
452     setOperationAction(ISD::SETCC, MVT::i32, Custom);
453 
454   if (Subtarget.hasFPU()) {
455     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
456     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
457     setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
458 
459     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
460     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
461     setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
462   }
463 
464   // PowerPC does not have BRCOND which requires SetCC
465   if (!Subtarget.useCRBits())
466     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
467 
468   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
469 
470   if (Subtarget.hasSPE()) {
471     // SPE has built-in conversions
472     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
473     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
474     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
475     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
476     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
477     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
478   } else {
479     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
480     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
481     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
482 
483     // PowerPC does not have [U|S]INT_TO_FP
484     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand);
485     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand);
486     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
487     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
488   }
489 
490   if (Subtarget.hasDirectMove() && isPPC64) {
491     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
492     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
493     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
494     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
495     if (TM.Options.UnsafeFPMath) {
496       setOperationAction(ISD::LRINT, MVT::f64, Legal);
497       setOperationAction(ISD::LRINT, MVT::f32, Legal);
498       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
499       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
500       setOperationAction(ISD::LROUND, MVT::f64, Legal);
501       setOperationAction(ISD::LROUND, MVT::f32, Legal);
502       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
503       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
504     }
505   } else {
506     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
507     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
508     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
509     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
510   }
511 
512   // We cannot sextinreg(i1).  Expand to shifts.
513   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
514 
515   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
516   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
517   // support continuation, user-level threading, and etc.. As a result, no
518   // other SjLj exception interfaces are implemented and please don't build
519   // your own exception handling based on them.
520   // LLVM/Clang supports zero-cost DWARF exception handling.
521   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
522   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
523 
524   // We want to legalize GlobalAddress and ConstantPool nodes into the
525   // appropriate instructions to materialize the address.
526   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
527   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
528   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
529   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
530   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
531   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
532   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
533   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
534   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
535   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
536 
537   // TRAP is legal.
538   setOperationAction(ISD::TRAP, MVT::Other, Legal);
539 
540   // TRAMPOLINE is custom lowered.
541   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
542   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
543 
544   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
545   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
546 
547   if (Subtarget.is64BitELFABI()) {
548     // VAARG always uses double-word chunks, so promote anything smaller.
549     setOperationAction(ISD::VAARG, MVT::i1, Promote);
550     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
551     setOperationAction(ISD::VAARG, MVT::i8, Promote);
552     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
553     setOperationAction(ISD::VAARG, MVT::i16, Promote);
554     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
555     setOperationAction(ISD::VAARG, MVT::i32, Promote);
556     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
557     setOperationAction(ISD::VAARG, MVT::Other, Expand);
558   } else if (Subtarget.is32BitELFABI()) {
559     // VAARG is custom lowered with the 32-bit SVR4 ABI.
560     setOperationAction(ISD::VAARG, MVT::Other, Custom);
561     setOperationAction(ISD::VAARG, MVT::i64, Custom);
562   } else
563     setOperationAction(ISD::VAARG, MVT::Other, Expand);
564 
565   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
566   if (Subtarget.is32BitELFABI())
567     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
568   else
569     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
570 
571   // Use the default implementation.
572   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
573   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
574   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
575   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
576   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
577   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
578   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
579   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
580   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
581 
582   // We want to custom lower some of our intrinsics.
583   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
584 
585   // To handle counter-based loop conditions.
586   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
587 
588   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
589   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
590   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
591   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
592 
593   // Comparisons that require checking two conditions.
594   if (Subtarget.hasSPE()) {
595     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
596     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
597     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
598     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
599   }
600   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
601   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
602   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
603   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
604   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
605   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
606   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
607   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
608   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
609   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
610   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
611   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
612 
613   if (Subtarget.has64BitSupport()) {
614     // They also have instructions for converting between i64 and fp.
615     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
616     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
617     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
618     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
619     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
620     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
621     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
622     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
623     // This is just the low 32 bits of a (signed) fp->i64 conversion.
624     // We cannot do this with Promote because i64 is not a legal type.
625     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
626     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
627 
628     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
629       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
630       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
631     }
632   } else {
633     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
634     if (Subtarget.hasSPE()) {
635       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
636       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
637     } else {
638       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
639       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
640     }
641   }
642 
643   // With the instructions enabled under FPCVT, we can do everything.
644   if (Subtarget.hasFPCVT()) {
645     if (Subtarget.has64BitSupport()) {
646       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
647       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
648       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
649       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
650       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
651       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
652       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
653       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
654     }
655 
656     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
657     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
658     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
659     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
660     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
661     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
662     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
663     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
664   }
665 
666   if (Subtarget.use64BitRegs()) {
667     // 64-bit PowerPC implementations can support i64 types directly
668     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
669     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
670     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
671     // 64-bit PowerPC wants to expand i128 shifts itself.
672     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
673     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
674     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
675   } else {
676     // 32-bit PowerPC wants to expand i64 shifts itself.
677     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
678     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
679     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
680   }
681 
682   // PowerPC has better expansions for funnel shifts than the generic
683   // TargetLowering::expandFunnelShift.
684   if (Subtarget.has64BitSupport()) {
685     setOperationAction(ISD::FSHL, MVT::i64, Custom);
686     setOperationAction(ISD::FSHR, MVT::i64, Custom);
687   }
688   setOperationAction(ISD::FSHL, MVT::i32, Custom);
689   setOperationAction(ISD::FSHR, MVT::i32, Custom);
690 
691   if (Subtarget.hasVSX()) {
692     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
693     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
694     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
695     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
696   }
697 
698   if (Subtarget.hasAltivec()) {
699     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
700       setOperationAction(ISD::SADDSAT, VT, Legal);
701       setOperationAction(ISD::SSUBSAT, VT, Legal);
702       setOperationAction(ISD::UADDSAT, VT, Legal);
703       setOperationAction(ISD::USUBSAT, VT, Legal);
704     }
705     // First set operation action for all vector types to expand. Then we
706     // will selectively turn on ones that can be effectively codegen'd.
707     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
708       // add/sub are legal for all supported vector VT's.
709       setOperationAction(ISD::ADD, VT, Legal);
710       setOperationAction(ISD::SUB, VT, Legal);
711 
712       // For v2i64, these are only valid with P8Vector. This is corrected after
713       // the loop.
714       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
715         setOperationAction(ISD::SMAX, VT, Legal);
716         setOperationAction(ISD::SMIN, VT, Legal);
717         setOperationAction(ISD::UMAX, VT, Legal);
718         setOperationAction(ISD::UMIN, VT, Legal);
719       }
720       else {
721         setOperationAction(ISD::SMAX, VT, Expand);
722         setOperationAction(ISD::SMIN, VT, Expand);
723         setOperationAction(ISD::UMAX, VT, Expand);
724         setOperationAction(ISD::UMIN, VT, Expand);
725       }
726 
727       if (Subtarget.hasVSX()) {
728         setOperationAction(ISD::FMAXNUM, VT, Legal);
729         setOperationAction(ISD::FMINNUM, VT, Legal);
730       }
731 
732       // Vector instructions introduced in P8
733       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
734         setOperationAction(ISD::CTPOP, VT, Legal);
735         setOperationAction(ISD::CTLZ, VT, Legal);
736       }
737       else {
738         setOperationAction(ISD::CTPOP, VT, Expand);
739         setOperationAction(ISD::CTLZ, VT, Expand);
740       }
741 
742       // Vector instructions introduced in P9
743       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
744         setOperationAction(ISD::CTTZ, VT, Legal);
745       else
746         setOperationAction(ISD::CTTZ, VT, Expand);
747 
748       // We promote all shuffles to v16i8.
749       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
750       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
751 
752       // We promote all non-typed operations to v4i32.
753       setOperationAction(ISD::AND   , VT, Promote);
754       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
755       setOperationAction(ISD::OR    , VT, Promote);
756       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
757       setOperationAction(ISD::XOR   , VT, Promote);
758       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
759       setOperationAction(ISD::LOAD  , VT, Promote);
760       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
761       setOperationAction(ISD::SELECT, VT, Promote);
762       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
763       setOperationAction(ISD::VSELECT, VT, Legal);
764       setOperationAction(ISD::SELECT_CC, VT, Promote);
765       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
766       setOperationAction(ISD::STORE, VT, Promote);
767       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
768 
769       // No other operations are legal.
770       setOperationAction(ISD::MUL , VT, Expand);
771       setOperationAction(ISD::SDIV, VT, Expand);
772       setOperationAction(ISD::SREM, VT, Expand);
773       setOperationAction(ISD::UDIV, VT, Expand);
774       setOperationAction(ISD::UREM, VT, Expand);
775       setOperationAction(ISD::FDIV, VT, Expand);
776       setOperationAction(ISD::FREM, VT, Expand);
777       setOperationAction(ISD::FNEG, VT, Expand);
778       setOperationAction(ISD::FSQRT, VT, Expand);
779       setOperationAction(ISD::FLOG, VT, Expand);
780       setOperationAction(ISD::FLOG10, VT, Expand);
781       setOperationAction(ISD::FLOG2, VT, Expand);
782       setOperationAction(ISD::FEXP, VT, Expand);
783       setOperationAction(ISD::FEXP2, VT, Expand);
784       setOperationAction(ISD::FSIN, VT, Expand);
785       setOperationAction(ISD::FCOS, VT, Expand);
786       setOperationAction(ISD::FABS, VT, Expand);
787       setOperationAction(ISD::FFLOOR, VT, Expand);
788       setOperationAction(ISD::FCEIL,  VT, Expand);
789       setOperationAction(ISD::FTRUNC, VT, Expand);
790       setOperationAction(ISD::FRINT,  VT, Expand);
791       setOperationAction(ISD::FNEARBYINT, VT, Expand);
792       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
793       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
794       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
795       setOperationAction(ISD::MULHU, VT, Expand);
796       setOperationAction(ISD::MULHS, VT, Expand);
797       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
798       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
799       setOperationAction(ISD::UDIVREM, VT, Expand);
800       setOperationAction(ISD::SDIVREM, VT, Expand);
801       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
802       setOperationAction(ISD::FPOW, VT, Expand);
803       setOperationAction(ISD::BSWAP, VT, Expand);
804       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
805       setOperationAction(ISD::ROTL, VT, Expand);
806       setOperationAction(ISD::ROTR, VT, Expand);
807 
808       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
809         setTruncStoreAction(VT, InnerVT, Expand);
810         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
811         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
812         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
813       }
814     }
815     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
816     if (!Subtarget.hasP8Vector()) {
817       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
818       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
819       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
820       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
821     }
822 
823     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
824     // with merges, splats, etc.
825     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
826 
827     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
828     // are cheap, so handle them before they get expanded to scalar.
829     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
830     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
831     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
832     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
833     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
834 
835     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
836     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
837     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
838     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
839     setOperationAction(ISD::SELECT, MVT::v4i32,
840                        Subtarget.useCRBits() ? Legal : Expand);
841     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
842     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
843     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
844     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
845     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
846     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
847     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
848     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
849     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
850     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
851     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
852     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
853     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
854 
855     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
856     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
857     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
858     if (Subtarget.hasAltivec())
859       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
860         setOperationAction(ISD::ROTL, VT, Legal);
861     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
862     if (Subtarget.hasP8Altivec())
863       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
864 
865     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
866     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
867     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
868     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
869 
870     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
871     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
872 
873     if (Subtarget.hasVSX()) {
874       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
875       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
876     }
877 
878     if (Subtarget.hasP8Altivec())
879       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
880     else
881       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
882 
883     if (Subtarget.isISA3_1()) {
884       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
885       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
886       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
887       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
888       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
889       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
890       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
891       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
892       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
893       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
894       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
895       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
896       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
897       setOperationAction(ISD::UREM, MVT::v1i128, Legal);
898       setOperationAction(ISD::SREM, MVT::v1i128, Legal);
899       setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
900       setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
901       setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
902     }
903 
904     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
905     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
906 
907     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
908     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
909 
910     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
911     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
912     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
913     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
914 
915     // Altivec does not contain unordered floating-point compare instructions
916     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
917     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
918     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
919     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
920 
921     if (Subtarget.hasVSX()) {
922       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
923       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
924       if (Subtarget.hasP8Vector()) {
925         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
926         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
927       }
928       if (Subtarget.hasDirectMove() && isPPC64) {
929         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
930         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
931         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
932         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
933         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
934         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
935         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
936         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
937       }
938       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
939 
940       // The nearbyint variants are not allowed to raise the inexact exception
941       // so we can only code-gen them with unsafe math.
942       if (TM.Options.UnsafeFPMath) {
943         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
944         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
945       }
946 
947       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
948       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
949       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
950       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
951       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
952       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
953       setOperationAction(ISD::FROUND, MVT::f64, Legal);
954       setOperationAction(ISD::FRINT, MVT::f64, Legal);
955 
956       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
957       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
958       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
959       setOperationAction(ISD::FROUND, MVT::f32, Legal);
960       setOperationAction(ISD::FRINT, MVT::f32, Legal);
961 
962       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
963       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
964 
965       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
966       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
967 
968       // Share the Altivec comparison restrictions.
969       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
970       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
971       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
972       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
973 
974       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
975       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
976 
977       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
978 
979       if (Subtarget.hasP8Vector())
980         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
981 
982       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
983 
984       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
985       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
986       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
987 
988       if (Subtarget.hasP8Altivec()) {
989         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
990         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
991         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
992 
993         // 128 bit shifts can be accomplished via 3 instructions for SHL and
994         // SRL, but not for SRA because of the instructions available:
995         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
996         // doing
997         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
998         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
999         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1000 
1001         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
1002       }
1003       else {
1004         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
1005         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1006         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1007 
1008         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1009 
1010         // VSX v2i64 only supports non-arithmetic operations.
1011         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1012         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1013       }
1014 
1015       if (Subtarget.isISA3_1())
1016         setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1017       else
1018         setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1019 
1020       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1021       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1022       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1023       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1024 
1025       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
1026 
1027       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1028       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1029       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1030       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1031       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1032       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1033       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1034       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1035 
1036       // Custom handling for partial vectors of integers converted to
1037       // floating point. We already have optimal handling for v2i32 through
1038       // the DAG combine, so those aren't necessary.
1039       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1040       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1041       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1042       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1043       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1044       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1045       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1046       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1047       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1048       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1049       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1050       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1051       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1052       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1053       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1054       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1055 
1056       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1057       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1058       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1059       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1060       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1061       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1062 
1063       if (Subtarget.hasDirectMove())
1064         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1065       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1066 
1067       // Handle constrained floating-point operations of vector.
1068       // The predictor is `hasVSX` because altivec instruction has
1069       // no exception but VSX vector instruction has.
1070       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1071       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1072       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1073       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1074       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1075       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1076       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1077       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1078       setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
1079       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1080       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1081       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1082       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1083 
1084       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1085       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1086       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1087       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1088       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1089       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1090       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1091       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1092       setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
1093       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1094       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1095       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1096       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1097 
1098       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1099     }
1100 
1101     if (Subtarget.hasP8Altivec()) {
1102       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1103       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1104     }
1105 
1106     if (Subtarget.hasP9Vector()) {
1107       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1108       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1109 
1110       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1111       // SRL, but not for SRA because of the instructions available:
1112       // VS{RL} and VS{RL}O.
1113       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1114       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1115       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1116 
1117       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1118       setOperationAction(ISD::FADD, MVT::f128, Legal);
1119       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1120       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1121       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1122       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1123       // No extending loads to f128 on PPC.
1124       for (MVT FPT : MVT::fp_valuetypes())
1125         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1126       setOperationAction(ISD::FMA, MVT::f128, Legal);
1127       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1128       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1129       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1130       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1131       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1132       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1133 
1134       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1135       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1136       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1137       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1138       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1139       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1140 
1141       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1142       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1143       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1144       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1145       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1146       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1147       // No implementation for these ops for PowerPC.
1148       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1149       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1150       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1151       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1152       setOperationAction(ISD::FREM, MVT::f128, Expand);
1153 
1154       // Handle constrained floating-point operations of fp128
1155       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1156       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1157       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1158       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1159       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1160       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1161       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1162       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1163       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1164       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1165       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1166       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1167       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1168       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1169       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1170       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1171       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1172       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1173       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1174       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1175     } else if (Subtarget.hasAltivec() && EnableSoftFP128) {
1176       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1177 
1178       for (MVT FPT : MVT::fp_valuetypes())
1179         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1180 
1181       setOperationAction(ISD::LOAD, MVT::f128, Promote);
1182       setOperationAction(ISD::STORE, MVT::f128, Promote);
1183 
1184       AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
1185       AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
1186 
1187       setOperationAction(ISD::FADD, MVT::f128, Expand);
1188       setOperationAction(ISD::FSUB, MVT::f128, Expand);
1189       setOperationAction(ISD::FMUL, MVT::f128, Expand);
1190       setOperationAction(ISD::FDIV, MVT::f128, Expand);
1191       setOperationAction(ISD::FNEG, MVT::f128, Expand);
1192       setOperationAction(ISD::FABS, MVT::f128, Expand);
1193       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1194       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1195       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1196       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1197       setOperationAction(ISD::FREM, MVT::f128, Expand);
1198       setOperationAction(ISD::FSQRT, MVT::f128, Expand);
1199       setOperationAction(ISD::FMA, MVT::f128, Expand);
1200       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
1201     }
1202 
1203     if (Subtarget.hasP9Altivec()) {
1204       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1205       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1206 
1207       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1208       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1209       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1210       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1211       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1212       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1213       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1214     }
1215   }
1216 
1217   if (Subtarget.pairedVectorMemops()) {
1218     addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1219     setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1220     setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1221   }
1222   if (Subtarget.hasMMA()) {
1223     addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1224     setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1225     setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1226     setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom);
1227   }
1228 
1229   if (Subtarget.has64BitSupport())
1230     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1231 
1232   if (Subtarget.isISA3_1())
1233     setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1234 
1235   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1236 
1237   if (!isPPC64) {
1238     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1239     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1240   }
1241 
1242   setBooleanContents(ZeroOrOneBooleanContent);
1243 
1244   if (Subtarget.hasAltivec()) {
1245     // Altivec instructions set fields to all zeros or all ones.
1246     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1247   }
1248 
1249   if (!isPPC64) {
1250     // These libcalls are not available in 32-bit.
1251     setLibcallName(RTLIB::SHL_I128, nullptr);
1252     setLibcallName(RTLIB::SRL_I128, nullptr);
1253     setLibcallName(RTLIB::SRA_I128, nullptr);
1254   }
1255 
1256   if (!isPPC64)
1257     setMaxAtomicSizeInBitsSupported(32);
1258 
1259   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1260 
1261   // We have target-specific dag combine patterns for the following nodes:
1262   setTargetDAGCombine(ISD::ADD);
1263   setTargetDAGCombine(ISD::SHL);
1264   setTargetDAGCombine(ISD::SRA);
1265   setTargetDAGCombine(ISD::SRL);
1266   setTargetDAGCombine(ISD::MUL);
1267   setTargetDAGCombine(ISD::FMA);
1268   setTargetDAGCombine(ISD::SINT_TO_FP);
1269   setTargetDAGCombine(ISD::BUILD_VECTOR);
1270   if (Subtarget.hasFPCVT())
1271     setTargetDAGCombine(ISD::UINT_TO_FP);
1272   setTargetDAGCombine(ISD::LOAD);
1273   setTargetDAGCombine(ISD::STORE);
1274   setTargetDAGCombine(ISD::BR_CC);
1275   if (Subtarget.useCRBits())
1276     setTargetDAGCombine(ISD::BRCOND);
1277   setTargetDAGCombine(ISD::BSWAP);
1278   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1279   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1280   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1281 
1282   setTargetDAGCombine(ISD::SIGN_EXTEND);
1283   setTargetDAGCombine(ISD::ZERO_EXTEND);
1284   setTargetDAGCombine(ISD::ANY_EXTEND);
1285 
1286   setTargetDAGCombine(ISD::TRUNCATE);
1287   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1288 
1289 
1290   if (Subtarget.useCRBits()) {
1291     setTargetDAGCombine(ISD::TRUNCATE);
1292     setTargetDAGCombine(ISD::SETCC);
1293     setTargetDAGCombine(ISD::SELECT_CC);
1294   }
1295 
1296   if (Subtarget.hasP9Altivec()) {
1297     setTargetDAGCombine(ISD::ABS);
1298     setTargetDAGCombine(ISD::VSELECT);
1299   }
1300 
1301   setLibcallName(RTLIB::LOG_F128, "logf128");
1302   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1303   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1304   setLibcallName(RTLIB::EXP_F128, "expf128");
1305   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1306   setLibcallName(RTLIB::SIN_F128, "sinf128");
1307   setLibcallName(RTLIB::COS_F128, "cosf128");
1308   setLibcallName(RTLIB::POW_F128, "powf128");
1309   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1310   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1311   setLibcallName(RTLIB::REM_F128, "fmodf128");
1312   setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1313   setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1314   setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1315   setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1316   setLibcallName(RTLIB::ROUND_F128, "roundf128");
1317   setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1318   setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1319   setLibcallName(RTLIB::RINT_F128, "rintf128");
1320   setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1321   setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1322   setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1323   setLibcallName(RTLIB::FMA_F128, "fmaf128");
1324 
1325   // With 32 condition bits, we don't need to sink (and duplicate) compares
1326   // aggressively in CodeGenPrep.
1327   if (Subtarget.useCRBits()) {
1328     setHasMultipleConditionRegisters();
1329     setJumpIsExpensive();
1330   }
1331 
1332   setMinFunctionAlignment(Align(4));
1333 
1334   switch (Subtarget.getCPUDirective()) {
1335   default: break;
1336   case PPC::DIR_970:
1337   case PPC::DIR_A2:
1338   case PPC::DIR_E500:
1339   case PPC::DIR_E500mc:
1340   case PPC::DIR_E5500:
1341   case PPC::DIR_PWR4:
1342   case PPC::DIR_PWR5:
1343   case PPC::DIR_PWR5X:
1344   case PPC::DIR_PWR6:
1345   case PPC::DIR_PWR6X:
1346   case PPC::DIR_PWR7:
1347   case PPC::DIR_PWR8:
1348   case PPC::DIR_PWR9:
1349   case PPC::DIR_PWR10:
1350   case PPC::DIR_PWR_FUTURE:
1351     setPrefLoopAlignment(Align(16));
1352     setPrefFunctionAlignment(Align(16));
1353     break;
1354   }
1355 
1356   if (Subtarget.enableMachineScheduler())
1357     setSchedulingPreference(Sched::Source);
1358   else
1359     setSchedulingPreference(Sched::Hybrid);
1360 
1361   computeRegisterProperties(STI.getRegisterInfo());
1362 
1363   // The Freescale cores do better with aggressive inlining of memcpy and
1364   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1365   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1366       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1367     MaxStoresPerMemset = 32;
1368     MaxStoresPerMemsetOptSize = 16;
1369     MaxStoresPerMemcpy = 32;
1370     MaxStoresPerMemcpyOptSize = 8;
1371     MaxStoresPerMemmove = 32;
1372     MaxStoresPerMemmoveOptSize = 8;
1373   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1374     // The A2 also benefits from (very) aggressive inlining of memcpy and
1375     // friends. The overhead of a the function call, even when warm, can be
1376     // over one hundred cycles.
1377     MaxStoresPerMemset = 128;
1378     MaxStoresPerMemcpy = 128;
1379     MaxStoresPerMemmove = 128;
1380     MaxLoadsPerMemcmp = 128;
1381   } else {
1382     MaxLoadsPerMemcmp = 8;
1383     MaxLoadsPerMemcmpOptSize = 4;
1384   }
1385 
1386   IsStrictFPEnabled = true;
1387 
1388   // Let the subtarget (CPU) decide if a predictable select is more expensive
1389   // than the corresponding branch. This information is used in CGP to decide
1390   // when to convert selects into branches.
1391   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1392 }
1393 
1394 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1395 /// the desired ByVal argument alignment.
1396 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1397   if (MaxAlign == MaxMaxAlign)
1398     return;
1399   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1400     if (MaxMaxAlign >= 32 &&
1401         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1402       MaxAlign = Align(32);
1403     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1404              MaxAlign < 16)
1405       MaxAlign = Align(16);
1406   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1407     Align EltAlign;
1408     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1409     if (EltAlign > MaxAlign)
1410       MaxAlign = EltAlign;
1411   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1412     for (auto *EltTy : STy->elements()) {
1413       Align EltAlign;
1414       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1415       if (EltAlign > MaxAlign)
1416         MaxAlign = EltAlign;
1417       if (MaxAlign == MaxMaxAlign)
1418         break;
1419     }
1420   }
1421 }
1422 
1423 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1424 /// function arguments in the caller parameter area.
1425 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1426                                                   const DataLayout &DL) const {
1427   // 16byte and wider vectors are passed on 16byte boundary.
1428   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1429   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1430   if (Subtarget.hasAltivec())
1431     getMaxByValAlign(Ty, Alignment, Align(16));
1432   return Alignment.value();
1433 }
1434 
1435 bool PPCTargetLowering::useSoftFloat() const {
1436   return Subtarget.useSoftFloat();
1437 }
1438 
1439 bool PPCTargetLowering::hasSPE() const {
1440   return Subtarget.hasSPE();
1441 }
1442 
1443 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1444   return VT.isScalarInteger();
1445 }
1446 
1447 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1448   switch ((PPCISD::NodeType)Opcode) {
1449   case PPCISD::FIRST_NUMBER:    break;
1450   case PPCISD::FSEL:            return "PPCISD::FSEL";
1451   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1452   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1453   case PPCISD::FCFID:           return "PPCISD::FCFID";
1454   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1455   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1456   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1457   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1458   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1459   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1460   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1461   case PPCISD::FP_TO_UINT_IN_VSR:
1462                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1463   case PPCISD::FP_TO_SINT_IN_VSR:
1464                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1465   case PPCISD::FRE:             return "PPCISD::FRE";
1466   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1467   case PPCISD::FTSQRT:
1468     return "PPCISD::FTSQRT";
1469   case PPCISD::FSQRT:
1470     return "PPCISD::FSQRT";
1471   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1472   case PPCISD::VPERM:           return "PPCISD::VPERM";
1473   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1474   case PPCISD::XXSPLTI_SP_TO_DP:
1475     return "PPCISD::XXSPLTI_SP_TO_DP";
1476   case PPCISD::XXSPLTI32DX:
1477     return "PPCISD::XXSPLTI32DX";
1478   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1479   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1480   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1481   case PPCISD::CMPB:            return "PPCISD::CMPB";
1482   case PPCISD::Hi:              return "PPCISD::Hi";
1483   case PPCISD::Lo:              return "PPCISD::Lo";
1484   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1485   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1486   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1487   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1488   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1489   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1490   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1491   case PPCISD::SRL:             return "PPCISD::SRL";
1492   case PPCISD::SRA:             return "PPCISD::SRA";
1493   case PPCISD::SHL:             return "PPCISD::SHL";
1494   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1495   case PPCISD::CALL:            return "PPCISD::CALL";
1496   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1497   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1498   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1499   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1500   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1501   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1502   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1503   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1504   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1505   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1506   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1507   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1508   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1509   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1510   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1511   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1512     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1513   case PPCISD::ANDI_rec_1_EQ_BIT:
1514     return "PPCISD::ANDI_rec_1_EQ_BIT";
1515   case PPCISD::ANDI_rec_1_GT_BIT:
1516     return "PPCISD::ANDI_rec_1_GT_BIT";
1517   case PPCISD::VCMP:            return "PPCISD::VCMP";
1518   case PPCISD::VCMP_rec:        return "PPCISD::VCMP_rec";
1519   case PPCISD::LBRX:            return "PPCISD::LBRX";
1520   case PPCISD::STBRX:           return "PPCISD::STBRX";
1521   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1522   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1523   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1524   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1525   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1526   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1527   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1528   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1529   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1530   case PPCISD::ST_VSR_SCAL_INT:
1531                                 return "PPCISD::ST_VSR_SCAL_INT";
1532   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1533   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1534   case PPCISD::BDZ:             return "PPCISD::BDZ";
1535   case PPCISD::MFFS:            return "PPCISD::MFFS";
1536   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1537   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1538   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1539   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1540   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1541   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1542   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1543   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1544   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1545   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1546   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1547   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1548   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1549   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1550   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1551   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1552   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1553   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1554   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1555   case PPCISD::PADDI_DTPREL:
1556     return "PPCISD::PADDI_DTPREL";
1557   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1558   case PPCISD::SC:              return "PPCISD::SC";
1559   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1560   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1561   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1562   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1563   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1564   case PPCISD::VABSD:           return "PPCISD::VABSD";
1565   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1566   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1567   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1568   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1569   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1570   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1571   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1572   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1573     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1574   case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1575     return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1576   case PPCISD::ACC_BUILD:       return "PPCISD::ACC_BUILD";
1577   case PPCISD::PAIR_BUILD:      return "PPCISD::PAIR_BUILD";
1578   case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1579   case PPCISD::XXMFACC:         return "PPCISD::XXMFACC";
1580   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1581   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1582   case PPCISD::STRICT_FADDRTZ:
1583     return "PPCISD::STRICT_FADDRTZ";
1584   case PPCISD::STRICT_FCTIDZ:
1585     return "PPCISD::STRICT_FCTIDZ";
1586   case PPCISD::STRICT_FCTIWZ:
1587     return "PPCISD::STRICT_FCTIWZ";
1588   case PPCISD::STRICT_FCTIDUZ:
1589     return "PPCISD::STRICT_FCTIDUZ";
1590   case PPCISD::STRICT_FCTIWUZ:
1591     return "PPCISD::STRICT_FCTIWUZ";
1592   case PPCISD::STRICT_FCFID:
1593     return "PPCISD::STRICT_FCFID";
1594   case PPCISD::STRICT_FCFIDU:
1595     return "PPCISD::STRICT_FCFIDU";
1596   case PPCISD::STRICT_FCFIDS:
1597     return "PPCISD::STRICT_FCFIDS";
1598   case PPCISD::STRICT_FCFIDUS:
1599     return "PPCISD::STRICT_FCFIDUS";
1600   case PPCISD::LXVRZX:          return "PPCISD::LXVRZX";
1601   }
1602   return nullptr;
1603 }
1604 
1605 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1606                                           EVT VT) const {
1607   if (!VT.isVector())
1608     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1609 
1610   return VT.changeVectorElementTypeToInteger();
1611 }
1612 
1613 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1614   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1615   return true;
1616 }
1617 
1618 //===----------------------------------------------------------------------===//
1619 // Node matching predicates, for use by the tblgen matching code.
1620 //===----------------------------------------------------------------------===//
1621 
1622 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1623 static bool isFloatingPointZero(SDValue Op) {
1624   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1625     return CFP->getValueAPF().isZero();
1626   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1627     // Maybe this has already been legalized into the constant pool?
1628     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1629       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1630         return CFP->getValueAPF().isZero();
1631   }
1632   return false;
1633 }
1634 
1635 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1636 /// true if Op is undef or if it matches the specified value.
1637 static bool isConstantOrUndef(int Op, int Val) {
1638   return Op < 0 || Op == Val;
1639 }
1640 
1641 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1642 /// VPKUHUM instruction.
1643 /// The ShuffleKind distinguishes between big-endian operations with
1644 /// two different inputs (0), either-endian operations with two identical
1645 /// inputs (1), and little-endian operations with two different inputs (2).
1646 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1647 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1648                                SelectionDAG &DAG) {
1649   bool IsLE = DAG.getDataLayout().isLittleEndian();
1650   if (ShuffleKind == 0) {
1651     if (IsLE)
1652       return false;
1653     for (unsigned i = 0; i != 16; ++i)
1654       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1655         return false;
1656   } else if (ShuffleKind == 2) {
1657     if (!IsLE)
1658       return false;
1659     for (unsigned i = 0; i != 16; ++i)
1660       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1661         return false;
1662   } else if (ShuffleKind == 1) {
1663     unsigned j = IsLE ? 0 : 1;
1664     for (unsigned i = 0; i != 8; ++i)
1665       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1666           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1667         return false;
1668   }
1669   return true;
1670 }
1671 
1672 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1673 /// VPKUWUM instruction.
1674 /// The ShuffleKind distinguishes between big-endian operations with
1675 /// two different inputs (0), either-endian operations with two identical
1676 /// inputs (1), and little-endian operations with two different inputs (2).
1677 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1678 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1679                                SelectionDAG &DAG) {
1680   bool IsLE = DAG.getDataLayout().isLittleEndian();
1681   if (ShuffleKind == 0) {
1682     if (IsLE)
1683       return false;
1684     for (unsigned i = 0; i != 16; i += 2)
1685       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1686           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1687         return false;
1688   } else if (ShuffleKind == 2) {
1689     if (!IsLE)
1690       return false;
1691     for (unsigned i = 0; i != 16; i += 2)
1692       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1693           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1694         return false;
1695   } else if (ShuffleKind == 1) {
1696     unsigned j = IsLE ? 0 : 2;
1697     for (unsigned i = 0; i != 8; i += 2)
1698       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1699           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1700           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1701           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1702         return false;
1703   }
1704   return true;
1705 }
1706 
1707 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1708 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1709 /// current subtarget.
1710 ///
1711 /// The ShuffleKind distinguishes between big-endian operations with
1712 /// two different inputs (0), either-endian operations with two identical
1713 /// inputs (1), and little-endian operations with two different inputs (2).
1714 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1715 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1716                                SelectionDAG &DAG) {
1717   const PPCSubtarget& Subtarget =
1718       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1719   if (!Subtarget.hasP8Vector())
1720     return false;
1721 
1722   bool IsLE = DAG.getDataLayout().isLittleEndian();
1723   if (ShuffleKind == 0) {
1724     if (IsLE)
1725       return false;
1726     for (unsigned i = 0; i != 16; i += 4)
1727       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1728           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1729           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1730           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1731         return false;
1732   } else if (ShuffleKind == 2) {
1733     if (!IsLE)
1734       return false;
1735     for (unsigned i = 0; i != 16; i += 4)
1736       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1737           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1738           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1739           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1740         return false;
1741   } else if (ShuffleKind == 1) {
1742     unsigned j = IsLE ? 0 : 4;
1743     for (unsigned i = 0; i != 8; i += 4)
1744       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1745           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1746           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1747           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1748           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1749           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1750           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1751           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1752         return false;
1753   }
1754   return true;
1755 }
1756 
1757 /// isVMerge - Common function, used to match vmrg* shuffles.
1758 ///
1759 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1760                      unsigned LHSStart, unsigned RHSStart) {
1761   if (N->getValueType(0) != MVT::v16i8)
1762     return false;
1763   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1764          "Unsupported merge size!");
1765 
1766   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1767     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1768       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1769                              LHSStart+j+i*UnitSize) ||
1770           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1771                              RHSStart+j+i*UnitSize))
1772         return false;
1773     }
1774   return true;
1775 }
1776 
1777 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1778 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1779 /// The ShuffleKind distinguishes between big-endian merges with two
1780 /// different inputs (0), either-endian merges with two identical inputs (1),
1781 /// and little-endian merges with two different inputs (2).  For the latter,
1782 /// the input operands are swapped (see PPCInstrAltivec.td).
1783 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1784                              unsigned ShuffleKind, SelectionDAG &DAG) {
1785   if (DAG.getDataLayout().isLittleEndian()) {
1786     if (ShuffleKind == 1) // unary
1787       return isVMerge(N, UnitSize, 0, 0);
1788     else if (ShuffleKind == 2) // swapped
1789       return isVMerge(N, UnitSize, 0, 16);
1790     else
1791       return false;
1792   } else {
1793     if (ShuffleKind == 1) // unary
1794       return isVMerge(N, UnitSize, 8, 8);
1795     else if (ShuffleKind == 0) // normal
1796       return isVMerge(N, UnitSize, 8, 24);
1797     else
1798       return false;
1799   }
1800 }
1801 
1802 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1803 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1804 /// The ShuffleKind distinguishes between big-endian merges with two
1805 /// different inputs (0), either-endian merges with two identical inputs (1),
1806 /// and little-endian merges with two different inputs (2).  For the latter,
1807 /// the input operands are swapped (see PPCInstrAltivec.td).
1808 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1809                              unsigned ShuffleKind, SelectionDAG &DAG) {
1810   if (DAG.getDataLayout().isLittleEndian()) {
1811     if (ShuffleKind == 1) // unary
1812       return isVMerge(N, UnitSize, 8, 8);
1813     else if (ShuffleKind == 2) // swapped
1814       return isVMerge(N, UnitSize, 8, 24);
1815     else
1816       return false;
1817   } else {
1818     if (ShuffleKind == 1) // unary
1819       return isVMerge(N, UnitSize, 0, 0);
1820     else if (ShuffleKind == 0) // normal
1821       return isVMerge(N, UnitSize, 0, 16);
1822     else
1823       return false;
1824   }
1825 }
1826 
1827 /**
1828  * Common function used to match vmrgew and vmrgow shuffles
1829  *
1830  * The indexOffset determines whether to look for even or odd words in
1831  * the shuffle mask. This is based on the of the endianness of the target
1832  * machine.
1833  *   - Little Endian:
1834  *     - Use offset of 0 to check for odd elements
1835  *     - Use offset of 4 to check for even elements
1836  *   - Big Endian:
1837  *     - Use offset of 0 to check for even elements
1838  *     - Use offset of 4 to check for odd elements
1839  * A detailed description of the vector element ordering for little endian and
1840  * big endian can be found at
1841  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1842  * Targeting your applications - what little endian and big endian IBM XL C/C++
1843  * compiler differences mean to you
1844  *
1845  * The mask to the shuffle vector instruction specifies the indices of the
1846  * elements from the two input vectors to place in the result. The elements are
1847  * numbered in array-access order, starting with the first vector. These vectors
1848  * are always of type v16i8, thus each vector will contain 16 elements of size
1849  * 8. More info on the shuffle vector can be found in the
1850  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1851  * Language Reference.
1852  *
1853  * The RHSStartValue indicates whether the same input vectors are used (unary)
1854  * or two different input vectors are used, based on the following:
1855  *   - If the instruction uses the same vector for both inputs, the range of the
1856  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1857  *     be 0.
1858  *   - If the instruction has two different vectors then the range of the
1859  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1860  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1861  *     to 31 specify elements in the second vector).
1862  *
1863  * \param[in] N The shuffle vector SD Node to analyze
1864  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1865  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1866  * vector to the shuffle_vector instruction
1867  * \return true iff this shuffle vector represents an even or odd word merge
1868  */
1869 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1870                      unsigned RHSStartValue) {
1871   if (N->getValueType(0) != MVT::v16i8)
1872     return false;
1873 
1874   for (unsigned i = 0; i < 2; ++i)
1875     for (unsigned j = 0; j < 4; ++j)
1876       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1877                              i*RHSStartValue+j+IndexOffset) ||
1878           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1879                              i*RHSStartValue+j+IndexOffset+8))
1880         return false;
1881   return true;
1882 }
1883 
1884 /**
1885  * Determine if the specified shuffle mask is suitable for the vmrgew or
1886  * vmrgow instructions.
1887  *
1888  * \param[in] N The shuffle vector SD Node to analyze
1889  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1890  * \param[in] ShuffleKind Identify the type of merge:
1891  *   - 0 = big-endian merge with two different inputs;
1892  *   - 1 = either-endian merge with two identical inputs;
1893  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1894  *     little-endian merges).
1895  * \param[in] DAG The current SelectionDAG
1896  * \return true iff this shuffle mask
1897  */
1898 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1899                               unsigned ShuffleKind, SelectionDAG &DAG) {
1900   if (DAG.getDataLayout().isLittleEndian()) {
1901     unsigned indexOffset = CheckEven ? 4 : 0;
1902     if (ShuffleKind == 1) // Unary
1903       return isVMerge(N, indexOffset, 0);
1904     else if (ShuffleKind == 2) // swapped
1905       return isVMerge(N, indexOffset, 16);
1906     else
1907       return false;
1908   }
1909   else {
1910     unsigned indexOffset = CheckEven ? 0 : 4;
1911     if (ShuffleKind == 1) // Unary
1912       return isVMerge(N, indexOffset, 0);
1913     else if (ShuffleKind == 0) // Normal
1914       return isVMerge(N, indexOffset, 16);
1915     else
1916       return false;
1917   }
1918   return false;
1919 }
1920 
1921 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1922 /// amount, otherwise return -1.
1923 /// The ShuffleKind distinguishes between big-endian operations with two
1924 /// different inputs (0), either-endian operations with two identical inputs
1925 /// (1), and little-endian operations with two different inputs (2).  For the
1926 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1927 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1928                              SelectionDAG &DAG) {
1929   if (N->getValueType(0) != MVT::v16i8)
1930     return -1;
1931 
1932   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1933 
1934   // Find the first non-undef value in the shuffle mask.
1935   unsigned i;
1936   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1937     /*search*/;
1938 
1939   if (i == 16) return -1;  // all undef.
1940 
1941   // Otherwise, check to see if the rest of the elements are consecutively
1942   // numbered from this value.
1943   unsigned ShiftAmt = SVOp->getMaskElt(i);
1944   if (ShiftAmt < i) return -1;
1945 
1946   ShiftAmt -= i;
1947   bool isLE = DAG.getDataLayout().isLittleEndian();
1948 
1949   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1950     // Check the rest of the elements to see if they are consecutive.
1951     for (++i; i != 16; ++i)
1952       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1953         return -1;
1954   } else if (ShuffleKind == 1) {
1955     // Check the rest of the elements to see if they are consecutive.
1956     for (++i; i != 16; ++i)
1957       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1958         return -1;
1959   } else
1960     return -1;
1961 
1962   if (isLE)
1963     ShiftAmt = 16 - ShiftAmt;
1964 
1965   return ShiftAmt;
1966 }
1967 
1968 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1969 /// specifies a splat of a single element that is suitable for input to
1970 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1971 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1972   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1973          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1974 
1975   // The consecutive indices need to specify an element, not part of two
1976   // different elements.  So abandon ship early if this isn't the case.
1977   if (N->getMaskElt(0) % EltSize != 0)
1978     return false;
1979 
1980   // This is a splat operation if each element of the permute is the same, and
1981   // if the value doesn't reference the second vector.
1982   unsigned ElementBase = N->getMaskElt(0);
1983 
1984   // FIXME: Handle UNDEF elements too!
1985   if (ElementBase >= 16)
1986     return false;
1987 
1988   // Check that the indices are consecutive, in the case of a multi-byte element
1989   // splatted with a v16i8 mask.
1990   for (unsigned i = 1; i != EltSize; ++i)
1991     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1992       return false;
1993 
1994   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1995     if (N->getMaskElt(i) < 0) continue;
1996     for (unsigned j = 0; j != EltSize; ++j)
1997       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1998         return false;
1999   }
2000   return true;
2001 }
2002 
2003 /// Check that the mask is shuffling N byte elements. Within each N byte
2004 /// element of the mask, the indices could be either in increasing or
2005 /// decreasing order as long as they are consecutive.
2006 /// \param[in] N the shuffle vector SD Node to analyze
2007 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2008 /// Word/DoubleWord/QuadWord).
2009 /// \param[in] StepLen the delta indices number among the N byte element, if
2010 /// the mask is in increasing/decreasing order then it is 1/-1.
2011 /// \return true iff the mask is shuffling N byte elements.
2012 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2013                                    int StepLen) {
2014   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2015          "Unexpected element width.");
2016   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2017 
2018   unsigned NumOfElem = 16 / Width;
2019   unsigned MaskVal[16]; //  Width is never greater than 16
2020   for (unsigned i = 0; i < NumOfElem; ++i) {
2021     MaskVal[0] = N->getMaskElt(i * Width);
2022     if ((StepLen == 1) && (MaskVal[0] % Width)) {
2023       return false;
2024     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2025       return false;
2026     }
2027 
2028     for (unsigned int j = 1; j < Width; ++j) {
2029       MaskVal[j] = N->getMaskElt(i * Width + j);
2030       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2031         return false;
2032       }
2033     }
2034   }
2035 
2036   return true;
2037 }
2038 
2039 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2040                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2041   if (!isNByteElemShuffleMask(N, 4, 1))
2042     return false;
2043 
2044   // Now we look at mask elements 0,4,8,12
2045   unsigned M0 = N->getMaskElt(0) / 4;
2046   unsigned M1 = N->getMaskElt(4) / 4;
2047   unsigned M2 = N->getMaskElt(8) / 4;
2048   unsigned M3 = N->getMaskElt(12) / 4;
2049   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2050   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2051 
2052   // Below, let H and L be arbitrary elements of the shuffle mask
2053   // where H is in the range [4,7] and L is in the range [0,3].
2054   // H, 1, 2, 3 or L, 5, 6, 7
2055   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2056       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2057     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2058     InsertAtByte = IsLE ? 12 : 0;
2059     Swap = M0 < 4;
2060     return true;
2061   }
2062   // 0, H, 2, 3 or 4, L, 6, 7
2063   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2064       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2065     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2066     InsertAtByte = IsLE ? 8 : 4;
2067     Swap = M1 < 4;
2068     return true;
2069   }
2070   // 0, 1, H, 3 or 4, 5, L, 7
2071   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2072       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2073     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2074     InsertAtByte = IsLE ? 4 : 8;
2075     Swap = M2 < 4;
2076     return true;
2077   }
2078   // 0, 1, 2, H or 4, 5, 6, L
2079   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2080       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2081     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2082     InsertAtByte = IsLE ? 0 : 12;
2083     Swap = M3 < 4;
2084     return true;
2085   }
2086 
2087   // If both vector operands for the shuffle are the same vector, the mask will
2088   // contain only elements from the first one and the second one will be undef.
2089   if (N->getOperand(1).isUndef()) {
2090     ShiftElts = 0;
2091     Swap = true;
2092     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2093     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2094       InsertAtByte = IsLE ? 12 : 0;
2095       return true;
2096     }
2097     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2098       InsertAtByte = IsLE ? 8 : 4;
2099       return true;
2100     }
2101     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2102       InsertAtByte = IsLE ? 4 : 8;
2103       return true;
2104     }
2105     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2106       InsertAtByte = IsLE ? 0 : 12;
2107       return true;
2108     }
2109   }
2110 
2111   return false;
2112 }
2113 
2114 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2115                                bool &Swap, bool IsLE) {
2116   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2117   // Ensure each byte index of the word is consecutive.
2118   if (!isNByteElemShuffleMask(N, 4, 1))
2119     return false;
2120 
2121   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2122   unsigned M0 = N->getMaskElt(0) / 4;
2123   unsigned M1 = N->getMaskElt(4) / 4;
2124   unsigned M2 = N->getMaskElt(8) / 4;
2125   unsigned M3 = N->getMaskElt(12) / 4;
2126 
2127   // If both vector operands for the shuffle are the same vector, the mask will
2128   // contain only elements from the first one and the second one will be undef.
2129   if (N->getOperand(1).isUndef()) {
2130     assert(M0 < 4 && "Indexing into an undef vector?");
2131     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2132       return false;
2133 
2134     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2135     Swap = false;
2136     return true;
2137   }
2138 
2139   // Ensure each word index of the ShuffleVector Mask is consecutive.
2140   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2141     return false;
2142 
2143   if (IsLE) {
2144     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2145       // Input vectors don't need to be swapped if the leading element
2146       // of the result is one of the 3 left elements of the second vector
2147       // (or if there is no shift to be done at all).
2148       Swap = false;
2149       ShiftElts = (8 - M0) % 8;
2150     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2151       // Input vectors need to be swapped if the leading element
2152       // of the result is one of the 3 left elements of the first vector
2153       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2154       Swap = true;
2155       ShiftElts = (4 - M0) % 4;
2156     }
2157 
2158     return true;
2159   } else {                                          // BE
2160     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2161       // Input vectors don't need to be swapped if the leading element
2162       // of the result is one of the 4 elements of the first vector.
2163       Swap = false;
2164       ShiftElts = M0;
2165     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2166       // Input vectors need to be swapped if the leading element
2167       // of the result is one of the 4 elements of the right vector.
2168       Swap = true;
2169       ShiftElts = M0 - 4;
2170     }
2171 
2172     return true;
2173   }
2174 }
2175 
2176 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2177   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2178 
2179   if (!isNByteElemShuffleMask(N, Width, -1))
2180     return false;
2181 
2182   for (int i = 0; i < 16; i += Width)
2183     if (N->getMaskElt(i) != i + Width - 1)
2184       return false;
2185 
2186   return true;
2187 }
2188 
2189 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2190   return isXXBRShuffleMaskHelper(N, 2);
2191 }
2192 
2193 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2194   return isXXBRShuffleMaskHelper(N, 4);
2195 }
2196 
2197 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2198   return isXXBRShuffleMaskHelper(N, 8);
2199 }
2200 
2201 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2202   return isXXBRShuffleMaskHelper(N, 16);
2203 }
2204 
2205 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2206 /// if the inputs to the instruction should be swapped and set \p DM to the
2207 /// value for the immediate.
2208 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2209 /// AND element 0 of the result comes from the first input (LE) or second input
2210 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2211 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2212 /// mask.
2213 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2214                                bool &Swap, bool IsLE) {
2215   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2216 
2217   // Ensure each byte index of the double word is consecutive.
2218   if (!isNByteElemShuffleMask(N, 8, 1))
2219     return false;
2220 
2221   unsigned M0 = N->getMaskElt(0) / 8;
2222   unsigned M1 = N->getMaskElt(8) / 8;
2223   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2224 
2225   // If both vector operands for the shuffle are the same vector, the mask will
2226   // contain only elements from the first one and the second one will be undef.
2227   if (N->getOperand(1).isUndef()) {
2228     if ((M0 | M1) < 2) {
2229       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2230       Swap = false;
2231       return true;
2232     } else
2233       return false;
2234   }
2235 
2236   if (IsLE) {
2237     if (M0 > 1 && M1 < 2) {
2238       Swap = false;
2239     } else if (M0 < 2 && M1 > 1) {
2240       M0 = (M0 + 2) % 4;
2241       M1 = (M1 + 2) % 4;
2242       Swap = true;
2243     } else
2244       return false;
2245 
2246     // Note: if control flow comes here that means Swap is already set above
2247     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2248     return true;
2249   } else { // BE
2250     if (M0 < 2 && M1 > 1) {
2251       Swap = false;
2252     } else if (M0 > 1 && M1 < 2) {
2253       M0 = (M0 + 2) % 4;
2254       M1 = (M1 + 2) % 4;
2255       Swap = true;
2256     } else
2257       return false;
2258 
2259     // Note: if control flow comes here that means Swap is already set above
2260     DM = (M0 << 1) + (M1 & 1);
2261     return true;
2262   }
2263 }
2264 
2265 
2266 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2267 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2268 /// elements are counted from the left of the vector register).
2269 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2270                                          SelectionDAG &DAG) {
2271   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2272   assert(isSplatShuffleMask(SVOp, EltSize));
2273   if (DAG.getDataLayout().isLittleEndian())
2274     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2275   else
2276     return SVOp->getMaskElt(0) / EltSize;
2277 }
2278 
2279 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2280 /// by using a vspltis[bhw] instruction of the specified element size, return
2281 /// the constant being splatted.  The ByteSize field indicates the number of
2282 /// bytes of each element [124] -> [bhw].
2283 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2284   SDValue OpVal(nullptr, 0);
2285 
2286   // If ByteSize of the splat is bigger than the element size of the
2287   // build_vector, then we have a case where we are checking for a splat where
2288   // multiple elements of the buildvector are folded together into a single
2289   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2290   unsigned EltSize = 16/N->getNumOperands();
2291   if (EltSize < ByteSize) {
2292     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2293     SDValue UniquedVals[4];
2294     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2295 
2296     // See if all of the elements in the buildvector agree across.
2297     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2298       if (N->getOperand(i).isUndef()) continue;
2299       // If the element isn't a constant, bail fully out.
2300       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2301 
2302       if (!UniquedVals[i&(Multiple-1)].getNode())
2303         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2304       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2305         return SDValue();  // no match.
2306     }
2307 
2308     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2309     // either constant or undef values that are identical for each chunk.  See
2310     // if these chunks can form into a larger vspltis*.
2311 
2312     // Check to see if all of the leading entries are either 0 or -1.  If
2313     // neither, then this won't fit into the immediate field.
2314     bool LeadingZero = true;
2315     bool LeadingOnes = true;
2316     for (unsigned i = 0; i != Multiple-1; ++i) {
2317       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2318 
2319       LeadingZero &= isNullConstant(UniquedVals[i]);
2320       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2321     }
2322     // Finally, check the least significant entry.
2323     if (LeadingZero) {
2324       if (!UniquedVals[Multiple-1].getNode())
2325         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2326       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2327       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2328         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2329     }
2330     if (LeadingOnes) {
2331       if (!UniquedVals[Multiple-1].getNode())
2332         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2333       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2334       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2335         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2336     }
2337 
2338     return SDValue();
2339   }
2340 
2341   // Check to see if this buildvec has a single non-undef value in its elements.
2342   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2343     if (N->getOperand(i).isUndef()) continue;
2344     if (!OpVal.getNode())
2345       OpVal = N->getOperand(i);
2346     else if (OpVal != N->getOperand(i))
2347       return SDValue();
2348   }
2349 
2350   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2351 
2352   unsigned ValSizeInBytes = EltSize;
2353   uint64_t Value = 0;
2354   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2355     Value = CN->getZExtValue();
2356   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2357     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2358     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2359   }
2360 
2361   // If the splat value is larger than the element value, then we can never do
2362   // this splat.  The only case that we could fit the replicated bits into our
2363   // immediate field for would be zero, and we prefer to use vxor for it.
2364   if (ValSizeInBytes < ByteSize) return SDValue();
2365 
2366   // If the element value is larger than the splat value, check if it consists
2367   // of a repeated bit pattern of size ByteSize.
2368   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2369     return SDValue();
2370 
2371   // Properly sign extend the value.
2372   int MaskVal = SignExtend32(Value, ByteSize * 8);
2373 
2374   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2375   if (MaskVal == 0) return SDValue();
2376 
2377   // Finally, if this value fits in a 5 bit sext field, return it
2378   if (SignExtend32<5>(MaskVal) == MaskVal)
2379     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2380   return SDValue();
2381 }
2382 
2383 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2384 /// amount, otherwise return -1.
2385 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2386   EVT VT = N->getValueType(0);
2387   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2388     return -1;
2389 
2390   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2391 
2392   // Find the first non-undef value in the shuffle mask.
2393   unsigned i;
2394   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2395     /*search*/;
2396 
2397   if (i == 4) return -1;  // all undef.
2398 
2399   // Otherwise, check to see if the rest of the elements are consecutively
2400   // numbered from this value.
2401   unsigned ShiftAmt = SVOp->getMaskElt(i);
2402   if (ShiftAmt < i) return -1;
2403   ShiftAmt -= i;
2404 
2405   // Check the rest of the elements to see if they are consecutive.
2406   for (++i; i != 4; ++i)
2407     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2408       return -1;
2409 
2410   return ShiftAmt;
2411 }
2412 
2413 //===----------------------------------------------------------------------===//
2414 //  Addressing Mode Selection
2415 //===----------------------------------------------------------------------===//
2416 
2417 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2418 /// or 64-bit immediate, and if the value can be accurately represented as a
2419 /// sign extension from a 16-bit value.  If so, this returns true and the
2420 /// immediate.
2421 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2422   if (!isa<ConstantSDNode>(N))
2423     return false;
2424 
2425   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2426   if (N->getValueType(0) == MVT::i32)
2427     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2428   else
2429     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2430 }
2431 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2432   return isIntS16Immediate(Op.getNode(), Imm);
2433 }
2434 
2435 
2436 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2437 /// be represented as an indexed [r+r] operation.
2438 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2439                                                SDValue &Index,
2440                                                SelectionDAG &DAG) const {
2441   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2442       UI != E; ++UI) {
2443     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2444       if (Memop->getMemoryVT() == MVT::f64) {
2445           Base = N.getOperand(0);
2446           Index = N.getOperand(1);
2447           return true;
2448       }
2449     }
2450   }
2451   return false;
2452 }
2453 
2454 /// isIntS34Immediate - This method tests if value of node given can be
2455 /// accurately represented as a sign extension from a 34-bit value.  If so,
2456 /// this returns true and the immediate.
2457 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2458   if (!isa<ConstantSDNode>(N))
2459     return false;
2460 
2461   Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2462   return isInt<34>(Imm);
2463 }
2464 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2465   return isIntS34Immediate(Op.getNode(), Imm);
2466 }
2467 
2468 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2469 /// can be represented as an indexed [r+r] operation.  Returns false if it
2470 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2471 /// non-zero and N can be represented by a base register plus a signed 16-bit
2472 /// displacement, make a more precise judgement by checking (displacement % \p
2473 /// EncodingAlignment).
2474 bool PPCTargetLowering::SelectAddressRegReg(
2475     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2476     MaybeAlign EncodingAlignment) const {
2477   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2478   // a [pc+imm].
2479   if (SelectAddressPCRel(N, Base))
2480     return false;
2481 
2482   int16_t Imm = 0;
2483   if (N.getOpcode() == ISD::ADD) {
2484     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2485     // SPE load/store can only handle 8-bit offsets.
2486     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2487         return true;
2488     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2489         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2490       return false; // r+i
2491     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2492       return false;    // r+i
2493 
2494     Base = N.getOperand(0);
2495     Index = N.getOperand(1);
2496     return true;
2497   } else if (N.getOpcode() == ISD::OR) {
2498     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2499         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2500       return false; // r+i can fold it if we can.
2501 
2502     // If this is an or of disjoint bitfields, we can codegen this as an add
2503     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2504     // disjoint.
2505     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2506 
2507     if (LHSKnown.Zero.getBoolValue()) {
2508       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2509       // If all of the bits are known zero on the LHS or RHS, the add won't
2510       // carry.
2511       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2512         Base = N.getOperand(0);
2513         Index = N.getOperand(1);
2514         return true;
2515       }
2516     }
2517   }
2518 
2519   return false;
2520 }
2521 
2522 // If we happen to be doing an i64 load or store into a stack slot that has
2523 // less than a 4-byte alignment, then the frame-index elimination may need to
2524 // use an indexed load or store instruction (because the offset may not be a
2525 // multiple of 4). The extra register needed to hold the offset comes from the
2526 // register scavenger, and it is possible that the scavenger will need to use
2527 // an emergency spill slot. As a result, we need to make sure that a spill slot
2528 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2529 // stack slot.
2530 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2531   // FIXME: This does not handle the LWA case.
2532   if (VT != MVT::i64)
2533     return;
2534 
2535   // NOTE: We'll exclude negative FIs here, which come from argument
2536   // lowering, because there are no known test cases triggering this problem
2537   // using packed structures (or similar). We can remove this exclusion if
2538   // we find such a test case. The reason why this is so test-case driven is
2539   // because this entire 'fixup' is only to prevent crashes (from the
2540   // register scavenger) on not-really-valid inputs. For example, if we have:
2541   //   %a = alloca i1
2542   //   %b = bitcast i1* %a to i64*
2543   //   store i64* a, i64 b
2544   // then the store should really be marked as 'align 1', but is not. If it
2545   // were marked as 'align 1' then the indexed form would have been
2546   // instruction-selected initially, and the problem this 'fixup' is preventing
2547   // won't happen regardless.
2548   if (FrameIdx < 0)
2549     return;
2550 
2551   MachineFunction &MF = DAG.getMachineFunction();
2552   MachineFrameInfo &MFI = MF.getFrameInfo();
2553 
2554   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2555     return;
2556 
2557   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2558   FuncInfo->setHasNonRISpills();
2559 }
2560 
2561 /// Returns true if the address N can be represented by a base register plus
2562 /// a signed 16-bit displacement [r+imm], and if it is not better
2563 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2564 /// displacements that are multiples of that value.
2565 bool PPCTargetLowering::SelectAddressRegImm(
2566     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2567     MaybeAlign EncodingAlignment) const {
2568   // FIXME dl should come from parent load or store, not from address
2569   SDLoc dl(N);
2570 
2571   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2572   // a [pc+imm].
2573   if (SelectAddressPCRel(N, Base))
2574     return false;
2575 
2576   // If this can be more profitably realized as r+r, fail.
2577   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2578     return false;
2579 
2580   if (N.getOpcode() == ISD::ADD) {
2581     int16_t imm = 0;
2582     if (isIntS16Immediate(N.getOperand(1), imm) &&
2583         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2584       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2585       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2586         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2587         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2588       } else {
2589         Base = N.getOperand(0);
2590       }
2591       return true; // [r+i]
2592     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2593       // Match LOAD (ADD (X, Lo(G))).
2594       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2595              && "Cannot handle constant offsets yet!");
2596       Disp = N.getOperand(1).getOperand(0);  // The global address.
2597       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2598              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2599              Disp.getOpcode() == ISD::TargetConstantPool ||
2600              Disp.getOpcode() == ISD::TargetJumpTable);
2601       Base = N.getOperand(0);
2602       return true;  // [&g+r]
2603     }
2604   } else if (N.getOpcode() == ISD::OR) {
2605     int16_t imm = 0;
2606     if (isIntS16Immediate(N.getOperand(1), imm) &&
2607         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2608       // If this is an or of disjoint bitfields, we can codegen this as an add
2609       // (for better address arithmetic) if the LHS and RHS of the OR are
2610       // provably disjoint.
2611       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2612 
2613       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2614         // If all of the bits are known zero on the LHS or RHS, the add won't
2615         // carry.
2616         if (FrameIndexSDNode *FI =
2617               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2618           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2619           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2620         } else {
2621           Base = N.getOperand(0);
2622         }
2623         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2624         return true;
2625       }
2626     }
2627   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2628     // Loading from a constant address.
2629 
2630     // If this address fits entirely in a 16-bit sext immediate field, codegen
2631     // this as "d, 0"
2632     int16_t Imm;
2633     if (isIntS16Immediate(CN, Imm) &&
2634         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2635       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2636       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2637                              CN->getValueType(0));
2638       return true;
2639     }
2640 
2641     // Handle 32-bit sext immediates with LIS + addr mode.
2642     if ((CN->getValueType(0) == MVT::i32 ||
2643          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2644         (!EncodingAlignment ||
2645          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2646       int Addr = (int)CN->getZExtValue();
2647 
2648       // Otherwise, break this down into an LIS + disp.
2649       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2650 
2651       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2652                                    MVT::i32);
2653       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2654       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2655       return true;
2656     }
2657   }
2658 
2659   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2660   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2661     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2662     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2663   } else
2664     Base = N;
2665   return true;      // [r+0]
2666 }
2667 
2668 /// Similar to the 16-bit case but for instructions that take a 34-bit
2669 /// displacement field (prefixed loads/stores).
2670 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp,
2671                                               SDValue &Base,
2672                                               SelectionDAG &DAG) const {
2673   // Only on 64-bit targets.
2674   if (N.getValueType() != MVT::i64)
2675     return false;
2676 
2677   SDLoc dl(N);
2678   int64_t Imm = 0;
2679 
2680   if (N.getOpcode() == ISD::ADD) {
2681     if (!isIntS34Immediate(N.getOperand(1), Imm))
2682       return false;
2683     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2684     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2685       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2686     else
2687       Base = N.getOperand(0);
2688     return true;
2689   }
2690 
2691   if (N.getOpcode() == ISD::OR) {
2692     if (!isIntS34Immediate(N.getOperand(1), Imm))
2693       return false;
2694     // If this is an or of disjoint bitfields, we can codegen this as an add
2695     // (for better address arithmetic) if the LHS and RHS of the OR are
2696     // provably disjoint.
2697     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2698     if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2699       return false;
2700     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2701       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2702     else
2703       Base = N.getOperand(0);
2704     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2705     return true;
2706   }
2707 
2708   if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2709     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2710     Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2711     return true;
2712   }
2713 
2714   return false;
2715 }
2716 
2717 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2718 /// represented as an indexed [r+r] operation.
2719 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2720                                                 SDValue &Index,
2721                                                 SelectionDAG &DAG) const {
2722   // Check to see if we can easily represent this as an [r+r] address.  This
2723   // will fail if it thinks that the address is more profitably represented as
2724   // reg+imm, e.g. where imm = 0.
2725   if (SelectAddressRegReg(N, Base, Index, DAG))
2726     return true;
2727 
2728   // If the address is the result of an add, we will utilize the fact that the
2729   // address calculation includes an implicit add.  However, we can reduce
2730   // register pressure if we do not materialize a constant just for use as the
2731   // index register.  We only get rid of the add if it is not an add of a
2732   // value and a 16-bit signed constant and both have a single use.
2733   int16_t imm = 0;
2734   if (N.getOpcode() == ISD::ADD &&
2735       (!isIntS16Immediate(N.getOperand(1), imm) ||
2736        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2737     Base = N.getOperand(0);
2738     Index = N.getOperand(1);
2739     return true;
2740   }
2741 
2742   // Otherwise, do it the hard way, using R0 as the base register.
2743   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2744                          N.getValueType());
2745   Index = N;
2746   return true;
2747 }
2748 
2749 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2750   Ty *PCRelCand = dyn_cast<Ty>(N);
2751   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2752 }
2753 
2754 /// Returns true if this address is a PC Relative address.
2755 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2756 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2757 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2758   // This is a materialize PC Relative node. Always select this as PC Relative.
2759   Base = N;
2760   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2761     return true;
2762   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2763       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2764       isValidPCRelNode<JumpTableSDNode>(N) ||
2765       isValidPCRelNode<BlockAddressSDNode>(N))
2766     return true;
2767   return false;
2768 }
2769 
2770 /// Returns true if we should use a direct load into vector instruction
2771 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2772 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2773 
2774   // If there are any other uses other than scalar to vector, then we should
2775   // keep it as a scalar load -> direct move pattern to prevent multiple
2776   // loads.
2777   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2778   if (!LD)
2779     return false;
2780 
2781   EVT MemVT = LD->getMemoryVT();
2782   if (!MemVT.isSimple())
2783     return false;
2784   switch(MemVT.getSimpleVT().SimpleTy) {
2785   case MVT::i64:
2786     break;
2787   case MVT::i32:
2788     if (!ST.hasP8Vector())
2789       return false;
2790     break;
2791   case MVT::i16:
2792   case MVT::i8:
2793     if (!ST.hasP9Vector())
2794       return false;
2795     break;
2796   default:
2797     return false;
2798   }
2799 
2800   SDValue LoadedVal(N, 0);
2801   if (!LoadedVal.hasOneUse())
2802     return false;
2803 
2804   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2805        UI != UE; ++UI)
2806     if (UI.getUse().get().getResNo() == 0 &&
2807         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2808         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2809       return false;
2810 
2811   return true;
2812 }
2813 
2814 /// getPreIndexedAddressParts - returns true by value, base pointer and
2815 /// offset pointer and addressing mode by reference if the node's address
2816 /// can be legally represented as pre-indexed load / store address.
2817 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2818                                                   SDValue &Offset,
2819                                                   ISD::MemIndexedMode &AM,
2820                                                   SelectionDAG &DAG) const {
2821   if (DisablePPCPreinc) return false;
2822 
2823   bool isLoad = true;
2824   SDValue Ptr;
2825   EVT VT;
2826   unsigned Alignment;
2827   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2828     Ptr = LD->getBasePtr();
2829     VT = LD->getMemoryVT();
2830     Alignment = LD->getAlignment();
2831   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2832     Ptr = ST->getBasePtr();
2833     VT  = ST->getMemoryVT();
2834     Alignment = ST->getAlignment();
2835     isLoad = false;
2836   } else
2837     return false;
2838 
2839   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2840   // instructions because we can fold these into a more efficient instruction
2841   // instead, (such as LXSD).
2842   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2843     return false;
2844   }
2845 
2846   // PowerPC doesn't have preinc load/store instructions for vectors
2847   if (VT.isVector())
2848     return false;
2849 
2850   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2851     // Common code will reject creating a pre-inc form if the base pointer
2852     // is a frame index, or if N is a store and the base pointer is either
2853     // the same as or a predecessor of the value being stored.  Check for
2854     // those situations here, and try with swapped Base/Offset instead.
2855     bool Swap = false;
2856 
2857     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2858       Swap = true;
2859     else if (!isLoad) {
2860       SDValue Val = cast<StoreSDNode>(N)->getValue();
2861       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2862         Swap = true;
2863     }
2864 
2865     if (Swap)
2866       std::swap(Base, Offset);
2867 
2868     AM = ISD::PRE_INC;
2869     return true;
2870   }
2871 
2872   // LDU/STU can only handle immediates that are a multiple of 4.
2873   if (VT != MVT::i64) {
2874     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2875       return false;
2876   } else {
2877     // LDU/STU need an address with at least 4-byte alignment.
2878     if (Alignment < 4)
2879       return false;
2880 
2881     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
2882       return false;
2883   }
2884 
2885   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2886     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2887     // sext i32 to i64 when addr mode is r+i.
2888     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2889         LD->getExtensionType() == ISD::SEXTLOAD &&
2890         isa<ConstantSDNode>(Offset))
2891       return false;
2892   }
2893 
2894   AM = ISD::PRE_INC;
2895   return true;
2896 }
2897 
2898 //===----------------------------------------------------------------------===//
2899 //  LowerOperation implementation
2900 //===----------------------------------------------------------------------===//
2901 
2902 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2903 /// and LoOpFlags to the target MO flags.
2904 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2905                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2906                                const GlobalValue *GV = nullptr) {
2907   HiOpFlags = PPCII::MO_HA;
2908   LoOpFlags = PPCII::MO_LO;
2909 
2910   // Don't use the pic base if not in PIC relocation model.
2911   if (IsPIC) {
2912     HiOpFlags |= PPCII::MO_PIC_FLAG;
2913     LoOpFlags |= PPCII::MO_PIC_FLAG;
2914   }
2915 }
2916 
2917 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2918                              SelectionDAG &DAG) {
2919   SDLoc DL(HiPart);
2920   EVT PtrVT = HiPart.getValueType();
2921   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2922 
2923   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2924   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2925 
2926   // With PIC, the first instruction is actually "GR+hi(&G)".
2927   if (isPIC)
2928     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2929                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2930 
2931   // Generate non-pic code that has direct accesses to the constant pool.
2932   // The address of the global is just (hi(&g)+lo(&g)).
2933   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2934 }
2935 
2936 static void setUsesTOCBasePtr(MachineFunction &MF) {
2937   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2938   FuncInfo->setUsesTOCBasePtr();
2939 }
2940 
2941 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2942   setUsesTOCBasePtr(DAG.getMachineFunction());
2943 }
2944 
2945 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2946                                        SDValue GA) const {
2947   const bool Is64Bit = Subtarget.isPPC64();
2948   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2949   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2950                         : Subtarget.isAIXABI()
2951                               ? DAG.getRegister(PPC::R2, VT)
2952                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2953   SDValue Ops[] = { GA, Reg };
2954   return DAG.getMemIntrinsicNode(
2955       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2956       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2957       MachineMemOperand::MOLoad);
2958 }
2959 
2960 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2961                                              SelectionDAG &DAG) const {
2962   EVT PtrVT = Op.getValueType();
2963   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2964   const Constant *C = CP->getConstVal();
2965 
2966   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2967   // The actual address of the GlobalValue is stored in the TOC.
2968   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2969     if (Subtarget.isUsingPCRelativeCalls()) {
2970       SDLoc DL(CP);
2971       EVT Ty = getPointerTy(DAG.getDataLayout());
2972       SDValue ConstPool = DAG.getTargetConstantPool(
2973           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2974       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2975     }
2976     setUsesTOCBasePtr(DAG);
2977     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2978     return getTOCEntry(DAG, SDLoc(CP), GA);
2979   }
2980 
2981   unsigned MOHiFlag, MOLoFlag;
2982   bool IsPIC = isPositionIndependent();
2983   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2984 
2985   if (IsPIC && Subtarget.isSVR4ABI()) {
2986     SDValue GA =
2987         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2988     return getTOCEntry(DAG, SDLoc(CP), GA);
2989   }
2990 
2991   SDValue CPIHi =
2992       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
2993   SDValue CPILo =
2994       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
2995   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2996 }
2997 
2998 // For 64-bit PowerPC, prefer the more compact relative encodings.
2999 // This trades 32 bits per jump table entry for one or two instructions
3000 // on the jump site.
3001 unsigned PPCTargetLowering::getJumpTableEncoding() const {
3002   if (isJumpTableRelative())
3003     return MachineJumpTableInfo::EK_LabelDifference32;
3004 
3005   return TargetLowering::getJumpTableEncoding();
3006 }
3007 
3008 bool PPCTargetLowering::isJumpTableRelative() const {
3009   if (UseAbsoluteJumpTables)
3010     return false;
3011   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3012     return true;
3013   return TargetLowering::isJumpTableRelative();
3014 }
3015 
3016 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
3017                                                     SelectionDAG &DAG) const {
3018   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3019     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3020 
3021   switch (getTargetMachine().getCodeModel()) {
3022   case CodeModel::Small:
3023   case CodeModel::Medium:
3024     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3025   default:
3026     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3027                        getPointerTy(DAG.getDataLayout()));
3028   }
3029 }
3030 
3031 const MCExpr *
3032 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
3033                                                 unsigned JTI,
3034                                                 MCContext &Ctx) const {
3035   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3036     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3037 
3038   switch (getTargetMachine().getCodeModel()) {
3039   case CodeModel::Small:
3040   case CodeModel::Medium:
3041     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3042   default:
3043     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3044   }
3045 }
3046 
3047 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3048   EVT PtrVT = Op.getValueType();
3049   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3050 
3051   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3052   if (Subtarget.isUsingPCRelativeCalls()) {
3053     SDLoc DL(JT);
3054     EVT Ty = getPointerTy(DAG.getDataLayout());
3055     SDValue GA =
3056         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3057     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3058     return MatAddr;
3059   }
3060 
3061   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3062   // The actual address of the GlobalValue is stored in the TOC.
3063   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3064     setUsesTOCBasePtr(DAG);
3065     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3066     return getTOCEntry(DAG, SDLoc(JT), GA);
3067   }
3068 
3069   unsigned MOHiFlag, MOLoFlag;
3070   bool IsPIC = isPositionIndependent();
3071   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3072 
3073   if (IsPIC && Subtarget.isSVR4ABI()) {
3074     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3075                                         PPCII::MO_PIC_FLAG);
3076     return getTOCEntry(DAG, SDLoc(GA), GA);
3077   }
3078 
3079   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3080   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3081   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3082 }
3083 
3084 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3085                                              SelectionDAG &DAG) const {
3086   EVT PtrVT = Op.getValueType();
3087   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3088   const BlockAddress *BA = BASDN->getBlockAddress();
3089 
3090   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3091   if (Subtarget.isUsingPCRelativeCalls()) {
3092     SDLoc DL(BASDN);
3093     EVT Ty = getPointerTy(DAG.getDataLayout());
3094     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3095                                            PPCII::MO_PCREL_FLAG);
3096     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3097     return MatAddr;
3098   }
3099 
3100   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3101   // The actual BlockAddress is stored in the TOC.
3102   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3103     setUsesTOCBasePtr(DAG);
3104     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3105     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3106   }
3107 
3108   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3109   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3110     return getTOCEntry(
3111         DAG, SDLoc(BASDN),
3112         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3113 
3114   unsigned MOHiFlag, MOLoFlag;
3115   bool IsPIC = isPositionIndependent();
3116   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3117   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3118   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3119   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3120 }
3121 
3122 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3123                                               SelectionDAG &DAG) const {
3124   // FIXME: TLS addresses currently use medium model code sequences,
3125   // which is the most useful form.  Eventually support for small and
3126   // large models could be added if users need it, at the cost of
3127   // additional complexity.
3128   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3129   if (DAG.getTarget().useEmulatedTLS())
3130     return LowerToTLSEmulatedModel(GA, DAG);
3131 
3132   SDLoc dl(GA);
3133   const GlobalValue *GV = GA->getGlobal();
3134   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3135   bool is64bit = Subtarget.isPPC64();
3136   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3137   PICLevel::Level picLevel = M->getPICLevel();
3138 
3139   const TargetMachine &TM = getTargetMachine();
3140   TLSModel::Model Model = TM.getTLSModel(GV);
3141 
3142   if (Model == TLSModel::LocalExec) {
3143     if (Subtarget.isUsingPCRelativeCalls()) {
3144       SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3145       SDValue TGA = DAG.getTargetGlobalAddress(
3146           GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3147       SDValue MatAddr =
3148           DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3149       return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3150     }
3151 
3152     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3153                                                PPCII::MO_TPREL_HA);
3154     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3155                                                PPCII::MO_TPREL_LO);
3156     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3157                              : DAG.getRegister(PPC::R2, MVT::i32);
3158 
3159     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3160     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3161   }
3162 
3163   if (Model == TLSModel::InitialExec) {
3164     bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3165     SDValue TGA = DAG.getTargetGlobalAddress(
3166         GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3167     SDValue TGATLS = DAG.getTargetGlobalAddress(
3168         GV, dl, PtrVT, 0,
3169         IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3170     SDValue TPOffset;
3171     if (IsPCRel) {
3172       SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3173       TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3174                              MachinePointerInfo());
3175     } else {
3176       SDValue GOTPtr;
3177       if (is64bit) {
3178         setUsesTOCBasePtr(DAG);
3179         SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3180         GOTPtr =
3181             DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3182       } else {
3183         if (!TM.isPositionIndependent())
3184           GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3185         else if (picLevel == PICLevel::SmallPIC)
3186           GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3187         else
3188           GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3189       }
3190       TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3191     }
3192     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3193   }
3194 
3195   if (Model == TLSModel::GeneralDynamic) {
3196     if (Subtarget.isUsingPCRelativeCalls()) {
3197       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3198                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3199       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3200     }
3201 
3202     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3203     SDValue GOTPtr;
3204     if (is64bit) {
3205       setUsesTOCBasePtr(DAG);
3206       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3207       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3208                                    GOTReg, TGA);
3209     } else {
3210       if (picLevel == PICLevel::SmallPIC)
3211         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3212       else
3213         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3214     }
3215     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3216                        GOTPtr, TGA, TGA);
3217   }
3218 
3219   if (Model == TLSModel::LocalDynamic) {
3220     if (Subtarget.isUsingPCRelativeCalls()) {
3221       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3222                                                PPCII::MO_GOT_TLSLD_PCREL_FLAG);
3223       SDValue MatPCRel =
3224           DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3225       return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3226     }
3227 
3228     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3229     SDValue GOTPtr;
3230     if (is64bit) {
3231       setUsesTOCBasePtr(DAG);
3232       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3233       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3234                            GOTReg, TGA);
3235     } else {
3236       if (picLevel == PICLevel::SmallPIC)
3237         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3238       else
3239         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3240     }
3241     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3242                                   PtrVT, GOTPtr, TGA, TGA);
3243     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3244                                       PtrVT, TLSAddr, TGA);
3245     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3246   }
3247 
3248   llvm_unreachable("Unknown TLS model!");
3249 }
3250 
3251 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3252                                               SelectionDAG &DAG) const {
3253   EVT PtrVT = Op.getValueType();
3254   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3255   SDLoc DL(GSDN);
3256   const GlobalValue *GV = GSDN->getGlobal();
3257 
3258   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3259   // The actual address of the GlobalValue is stored in the TOC.
3260   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3261     if (Subtarget.isUsingPCRelativeCalls()) {
3262       EVT Ty = getPointerTy(DAG.getDataLayout());
3263       if (isAccessedAsGotIndirect(Op)) {
3264         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3265                                                 PPCII::MO_PCREL_FLAG |
3266                                                     PPCII::MO_GOT_FLAG);
3267         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3268         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3269                                    MachinePointerInfo());
3270         return Load;
3271       } else {
3272         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3273                                                 PPCII::MO_PCREL_FLAG);
3274         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3275       }
3276     }
3277     setUsesTOCBasePtr(DAG);
3278     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3279     return getTOCEntry(DAG, DL, GA);
3280   }
3281 
3282   unsigned MOHiFlag, MOLoFlag;
3283   bool IsPIC = isPositionIndependent();
3284   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3285 
3286   if (IsPIC && Subtarget.isSVR4ABI()) {
3287     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3288                                             GSDN->getOffset(),
3289                                             PPCII::MO_PIC_FLAG);
3290     return getTOCEntry(DAG, DL, GA);
3291   }
3292 
3293   SDValue GAHi =
3294     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3295   SDValue GALo =
3296     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3297 
3298   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3299 }
3300 
3301 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3302   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3303   SDLoc dl(Op);
3304 
3305   if (Op.getValueType() == MVT::v2i64) {
3306     // When the operands themselves are v2i64 values, we need to do something
3307     // special because VSX has no underlying comparison operations for these.
3308     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3309       // Equality can be handled by casting to the legal type for Altivec
3310       // comparisons, everything else needs to be expanded.
3311       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3312         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3313                  DAG.getSetCC(dl, MVT::v4i32,
3314                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3315                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3316                    CC));
3317       }
3318 
3319       return SDValue();
3320     }
3321 
3322     // We handle most of these in the usual way.
3323     return Op;
3324   }
3325 
3326   // If we're comparing for equality to zero, expose the fact that this is
3327   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3328   // fold the new nodes.
3329   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3330     return V;
3331 
3332   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3333     // Leave comparisons against 0 and -1 alone for now, since they're usually
3334     // optimized.  FIXME: revisit this when we can custom lower all setcc
3335     // optimizations.
3336     if (C->isAllOnesValue() || C->isNullValue())
3337       return SDValue();
3338   }
3339 
3340   // If we have an integer seteq/setne, turn it into a compare against zero
3341   // by xor'ing the rhs with the lhs, which is faster than setting a
3342   // condition register, reading it back out, and masking the correct bit.  The
3343   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3344   // the result to other bit-twiddling opportunities.
3345   EVT LHSVT = Op.getOperand(0).getValueType();
3346   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3347     EVT VT = Op.getValueType();
3348     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3349                                 Op.getOperand(1));
3350     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3351   }
3352   return SDValue();
3353 }
3354 
3355 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3356   SDNode *Node = Op.getNode();
3357   EVT VT = Node->getValueType(0);
3358   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3359   SDValue InChain = Node->getOperand(0);
3360   SDValue VAListPtr = Node->getOperand(1);
3361   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3362   SDLoc dl(Node);
3363 
3364   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3365 
3366   // gpr_index
3367   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3368                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3369   InChain = GprIndex.getValue(1);
3370 
3371   if (VT == MVT::i64) {
3372     // Check if GprIndex is even
3373     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3374                                  DAG.getConstant(1, dl, MVT::i32));
3375     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3376                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3377     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3378                                           DAG.getConstant(1, dl, MVT::i32));
3379     // Align GprIndex to be even if it isn't
3380     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3381                            GprIndex);
3382   }
3383 
3384   // fpr index is 1 byte after gpr
3385   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3386                                DAG.getConstant(1, dl, MVT::i32));
3387 
3388   // fpr
3389   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3390                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3391   InChain = FprIndex.getValue(1);
3392 
3393   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3394                                        DAG.getConstant(8, dl, MVT::i32));
3395 
3396   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3397                                         DAG.getConstant(4, dl, MVT::i32));
3398 
3399   // areas
3400   SDValue OverflowArea =
3401       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3402   InChain = OverflowArea.getValue(1);
3403 
3404   SDValue RegSaveArea =
3405       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3406   InChain = RegSaveArea.getValue(1);
3407 
3408   // select overflow_area if index > 8
3409   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3410                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3411 
3412   // adjustment constant gpr_index * 4/8
3413   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3414                                     VT.isInteger() ? GprIndex : FprIndex,
3415                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3416                                                     MVT::i32));
3417 
3418   // OurReg = RegSaveArea + RegConstant
3419   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3420                                RegConstant);
3421 
3422   // Floating types are 32 bytes into RegSaveArea
3423   if (VT.isFloatingPoint())
3424     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3425                          DAG.getConstant(32, dl, MVT::i32));
3426 
3427   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3428   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3429                                    VT.isInteger() ? GprIndex : FprIndex,
3430                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3431                                                    MVT::i32));
3432 
3433   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3434                               VT.isInteger() ? VAListPtr : FprPtr,
3435                               MachinePointerInfo(SV), MVT::i8);
3436 
3437   // determine if we should load from reg_save_area or overflow_area
3438   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3439 
3440   // increase overflow_area by 4/8 if gpr/fpr > 8
3441   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3442                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3443                                           dl, MVT::i32));
3444 
3445   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3446                              OverflowAreaPlusN);
3447 
3448   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3449                               MachinePointerInfo(), MVT::i32);
3450 
3451   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3452 }
3453 
3454 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3455   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3456 
3457   // We have to copy the entire va_list struct:
3458   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3459   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3460                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3461                        false, true, false, MachinePointerInfo(),
3462                        MachinePointerInfo());
3463 }
3464 
3465 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3466                                                   SelectionDAG &DAG) const {
3467   if (Subtarget.isAIXABI())
3468     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3469 
3470   return Op.getOperand(0);
3471 }
3472 
3473 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3474                                                 SelectionDAG &DAG) const {
3475   if (Subtarget.isAIXABI())
3476     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3477 
3478   SDValue Chain = Op.getOperand(0);
3479   SDValue Trmp = Op.getOperand(1); // trampoline
3480   SDValue FPtr = Op.getOperand(2); // nested function
3481   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3482   SDLoc dl(Op);
3483 
3484   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3485   bool isPPC64 = (PtrVT == MVT::i64);
3486   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3487 
3488   TargetLowering::ArgListTy Args;
3489   TargetLowering::ArgListEntry Entry;
3490 
3491   Entry.Ty = IntPtrTy;
3492   Entry.Node = Trmp; Args.push_back(Entry);
3493 
3494   // TrampSize == (isPPC64 ? 48 : 40);
3495   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3496                                isPPC64 ? MVT::i64 : MVT::i32);
3497   Args.push_back(Entry);
3498 
3499   Entry.Node = FPtr; Args.push_back(Entry);
3500   Entry.Node = Nest; Args.push_back(Entry);
3501 
3502   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3503   TargetLowering::CallLoweringInfo CLI(DAG);
3504   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3505       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3506       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3507 
3508   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3509   return CallResult.second;
3510 }
3511 
3512 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3513   MachineFunction &MF = DAG.getMachineFunction();
3514   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3515   EVT PtrVT = getPointerTy(MF.getDataLayout());
3516 
3517   SDLoc dl(Op);
3518 
3519   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3520     // vastart just stores the address of the VarArgsFrameIndex slot into the
3521     // memory location argument.
3522     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3523     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3524     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3525                         MachinePointerInfo(SV));
3526   }
3527 
3528   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3529   // We suppose the given va_list is already allocated.
3530   //
3531   // typedef struct {
3532   //  char gpr;     /* index into the array of 8 GPRs
3533   //                 * stored in the register save area
3534   //                 * gpr=0 corresponds to r3,
3535   //                 * gpr=1 to r4, etc.
3536   //                 */
3537   //  char fpr;     /* index into the array of 8 FPRs
3538   //                 * stored in the register save area
3539   //                 * fpr=0 corresponds to f1,
3540   //                 * fpr=1 to f2, etc.
3541   //                 */
3542   //  char *overflow_arg_area;
3543   //                /* location on stack that holds
3544   //                 * the next overflow argument
3545   //                 */
3546   //  char *reg_save_area;
3547   //               /* where r3:r10 and f1:f8 (if saved)
3548   //                * are stored
3549   //                */
3550   // } va_list[1];
3551 
3552   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3553   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3554   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3555                                             PtrVT);
3556   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3557                                  PtrVT);
3558 
3559   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3560   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3561 
3562   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3563   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3564 
3565   uint64_t FPROffset = 1;
3566   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3567 
3568   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3569 
3570   // Store first byte : number of int regs
3571   SDValue firstStore =
3572       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3573                         MachinePointerInfo(SV), MVT::i8);
3574   uint64_t nextOffset = FPROffset;
3575   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3576                                   ConstFPROffset);
3577 
3578   // Store second byte : number of float regs
3579   SDValue secondStore =
3580       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3581                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3582   nextOffset += StackOffset;
3583   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3584 
3585   // Store second word : arguments given on stack
3586   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3587                                     MachinePointerInfo(SV, nextOffset));
3588   nextOffset += FrameOffset;
3589   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3590 
3591   // Store third word : arguments given in registers
3592   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3593                       MachinePointerInfo(SV, nextOffset));
3594 }
3595 
3596 /// FPR - The set of FP registers that should be allocated for arguments
3597 /// on Darwin and AIX.
3598 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3599                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3600                                 PPC::F11, PPC::F12, PPC::F13};
3601 
3602 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3603 /// the stack.
3604 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3605                                        unsigned PtrByteSize) {
3606   unsigned ArgSize = ArgVT.getStoreSize();
3607   if (Flags.isByVal())
3608     ArgSize = Flags.getByValSize();
3609 
3610   // Round up to multiples of the pointer size, except for array members,
3611   // which are always packed.
3612   if (!Flags.isInConsecutiveRegs())
3613     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3614 
3615   return ArgSize;
3616 }
3617 
3618 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3619 /// on the stack.
3620 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3621                                          ISD::ArgFlagsTy Flags,
3622                                          unsigned PtrByteSize) {
3623   Align Alignment(PtrByteSize);
3624 
3625   // Altivec parameters are padded to a 16 byte boundary.
3626   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3627       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3628       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3629       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3630     Alignment = Align(16);
3631 
3632   // ByVal parameters are aligned as requested.
3633   if (Flags.isByVal()) {
3634     auto BVAlign = Flags.getNonZeroByValAlign();
3635     if (BVAlign > PtrByteSize) {
3636       if (BVAlign.value() % PtrByteSize != 0)
3637         llvm_unreachable(
3638             "ByVal alignment is not a multiple of the pointer size");
3639 
3640       Alignment = BVAlign;
3641     }
3642   }
3643 
3644   // Array members are always packed to their original alignment.
3645   if (Flags.isInConsecutiveRegs()) {
3646     // If the array member was split into multiple registers, the first
3647     // needs to be aligned to the size of the full type.  (Except for
3648     // ppcf128, which is only aligned as its f64 components.)
3649     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3650       Alignment = Align(OrigVT.getStoreSize());
3651     else
3652       Alignment = Align(ArgVT.getStoreSize());
3653   }
3654 
3655   return Alignment;
3656 }
3657 
3658 /// CalculateStackSlotUsed - Return whether this argument will use its
3659 /// stack slot (instead of being passed in registers).  ArgOffset,
3660 /// AvailableFPRs, and AvailableVRs must hold the current argument
3661 /// position, and will be updated to account for this argument.
3662 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3663                                    unsigned PtrByteSize, unsigned LinkageSize,
3664                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3665                                    unsigned &AvailableFPRs,
3666                                    unsigned &AvailableVRs) {
3667   bool UseMemory = false;
3668 
3669   // Respect alignment of argument on the stack.
3670   Align Alignment =
3671       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3672   ArgOffset = alignTo(ArgOffset, Alignment);
3673   // If there's no space left in the argument save area, we must
3674   // use memory (this check also catches zero-sized arguments).
3675   if (ArgOffset >= LinkageSize + ParamAreaSize)
3676     UseMemory = true;
3677 
3678   // Allocate argument on the stack.
3679   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3680   if (Flags.isInConsecutiveRegsLast())
3681     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3682   // If we overran the argument save area, we must use memory
3683   // (this check catches arguments passed partially in memory)
3684   if (ArgOffset > LinkageSize + ParamAreaSize)
3685     UseMemory = true;
3686 
3687   // However, if the argument is actually passed in an FPR or a VR,
3688   // we don't use memory after all.
3689   if (!Flags.isByVal()) {
3690     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3691       if (AvailableFPRs > 0) {
3692         --AvailableFPRs;
3693         return false;
3694       }
3695     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3696         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3697         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3698         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3699       if (AvailableVRs > 0) {
3700         --AvailableVRs;
3701         return false;
3702       }
3703   }
3704 
3705   return UseMemory;
3706 }
3707 
3708 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3709 /// ensure minimum alignment required for target.
3710 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3711                                      unsigned NumBytes) {
3712   return alignTo(NumBytes, Lowering->getStackAlign());
3713 }
3714 
3715 SDValue PPCTargetLowering::LowerFormalArguments(
3716     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3717     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3718     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3719   if (Subtarget.isAIXABI())
3720     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3721                                     InVals);
3722   if (Subtarget.is64BitELFABI())
3723     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3724                                        InVals);
3725   if (Subtarget.is32BitELFABI())
3726     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3727                                        InVals);
3728 
3729   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3730                                      InVals);
3731 }
3732 
3733 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3734     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3735     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3736     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3737 
3738   // 32-bit SVR4 ABI Stack Frame Layout:
3739   //              +-----------------------------------+
3740   //        +-->  |            Back chain             |
3741   //        |     +-----------------------------------+
3742   //        |     | Floating-point register save area |
3743   //        |     +-----------------------------------+
3744   //        |     |    General register save area     |
3745   //        |     +-----------------------------------+
3746   //        |     |          CR save word             |
3747   //        |     +-----------------------------------+
3748   //        |     |         VRSAVE save word          |
3749   //        |     +-----------------------------------+
3750   //        |     |         Alignment padding         |
3751   //        |     +-----------------------------------+
3752   //        |     |     Vector register save area     |
3753   //        |     +-----------------------------------+
3754   //        |     |       Local variable space        |
3755   //        |     +-----------------------------------+
3756   //        |     |        Parameter list area        |
3757   //        |     +-----------------------------------+
3758   //        |     |           LR save word            |
3759   //        |     +-----------------------------------+
3760   // SP-->  +---  |            Back chain             |
3761   //              +-----------------------------------+
3762   //
3763   // Specifications:
3764   //   System V Application Binary Interface PowerPC Processor Supplement
3765   //   AltiVec Technology Programming Interface Manual
3766 
3767   MachineFunction &MF = DAG.getMachineFunction();
3768   MachineFrameInfo &MFI = MF.getFrameInfo();
3769   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3770 
3771   EVT PtrVT = getPointerTy(MF.getDataLayout());
3772   // Potential tail calls could cause overwriting of argument stack slots.
3773   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3774                        (CallConv == CallingConv::Fast));
3775   const Align PtrAlign(4);
3776 
3777   // Assign locations to all of the incoming arguments.
3778   SmallVector<CCValAssign, 16> ArgLocs;
3779   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3780                  *DAG.getContext());
3781 
3782   // Reserve space for the linkage area on the stack.
3783   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3784   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3785   if (useSoftFloat())
3786     CCInfo.PreAnalyzeFormalArguments(Ins);
3787 
3788   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3789   CCInfo.clearWasPPCF128();
3790 
3791   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3792     CCValAssign &VA = ArgLocs[i];
3793 
3794     // Arguments stored in registers.
3795     if (VA.isRegLoc()) {
3796       const TargetRegisterClass *RC;
3797       EVT ValVT = VA.getValVT();
3798 
3799       switch (ValVT.getSimpleVT().SimpleTy) {
3800         default:
3801           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3802         case MVT::i1:
3803         case MVT::i32:
3804           RC = &PPC::GPRCRegClass;
3805           break;
3806         case MVT::f32:
3807           if (Subtarget.hasP8Vector())
3808             RC = &PPC::VSSRCRegClass;
3809           else if (Subtarget.hasSPE())
3810             RC = &PPC::GPRCRegClass;
3811           else
3812             RC = &PPC::F4RCRegClass;
3813           break;
3814         case MVT::f64:
3815           if (Subtarget.hasVSX())
3816             RC = &PPC::VSFRCRegClass;
3817           else if (Subtarget.hasSPE())
3818             // SPE passes doubles in GPR pairs.
3819             RC = &PPC::GPRCRegClass;
3820           else
3821             RC = &PPC::F8RCRegClass;
3822           break;
3823         case MVT::v16i8:
3824         case MVT::v8i16:
3825         case MVT::v4i32:
3826           RC = &PPC::VRRCRegClass;
3827           break;
3828         case MVT::v4f32:
3829           RC = &PPC::VRRCRegClass;
3830           break;
3831         case MVT::v2f64:
3832         case MVT::v2i64:
3833           RC = &PPC::VRRCRegClass;
3834           break;
3835       }
3836 
3837       SDValue ArgValue;
3838       // Transform the arguments stored in physical registers into
3839       // virtual ones.
3840       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3841         assert(i + 1 < e && "No second half of double precision argument");
3842         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3843         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3844         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3845         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3846         if (!Subtarget.isLittleEndian())
3847           std::swap (ArgValueLo, ArgValueHi);
3848         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3849                                ArgValueHi);
3850       } else {
3851         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3852         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3853                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3854         if (ValVT == MVT::i1)
3855           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3856       }
3857 
3858       InVals.push_back(ArgValue);
3859     } else {
3860       // Argument stored in memory.
3861       assert(VA.isMemLoc());
3862 
3863       // Get the extended size of the argument type in stack
3864       unsigned ArgSize = VA.getLocVT().getStoreSize();
3865       // Get the actual size of the argument type
3866       unsigned ObjSize = VA.getValVT().getStoreSize();
3867       unsigned ArgOffset = VA.getLocMemOffset();
3868       // Stack objects in PPC32 are right justified.
3869       ArgOffset += ArgSize - ObjSize;
3870       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3871 
3872       // Create load nodes to retrieve arguments from the stack.
3873       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3874       InVals.push_back(
3875           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3876     }
3877   }
3878 
3879   // Assign locations to all of the incoming aggregate by value arguments.
3880   // Aggregates passed by value are stored in the local variable space of the
3881   // caller's stack frame, right above the parameter list area.
3882   SmallVector<CCValAssign, 16> ByValArgLocs;
3883   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3884                       ByValArgLocs, *DAG.getContext());
3885 
3886   // Reserve stack space for the allocations in CCInfo.
3887   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
3888 
3889   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3890 
3891   // Area that is at least reserved in the caller of this function.
3892   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3893   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3894 
3895   // Set the size that is at least reserved in caller of this function.  Tail
3896   // call optimized function's reserved stack space needs to be aligned so that
3897   // taking the difference between two stack areas will result in an aligned
3898   // stack.
3899   MinReservedArea =
3900       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3901   FuncInfo->setMinReservedArea(MinReservedArea);
3902 
3903   SmallVector<SDValue, 8> MemOps;
3904 
3905   // If the function takes variable number of arguments, make a frame index for
3906   // the start of the first vararg value... for expansion of llvm.va_start.
3907   if (isVarArg) {
3908     static const MCPhysReg GPArgRegs[] = {
3909       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3910       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3911     };
3912     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3913 
3914     static const MCPhysReg FPArgRegs[] = {
3915       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3916       PPC::F8
3917     };
3918     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3919 
3920     if (useSoftFloat() || hasSPE())
3921        NumFPArgRegs = 0;
3922 
3923     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3924     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3925 
3926     // Make room for NumGPArgRegs and NumFPArgRegs.
3927     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3928                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3929 
3930     FuncInfo->setVarArgsStackOffset(
3931       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3932                             CCInfo.getNextStackOffset(), true));
3933 
3934     FuncInfo->setVarArgsFrameIndex(
3935         MFI.CreateStackObject(Depth, Align(8), false));
3936     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3937 
3938     // The fixed integer arguments of a variadic function are stored to the
3939     // VarArgsFrameIndex on the stack so that they may be loaded by
3940     // dereferencing the result of va_next.
3941     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3942       // Get an existing live-in vreg, or add a new one.
3943       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3944       if (!VReg)
3945         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3946 
3947       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3948       SDValue Store =
3949           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3950       MemOps.push_back(Store);
3951       // Increment the address by four for the next argument to store
3952       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3953       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3954     }
3955 
3956     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3957     // is set.
3958     // The double arguments are stored to the VarArgsFrameIndex
3959     // on the stack.
3960     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3961       // Get an existing live-in vreg, or add a new one.
3962       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3963       if (!VReg)
3964         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3965 
3966       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3967       SDValue Store =
3968           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3969       MemOps.push_back(Store);
3970       // Increment the address by eight for the next argument to store
3971       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3972                                          PtrVT);
3973       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3974     }
3975   }
3976 
3977   if (!MemOps.empty())
3978     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3979 
3980   return Chain;
3981 }
3982 
3983 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3984 // value to MVT::i64 and then truncate to the correct register size.
3985 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3986                                              EVT ObjectVT, SelectionDAG &DAG,
3987                                              SDValue ArgVal,
3988                                              const SDLoc &dl) const {
3989   if (Flags.isSExt())
3990     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3991                          DAG.getValueType(ObjectVT));
3992   else if (Flags.isZExt())
3993     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3994                          DAG.getValueType(ObjectVT));
3995 
3996   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3997 }
3998 
3999 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
4000     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4001     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4002     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4003   // TODO: add description of PPC stack frame format, or at least some docs.
4004   //
4005   bool isELFv2ABI = Subtarget.isELFv2ABI();
4006   bool isLittleEndian = Subtarget.isLittleEndian();
4007   MachineFunction &MF = DAG.getMachineFunction();
4008   MachineFrameInfo &MFI = MF.getFrameInfo();
4009   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4010 
4011   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4012          "fastcc not supported on varargs functions");
4013 
4014   EVT PtrVT = getPointerTy(MF.getDataLayout());
4015   // Potential tail calls could cause overwriting of argument stack slots.
4016   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4017                        (CallConv == CallingConv::Fast));
4018   unsigned PtrByteSize = 8;
4019   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4020 
4021   static const MCPhysReg GPR[] = {
4022     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4023     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4024   };
4025   static const MCPhysReg VR[] = {
4026     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4027     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4028   };
4029 
4030   const unsigned Num_GPR_Regs = array_lengthof(GPR);
4031   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4032   const unsigned Num_VR_Regs  = array_lengthof(VR);
4033 
4034   // Do a first pass over the arguments to determine whether the ABI
4035   // guarantees that our caller has allocated the parameter save area
4036   // on its stack frame.  In the ELFv1 ABI, this is always the case;
4037   // in the ELFv2 ABI, it is true if this is a vararg function or if
4038   // any parameter is located in a stack slot.
4039 
4040   bool HasParameterArea = !isELFv2ABI || isVarArg;
4041   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4042   unsigned NumBytes = LinkageSize;
4043   unsigned AvailableFPRs = Num_FPR_Regs;
4044   unsigned AvailableVRs = Num_VR_Regs;
4045   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4046     if (Ins[i].Flags.isNest())
4047       continue;
4048 
4049     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
4050                                PtrByteSize, LinkageSize, ParamAreaSize,
4051                                NumBytes, AvailableFPRs, AvailableVRs))
4052       HasParameterArea = true;
4053   }
4054 
4055   // Add DAG nodes to load the arguments or copy them out of registers.  On
4056   // entry to a function on PPC, the arguments start after the linkage area,
4057   // although the first ones are often in registers.
4058 
4059   unsigned ArgOffset = LinkageSize;
4060   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4061   SmallVector<SDValue, 8> MemOps;
4062   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4063   unsigned CurArgIdx = 0;
4064   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4065     SDValue ArgVal;
4066     bool needsLoad = false;
4067     EVT ObjectVT = Ins[ArgNo].VT;
4068     EVT OrigVT = Ins[ArgNo].ArgVT;
4069     unsigned ObjSize = ObjectVT.getStoreSize();
4070     unsigned ArgSize = ObjSize;
4071     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4072     if (Ins[ArgNo].isOrigArg()) {
4073       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4074       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4075     }
4076     // We re-align the argument offset for each argument, except when using the
4077     // fast calling convention, when we need to make sure we do that only when
4078     // we'll actually use a stack slot.
4079     unsigned CurArgOffset;
4080     Align Alignment;
4081     auto ComputeArgOffset = [&]() {
4082       /* Respect alignment of argument on the stack.  */
4083       Alignment =
4084           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4085       ArgOffset = alignTo(ArgOffset, Alignment);
4086       CurArgOffset = ArgOffset;
4087     };
4088 
4089     if (CallConv != CallingConv::Fast) {
4090       ComputeArgOffset();
4091 
4092       /* Compute GPR index associated with argument offset.  */
4093       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4094       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4095     }
4096 
4097     // FIXME the codegen can be much improved in some cases.
4098     // We do not have to keep everything in memory.
4099     if (Flags.isByVal()) {
4100       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4101 
4102       if (CallConv == CallingConv::Fast)
4103         ComputeArgOffset();
4104 
4105       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4106       ObjSize = Flags.getByValSize();
4107       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4108       // Empty aggregate parameters do not take up registers.  Examples:
4109       //   struct { } a;
4110       //   union  { } b;
4111       //   int c[0];
4112       // etc.  However, we have to provide a place-holder in InVals, so
4113       // pretend we have an 8-byte item at the current address for that
4114       // purpose.
4115       if (!ObjSize) {
4116         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4117         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4118         InVals.push_back(FIN);
4119         continue;
4120       }
4121 
4122       // Create a stack object covering all stack doublewords occupied
4123       // by the argument.  If the argument is (fully or partially) on
4124       // the stack, or if the argument is fully in registers but the
4125       // caller has allocated the parameter save anyway, we can refer
4126       // directly to the caller's stack frame.  Otherwise, create a
4127       // local copy in our own frame.
4128       int FI;
4129       if (HasParameterArea ||
4130           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4131         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4132       else
4133         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4134       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4135 
4136       // Handle aggregates smaller than 8 bytes.
4137       if (ObjSize < PtrByteSize) {
4138         // The value of the object is its address, which differs from the
4139         // address of the enclosing doubleword on big-endian systems.
4140         SDValue Arg = FIN;
4141         if (!isLittleEndian) {
4142           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4143           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4144         }
4145         InVals.push_back(Arg);
4146 
4147         if (GPR_idx != Num_GPR_Regs) {
4148           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4149           FuncInfo->addLiveInAttr(VReg, Flags);
4150           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4151           SDValue Store;
4152 
4153           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
4154             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
4155                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
4156             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4157                                       MachinePointerInfo(&*FuncArg), ObjType);
4158           } else {
4159             // For sizes that don't fit a truncating store (3, 5, 6, 7),
4160             // store the whole register as-is to the parameter save area
4161             // slot.
4162             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4163                                  MachinePointerInfo(&*FuncArg));
4164           }
4165 
4166           MemOps.push_back(Store);
4167         }
4168         // Whether we copied from a register or not, advance the offset
4169         // into the parameter save area by a full doubleword.
4170         ArgOffset += PtrByteSize;
4171         continue;
4172       }
4173 
4174       // The value of the object is its address, which is the address of
4175       // its first stack doubleword.
4176       InVals.push_back(FIN);
4177 
4178       // Store whatever pieces of the object are in registers to memory.
4179       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4180         if (GPR_idx == Num_GPR_Regs)
4181           break;
4182 
4183         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4184         FuncInfo->addLiveInAttr(VReg, Flags);
4185         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4186         SDValue Addr = FIN;
4187         if (j) {
4188           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4189           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4190         }
4191         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4192                                      MachinePointerInfo(&*FuncArg, j));
4193         MemOps.push_back(Store);
4194         ++GPR_idx;
4195       }
4196       ArgOffset += ArgSize;
4197       continue;
4198     }
4199 
4200     switch (ObjectVT.getSimpleVT().SimpleTy) {
4201     default: llvm_unreachable("Unhandled argument type!");
4202     case MVT::i1:
4203     case MVT::i32:
4204     case MVT::i64:
4205       if (Flags.isNest()) {
4206         // The 'nest' parameter, if any, is passed in R11.
4207         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4208         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4209 
4210         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4211           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4212 
4213         break;
4214       }
4215 
4216       // These can be scalar arguments or elements of an integer array type
4217       // passed directly.  Clang may use those instead of "byval" aggregate
4218       // types to avoid forcing arguments to memory unnecessarily.
4219       if (GPR_idx != Num_GPR_Regs) {
4220         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4221         FuncInfo->addLiveInAttr(VReg, Flags);
4222         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4223 
4224         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4225           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4226           // value to MVT::i64 and then truncate to the correct register size.
4227           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4228       } else {
4229         if (CallConv == CallingConv::Fast)
4230           ComputeArgOffset();
4231 
4232         needsLoad = true;
4233         ArgSize = PtrByteSize;
4234       }
4235       if (CallConv != CallingConv::Fast || needsLoad)
4236         ArgOffset += 8;
4237       break;
4238 
4239     case MVT::f32:
4240     case MVT::f64:
4241       // These can be scalar arguments or elements of a float array type
4242       // passed directly.  The latter are used to implement ELFv2 homogenous
4243       // float aggregates.
4244       if (FPR_idx != Num_FPR_Regs) {
4245         unsigned VReg;
4246 
4247         if (ObjectVT == MVT::f32)
4248           VReg = MF.addLiveIn(FPR[FPR_idx],
4249                               Subtarget.hasP8Vector()
4250                                   ? &PPC::VSSRCRegClass
4251                                   : &PPC::F4RCRegClass);
4252         else
4253           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4254                                                 ? &PPC::VSFRCRegClass
4255                                                 : &PPC::F8RCRegClass);
4256 
4257         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4258         ++FPR_idx;
4259       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4260         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4261         // once we support fp <-> gpr moves.
4262 
4263         // This can only ever happen in the presence of f32 array types,
4264         // since otherwise we never run out of FPRs before running out
4265         // of GPRs.
4266         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4267         FuncInfo->addLiveInAttr(VReg, Flags);
4268         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4269 
4270         if (ObjectVT == MVT::f32) {
4271           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4272             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4273                                  DAG.getConstant(32, dl, MVT::i32));
4274           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4275         }
4276 
4277         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4278       } else {
4279         if (CallConv == CallingConv::Fast)
4280           ComputeArgOffset();
4281 
4282         needsLoad = true;
4283       }
4284 
4285       // When passing an array of floats, the array occupies consecutive
4286       // space in the argument area; only round up to the next doubleword
4287       // at the end of the array.  Otherwise, each float takes 8 bytes.
4288       if (CallConv != CallingConv::Fast || needsLoad) {
4289         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4290         ArgOffset += ArgSize;
4291         if (Flags.isInConsecutiveRegsLast())
4292           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4293       }
4294       break;
4295     case MVT::v4f32:
4296     case MVT::v4i32:
4297     case MVT::v8i16:
4298     case MVT::v16i8:
4299     case MVT::v2f64:
4300     case MVT::v2i64:
4301     case MVT::v1i128:
4302     case MVT::f128:
4303       // These can be scalar arguments or elements of a vector array type
4304       // passed directly.  The latter are used to implement ELFv2 homogenous
4305       // vector aggregates.
4306       if (VR_idx != Num_VR_Regs) {
4307         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4308         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4309         ++VR_idx;
4310       } else {
4311         if (CallConv == CallingConv::Fast)
4312           ComputeArgOffset();
4313         needsLoad = true;
4314       }
4315       if (CallConv != CallingConv::Fast || needsLoad)
4316         ArgOffset += 16;
4317       break;
4318     }
4319 
4320     // We need to load the argument to a virtual register if we determined
4321     // above that we ran out of physical registers of the appropriate type.
4322     if (needsLoad) {
4323       if (ObjSize < ArgSize && !isLittleEndian)
4324         CurArgOffset += ArgSize - ObjSize;
4325       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4326       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4327       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4328     }
4329 
4330     InVals.push_back(ArgVal);
4331   }
4332 
4333   // Area that is at least reserved in the caller of this function.
4334   unsigned MinReservedArea;
4335   if (HasParameterArea)
4336     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4337   else
4338     MinReservedArea = LinkageSize;
4339 
4340   // Set the size that is at least reserved in caller of this function.  Tail
4341   // call optimized functions' reserved stack space needs to be aligned so that
4342   // taking the difference between two stack areas will result in an aligned
4343   // stack.
4344   MinReservedArea =
4345       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4346   FuncInfo->setMinReservedArea(MinReservedArea);
4347 
4348   // If the function takes variable number of arguments, make a frame index for
4349   // the start of the first vararg value... for expansion of llvm.va_start.
4350   // On ELFv2ABI spec, it writes:
4351   // C programs that are intended to be *portable* across different compilers
4352   // and architectures must use the header file <stdarg.h> to deal with variable
4353   // argument lists.
4354   if (isVarArg && MFI.hasVAStart()) {
4355     int Depth = ArgOffset;
4356 
4357     FuncInfo->setVarArgsFrameIndex(
4358       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4359     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4360 
4361     // If this function is vararg, store any remaining integer argument regs
4362     // to their spots on the stack so that they may be loaded by dereferencing
4363     // the result of va_next.
4364     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4365          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4366       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4367       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4368       SDValue Store =
4369           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4370       MemOps.push_back(Store);
4371       // Increment the address by four for the next argument to store
4372       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4373       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4374     }
4375   }
4376 
4377   if (!MemOps.empty())
4378     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4379 
4380   return Chain;
4381 }
4382 
4383 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4384     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4385     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4386     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4387   // TODO: add description of PPC stack frame format, or at least some docs.
4388   //
4389   MachineFunction &MF = DAG.getMachineFunction();
4390   MachineFrameInfo &MFI = MF.getFrameInfo();
4391   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4392 
4393   EVT PtrVT = getPointerTy(MF.getDataLayout());
4394   bool isPPC64 = PtrVT == MVT::i64;
4395   // Potential tail calls could cause overwriting of argument stack slots.
4396   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4397                        (CallConv == CallingConv::Fast));
4398   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4399   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4400   unsigned ArgOffset = LinkageSize;
4401   // Area that is at least reserved in caller of this function.
4402   unsigned MinReservedArea = ArgOffset;
4403 
4404   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4405     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4406     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4407   };
4408   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4409     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4410     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4411   };
4412   static const MCPhysReg VR[] = {
4413     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4414     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4415   };
4416 
4417   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4418   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4419   const unsigned Num_VR_Regs  = array_lengthof( VR);
4420 
4421   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4422 
4423   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4424 
4425   // In 32-bit non-varargs functions, the stack space for vectors is after the
4426   // stack space for non-vectors.  We do not use this space unless we have
4427   // too many vectors to fit in registers, something that only occurs in
4428   // constructed examples:), but we have to walk the arglist to figure
4429   // that out...for the pathological case, compute VecArgOffset as the
4430   // start of the vector parameter area.  Computing VecArgOffset is the
4431   // entire point of the following loop.
4432   unsigned VecArgOffset = ArgOffset;
4433   if (!isVarArg && !isPPC64) {
4434     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4435          ++ArgNo) {
4436       EVT ObjectVT = Ins[ArgNo].VT;
4437       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4438 
4439       if (Flags.isByVal()) {
4440         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4441         unsigned ObjSize = Flags.getByValSize();
4442         unsigned ArgSize =
4443                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4444         VecArgOffset += ArgSize;
4445         continue;
4446       }
4447 
4448       switch(ObjectVT.getSimpleVT().SimpleTy) {
4449       default: llvm_unreachable("Unhandled argument type!");
4450       case MVT::i1:
4451       case MVT::i32:
4452       case MVT::f32:
4453         VecArgOffset += 4;
4454         break;
4455       case MVT::i64:  // PPC64
4456       case MVT::f64:
4457         // FIXME: We are guaranteed to be !isPPC64 at this point.
4458         // Does MVT::i64 apply?
4459         VecArgOffset += 8;
4460         break;
4461       case MVT::v4f32:
4462       case MVT::v4i32:
4463       case MVT::v8i16:
4464       case MVT::v16i8:
4465         // Nothing to do, we're only looking at Nonvector args here.
4466         break;
4467       }
4468     }
4469   }
4470   // We've found where the vector parameter area in memory is.  Skip the
4471   // first 12 parameters; these don't use that memory.
4472   VecArgOffset = ((VecArgOffset+15)/16)*16;
4473   VecArgOffset += 12*16;
4474 
4475   // Add DAG nodes to load the arguments or copy them out of registers.  On
4476   // entry to a function on PPC, the arguments start after the linkage area,
4477   // although the first ones are often in registers.
4478 
4479   SmallVector<SDValue, 8> MemOps;
4480   unsigned nAltivecParamsAtEnd = 0;
4481   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4482   unsigned CurArgIdx = 0;
4483   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4484     SDValue ArgVal;
4485     bool needsLoad = false;
4486     EVT ObjectVT = Ins[ArgNo].VT;
4487     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4488     unsigned ArgSize = ObjSize;
4489     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4490     if (Ins[ArgNo].isOrigArg()) {
4491       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4492       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4493     }
4494     unsigned CurArgOffset = ArgOffset;
4495 
4496     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4497     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4498         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4499       if (isVarArg || isPPC64) {
4500         MinReservedArea = ((MinReservedArea+15)/16)*16;
4501         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4502                                                   Flags,
4503                                                   PtrByteSize);
4504       } else  nAltivecParamsAtEnd++;
4505     } else
4506       // Calculate min reserved area.
4507       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4508                                                 Flags,
4509                                                 PtrByteSize);
4510 
4511     // FIXME the codegen can be much improved in some cases.
4512     // We do not have to keep everything in memory.
4513     if (Flags.isByVal()) {
4514       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4515 
4516       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4517       ObjSize = Flags.getByValSize();
4518       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4519       // Objects of size 1 and 2 are right justified, everything else is
4520       // left justified.  This means the memory address is adjusted forwards.
4521       if (ObjSize==1 || ObjSize==2) {
4522         CurArgOffset = CurArgOffset + (4 - ObjSize);
4523       }
4524       // The value of the object is its address.
4525       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4526       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4527       InVals.push_back(FIN);
4528       if (ObjSize==1 || ObjSize==2) {
4529         if (GPR_idx != Num_GPR_Regs) {
4530           unsigned VReg;
4531           if (isPPC64)
4532             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4533           else
4534             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4535           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4536           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4537           SDValue Store =
4538               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4539                                 MachinePointerInfo(&*FuncArg), ObjType);
4540           MemOps.push_back(Store);
4541           ++GPR_idx;
4542         }
4543 
4544         ArgOffset += PtrByteSize;
4545 
4546         continue;
4547       }
4548       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4549         // Store whatever pieces of the object are in registers
4550         // to memory.  ArgOffset will be the address of the beginning
4551         // of the object.
4552         if (GPR_idx != Num_GPR_Regs) {
4553           unsigned VReg;
4554           if (isPPC64)
4555             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4556           else
4557             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4558           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4559           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4560           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4561           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4562                                        MachinePointerInfo(&*FuncArg, j));
4563           MemOps.push_back(Store);
4564           ++GPR_idx;
4565           ArgOffset += PtrByteSize;
4566         } else {
4567           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4568           break;
4569         }
4570       }
4571       continue;
4572     }
4573 
4574     switch (ObjectVT.getSimpleVT().SimpleTy) {
4575     default: llvm_unreachable("Unhandled argument type!");
4576     case MVT::i1:
4577     case MVT::i32:
4578       if (!isPPC64) {
4579         if (GPR_idx != Num_GPR_Regs) {
4580           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4581           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4582 
4583           if (ObjectVT == MVT::i1)
4584             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4585 
4586           ++GPR_idx;
4587         } else {
4588           needsLoad = true;
4589           ArgSize = PtrByteSize;
4590         }
4591         // All int arguments reserve stack space in the Darwin ABI.
4592         ArgOffset += PtrByteSize;
4593         break;
4594       }
4595       LLVM_FALLTHROUGH;
4596     case MVT::i64:  // PPC64
4597       if (GPR_idx != Num_GPR_Regs) {
4598         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4599         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4600 
4601         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4602           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4603           // value to MVT::i64 and then truncate to the correct register size.
4604           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4605 
4606         ++GPR_idx;
4607       } else {
4608         needsLoad = true;
4609         ArgSize = PtrByteSize;
4610       }
4611       // All int arguments reserve stack space in the Darwin ABI.
4612       ArgOffset += 8;
4613       break;
4614 
4615     case MVT::f32:
4616     case MVT::f64:
4617       // Every 4 bytes of argument space consumes one of the GPRs available for
4618       // argument passing.
4619       if (GPR_idx != Num_GPR_Regs) {
4620         ++GPR_idx;
4621         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4622           ++GPR_idx;
4623       }
4624       if (FPR_idx != Num_FPR_Regs) {
4625         unsigned VReg;
4626 
4627         if (ObjectVT == MVT::f32)
4628           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4629         else
4630           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4631 
4632         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4633         ++FPR_idx;
4634       } else {
4635         needsLoad = true;
4636       }
4637 
4638       // All FP arguments reserve stack space in the Darwin ABI.
4639       ArgOffset += isPPC64 ? 8 : ObjSize;
4640       break;
4641     case MVT::v4f32:
4642     case MVT::v4i32:
4643     case MVT::v8i16:
4644     case MVT::v16i8:
4645       // Note that vector arguments in registers don't reserve stack space,
4646       // except in varargs functions.
4647       if (VR_idx != Num_VR_Regs) {
4648         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4649         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4650         if (isVarArg) {
4651           while ((ArgOffset % 16) != 0) {
4652             ArgOffset += PtrByteSize;
4653             if (GPR_idx != Num_GPR_Regs)
4654               GPR_idx++;
4655           }
4656           ArgOffset += 16;
4657           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4658         }
4659         ++VR_idx;
4660       } else {
4661         if (!isVarArg && !isPPC64) {
4662           // Vectors go after all the nonvectors.
4663           CurArgOffset = VecArgOffset;
4664           VecArgOffset += 16;
4665         } else {
4666           // Vectors are aligned.
4667           ArgOffset = ((ArgOffset+15)/16)*16;
4668           CurArgOffset = ArgOffset;
4669           ArgOffset += 16;
4670         }
4671         needsLoad = true;
4672       }
4673       break;
4674     }
4675 
4676     // We need to load the argument to a virtual register if we determined above
4677     // that we ran out of physical registers of the appropriate type.
4678     if (needsLoad) {
4679       int FI = MFI.CreateFixedObject(ObjSize,
4680                                      CurArgOffset + (ArgSize - ObjSize),
4681                                      isImmutable);
4682       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4683       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4684     }
4685 
4686     InVals.push_back(ArgVal);
4687   }
4688 
4689   // Allow for Altivec parameters at the end, if needed.
4690   if (nAltivecParamsAtEnd) {
4691     MinReservedArea = ((MinReservedArea+15)/16)*16;
4692     MinReservedArea += 16*nAltivecParamsAtEnd;
4693   }
4694 
4695   // Area that is at least reserved in the caller of this function.
4696   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4697 
4698   // Set the size that is at least reserved in caller of this function.  Tail
4699   // call optimized functions' reserved stack space needs to be aligned so that
4700   // taking the difference between two stack areas will result in an aligned
4701   // stack.
4702   MinReservedArea =
4703       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4704   FuncInfo->setMinReservedArea(MinReservedArea);
4705 
4706   // If the function takes variable number of arguments, make a frame index for
4707   // the start of the first vararg value... for expansion of llvm.va_start.
4708   if (isVarArg) {
4709     int Depth = ArgOffset;
4710 
4711     FuncInfo->setVarArgsFrameIndex(
4712       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4713                             Depth, true));
4714     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4715 
4716     // If this function is vararg, store any remaining integer argument regs
4717     // to their spots on the stack so that they may be loaded by dereferencing
4718     // the result of va_next.
4719     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4720       unsigned VReg;
4721 
4722       if (isPPC64)
4723         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4724       else
4725         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4726 
4727       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4728       SDValue Store =
4729           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4730       MemOps.push_back(Store);
4731       // Increment the address by four for the next argument to store
4732       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4733       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4734     }
4735   }
4736 
4737   if (!MemOps.empty())
4738     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4739 
4740   return Chain;
4741 }
4742 
4743 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4744 /// adjusted to accommodate the arguments for the tailcall.
4745 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4746                                    unsigned ParamSize) {
4747 
4748   if (!isTailCall) return 0;
4749 
4750   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4751   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4752   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4753   // Remember only if the new adjustment is bigger.
4754   if (SPDiff < FI->getTailCallSPDelta())
4755     FI->setTailCallSPDelta(SPDiff);
4756 
4757   return SPDiff;
4758 }
4759 
4760 static bool isFunctionGlobalAddress(SDValue Callee);
4761 
4762 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4763                               const TargetMachine &TM) {
4764   // It does not make sense to call callsShareTOCBase() with a caller that
4765   // is PC Relative since PC Relative callers do not have a TOC.
4766 #ifndef NDEBUG
4767   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4768   assert(!STICaller->isUsingPCRelativeCalls() &&
4769          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4770 #endif
4771 
4772   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4773   // don't have enough information to determine if the caller and callee share
4774   // the same  TOC base, so we have to pessimistically assume they don't for
4775   // correctness.
4776   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4777   if (!G)
4778     return false;
4779 
4780   const GlobalValue *GV = G->getGlobal();
4781 
4782   // If the callee is preemptable, then the static linker will use a plt-stub
4783   // which saves the toc to the stack, and needs a nop after the call
4784   // instruction to convert to a toc-restore.
4785   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4786     return false;
4787 
4788   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4789   // We may need a TOC restore in the situation where the caller requires a
4790   // valid TOC but the callee is PC Relative and does not.
4791   const Function *F = dyn_cast<Function>(GV);
4792   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4793 
4794   // If we have an Alias we can try to get the function from there.
4795   if (Alias) {
4796     const GlobalObject *GlobalObj = Alias->getBaseObject();
4797     F = dyn_cast<Function>(GlobalObj);
4798   }
4799 
4800   // If we still have no valid function pointer we do not have enough
4801   // information to determine if the callee uses PC Relative calls so we must
4802   // assume that it does.
4803   if (!F)
4804     return false;
4805 
4806   // If the callee uses PC Relative we cannot guarantee that the callee won't
4807   // clobber the TOC of the caller and so we must assume that the two
4808   // functions do not share a TOC base.
4809   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4810   if (STICallee->isUsingPCRelativeCalls())
4811     return false;
4812 
4813   // If the GV is not a strong definition then we need to assume it can be
4814   // replaced by another function at link time. The function that replaces
4815   // it may not share the same TOC as the caller since the callee may be
4816   // replaced by a PC Relative version of the same function.
4817   if (!GV->isStrongDefinitionForLinker())
4818     return false;
4819 
4820   // The medium and large code models are expected to provide a sufficiently
4821   // large TOC to provide all data addressing needs of a module with a
4822   // single TOC.
4823   if (CodeModel::Medium == TM.getCodeModel() ||
4824       CodeModel::Large == TM.getCodeModel())
4825     return true;
4826 
4827   // Any explicitly-specified sections and section prefixes must also match.
4828   // Also, if we're using -ffunction-sections, then each function is always in
4829   // a different section (the same is true for COMDAT functions).
4830   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4831       GV->getSection() != Caller->getSection())
4832     return false;
4833   if (const auto *F = dyn_cast<Function>(GV)) {
4834     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4835       return false;
4836   }
4837 
4838   return true;
4839 }
4840 
4841 static bool
4842 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4843                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4844   assert(Subtarget.is64BitELFABI());
4845 
4846   const unsigned PtrByteSize = 8;
4847   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4848 
4849   static const MCPhysReg GPR[] = {
4850     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4851     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4852   };
4853   static const MCPhysReg VR[] = {
4854     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4855     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4856   };
4857 
4858   const unsigned NumGPRs = array_lengthof(GPR);
4859   const unsigned NumFPRs = 13;
4860   const unsigned NumVRs = array_lengthof(VR);
4861   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4862 
4863   unsigned NumBytes = LinkageSize;
4864   unsigned AvailableFPRs = NumFPRs;
4865   unsigned AvailableVRs = NumVRs;
4866 
4867   for (const ISD::OutputArg& Param : Outs) {
4868     if (Param.Flags.isNest()) continue;
4869 
4870     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4871                                LinkageSize, ParamAreaSize, NumBytes,
4872                                AvailableFPRs, AvailableVRs))
4873       return true;
4874   }
4875   return false;
4876 }
4877 
4878 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4879   if (CB.arg_size() != CallerFn->arg_size())
4880     return false;
4881 
4882   auto CalleeArgIter = CB.arg_begin();
4883   auto CalleeArgEnd = CB.arg_end();
4884   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4885 
4886   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4887     const Value* CalleeArg = *CalleeArgIter;
4888     const Value* CallerArg = &(*CallerArgIter);
4889     if (CalleeArg == CallerArg)
4890       continue;
4891 
4892     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4893     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4894     //      }
4895     // 1st argument of callee is undef and has the same type as caller.
4896     if (CalleeArg->getType() == CallerArg->getType() &&
4897         isa<UndefValue>(CalleeArg))
4898       continue;
4899 
4900     return false;
4901   }
4902 
4903   return true;
4904 }
4905 
4906 // Returns true if TCO is possible between the callers and callees
4907 // calling conventions.
4908 static bool
4909 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4910                                     CallingConv::ID CalleeCC) {
4911   // Tail calls are possible with fastcc and ccc.
4912   auto isTailCallableCC  = [] (CallingConv::ID CC){
4913       return  CC == CallingConv::C || CC == CallingConv::Fast;
4914   };
4915   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4916     return false;
4917 
4918   // We can safely tail call both fastcc and ccc callees from a c calling
4919   // convention caller. If the caller is fastcc, we may have less stack space
4920   // than a non-fastcc caller with the same signature so disable tail-calls in
4921   // that case.
4922   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4923 }
4924 
4925 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4926     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4927     const SmallVectorImpl<ISD::OutputArg> &Outs,
4928     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4929   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4930 
4931   if (DisableSCO && !TailCallOpt) return false;
4932 
4933   // Variadic argument functions are not supported.
4934   if (isVarArg) return false;
4935 
4936   auto &Caller = DAG.getMachineFunction().getFunction();
4937   // Check that the calling conventions are compatible for tco.
4938   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4939     return false;
4940 
4941   // Caller contains any byval parameter is not supported.
4942   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4943     return false;
4944 
4945   // Callee contains any byval parameter is not supported, too.
4946   // Note: This is a quick work around, because in some cases, e.g.
4947   // caller's stack size > callee's stack size, we are still able to apply
4948   // sibling call optimization. For example, gcc is able to do SCO for caller1
4949   // in the following example, but not for caller2.
4950   //   struct test {
4951   //     long int a;
4952   //     char ary[56];
4953   //   } gTest;
4954   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4955   //     b->a = v.a;
4956   //     return 0;
4957   //   }
4958   //   void caller1(struct test a, struct test c, struct test *b) {
4959   //     callee(gTest, b); }
4960   //   void caller2(struct test *b) { callee(gTest, b); }
4961   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4962     return false;
4963 
4964   // If callee and caller use different calling conventions, we cannot pass
4965   // parameters on stack since offsets for the parameter area may be different.
4966   if (Caller.getCallingConv() != CalleeCC &&
4967       needStackSlotPassParameters(Subtarget, Outs))
4968     return false;
4969 
4970   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4971   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4972   // callee potentially have different TOC bases then we cannot tail call since
4973   // we need to restore the TOC pointer after the call.
4974   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4975   // We cannot guarantee this for indirect calls or calls to external functions.
4976   // When PC-Relative addressing is used, the concept of the TOC is no longer
4977   // applicable so this check is not required.
4978   // Check first for indirect calls.
4979   if (!Subtarget.isUsingPCRelativeCalls() &&
4980       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4981     return false;
4982 
4983   // Check if we share the TOC base.
4984   if (!Subtarget.isUsingPCRelativeCalls() &&
4985       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4986     return false;
4987 
4988   // TCO allows altering callee ABI, so we don't have to check further.
4989   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4990     return true;
4991 
4992   if (DisableSCO) return false;
4993 
4994   // If callee use the same argument list that caller is using, then we can
4995   // apply SCO on this case. If it is not, then we need to check if callee needs
4996   // stack for passing arguments.
4997   // PC Relative tail calls may not have a CallBase.
4998   // If there is no CallBase we cannot verify if we have the same argument
4999   // list so assume that we don't have the same argument list.
5000   if (CB && !hasSameArgumentList(&Caller, *CB) &&
5001       needStackSlotPassParameters(Subtarget, Outs))
5002     return false;
5003   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
5004     return false;
5005 
5006   return true;
5007 }
5008 
5009 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
5010 /// for tail call optimization. Targets which want to do tail call
5011 /// optimization should implement this function.
5012 bool
5013 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
5014                                                      CallingConv::ID CalleeCC,
5015                                                      bool isVarArg,
5016                                       const SmallVectorImpl<ISD::InputArg> &Ins,
5017                                                      SelectionDAG& DAG) const {
5018   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5019     return false;
5020 
5021   // Variable argument functions are not supported.
5022   if (isVarArg)
5023     return false;
5024 
5025   MachineFunction &MF = DAG.getMachineFunction();
5026   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
5027   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
5028     // Functions containing by val parameters are not supported.
5029     for (unsigned i = 0; i != Ins.size(); i++) {
5030        ISD::ArgFlagsTy Flags = Ins[i].Flags;
5031        if (Flags.isByVal()) return false;
5032     }
5033 
5034     // Non-PIC/GOT tail calls are supported.
5035     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
5036       return true;
5037 
5038     // At the moment we can only do local tail calls (in same module, hidden
5039     // or protected) if we are generating PIC.
5040     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
5041       return G->getGlobal()->hasHiddenVisibility()
5042           || G->getGlobal()->hasProtectedVisibility();
5043   }
5044 
5045   return false;
5046 }
5047 
5048 /// isCallCompatibleAddress - Return the immediate to use if the specified
5049 /// 32-bit value is representable in the immediate field of a BxA instruction.
5050 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
5051   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5052   if (!C) return nullptr;
5053 
5054   int Addr = C->getZExtValue();
5055   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
5056       SignExtend32<26>(Addr) != Addr)
5057     return nullptr;  // Top 6 bits have to be sext of immediate.
5058 
5059   return DAG
5060       .getConstant(
5061           (int)C->getZExtValue() >> 2, SDLoc(Op),
5062           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
5063       .getNode();
5064 }
5065 
5066 namespace {
5067 
5068 struct TailCallArgumentInfo {
5069   SDValue Arg;
5070   SDValue FrameIdxOp;
5071   int FrameIdx = 0;
5072 
5073   TailCallArgumentInfo() = default;
5074 };
5075 
5076 } // end anonymous namespace
5077 
5078 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
5079 static void StoreTailCallArgumentsToStackSlot(
5080     SelectionDAG &DAG, SDValue Chain,
5081     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
5082     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
5083   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
5084     SDValue Arg = TailCallArgs[i].Arg;
5085     SDValue FIN = TailCallArgs[i].FrameIdxOp;
5086     int FI = TailCallArgs[i].FrameIdx;
5087     // Store relative to framepointer.
5088     MemOpChains.push_back(DAG.getStore(
5089         Chain, dl, Arg, FIN,
5090         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
5091   }
5092 }
5093 
5094 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
5095 /// the appropriate stack slot for the tail call optimized function call.
5096 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
5097                                              SDValue OldRetAddr, SDValue OldFP,
5098                                              int SPDiff, const SDLoc &dl) {
5099   if (SPDiff) {
5100     // Calculate the new stack slot for the return address.
5101     MachineFunction &MF = DAG.getMachineFunction();
5102     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
5103     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
5104     bool isPPC64 = Subtarget.isPPC64();
5105     int SlotSize = isPPC64 ? 8 : 4;
5106     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
5107     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
5108                                                          NewRetAddrLoc, true);
5109     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5110     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
5111     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
5112                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
5113   }
5114   return Chain;
5115 }
5116 
5117 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5118 /// the position of the argument.
5119 static void
5120 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
5121                          SDValue Arg, int SPDiff, unsigned ArgOffset,
5122                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
5123   int Offset = ArgOffset + SPDiff;
5124   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5125   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5126   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5127   SDValue FIN = DAG.getFrameIndex(FI, VT);
5128   TailCallArgumentInfo Info;
5129   Info.Arg = Arg;
5130   Info.FrameIdxOp = FIN;
5131   Info.FrameIdx = FI;
5132   TailCallArguments.push_back(Info);
5133 }
5134 
5135 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5136 /// stack slot. Returns the chain as result and the loaded frame pointers in
5137 /// LROpOut/FPOpout. Used when tail calling.
5138 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5139     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5140     SDValue &FPOpOut, const SDLoc &dl) const {
5141   if (SPDiff) {
5142     // Load the LR and FP stack slot for later adjusting.
5143     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5144     LROpOut = getReturnAddrFrameIndex(DAG);
5145     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5146     Chain = SDValue(LROpOut.getNode(), 1);
5147   }
5148   return Chain;
5149 }
5150 
5151 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5152 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5153 /// specified by the specific parameter attribute. The copy will be passed as
5154 /// a byval function parameter.
5155 /// Sometimes what we are copying is the end of a larger object, the part that
5156 /// does not fit in registers.
5157 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5158                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5159                                          SelectionDAG &DAG, const SDLoc &dl) {
5160   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5161   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5162                        Flags.getNonZeroByValAlign(), false, false, false,
5163                        MachinePointerInfo(), MachinePointerInfo());
5164 }
5165 
5166 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5167 /// tail calls.
5168 static void LowerMemOpCallTo(
5169     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5170     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5171     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5172     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5173   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5174   if (!isTailCall) {
5175     if (isVector) {
5176       SDValue StackPtr;
5177       if (isPPC64)
5178         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5179       else
5180         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5181       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5182                            DAG.getConstant(ArgOffset, dl, PtrVT));
5183     }
5184     MemOpChains.push_back(
5185         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5186     // Calculate and remember argument location.
5187   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5188                                   TailCallArguments);
5189 }
5190 
5191 static void
5192 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5193                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5194                 SDValue FPOp,
5195                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5196   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5197   // might overwrite each other in case of tail call optimization.
5198   SmallVector<SDValue, 8> MemOpChains2;
5199   // Do not flag preceding copytoreg stuff together with the following stuff.
5200   InFlag = SDValue();
5201   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5202                                     MemOpChains2, dl);
5203   if (!MemOpChains2.empty())
5204     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5205 
5206   // Store the return address to the appropriate stack slot.
5207   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5208 
5209   // Emit callseq_end just before tailcall node.
5210   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5211                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5212   InFlag = Chain.getValue(1);
5213 }
5214 
5215 // Is this global address that of a function that can be called by name? (as
5216 // opposed to something that must hold a descriptor for an indirect call).
5217 static bool isFunctionGlobalAddress(SDValue Callee) {
5218   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5219     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5220         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5221       return false;
5222 
5223     return G->getGlobal()->getValueType()->isFunctionTy();
5224   }
5225 
5226   return false;
5227 }
5228 
5229 SDValue PPCTargetLowering::LowerCallResult(
5230     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5231     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5232     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5233   SmallVector<CCValAssign, 16> RVLocs;
5234   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5235                     *DAG.getContext());
5236 
5237   CCRetInfo.AnalyzeCallResult(
5238       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5239                ? RetCC_PPC_Cold
5240                : RetCC_PPC);
5241 
5242   // Copy all of the result registers out of their specified physreg.
5243   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5244     CCValAssign &VA = RVLocs[i];
5245     assert(VA.isRegLoc() && "Can only return in registers!");
5246 
5247     SDValue Val;
5248 
5249     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5250       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5251                                       InFlag);
5252       Chain = Lo.getValue(1);
5253       InFlag = Lo.getValue(2);
5254       VA = RVLocs[++i]; // skip ahead to next loc
5255       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5256                                       InFlag);
5257       Chain = Hi.getValue(1);
5258       InFlag = Hi.getValue(2);
5259       if (!Subtarget.isLittleEndian())
5260         std::swap (Lo, Hi);
5261       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5262     } else {
5263       Val = DAG.getCopyFromReg(Chain, dl,
5264                                VA.getLocReg(), VA.getLocVT(), InFlag);
5265       Chain = Val.getValue(1);
5266       InFlag = Val.getValue(2);
5267     }
5268 
5269     switch (VA.getLocInfo()) {
5270     default: llvm_unreachable("Unknown loc info!");
5271     case CCValAssign::Full: break;
5272     case CCValAssign::AExt:
5273       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5274       break;
5275     case CCValAssign::ZExt:
5276       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5277                         DAG.getValueType(VA.getValVT()));
5278       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5279       break;
5280     case CCValAssign::SExt:
5281       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5282                         DAG.getValueType(VA.getValVT()));
5283       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5284       break;
5285     }
5286 
5287     InVals.push_back(Val);
5288   }
5289 
5290   return Chain;
5291 }
5292 
5293 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5294                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5295   // PatchPoint calls are not indirect.
5296   if (isPatchPoint)
5297     return false;
5298 
5299   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5300     return false;
5301 
5302   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5303   // becuase the immediate function pointer points to a descriptor instead of
5304   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5305   // pointer immediate points to the global entry point, while the BLA would
5306   // need to jump to the local entry point (see rL211174).
5307   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5308       isBLACompatibleAddress(Callee, DAG))
5309     return false;
5310 
5311   return true;
5312 }
5313 
5314 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5315 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5316   return Subtarget.isAIXABI() ||
5317          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5318 }
5319 
5320 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5321                               const Function &Caller,
5322                               const SDValue &Callee,
5323                               const PPCSubtarget &Subtarget,
5324                               const TargetMachine &TM) {
5325   if (CFlags.IsTailCall)
5326     return PPCISD::TC_RETURN;
5327 
5328   // This is a call through a function pointer.
5329   if (CFlags.IsIndirect) {
5330     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5331     // indirect calls. The save of the caller's TOC pointer to the stack will be
5332     // inserted into the DAG as part of call lowering. The restore of the TOC
5333     // pointer is modeled by using a pseudo instruction for the call opcode that
5334     // represents the 2 instruction sequence of an indirect branch and link,
5335     // immediately followed by a load of the TOC pointer from the the stack save
5336     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5337     // as it is not saved or used.
5338     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5339                                                : PPCISD::BCTRL;
5340   }
5341 
5342   if (Subtarget.isUsingPCRelativeCalls()) {
5343     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5344     return PPCISD::CALL_NOTOC;
5345   }
5346 
5347   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5348   // immediately following the call instruction if the caller and callee may
5349   // have different TOC bases. At link time if the linker determines the calls
5350   // may not share a TOC base, the call is redirected to a trampoline inserted
5351   // by the linker. The trampoline will (among other things) save the callers
5352   // TOC pointer at an ABI designated offset in the linkage area and the linker
5353   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5354   // into gpr2.
5355   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5356     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5357                                                   : PPCISD::CALL_NOP;
5358 
5359   return PPCISD::CALL;
5360 }
5361 
5362 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5363                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5364   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5365     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5366       return SDValue(Dest, 0);
5367 
5368   // Returns true if the callee is local, and false otherwise.
5369   auto isLocalCallee = [&]() {
5370     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5371     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5372     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5373 
5374     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5375            !dyn_cast_or_null<GlobalIFunc>(GV);
5376   };
5377 
5378   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5379   // a static relocation model causes some versions of GNU LD (2.17.50, at
5380   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5381   // built with secure-PLT.
5382   bool UsePlt =
5383       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5384       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5385 
5386   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5387     const TargetMachine &TM = Subtarget.getTargetMachine();
5388     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5389     MCSymbolXCOFF *S =
5390         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5391 
5392     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5393     return DAG.getMCSymbol(S, PtrVT);
5394   };
5395 
5396   if (isFunctionGlobalAddress(Callee)) {
5397     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5398 
5399     if (Subtarget.isAIXABI()) {
5400       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5401       return getAIXFuncEntryPointSymbolSDNode(GV);
5402     }
5403     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5404                                       UsePlt ? PPCII::MO_PLT : 0);
5405   }
5406 
5407   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5408     const char *SymName = S->getSymbol();
5409     if (Subtarget.isAIXABI()) {
5410       // If there exists a user-declared function whose name is the same as the
5411       // ExternalSymbol's, then we pick up the user-declared version.
5412       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5413       if (const Function *F =
5414               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5415         return getAIXFuncEntryPointSymbolSDNode(F);
5416 
5417       // On AIX, direct function calls reference the symbol for the function's
5418       // entry point, which is named by prepending a "." before the function's
5419       // C-linkage name. A Qualname is returned here because an external
5420       // function entry point is a csect with XTY_ER property.
5421       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5422         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5423         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5424             (Twine(".") + Twine(SymName)).str(), XCOFF::XMC_PR, XCOFF::XTY_ER,
5425             SectionKind::getMetadata());
5426         return Sec->getQualNameSymbol();
5427       };
5428 
5429       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5430     }
5431     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5432                                        UsePlt ? PPCII::MO_PLT : 0);
5433   }
5434 
5435   // No transformation needed.
5436   assert(Callee.getNode() && "What no callee?");
5437   return Callee;
5438 }
5439 
5440 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5441   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5442          "Expected a CALLSEQ_STARTSDNode.");
5443 
5444   // The last operand is the chain, except when the node has glue. If the node
5445   // has glue, then the last operand is the glue, and the chain is the second
5446   // last operand.
5447   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5448   if (LastValue.getValueType() != MVT::Glue)
5449     return LastValue;
5450 
5451   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5452 }
5453 
5454 // Creates the node that moves a functions address into the count register
5455 // to prepare for an indirect call instruction.
5456 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5457                                 SDValue &Glue, SDValue &Chain,
5458                                 const SDLoc &dl) {
5459   SDValue MTCTROps[] = {Chain, Callee, Glue};
5460   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5461   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5462                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5463   // The glue is the second value produced.
5464   Glue = Chain.getValue(1);
5465 }
5466 
5467 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5468                                           SDValue &Glue, SDValue &Chain,
5469                                           SDValue CallSeqStart,
5470                                           const CallBase *CB, const SDLoc &dl,
5471                                           bool hasNest,
5472                                           const PPCSubtarget &Subtarget) {
5473   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5474   // entry point, but to the function descriptor (the function entry point
5475   // address is part of the function descriptor though).
5476   // The function descriptor is a three doubleword structure with the
5477   // following fields: function entry point, TOC base address and
5478   // environment pointer.
5479   // Thus for a call through a function pointer, the following actions need
5480   // to be performed:
5481   //   1. Save the TOC of the caller in the TOC save area of its stack
5482   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5483   //   2. Load the address of the function entry point from the function
5484   //      descriptor.
5485   //   3. Load the TOC of the callee from the function descriptor into r2.
5486   //   4. Load the environment pointer from the function descriptor into
5487   //      r11.
5488   //   5. Branch to the function entry point address.
5489   //   6. On return of the callee, the TOC of the caller needs to be
5490   //      restored (this is done in FinishCall()).
5491   //
5492   // The loads are scheduled at the beginning of the call sequence, and the
5493   // register copies are flagged together to ensure that no other
5494   // operations can be scheduled in between. E.g. without flagging the
5495   // copies together, a TOC access in the caller could be scheduled between
5496   // the assignment of the callee TOC and the branch to the callee, which leads
5497   // to incorrect code.
5498 
5499   // Start by loading the function address from the descriptor.
5500   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5501   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5502                       ? (MachineMemOperand::MODereferenceable |
5503                          MachineMemOperand::MOInvariant)
5504                       : MachineMemOperand::MONone;
5505 
5506   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5507 
5508   // Registers used in building the DAG.
5509   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5510   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5511 
5512   // Offsets of descriptor members.
5513   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5514   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5515 
5516   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5517   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5518 
5519   // One load for the functions entry point address.
5520   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5521                                     Alignment, MMOFlags);
5522 
5523   // One for loading the TOC anchor for the module that contains the called
5524   // function.
5525   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5526   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5527   SDValue TOCPtr =
5528       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5529                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5530 
5531   // One for loading the environment pointer.
5532   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5533   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5534   SDValue LoadEnvPtr =
5535       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5536                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5537 
5538 
5539   // Then copy the newly loaded TOC anchor to the TOC pointer.
5540   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5541   Chain = TOCVal.getValue(0);
5542   Glue = TOCVal.getValue(1);
5543 
5544   // If the function call has an explicit 'nest' parameter, it takes the
5545   // place of the environment pointer.
5546   assert((!hasNest || !Subtarget.isAIXABI()) &&
5547          "Nest parameter is not supported on AIX.");
5548   if (!hasNest) {
5549     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5550     Chain = EnvVal.getValue(0);
5551     Glue = EnvVal.getValue(1);
5552   }
5553 
5554   // The rest of the indirect call sequence is the same as the non-descriptor
5555   // DAG.
5556   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5557 }
5558 
5559 static void
5560 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5561                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5562                   SelectionDAG &DAG,
5563                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5564                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5565                   const PPCSubtarget &Subtarget) {
5566   const bool IsPPC64 = Subtarget.isPPC64();
5567   // MVT for a general purpose register.
5568   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5569 
5570   // First operand is always the chain.
5571   Ops.push_back(Chain);
5572 
5573   // If it's a direct call pass the callee as the second operand.
5574   if (!CFlags.IsIndirect)
5575     Ops.push_back(Callee);
5576   else {
5577     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5578 
5579     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5580     // on the stack (this would have been done in `LowerCall_64SVR4` or
5581     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5582     // represents both the indirect branch and a load that restores the TOC
5583     // pointer from the linkage area. The operand for the TOC restore is an add
5584     // of the TOC save offset to the stack pointer. This must be the second
5585     // operand: after the chain input but before any other variadic arguments.
5586     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5587     // saved or used.
5588     if (isTOCSaveRestoreRequired(Subtarget)) {
5589       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5590 
5591       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5592       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5593       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5594       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5595       Ops.push_back(AddTOC);
5596     }
5597 
5598     // Add the register used for the environment pointer.
5599     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5600       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5601                                     RegVT));
5602 
5603 
5604     // Add CTR register as callee so a bctr can be emitted later.
5605     if (CFlags.IsTailCall)
5606       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5607   }
5608 
5609   // If this is a tail call add stack pointer delta.
5610   if (CFlags.IsTailCall)
5611     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5612 
5613   // Add argument registers to the end of the list so that they are known live
5614   // into the call.
5615   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5616     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5617                                   RegsToPass[i].second.getValueType()));
5618 
5619   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5620   // no way to mark dependencies as implicit here.
5621   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5622   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5623        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5624     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5625 
5626   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5627   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5628     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5629 
5630   // Add a register mask operand representing the call-preserved registers.
5631   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5632   const uint32_t *Mask =
5633       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5634   assert(Mask && "Missing call preserved mask for calling convention");
5635   Ops.push_back(DAG.getRegisterMask(Mask));
5636 
5637   // If the glue is valid, it is the last operand.
5638   if (Glue.getNode())
5639     Ops.push_back(Glue);
5640 }
5641 
5642 SDValue PPCTargetLowering::FinishCall(
5643     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5644     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5645     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5646     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5647     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5648 
5649   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5650       Subtarget.isAIXABI())
5651     setUsesTOCBasePtr(DAG);
5652 
5653   unsigned CallOpc =
5654       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5655                     Subtarget, DAG.getTarget());
5656 
5657   if (!CFlags.IsIndirect)
5658     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5659   else if (Subtarget.usesFunctionDescriptors())
5660     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5661                                   dl, CFlags.HasNest, Subtarget);
5662   else
5663     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5664 
5665   // Build the operand list for the call instruction.
5666   SmallVector<SDValue, 8> Ops;
5667   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5668                     SPDiff, Subtarget);
5669 
5670   // Emit tail call.
5671   if (CFlags.IsTailCall) {
5672     // Indirect tail call when using PC Relative calls do not have the same
5673     // constraints.
5674     assert(((Callee.getOpcode() == ISD::Register &&
5675              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5676             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5677             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5678             isa<ConstantSDNode>(Callee) ||
5679             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5680            "Expecting a global address, external symbol, absolute value, "
5681            "register or an indirect tail call when PC Relative calls are "
5682            "used.");
5683     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5684     assert(CallOpc == PPCISD::TC_RETURN &&
5685            "Unexpected call opcode for a tail call.");
5686     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5687     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5688   }
5689 
5690   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5691   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5692   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5693   Glue = Chain.getValue(1);
5694 
5695   // When performing tail call optimization the callee pops its arguments off
5696   // the stack. Account for this here so these bytes can be pushed back on in
5697   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5698   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5699                          getTargetMachine().Options.GuaranteedTailCallOpt)
5700                             ? NumBytes
5701                             : 0;
5702 
5703   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5704                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5705                              Glue, dl);
5706   Glue = Chain.getValue(1);
5707 
5708   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5709                          DAG, InVals);
5710 }
5711 
5712 SDValue
5713 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5714                              SmallVectorImpl<SDValue> &InVals) const {
5715   SelectionDAG &DAG                     = CLI.DAG;
5716   SDLoc &dl                             = CLI.DL;
5717   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5718   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5719   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5720   SDValue Chain                         = CLI.Chain;
5721   SDValue Callee                        = CLI.Callee;
5722   bool &isTailCall                      = CLI.IsTailCall;
5723   CallingConv::ID CallConv              = CLI.CallConv;
5724   bool isVarArg                         = CLI.IsVarArg;
5725   bool isPatchPoint                     = CLI.IsPatchPoint;
5726   const CallBase *CB                    = CLI.CB;
5727 
5728   if (isTailCall) {
5729     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5730       isTailCall = false;
5731     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5732       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5733           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5734     else
5735       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5736                                                      Ins, DAG);
5737     if (isTailCall) {
5738       ++NumTailCalls;
5739       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5740         ++NumSiblingCalls;
5741 
5742       // PC Relative calls no longer guarantee that the callee is a Global
5743       // Address Node. The callee could be an indirect tail call in which
5744       // case the SDValue for the callee could be a load (to load the address
5745       // of a function pointer) or it may be a register copy (to move the
5746       // address of the callee from a function parameter into a virtual
5747       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5748       assert((Subtarget.isUsingPCRelativeCalls() ||
5749               isa<GlobalAddressSDNode>(Callee)) &&
5750              "Callee should be an llvm::Function object.");
5751 
5752       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5753                         << "\nTCO callee: ");
5754       LLVM_DEBUG(Callee.dump());
5755     }
5756   }
5757 
5758   if (!isTailCall && CB && CB->isMustTailCall())
5759     report_fatal_error("failed to perform tail call elimination on a call "
5760                        "site marked musttail");
5761 
5762   // When long calls (i.e. indirect calls) are always used, calls are always
5763   // made via function pointer. If we have a function name, first translate it
5764   // into a pointer.
5765   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5766       !isTailCall)
5767     Callee = LowerGlobalAddress(Callee, DAG);
5768 
5769   CallFlags CFlags(
5770       CallConv, isTailCall, isVarArg, isPatchPoint,
5771       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5772       // hasNest
5773       Subtarget.is64BitELFABI() &&
5774           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5775       CLI.NoMerge);
5776 
5777   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5778     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5779                             InVals, CB);
5780 
5781   if (Subtarget.isSVR4ABI())
5782     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5783                             InVals, CB);
5784 
5785   if (Subtarget.isAIXABI())
5786     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5787                          InVals, CB);
5788 
5789   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5790                           InVals, CB);
5791 }
5792 
5793 SDValue PPCTargetLowering::LowerCall_32SVR4(
5794     SDValue Chain, SDValue Callee, CallFlags CFlags,
5795     const SmallVectorImpl<ISD::OutputArg> &Outs,
5796     const SmallVectorImpl<SDValue> &OutVals,
5797     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5798     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5799     const CallBase *CB) const {
5800   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5801   // of the 32-bit SVR4 ABI stack frame layout.
5802 
5803   const CallingConv::ID CallConv = CFlags.CallConv;
5804   const bool IsVarArg = CFlags.IsVarArg;
5805   const bool IsTailCall = CFlags.IsTailCall;
5806 
5807   assert((CallConv == CallingConv::C ||
5808           CallConv == CallingConv::Cold ||
5809           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5810 
5811   const Align PtrAlign(4);
5812 
5813   MachineFunction &MF = DAG.getMachineFunction();
5814 
5815   // Mark this function as potentially containing a function that contains a
5816   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5817   // and restoring the callers stack pointer in this functions epilog. This is
5818   // done because by tail calling the called function might overwrite the value
5819   // in this function's (MF) stack pointer stack slot 0(SP).
5820   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5821       CallConv == CallingConv::Fast)
5822     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5823 
5824   // Count how many bytes are to be pushed on the stack, including the linkage
5825   // area, parameter list area and the part of the local variable space which
5826   // contains copies of aggregates which are passed by value.
5827 
5828   // Assign locations to all of the outgoing arguments.
5829   SmallVector<CCValAssign, 16> ArgLocs;
5830   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5831 
5832   // Reserve space for the linkage area on the stack.
5833   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5834                        PtrAlign);
5835   if (useSoftFloat())
5836     CCInfo.PreAnalyzeCallOperands(Outs);
5837 
5838   if (IsVarArg) {
5839     // Handle fixed and variable vector arguments differently.
5840     // Fixed vector arguments go into registers as long as registers are
5841     // available. Variable vector arguments always go into memory.
5842     unsigned NumArgs = Outs.size();
5843 
5844     for (unsigned i = 0; i != NumArgs; ++i) {
5845       MVT ArgVT = Outs[i].VT;
5846       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5847       bool Result;
5848 
5849       if (Outs[i].IsFixed) {
5850         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5851                                CCInfo);
5852       } else {
5853         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5854                                       ArgFlags, CCInfo);
5855       }
5856 
5857       if (Result) {
5858 #ifndef NDEBUG
5859         errs() << "Call operand #" << i << " has unhandled type "
5860              << EVT(ArgVT).getEVTString() << "\n";
5861 #endif
5862         llvm_unreachable(nullptr);
5863       }
5864     }
5865   } else {
5866     // All arguments are treated the same.
5867     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5868   }
5869   CCInfo.clearWasPPCF128();
5870 
5871   // Assign locations to all of the outgoing aggregate by value arguments.
5872   SmallVector<CCValAssign, 16> ByValArgLocs;
5873   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5874 
5875   // Reserve stack space for the allocations in CCInfo.
5876   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5877 
5878   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5879 
5880   // Size of the linkage area, parameter list area and the part of the local
5881   // space variable where copies of aggregates which are passed by value are
5882   // stored.
5883   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5884 
5885   // Calculate by how many bytes the stack has to be adjusted in case of tail
5886   // call optimization.
5887   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5888 
5889   // Adjust the stack pointer for the new arguments...
5890   // These operations are automatically eliminated by the prolog/epilog pass
5891   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5892   SDValue CallSeqStart = Chain;
5893 
5894   // Load the return address and frame pointer so it can be moved somewhere else
5895   // later.
5896   SDValue LROp, FPOp;
5897   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5898 
5899   // Set up a copy of the stack pointer for use loading and storing any
5900   // arguments that may not fit in the registers available for argument
5901   // passing.
5902   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5903 
5904   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5905   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5906   SmallVector<SDValue, 8> MemOpChains;
5907 
5908   bool seenFloatArg = false;
5909   // Walk the register/memloc assignments, inserting copies/loads.
5910   // i - Tracks the index into the list of registers allocated for the call
5911   // RealArgIdx - Tracks the index into the list of actual function arguments
5912   // j - Tracks the index into the list of byval arguments
5913   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5914        i != e;
5915        ++i, ++RealArgIdx) {
5916     CCValAssign &VA = ArgLocs[i];
5917     SDValue Arg = OutVals[RealArgIdx];
5918     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5919 
5920     if (Flags.isByVal()) {
5921       // Argument is an aggregate which is passed by value, thus we need to
5922       // create a copy of it in the local variable space of the current stack
5923       // frame (which is the stack frame of the caller) and pass the address of
5924       // this copy to the callee.
5925       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5926       CCValAssign &ByValVA = ByValArgLocs[j++];
5927       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5928 
5929       // Memory reserved in the local variable space of the callers stack frame.
5930       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5931 
5932       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5933       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5934                            StackPtr, PtrOff);
5935 
5936       // Create a copy of the argument in the local area of the current
5937       // stack frame.
5938       SDValue MemcpyCall =
5939         CreateCopyOfByValArgument(Arg, PtrOff,
5940                                   CallSeqStart.getNode()->getOperand(0),
5941                                   Flags, DAG, dl);
5942 
5943       // This must go outside the CALLSEQ_START..END.
5944       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5945                                                      SDLoc(MemcpyCall));
5946       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5947                              NewCallSeqStart.getNode());
5948       Chain = CallSeqStart = NewCallSeqStart;
5949 
5950       // Pass the address of the aggregate copy on the stack either in a
5951       // physical register or in the parameter list area of the current stack
5952       // frame to the callee.
5953       Arg = PtrOff;
5954     }
5955 
5956     // When useCRBits() is true, there can be i1 arguments.
5957     // It is because getRegisterType(MVT::i1) => MVT::i1,
5958     // and for other integer types getRegisterType() => MVT::i32.
5959     // Extend i1 and ensure callee will get i32.
5960     if (Arg.getValueType() == MVT::i1)
5961       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5962                         dl, MVT::i32, Arg);
5963 
5964     if (VA.isRegLoc()) {
5965       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5966       // Put argument in a physical register.
5967       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5968         bool IsLE = Subtarget.isLittleEndian();
5969         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5970                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5971         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5972         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5973                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5974         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5975                              SVal.getValue(0)));
5976       } else
5977         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5978     } else {
5979       // Put argument in the parameter list area of the current stack frame.
5980       assert(VA.isMemLoc());
5981       unsigned LocMemOffset = VA.getLocMemOffset();
5982 
5983       if (!IsTailCall) {
5984         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5985         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5986                              StackPtr, PtrOff);
5987 
5988         MemOpChains.push_back(
5989             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5990       } else {
5991         // Calculate and remember argument location.
5992         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5993                                  TailCallArguments);
5994       }
5995     }
5996   }
5997 
5998   if (!MemOpChains.empty())
5999     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6000 
6001   // Build a sequence of copy-to-reg nodes chained together with token chain
6002   // and flag operands which copy the outgoing args into the appropriate regs.
6003   SDValue InFlag;
6004   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6005     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6006                              RegsToPass[i].second, InFlag);
6007     InFlag = Chain.getValue(1);
6008   }
6009 
6010   // Set CR bit 6 to true if this is a vararg call with floating args passed in
6011   // registers.
6012   if (IsVarArg) {
6013     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
6014     SDValue Ops[] = { Chain, InFlag };
6015 
6016     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
6017                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
6018 
6019     InFlag = Chain.getValue(1);
6020   }
6021 
6022   if (IsTailCall)
6023     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6024                     TailCallArguments);
6025 
6026   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6027                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6028 }
6029 
6030 // Copy an argument into memory, being careful to do this outside the
6031 // call sequence for the call to which the argument belongs.
6032 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
6033     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
6034     SelectionDAG &DAG, const SDLoc &dl) const {
6035   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
6036                         CallSeqStart.getNode()->getOperand(0),
6037                         Flags, DAG, dl);
6038   // The MEMCPY must go outside the CALLSEQ_START..END.
6039   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
6040   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
6041                                                  SDLoc(MemcpyCall));
6042   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
6043                          NewCallSeqStart.getNode());
6044   return NewCallSeqStart;
6045 }
6046 
6047 SDValue PPCTargetLowering::LowerCall_64SVR4(
6048     SDValue Chain, SDValue Callee, CallFlags CFlags,
6049     const SmallVectorImpl<ISD::OutputArg> &Outs,
6050     const SmallVectorImpl<SDValue> &OutVals,
6051     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6052     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6053     const CallBase *CB) const {
6054   bool isELFv2ABI = Subtarget.isELFv2ABI();
6055   bool isLittleEndian = Subtarget.isLittleEndian();
6056   unsigned NumOps = Outs.size();
6057   bool IsSibCall = false;
6058   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
6059 
6060   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6061   unsigned PtrByteSize = 8;
6062 
6063   MachineFunction &MF = DAG.getMachineFunction();
6064 
6065   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
6066     IsSibCall = true;
6067 
6068   // Mark this function as potentially containing a function that contains a
6069   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6070   // and restoring the callers stack pointer in this functions epilog. This is
6071   // done because by tail calling the called function might overwrite the value
6072   // in this function's (MF) stack pointer stack slot 0(SP).
6073   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6074     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6075 
6076   assert(!(IsFastCall && CFlags.IsVarArg) &&
6077          "fastcc not supported on varargs functions");
6078 
6079   // Count how many bytes are to be pushed on the stack, including the linkage
6080   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
6081   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
6082   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
6083   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6084   unsigned NumBytes = LinkageSize;
6085   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6086 
6087   static const MCPhysReg GPR[] = {
6088     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6089     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6090   };
6091   static const MCPhysReg VR[] = {
6092     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6093     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6094   };
6095 
6096   const unsigned NumGPRs = array_lengthof(GPR);
6097   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
6098   const unsigned NumVRs  = array_lengthof(VR);
6099 
6100   // On ELFv2, we can avoid allocating the parameter area if all the arguments
6101   // can be passed to the callee in registers.
6102   // For the fast calling convention, there is another check below.
6103   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6104   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6105   if (!HasParameterArea) {
6106     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6107     unsigned AvailableFPRs = NumFPRs;
6108     unsigned AvailableVRs = NumVRs;
6109     unsigned NumBytesTmp = NumBytes;
6110     for (unsigned i = 0; i != NumOps; ++i) {
6111       if (Outs[i].Flags.isNest()) continue;
6112       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6113                                  PtrByteSize, LinkageSize, ParamAreaSize,
6114                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
6115         HasParameterArea = true;
6116     }
6117   }
6118 
6119   // When using the fast calling convention, we don't provide backing for
6120   // arguments that will be in registers.
6121   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6122 
6123   // Avoid allocating parameter area for fastcc functions if all the arguments
6124   // can be passed in the registers.
6125   if (IsFastCall)
6126     HasParameterArea = false;
6127 
6128   // Add up all the space actually used.
6129   for (unsigned i = 0; i != NumOps; ++i) {
6130     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6131     EVT ArgVT = Outs[i].VT;
6132     EVT OrigVT = Outs[i].ArgVT;
6133 
6134     if (Flags.isNest())
6135       continue;
6136 
6137     if (IsFastCall) {
6138       if (Flags.isByVal()) {
6139         NumGPRsUsed += (Flags.getByValSize()+7)/8;
6140         if (NumGPRsUsed > NumGPRs)
6141           HasParameterArea = true;
6142       } else {
6143         switch (ArgVT.getSimpleVT().SimpleTy) {
6144         default: llvm_unreachable("Unexpected ValueType for argument!");
6145         case MVT::i1:
6146         case MVT::i32:
6147         case MVT::i64:
6148           if (++NumGPRsUsed <= NumGPRs)
6149             continue;
6150           break;
6151         case MVT::v4i32:
6152         case MVT::v8i16:
6153         case MVT::v16i8:
6154         case MVT::v2f64:
6155         case MVT::v2i64:
6156         case MVT::v1i128:
6157         case MVT::f128:
6158           if (++NumVRsUsed <= NumVRs)
6159             continue;
6160           break;
6161         case MVT::v4f32:
6162           if (++NumVRsUsed <= NumVRs)
6163             continue;
6164           break;
6165         case MVT::f32:
6166         case MVT::f64:
6167           if (++NumFPRsUsed <= NumFPRs)
6168             continue;
6169           break;
6170         }
6171         HasParameterArea = true;
6172       }
6173     }
6174 
6175     /* Respect alignment of argument on the stack.  */
6176     auto Alignement =
6177         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6178     NumBytes = alignTo(NumBytes, Alignement);
6179 
6180     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6181     if (Flags.isInConsecutiveRegsLast())
6182       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6183   }
6184 
6185   unsigned NumBytesActuallyUsed = NumBytes;
6186 
6187   // In the old ELFv1 ABI,
6188   // the prolog code of the callee may store up to 8 GPR argument registers to
6189   // the stack, allowing va_start to index over them in memory if its varargs.
6190   // Because we cannot tell if this is needed on the caller side, we have to
6191   // conservatively assume that it is needed.  As such, make sure we have at
6192   // least enough stack space for the caller to store the 8 GPRs.
6193   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6194   // really requires memory operands, e.g. a vararg function.
6195   if (HasParameterArea)
6196     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6197   else
6198     NumBytes = LinkageSize;
6199 
6200   // Tail call needs the stack to be aligned.
6201   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6202     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6203 
6204   int SPDiff = 0;
6205 
6206   // Calculate by how many bytes the stack has to be adjusted in case of tail
6207   // call optimization.
6208   if (!IsSibCall)
6209     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6210 
6211   // To protect arguments on the stack from being clobbered in a tail call,
6212   // force all the loads to happen before doing any other lowering.
6213   if (CFlags.IsTailCall)
6214     Chain = DAG.getStackArgumentTokenFactor(Chain);
6215 
6216   // Adjust the stack pointer for the new arguments...
6217   // These operations are automatically eliminated by the prolog/epilog pass
6218   if (!IsSibCall)
6219     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6220   SDValue CallSeqStart = Chain;
6221 
6222   // Load the return address and frame pointer so it can be move somewhere else
6223   // later.
6224   SDValue LROp, FPOp;
6225   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6226 
6227   // Set up a copy of the stack pointer for use loading and storing any
6228   // arguments that may not fit in the registers available for argument
6229   // passing.
6230   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6231 
6232   // Figure out which arguments are going to go in registers, and which in
6233   // memory.  Also, if this is a vararg function, floating point operations
6234   // must be stored to our stack, and loaded into integer regs as well, if
6235   // any integer regs are available for argument passing.
6236   unsigned ArgOffset = LinkageSize;
6237 
6238   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6239   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6240 
6241   SmallVector<SDValue, 8> MemOpChains;
6242   for (unsigned i = 0; i != NumOps; ++i) {
6243     SDValue Arg = OutVals[i];
6244     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6245     EVT ArgVT = Outs[i].VT;
6246     EVT OrigVT = Outs[i].ArgVT;
6247 
6248     // PtrOff will be used to store the current argument to the stack if a
6249     // register cannot be found for it.
6250     SDValue PtrOff;
6251 
6252     // We re-align the argument offset for each argument, except when using the
6253     // fast calling convention, when we need to make sure we do that only when
6254     // we'll actually use a stack slot.
6255     auto ComputePtrOff = [&]() {
6256       /* Respect alignment of argument on the stack.  */
6257       auto Alignment =
6258           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6259       ArgOffset = alignTo(ArgOffset, Alignment);
6260 
6261       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6262 
6263       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6264     };
6265 
6266     if (!IsFastCall) {
6267       ComputePtrOff();
6268 
6269       /* Compute GPR index associated with argument offset.  */
6270       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6271       GPR_idx = std::min(GPR_idx, NumGPRs);
6272     }
6273 
6274     // Promote integers to 64-bit values.
6275     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6276       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6277       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6278       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6279     }
6280 
6281     // FIXME memcpy is used way more than necessary.  Correctness first.
6282     // Note: "by value" is code for passing a structure by value, not
6283     // basic types.
6284     if (Flags.isByVal()) {
6285       // Note: Size includes alignment padding, so
6286       //   struct x { short a; char b; }
6287       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6288       // These are the proper values we need for right-justifying the
6289       // aggregate in a parameter register.
6290       unsigned Size = Flags.getByValSize();
6291 
6292       // An empty aggregate parameter takes up no storage and no
6293       // registers.
6294       if (Size == 0)
6295         continue;
6296 
6297       if (IsFastCall)
6298         ComputePtrOff();
6299 
6300       // All aggregates smaller than 8 bytes must be passed right-justified.
6301       if (Size==1 || Size==2 || Size==4) {
6302         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6303         if (GPR_idx != NumGPRs) {
6304           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6305                                         MachinePointerInfo(), VT);
6306           MemOpChains.push_back(Load.getValue(1));
6307           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6308 
6309           ArgOffset += PtrByteSize;
6310           continue;
6311         }
6312       }
6313 
6314       if (GPR_idx == NumGPRs && Size < 8) {
6315         SDValue AddPtr = PtrOff;
6316         if (!isLittleEndian) {
6317           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6318                                           PtrOff.getValueType());
6319           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6320         }
6321         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6322                                                           CallSeqStart,
6323                                                           Flags, DAG, dl);
6324         ArgOffset += PtrByteSize;
6325         continue;
6326       }
6327       // Copy entire object into memory.  There are cases where gcc-generated
6328       // code assumes it is there, even if it could be put entirely into
6329       // registers.  (This is not what the doc says.)
6330 
6331       // FIXME: The above statement is likely due to a misunderstanding of the
6332       // documents.  All arguments must be copied into the parameter area BY
6333       // THE CALLEE in the event that the callee takes the address of any
6334       // formal argument.  That has not yet been implemented.  However, it is
6335       // reasonable to use the stack area as a staging area for the register
6336       // load.
6337 
6338       // Skip this for small aggregates, as we will use the same slot for a
6339       // right-justified copy, below.
6340       if (Size >= 8)
6341         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6342                                                           CallSeqStart,
6343                                                           Flags, DAG, dl);
6344 
6345       // When a register is available, pass a small aggregate right-justified.
6346       if (Size < 8 && GPR_idx != NumGPRs) {
6347         // The easiest way to get this right-justified in a register
6348         // is to copy the structure into the rightmost portion of a
6349         // local variable slot, then load the whole slot into the
6350         // register.
6351         // FIXME: The memcpy seems to produce pretty awful code for
6352         // small aggregates, particularly for packed ones.
6353         // FIXME: It would be preferable to use the slot in the
6354         // parameter save area instead of a new local variable.
6355         SDValue AddPtr = PtrOff;
6356         if (!isLittleEndian) {
6357           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6358           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6359         }
6360         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6361                                                           CallSeqStart,
6362                                                           Flags, DAG, dl);
6363 
6364         // Load the slot into the register.
6365         SDValue Load =
6366             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6367         MemOpChains.push_back(Load.getValue(1));
6368         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6369 
6370         // Done with this argument.
6371         ArgOffset += PtrByteSize;
6372         continue;
6373       }
6374 
6375       // For aggregates larger than PtrByteSize, copy the pieces of the
6376       // object that fit into registers from the parameter save area.
6377       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6378         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6379         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6380         if (GPR_idx != NumGPRs) {
6381           SDValue Load =
6382               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6383           MemOpChains.push_back(Load.getValue(1));
6384           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6385           ArgOffset += PtrByteSize;
6386         } else {
6387           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6388           break;
6389         }
6390       }
6391       continue;
6392     }
6393 
6394     switch (Arg.getSimpleValueType().SimpleTy) {
6395     default: llvm_unreachable("Unexpected ValueType for argument!");
6396     case MVT::i1:
6397     case MVT::i32:
6398     case MVT::i64:
6399       if (Flags.isNest()) {
6400         // The 'nest' parameter, if any, is passed in R11.
6401         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6402         break;
6403       }
6404 
6405       // These can be scalar arguments or elements of an integer array type
6406       // passed directly.  Clang may use those instead of "byval" aggregate
6407       // types to avoid forcing arguments to memory unnecessarily.
6408       if (GPR_idx != NumGPRs) {
6409         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6410       } else {
6411         if (IsFastCall)
6412           ComputePtrOff();
6413 
6414         assert(HasParameterArea &&
6415                "Parameter area must exist to pass an argument in memory.");
6416         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6417                          true, CFlags.IsTailCall, false, MemOpChains,
6418                          TailCallArguments, dl);
6419         if (IsFastCall)
6420           ArgOffset += PtrByteSize;
6421       }
6422       if (!IsFastCall)
6423         ArgOffset += PtrByteSize;
6424       break;
6425     case MVT::f32:
6426     case MVT::f64: {
6427       // These can be scalar arguments or elements of a float array type
6428       // passed directly.  The latter are used to implement ELFv2 homogenous
6429       // float aggregates.
6430 
6431       // Named arguments go into FPRs first, and once they overflow, the
6432       // remaining arguments go into GPRs and then the parameter save area.
6433       // Unnamed arguments for vararg functions always go to GPRs and
6434       // then the parameter save area.  For now, put all arguments to vararg
6435       // routines always in both locations (FPR *and* GPR or stack slot).
6436       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6437       bool NeededLoad = false;
6438 
6439       // First load the argument into the next available FPR.
6440       if (FPR_idx != NumFPRs)
6441         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6442 
6443       // Next, load the argument into GPR or stack slot if needed.
6444       if (!NeedGPROrStack)
6445         ;
6446       else if (GPR_idx != NumGPRs && !IsFastCall) {
6447         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6448         // once we support fp <-> gpr moves.
6449 
6450         // In the non-vararg case, this can only ever happen in the
6451         // presence of f32 array types, since otherwise we never run
6452         // out of FPRs before running out of GPRs.
6453         SDValue ArgVal;
6454 
6455         // Double values are always passed in a single GPR.
6456         if (Arg.getValueType() != MVT::f32) {
6457           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6458 
6459         // Non-array float values are extended and passed in a GPR.
6460         } else if (!Flags.isInConsecutiveRegs()) {
6461           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6462           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6463 
6464         // If we have an array of floats, we collect every odd element
6465         // together with its predecessor into one GPR.
6466         } else if (ArgOffset % PtrByteSize != 0) {
6467           SDValue Lo, Hi;
6468           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6469           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6470           if (!isLittleEndian)
6471             std::swap(Lo, Hi);
6472           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6473 
6474         // The final element, if even, goes into the first half of a GPR.
6475         } else if (Flags.isInConsecutiveRegsLast()) {
6476           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6477           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6478           if (!isLittleEndian)
6479             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6480                                  DAG.getConstant(32, dl, MVT::i32));
6481 
6482         // Non-final even elements are skipped; they will be handled
6483         // together the with subsequent argument on the next go-around.
6484         } else
6485           ArgVal = SDValue();
6486 
6487         if (ArgVal.getNode())
6488           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6489       } else {
6490         if (IsFastCall)
6491           ComputePtrOff();
6492 
6493         // Single-precision floating-point values are mapped to the
6494         // second (rightmost) word of the stack doubleword.
6495         if (Arg.getValueType() == MVT::f32 &&
6496             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6497           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6498           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6499         }
6500 
6501         assert(HasParameterArea &&
6502                "Parameter area must exist to pass an argument in memory.");
6503         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6504                          true, CFlags.IsTailCall, false, MemOpChains,
6505                          TailCallArguments, dl);
6506 
6507         NeededLoad = true;
6508       }
6509       // When passing an array of floats, the array occupies consecutive
6510       // space in the argument area; only round up to the next doubleword
6511       // at the end of the array.  Otherwise, each float takes 8 bytes.
6512       if (!IsFastCall || NeededLoad) {
6513         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6514                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6515         if (Flags.isInConsecutiveRegsLast())
6516           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6517       }
6518       break;
6519     }
6520     case MVT::v4f32:
6521     case MVT::v4i32:
6522     case MVT::v8i16:
6523     case MVT::v16i8:
6524     case MVT::v2f64:
6525     case MVT::v2i64:
6526     case MVT::v1i128:
6527     case MVT::f128:
6528       // These can be scalar arguments or elements of a vector array type
6529       // passed directly.  The latter are used to implement ELFv2 homogenous
6530       // vector aggregates.
6531 
6532       // For a varargs call, named arguments go into VRs or on the stack as
6533       // usual; unnamed arguments always go to the stack or the corresponding
6534       // GPRs when within range.  For now, we always put the value in both
6535       // locations (or even all three).
6536       if (CFlags.IsVarArg) {
6537         assert(HasParameterArea &&
6538                "Parameter area must exist if we have a varargs call.");
6539         // We could elide this store in the case where the object fits
6540         // entirely in R registers.  Maybe later.
6541         SDValue Store =
6542             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6543         MemOpChains.push_back(Store);
6544         if (VR_idx != NumVRs) {
6545           SDValue Load =
6546               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6547           MemOpChains.push_back(Load.getValue(1));
6548           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6549         }
6550         ArgOffset += 16;
6551         for (unsigned i=0; i<16; i+=PtrByteSize) {
6552           if (GPR_idx == NumGPRs)
6553             break;
6554           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6555                                    DAG.getConstant(i, dl, PtrVT));
6556           SDValue Load =
6557               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6558           MemOpChains.push_back(Load.getValue(1));
6559           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6560         }
6561         break;
6562       }
6563 
6564       // Non-varargs Altivec params go into VRs or on the stack.
6565       if (VR_idx != NumVRs) {
6566         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6567       } else {
6568         if (IsFastCall)
6569           ComputePtrOff();
6570 
6571         assert(HasParameterArea &&
6572                "Parameter area must exist to pass an argument in memory.");
6573         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6574                          true, CFlags.IsTailCall, true, MemOpChains,
6575                          TailCallArguments, dl);
6576         if (IsFastCall)
6577           ArgOffset += 16;
6578       }
6579 
6580       if (!IsFastCall)
6581         ArgOffset += 16;
6582       break;
6583     }
6584   }
6585 
6586   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6587          "mismatch in size of parameter area");
6588   (void)NumBytesActuallyUsed;
6589 
6590   if (!MemOpChains.empty())
6591     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6592 
6593   // Check if this is an indirect call (MTCTR/BCTRL).
6594   // See prepareDescriptorIndirectCall and buildCallOperands for more
6595   // information about calls through function pointers in the 64-bit SVR4 ABI.
6596   if (CFlags.IsIndirect) {
6597     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6598     // caller in the TOC save area.
6599     if (isTOCSaveRestoreRequired(Subtarget)) {
6600       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6601       // Load r2 into a virtual register and store it to the TOC save area.
6602       setUsesTOCBasePtr(DAG);
6603       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6604       // TOC save area offset.
6605       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6606       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6607       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6608       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6609                            MachinePointerInfo::getStack(
6610                                DAG.getMachineFunction(), TOCSaveOffset));
6611     }
6612     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6613     // This does not mean the MTCTR instruction must use R12; it's easier
6614     // to model this as an extra parameter, so do that.
6615     if (isELFv2ABI && !CFlags.IsPatchPoint)
6616       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6617   }
6618 
6619   // Build a sequence of copy-to-reg nodes chained together with token chain
6620   // and flag operands which copy the outgoing args into the appropriate regs.
6621   SDValue InFlag;
6622   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6623     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6624                              RegsToPass[i].second, InFlag);
6625     InFlag = Chain.getValue(1);
6626   }
6627 
6628   if (CFlags.IsTailCall && !IsSibCall)
6629     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6630                     TailCallArguments);
6631 
6632   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6633                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6634 }
6635 
6636 SDValue PPCTargetLowering::LowerCall_Darwin(
6637     SDValue Chain, SDValue Callee, CallFlags CFlags,
6638     const SmallVectorImpl<ISD::OutputArg> &Outs,
6639     const SmallVectorImpl<SDValue> &OutVals,
6640     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6641     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6642     const CallBase *CB) const {
6643   unsigned NumOps = Outs.size();
6644 
6645   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6646   bool isPPC64 = PtrVT == MVT::i64;
6647   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6648 
6649   MachineFunction &MF = DAG.getMachineFunction();
6650 
6651   // Mark this function as potentially containing a function that contains a
6652   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6653   // and restoring the callers stack pointer in this functions epilog. This is
6654   // done because by tail calling the called function might overwrite the value
6655   // in this function's (MF) stack pointer stack slot 0(SP).
6656   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6657       CFlags.CallConv == CallingConv::Fast)
6658     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6659 
6660   // Count how many bytes are to be pushed on the stack, including the linkage
6661   // area, and parameter passing area.  We start with 24/48 bytes, which is
6662   // prereserved space for [SP][CR][LR][3 x unused].
6663   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6664   unsigned NumBytes = LinkageSize;
6665 
6666   // Add up all the space actually used.
6667   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6668   // they all go in registers, but we must reserve stack space for them for
6669   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6670   // assigned stack space in order, with padding so Altivec parameters are
6671   // 16-byte aligned.
6672   unsigned nAltivecParamsAtEnd = 0;
6673   for (unsigned i = 0; i != NumOps; ++i) {
6674     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6675     EVT ArgVT = Outs[i].VT;
6676     // Varargs Altivec parameters are padded to a 16 byte boundary.
6677     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6678         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6679         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6680       if (!CFlags.IsVarArg && !isPPC64) {
6681         // Non-varargs Altivec parameters go after all the non-Altivec
6682         // parameters; handle those later so we know how much padding we need.
6683         nAltivecParamsAtEnd++;
6684         continue;
6685       }
6686       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6687       NumBytes = ((NumBytes+15)/16)*16;
6688     }
6689     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6690   }
6691 
6692   // Allow for Altivec parameters at the end, if needed.
6693   if (nAltivecParamsAtEnd) {
6694     NumBytes = ((NumBytes+15)/16)*16;
6695     NumBytes += 16*nAltivecParamsAtEnd;
6696   }
6697 
6698   // The prolog code of the callee may store up to 8 GPR argument registers to
6699   // the stack, allowing va_start to index over them in memory if its varargs.
6700   // Because we cannot tell if this is needed on the caller side, we have to
6701   // conservatively assume that it is needed.  As such, make sure we have at
6702   // least enough stack space for the caller to store the 8 GPRs.
6703   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6704 
6705   // Tail call needs the stack to be aligned.
6706   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6707       CFlags.CallConv == CallingConv::Fast)
6708     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6709 
6710   // Calculate by how many bytes the stack has to be adjusted in case of tail
6711   // call optimization.
6712   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6713 
6714   // To protect arguments on the stack from being clobbered in a tail call,
6715   // force all the loads to happen before doing any other lowering.
6716   if (CFlags.IsTailCall)
6717     Chain = DAG.getStackArgumentTokenFactor(Chain);
6718 
6719   // Adjust the stack pointer for the new arguments...
6720   // These operations are automatically eliminated by the prolog/epilog pass
6721   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6722   SDValue CallSeqStart = Chain;
6723 
6724   // Load the return address and frame pointer so it can be move somewhere else
6725   // later.
6726   SDValue LROp, FPOp;
6727   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6728 
6729   // Set up a copy of the stack pointer for use loading and storing any
6730   // arguments that may not fit in the registers available for argument
6731   // passing.
6732   SDValue StackPtr;
6733   if (isPPC64)
6734     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6735   else
6736     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6737 
6738   // Figure out which arguments are going to go in registers, and which in
6739   // memory.  Also, if this is a vararg function, floating point operations
6740   // must be stored to our stack, and loaded into integer regs as well, if
6741   // any integer regs are available for argument passing.
6742   unsigned ArgOffset = LinkageSize;
6743   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6744 
6745   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6746     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6747     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6748   };
6749   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6750     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6751     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6752   };
6753   static const MCPhysReg VR[] = {
6754     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6755     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6756   };
6757   const unsigned NumGPRs = array_lengthof(GPR_32);
6758   const unsigned NumFPRs = 13;
6759   const unsigned NumVRs  = array_lengthof(VR);
6760 
6761   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6762 
6763   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6764   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6765 
6766   SmallVector<SDValue, 8> MemOpChains;
6767   for (unsigned i = 0; i != NumOps; ++i) {
6768     SDValue Arg = OutVals[i];
6769     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6770 
6771     // PtrOff will be used to store the current argument to the stack if a
6772     // register cannot be found for it.
6773     SDValue PtrOff;
6774 
6775     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6776 
6777     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6778 
6779     // On PPC64, promote integers to 64-bit values.
6780     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6781       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6782       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6783       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6784     }
6785 
6786     // FIXME memcpy is used way more than necessary.  Correctness first.
6787     // Note: "by value" is code for passing a structure by value, not
6788     // basic types.
6789     if (Flags.isByVal()) {
6790       unsigned Size = Flags.getByValSize();
6791       // Very small objects are passed right-justified.  Everything else is
6792       // passed left-justified.
6793       if (Size==1 || Size==2) {
6794         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6795         if (GPR_idx != NumGPRs) {
6796           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6797                                         MachinePointerInfo(), VT);
6798           MemOpChains.push_back(Load.getValue(1));
6799           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6800 
6801           ArgOffset += PtrByteSize;
6802         } else {
6803           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6804                                           PtrOff.getValueType());
6805           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6806           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6807                                                             CallSeqStart,
6808                                                             Flags, DAG, dl);
6809           ArgOffset += PtrByteSize;
6810         }
6811         continue;
6812       }
6813       // Copy entire object into memory.  There are cases where gcc-generated
6814       // code assumes it is there, even if it could be put entirely into
6815       // registers.  (This is not what the doc says.)
6816       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6817                                                         CallSeqStart,
6818                                                         Flags, DAG, dl);
6819 
6820       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6821       // copy the pieces of the object that fit into registers from the
6822       // parameter save area.
6823       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6824         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6825         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6826         if (GPR_idx != NumGPRs) {
6827           SDValue Load =
6828               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6829           MemOpChains.push_back(Load.getValue(1));
6830           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6831           ArgOffset += PtrByteSize;
6832         } else {
6833           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6834           break;
6835         }
6836       }
6837       continue;
6838     }
6839 
6840     switch (Arg.getSimpleValueType().SimpleTy) {
6841     default: llvm_unreachable("Unexpected ValueType for argument!");
6842     case MVT::i1:
6843     case MVT::i32:
6844     case MVT::i64:
6845       if (GPR_idx != NumGPRs) {
6846         if (Arg.getValueType() == MVT::i1)
6847           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6848 
6849         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6850       } else {
6851         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6852                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6853                          TailCallArguments, dl);
6854       }
6855       ArgOffset += PtrByteSize;
6856       break;
6857     case MVT::f32:
6858     case MVT::f64:
6859       if (FPR_idx != NumFPRs) {
6860         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6861 
6862         if (CFlags.IsVarArg) {
6863           SDValue Store =
6864               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6865           MemOpChains.push_back(Store);
6866 
6867           // Float varargs are always shadowed in available integer registers
6868           if (GPR_idx != NumGPRs) {
6869             SDValue Load =
6870                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6871             MemOpChains.push_back(Load.getValue(1));
6872             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6873           }
6874           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6875             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6876             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6877             SDValue Load =
6878                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6879             MemOpChains.push_back(Load.getValue(1));
6880             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6881           }
6882         } else {
6883           // If we have any FPRs remaining, we may also have GPRs remaining.
6884           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6885           // GPRs.
6886           if (GPR_idx != NumGPRs)
6887             ++GPR_idx;
6888           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6889               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6890             ++GPR_idx;
6891         }
6892       } else
6893         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6894                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6895                          TailCallArguments, dl);
6896       if (isPPC64)
6897         ArgOffset += 8;
6898       else
6899         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6900       break;
6901     case MVT::v4f32:
6902     case MVT::v4i32:
6903     case MVT::v8i16:
6904     case MVT::v16i8:
6905       if (CFlags.IsVarArg) {
6906         // These go aligned on the stack, or in the corresponding R registers
6907         // when within range.  The Darwin PPC ABI doc claims they also go in
6908         // V registers; in fact gcc does this only for arguments that are
6909         // prototyped, not for those that match the ...  We do it for all
6910         // arguments, seems to work.
6911         while (ArgOffset % 16 !=0) {
6912           ArgOffset += PtrByteSize;
6913           if (GPR_idx != NumGPRs)
6914             GPR_idx++;
6915         }
6916         // We could elide this store in the case where the object fits
6917         // entirely in R registers.  Maybe later.
6918         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6919                              DAG.getConstant(ArgOffset, dl, PtrVT));
6920         SDValue Store =
6921             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6922         MemOpChains.push_back(Store);
6923         if (VR_idx != NumVRs) {
6924           SDValue Load =
6925               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6926           MemOpChains.push_back(Load.getValue(1));
6927           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6928         }
6929         ArgOffset += 16;
6930         for (unsigned i=0; i<16; i+=PtrByteSize) {
6931           if (GPR_idx == NumGPRs)
6932             break;
6933           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6934                                    DAG.getConstant(i, dl, PtrVT));
6935           SDValue Load =
6936               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6937           MemOpChains.push_back(Load.getValue(1));
6938           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6939         }
6940         break;
6941       }
6942 
6943       // Non-varargs Altivec params generally go in registers, but have
6944       // stack space allocated at the end.
6945       if (VR_idx != NumVRs) {
6946         // Doesn't have GPR space allocated.
6947         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6948       } else if (nAltivecParamsAtEnd==0) {
6949         // We are emitting Altivec params in order.
6950         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6951                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6952                          TailCallArguments, dl);
6953         ArgOffset += 16;
6954       }
6955       break;
6956     }
6957   }
6958   // If all Altivec parameters fit in registers, as they usually do,
6959   // they get stack space following the non-Altivec parameters.  We
6960   // don't track this here because nobody below needs it.
6961   // If there are more Altivec parameters than fit in registers emit
6962   // the stores here.
6963   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6964     unsigned j = 0;
6965     // Offset is aligned; skip 1st 12 params which go in V registers.
6966     ArgOffset = ((ArgOffset+15)/16)*16;
6967     ArgOffset += 12*16;
6968     for (unsigned i = 0; i != NumOps; ++i) {
6969       SDValue Arg = OutVals[i];
6970       EVT ArgType = Outs[i].VT;
6971       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6972           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6973         if (++j > NumVRs) {
6974           SDValue PtrOff;
6975           // We are emitting Altivec params in order.
6976           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6977                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6978                            TailCallArguments, dl);
6979           ArgOffset += 16;
6980         }
6981       }
6982     }
6983   }
6984 
6985   if (!MemOpChains.empty())
6986     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6987 
6988   // On Darwin, R12 must contain the address of an indirect callee.  This does
6989   // not mean the MTCTR instruction must use R12; it's easier to model this as
6990   // an extra parameter, so do that.
6991   if (CFlags.IsIndirect) {
6992     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6993     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6994                                                    PPC::R12), Callee));
6995   }
6996 
6997   // Build a sequence of copy-to-reg nodes chained together with token chain
6998   // and flag operands which copy the outgoing args into the appropriate regs.
6999   SDValue InFlag;
7000   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
7001     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
7002                              RegsToPass[i].second, InFlag);
7003     InFlag = Chain.getValue(1);
7004   }
7005 
7006   if (CFlags.IsTailCall)
7007     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
7008                     TailCallArguments);
7009 
7010   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7011                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7012 }
7013 
7014 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
7015                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
7016                    CCState &State) {
7017 
7018   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
7019       State.getMachineFunction().getSubtarget());
7020   const bool IsPPC64 = Subtarget.isPPC64();
7021   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
7022   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
7023 
7024   if (ValVT.isVector() && !State.getMachineFunction()
7025                                .getTarget()
7026                                .Options.EnableAIXExtendedAltivecABI)
7027     report_fatal_error("the default Altivec AIX ABI is not yet supported");
7028 
7029   if (ValVT == MVT::f128)
7030     report_fatal_error("f128 is unimplemented on AIX.");
7031 
7032   if (ArgFlags.isNest())
7033     report_fatal_error("Nest arguments are unimplemented.");
7034 
7035   static const MCPhysReg GPR_32[] = {// 32-bit registers.
7036                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7037                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7038   static const MCPhysReg GPR_64[] = {// 64-bit registers.
7039                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7040                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7041 
7042   static const MCPhysReg VR[] = {// Vector registers.
7043                                  PPC::V2,  PPC::V3,  PPC::V4,  PPC::V5,
7044                                  PPC::V6,  PPC::V7,  PPC::V8,  PPC::V9,
7045                                  PPC::V10, PPC::V11, PPC::V12, PPC::V13};
7046 
7047   if (ArgFlags.isByVal()) {
7048     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
7049       report_fatal_error("Pass-by-value arguments with alignment greater than "
7050                          "register width are not supported.");
7051 
7052     const unsigned ByValSize = ArgFlags.getByValSize();
7053 
7054     // An empty aggregate parameter takes up no storage and no registers,
7055     // but needs a MemLoc for a stack slot for the formal arguments side.
7056     if (ByValSize == 0) {
7057       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
7058                                        State.getNextStackOffset(), RegVT,
7059                                        LocInfo));
7060       return false;
7061     }
7062 
7063     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
7064     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
7065     for (const unsigned E = Offset + StackSize; Offset < E;
7066          Offset += PtrAlign.value()) {
7067       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
7068         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7069       else {
7070         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
7071                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
7072                                          LocInfo));
7073         break;
7074       }
7075     }
7076     return false;
7077   }
7078 
7079   // Arguments always reserve parameter save area.
7080   switch (ValVT.SimpleTy) {
7081   default:
7082     report_fatal_error("Unhandled value type for argument.");
7083   case MVT::i64:
7084     // i64 arguments should have been split to i32 for PPC32.
7085     assert(IsPPC64 && "PPC32 should have split i64 values.");
7086     LLVM_FALLTHROUGH;
7087   case MVT::i1:
7088   case MVT::i32: {
7089     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
7090     // AIX integer arguments are always passed in register width.
7091     if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
7092       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
7093                                   : CCValAssign::LocInfo::ZExt;
7094     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
7095       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7096     else
7097       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
7098 
7099     return false;
7100   }
7101   case MVT::f32:
7102   case MVT::f64: {
7103     // Parameter save area (PSA) is reserved even if the float passes in fpr.
7104     const unsigned StoreSize = LocVT.getStoreSize();
7105     // Floats are always 4-byte aligned in the PSA on AIX.
7106     // This includes f64 in 64-bit mode for ABI compatibility.
7107     const unsigned Offset =
7108         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
7109     unsigned FReg = State.AllocateReg(FPR);
7110     if (FReg)
7111       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
7112 
7113     // Reserve and initialize GPRs or initialize the PSA as required.
7114     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
7115       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
7116         assert(FReg && "An FPR should be available when a GPR is reserved.");
7117         if (State.isVarArg()) {
7118           // Successfully reserved GPRs are only initialized for vararg calls.
7119           // Custom handling is required for:
7120           //   f64 in PPC32 needs to be split into 2 GPRs.
7121           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
7122           State.addLoc(
7123               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7124         }
7125       } else {
7126         // If there are insufficient GPRs, the PSA needs to be initialized.
7127         // Initialization occurs even if an FPR was initialized for
7128         // compatibility with the AIX XL compiler. The full memory for the
7129         // argument will be initialized even if a prior word is saved in GPR.
7130         // A custom memLoc is used when the argument also passes in FPR so
7131         // that the callee handling can skip over it easily.
7132         State.addLoc(
7133             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
7134                                              LocInfo)
7135                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7136         break;
7137       }
7138     }
7139 
7140     return false;
7141   }
7142   case MVT::v4f32:
7143   case MVT::v4i32:
7144   case MVT::v8i16:
7145   case MVT::v16i8:
7146   case MVT::v2i64:
7147   case MVT::v2f64:
7148   case MVT::v1i128: {
7149     if (State.isVarArg())
7150       report_fatal_error(
7151           "variadic arguments for vector types are unimplemented for AIX");
7152 
7153     if (unsigned VReg = State.AllocateReg(VR))
7154       State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
7155     else {
7156       report_fatal_error(
7157           "passing vector parameters to the stack is unimplemented for AIX");
7158     }
7159     return false;
7160   }
7161   }
7162   return true;
7163 }
7164 
7165 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
7166                                                     bool IsPPC64) {
7167   assert((IsPPC64 || SVT != MVT::i64) &&
7168          "i64 should have been split for 32-bit codegen.");
7169 
7170   switch (SVT) {
7171   default:
7172     report_fatal_error("Unexpected value type for formal argument");
7173   case MVT::i1:
7174   case MVT::i32:
7175   case MVT::i64:
7176     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7177   case MVT::f32:
7178     return &PPC::F4RCRegClass;
7179   case MVT::f64:
7180     return &PPC::F8RCRegClass;
7181   case MVT::v4f32:
7182   case MVT::v4i32:
7183   case MVT::v8i16:
7184   case MVT::v16i8:
7185   case MVT::v2i64:
7186   case MVT::v2f64:
7187   case MVT::v1i128:
7188     return &PPC::VRRCRegClass;
7189   }
7190 }
7191 
7192 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
7193                                         SelectionDAG &DAG, SDValue ArgValue,
7194                                         MVT LocVT, const SDLoc &dl) {
7195   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7196   assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
7197 
7198   if (Flags.isSExt())
7199     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7200                            DAG.getValueType(ValVT));
7201   else if (Flags.isZExt())
7202     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7203                            DAG.getValueType(ValVT));
7204 
7205   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7206 }
7207 
7208 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7209   const unsigned LASize = FL->getLinkageSize();
7210 
7211   if (PPC::GPRCRegClass.contains(Reg)) {
7212     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7213            "Reg must be a valid argument register!");
7214     return LASize + 4 * (Reg - PPC::R3);
7215   }
7216 
7217   if (PPC::G8RCRegClass.contains(Reg)) {
7218     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7219            "Reg must be a valid argument register!");
7220     return LASize + 8 * (Reg - PPC::X3);
7221   }
7222 
7223   llvm_unreachable("Only general purpose registers expected.");
7224 }
7225 
7226 //   AIX ABI Stack Frame Layout:
7227 //
7228 //   Low Memory +--------------------------------------------+
7229 //   SP   +---> | Back chain                                 | ---+
7230 //        |     +--------------------------------------------+    |
7231 //        |     | Saved Condition Register                   |    |
7232 //        |     +--------------------------------------------+    |
7233 //        |     | Saved Linkage Register                     |    |
7234 //        |     +--------------------------------------------+    | Linkage Area
7235 //        |     | Reserved for compilers                     |    |
7236 //        |     +--------------------------------------------+    |
7237 //        |     | Reserved for binders                       |    |
7238 //        |     +--------------------------------------------+    |
7239 //        |     | Saved TOC pointer                          | ---+
7240 //        |     +--------------------------------------------+
7241 //        |     | Parameter save area                        |
7242 //        |     +--------------------------------------------+
7243 //        |     | Alloca space                               |
7244 //        |     +--------------------------------------------+
7245 //        |     | Local variable space                       |
7246 //        |     +--------------------------------------------+
7247 //        |     | Float/int conversion temporary             |
7248 //        |     +--------------------------------------------+
7249 //        |     | Save area for AltiVec registers            |
7250 //        |     +--------------------------------------------+
7251 //        |     | AltiVec alignment padding                  |
7252 //        |     +--------------------------------------------+
7253 //        |     | Save area for VRSAVE register              |
7254 //        |     +--------------------------------------------+
7255 //        |     | Save area for General Purpose registers    |
7256 //        |     +--------------------------------------------+
7257 //        |     | Save area for Floating Point registers     |
7258 //        |     +--------------------------------------------+
7259 //        +---- | Back chain                                 |
7260 // High Memory  +--------------------------------------------+
7261 //
7262 //  Specifications:
7263 //  AIX 7.2 Assembler Language Reference
7264 //  Subroutine linkage convention
7265 
7266 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7267     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7268     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7269     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7270 
7271   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7272           CallConv == CallingConv::Fast) &&
7273          "Unexpected calling convention!");
7274 
7275   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7276     report_fatal_error("Tail call support is unimplemented on AIX.");
7277 
7278   if (useSoftFloat())
7279     report_fatal_error("Soft float support is unimplemented on AIX.");
7280 
7281   const PPCSubtarget &Subtarget =
7282       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7283 
7284   const bool IsPPC64 = Subtarget.isPPC64();
7285   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7286 
7287   // Assign locations to all of the incoming arguments.
7288   SmallVector<CCValAssign, 16> ArgLocs;
7289   MachineFunction &MF = DAG.getMachineFunction();
7290   MachineFrameInfo &MFI = MF.getFrameInfo();
7291   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7292   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7293 
7294   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7295   // Reserve space for the linkage area on the stack.
7296   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7297   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7298   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7299 
7300   SmallVector<SDValue, 8> MemOps;
7301 
7302   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7303     CCValAssign &VA = ArgLocs[I++];
7304     MVT LocVT = VA.getLocVT();
7305     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7306     if (VA.isMemLoc() && VA.getValVT().isVector())
7307       report_fatal_error(
7308           "passing vector parameters to the stack is unimplemented for AIX");
7309 
7310     // For compatibility with the AIX XL compiler, the float args in the
7311     // parameter save area are initialized even if the argument is available
7312     // in register.  The caller is required to initialize both the register
7313     // and memory, however, the callee can choose to expect it in either.
7314     // The memloc is dismissed here because the argument is retrieved from
7315     // the register.
7316     if (VA.isMemLoc() && VA.needsCustom())
7317       continue;
7318 
7319     if (VA.isRegLoc()) {
7320       if (VA.getValVT().isScalarInteger())
7321         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7322       else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector())
7323         FuncInfo->appendParameterType(VA.getValVT().SimpleTy == MVT::f32
7324                                           ? PPCFunctionInfo::ShortFloatPoint
7325                                           : PPCFunctionInfo::LongFloatPoint);
7326     }
7327 
7328     if (Flags.isByVal() && VA.isMemLoc()) {
7329       const unsigned Size =
7330           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7331                   PtrByteSize);
7332       const int FI = MF.getFrameInfo().CreateFixedObject(
7333           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7334           /* IsAliased */ true);
7335       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7336       InVals.push_back(FIN);
7337 
7338       continue;
7339     }
7340 
7341     if (Flags.isByVal()) {
7342       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7343 
7344       const MCPhysReg ArgReg = VA.getLocReg();
7345       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7346 
7347       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7348         report_fatal_error("Over aligned byvals not supported yet.");
7349 
7350       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7351       const int FI = MF.getFrameInfo().CreateFixedObject(
7352           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7353           /* IsAliased */ true);
7354       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7355       InVals.push_back(FIN);
7356 
7357       // Add live ins for all the RegLocs for the same ByVal.
7358       const TargetRegisterClass *RegClass =
7359           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7360 
7361       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7362                                                unsigned Offset) {
7363         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7364         // Since the callers side has left justified the aggregate in the
7365         // register, we can simply store the entire register into the stack
7366         // slot.
7367         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7368         // The store to the fixedstack object is needed becuase accessing a
7369         // field of the ByVal will use a gep and load. Ideally we will optimize
7370         // to extracting the value from the register directly, and elide the
7371         // stores when the arguments address is not taken, but that will need to
7372         // be future work.
7373         SDValue Store = DAG.getStore(
7374             CopyFrom.getValue(1), dl, CopyFrom,
7375             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7376             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7377 
7378         MemOps.push_back(Store);
7379       };
7380 
7381       unsigned Offset = 0;
7382       HandleRegLoc(VA.getLocReg(), Offset);
7383       Offset += PtrByteSize;
7384       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7385            Offset += PtrByteSize) {
7386         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7387                "RegLocs should be for ByVal argument.");
7388 
7389         const CCValAssign RL = ArgLocs[I++];
7390         HandleRegLoc(RL.getLocReg(), Offset);
7391         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7392       }
7393 
7394       if (Offset != StackSize) {
7395         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7396                "Expected MemLoc for remaining bytes.");
7397         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7398         // Consume the MemLoc.The InVal has already been emitted, so nothing
7399         // more needs to be done.
7400         ++I;
7401       }
7402 
7403       continue;
7404     }
7405 
7406     EVT ValVT = VA.getValVT();
7407     if (VA.isRegLoc() && !VA.needsCustom()) {
7408       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7409       unsigned VReg =
7410           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7411       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7412       if (ValVT.isScalarInteger() &&
7413           (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7414         ArgValue =
7415             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7416       }
7417       InVals.push_back(ArgValue);
7418       continue;
7419     }
7420     if (VA.isMemLoc()) {
7421       const unsigned LocSize = LocVT.getStoreSize();
7422       const unsigned ValSize = ValVT.getStoreSize();
7423       assert((ValSize <= LocSize) &&
7424              "Object size is larger than size of MemLoc");
7425       int CurArgOffset = VA.getLocMemOffset();
7426       // Objects are right-justified because AIX is big-endian.
7427       if (LocSize > ValSize)
7428         CurArgOffset += LocSize - ValSize;
7429       // Potential tail calls could cause overwriting of argument stack slots.
7430       const bool IsImmutable =
7431           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7432             (CallConv == CallingConv::Fast));
7433       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7434       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7435       SDValue ArgValue =
7436           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7437       InVals.push_back(ArgValue);
7438       continue;
7439     }
7440   }
7441 
7442   // On AIX a minimum of 8 words is saved to the parameter save area.
7443   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7444   // Area that is at least reserved in the caller of this function.
7445   unsigned CallerReservedArea =
7446       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7447 
7448   // Set the size that is at least reserved in caller of this function. Tail
7449   // call optimized function's reserved stack space needs to be aligned so
7450   // that taking the difference between two stack areas will result in an
7451   // aligned stack.
7452   CallerReservedArea =
7453       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7454   FuncInfo->setMinReservedArea(CallerReservedArea);
7455 
7456   if (isVarArg) {
7457     FuncInfo->setVarArgsFrameIndex(
7458         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7459     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7460 
7461     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7462                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7463 
7464     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7465                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7466     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7467 
7468     // The fixed integer arguments of a variadic function are stored to the
7469     // VarArgsFrameIndex on the stack so that they may be loaded by
7470     // dereferencing the result of va_next.
7471     for (unsigned GPRIndex =
7472              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7473          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7474 
7475       const unsigned VReg =
7476           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7477                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7478 
7479       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7480       SDValue Store =
7481           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7482       MemOps.push_back(Store);
7483       // Increment the address for the next argument to store.
7484       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7485       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7486     }
7487   }
7488 
7489   if (!MemOps.empty())
7490     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7491 
7492   return Chain;
7493 }
7494 
7495 SDValue PPCTargetLowering::LowerCall_AIX(
7496     SDValue Chain, SDValue Callee, CallFlags CFlags,
7497     const SmallVectorImpl<ISD::OutputArg> &Outs,
7498     const SmallVectorImpl<SDValue> &OutVals,
7499     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7500     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7501     const CallBase *CB) const {
7502   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7503   // AIX ABI stack frame layout.
7504 
7505   assert((CFlags.CallConv == CallingConv::C ||
7506           CFlags.CallConv == CallingConv::Cold ||
7507           CFlags.CallConv == CallingConv::Fast) &&
7508          "Unexpected calling convention!");
7509 
7510   if (CFlags.IsPatchPoint)
7511     report_fatal_error("This call type is unimplemented on AIX.");
7512 
7513   const PPCSubtarget& Subtarget =
7514       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7515 
7516   MachineFunction &MF = DAG.getMachineFunction();
7517   SmallVector<CCValAssign, 16> ArgLocs;
7518   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7519                  *DAG.getContext());
7520 
7521   // Reserve space for the linkage save area (LSA) on the stack.
7522   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7523   //   [SP][CR][LR][2 x reserved][TOC].
7524   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7525   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7526   const bool IsPPC64 = Subtarget.isPPC64();
7527   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7528   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7529   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7530   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7531 
7532   // The prolog code of the callee may store up to 8 GPR argument registers to
7533   // the stack, allowing va_start to index over them in memory if the callee
7534   // is variadic.
7535   // Because we cannot tell if this is needed on the caller side, we have to
7536   // conservatively assume that it is needed.  As such, make sure we have at
7537   // least enough stack space for the caller to store the 8 GPRs.
7538   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7539   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7540                                      CCInfo.getNextStackOffset());
7541 
7542   // Adjust the stack pointer for the new arguments...
7543   // These operations are automatically eliminated by the prolog/epilog pass.
7544   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7545   SDValue CallSeqStart = Chain;
7546 
7547   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7548   SmallVector<SDValue, 8> MemOpChains;
7549 
7550   // Set up a copy of the stack pointer for loading and storing any
7551   // arguments that may not fit in the registers available for argument
7552   // passing.
7553   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7554                                    : DAG.getRegister(PPC::R1, MVT::i32);
7555 
7556   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7557     const unsigned ValNo = ArgLocs[I].getValNo();
7558     SDValue Arg = OutVals[ValNo];
7559     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7560 
7561     if (Flags.isByVal()) {
7562       const unsigned ByValSize = Flags.getByValSize();
7563 
7564       // Nothing to do for zero-sized ByVals on the caller side.
7565       if (!ByValSize) {
7566         ++I;
7567         continue;
7568       }
7569 
7570       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7571         return DAG.getExtLoad(
7572             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7573             (LoadOffset != 0)
7574                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7575                 : Arg,
7576             MachinePointerInfo(), VT);
7577       };
7578 
7579       unsigned LoadOffset = 0;
7580 
7581       // Initialize registers, which are fully occupied by the by-val argument.
7582       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7583         SDValue Load = GetLoad(PtrVT, LoadOffset);
7584         MemOpChains.push_back(Load.getValue(1));
7585         LoadOffset += PtrByteSize;
7586         const CCValAssign &ByValVA = ArgLocs[I++];
7587         assert(ByValVA.getValNo() == ValNo &&
7588                "Unexpected location for pass-by-value argument.");
7589         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7590       }
7591 
7592       if (LoadOffset == ByValSize)
7593         continue;
7594 
7595       // There must be one more loc to handle the remainder.
7596       assert(ArgLocs[I].getValNo() == ValNo &&
7597              "Expected additional location for by-value argument.");
7598 
7599       if (ArgLocs[I].isMemLoc()) {
7600         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7601         const CCValAssign &ByValVA = ArgLocs[I++];
7602         ISD::ArgFlagsTy MemcpyFlags = Flags;
7603         // Only memcpy the bytes that don't pass in register.
7604         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7605         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7606             (LoadOffset != 0)
7607                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7608                 : Arg,
7609             DAG.getObjectPtrOffset(dl, StackPtr,
7610                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7611             CallSeqStart, MemcpyFlags, DAG, dl);
7612         continue;
7613       }
7614 
7615       // Initialize the final register residue.
7616       // Any residue that occupies the final by-val arg register must be
7617       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7618       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7619       // 2 and 1 byte loads.
7620       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7621       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7622              "Unexpected register residue for by-value argument.");
7623       SDValue ResidueVal;
7624       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7625         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7626         const MVT VT =
7627             N == 1 ? MVT::i8
7628                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7629         SDValue Load = GetLoad(VT, LoadOffset);
7630         MemOpChains.push_back(Load.getValue(1));
7631         LoadOffset += N;
7632         Bytes += N;
7633 
7634         // By-val arguments are passed left-justfied in register.
7635         // Every load here needs to be shifted, otherwise a full register load
7636         // should have been used.
7637         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7638                "Unexpected load emitted during handling of pass-by-value "
7639                "argument.");
7640         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7641         EVT ShiftAmountTy =
7642             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7643         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7644         SDValue ShiftedLoad =
7645             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7646         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7647                                               ShiftedLoad)
7648                                 : ShiftedLoad;
7649       }
7650 
7651       const CCValAssign &ByValVA = ArgLocs[I++];
7652       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7653       continue;
7654     }
7655 
7656     CCValAssign &VA = ArgLocs[I++];
7657     const MVT LocVT = VA.getLocVT();
7658     const MVT ValVT = VA.getValVT();
7659 
7660     if (VA.isMemLoc() && VA.getValVT().isVector())
7661       report_fatal_error(
7662           "passing vector parameters to the stack is unimplemented for AIX");
7663 
7664     switch (VA.getLocInfo()) {
7665     default:
7666       report_fatal_error("Unexpected argument extension type.");
7667     case CCValAssign::Full:
7668       break;
7669     case CCValAssign::ZExt:
7670       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7671       break;
7672     case CCValAssign::SExt:
7673       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7674       break;
7675     }
7676 
7677     if (VA.isRegLoc() && !VA.needsCustom()) {
7678       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7679       continue;
7680     }
7681 
7682     if (VA.isMemLoc()) {
7683       SDValue PtrOff =
7684           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7685       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7686       MemOpChains.push_back(
7687           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7688 
7689       continue;
7690     }
7691 
7692     // Custom handling is used for GPR initializations for vararg float
7693     // arguments.
7694     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7695            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7696            "Unexpected register handling for calling convention.");
7697 
7698     SDValue ArgAsInt =
7699         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7700 
7701     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7702       // f32 in 32-bit GPR
7703       // f64 in 64-bit GPR
7704       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7705     else if (Arg.getValueType().getFixedSizeInBits() <
7706              LocVT.getFixedSizeInBits())
7707       // f32 in 64-bit GPR.
7708       RegsToPass.push_back(std::make_pair(
7709           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7710     else {
7711       // f64 in two 32-bit GPRs
7712       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7713       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7714              "Unexpected custom register for argument!");
7715       CCValAssign &GPR1 = VA;
7716       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7717                                      DAG.getConstant(32, dl, MVT::i8));
7718       RegsToPass.push_back(std::make_pair(
7719           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7720 
7721       if (I != E) {
7722         // If only 1 GPR was available, there will only be one custom GPR and
7723         // the argument will also pass in memory.
7724         CCValAssign &PeekArg = ArgLocs[I];
7725         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7726           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7727           CCValAssign &GPR2 = ArgLocs[I++];
7728           RegsToPass.push_back(std::make_pair(
7729               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7730         }
7731       }
7732     }
7733   }
7734 
7735   if (!MemOpChains.empty())
7736     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7737 
7738   // For indirect calls, we need to save the TOC base to the stack for
7739   // restoration after the call.
7740   if (CFlags.IsIndirect) {
7741     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7742     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7743     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7744     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7745     const unsigned TOCSaveOffset =
7746         Subtarget.getFrameLowering()->getTOCSaveOffset();
7747 
7748     setUsesTOCBasePtr(DAG);
7749     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7750     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7751     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7752     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7753     Chain = DAG.getStore(
7754         Val.getValue(1), dl, Val, AddPtr,
7755         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7756   }
7757 
7758   // Build a sequence of copy-to-reg nodes chained together with token chain
7759   // and flag operands which copy the outgoing args into the appropriate regs.
7760   SDValue InFlag;
7761   for (auto Reg : RegsToPass) {
7762     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7763     InFlag = Chain.getValue(1);
7764   }
7765 
7766   const int SPDiff = 0;
7767   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7768                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7769 }
7770 
7771 bool
7772 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7773                                   MachineFunction &MF, bool isVarArg,
7774                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7775                                   LLVMContext &Context) const {
7776   SmallVector<CCValAssign, 16> RVLocs;
7777   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7778   return CCInfo.CheckReturn(
7779       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7780                 ? RetCC_PPC_Cold
7781                 : RetCC_PPC);
7782 }
7783 
7784 SDValue
7785 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7786                                bool isVarArg,
7787                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7788                                const SmallVectorImpl<SDValue> &OutVals,
7789                                const SDLoc &dl, SelectionDAG &DAG) const {
7790   SmallVector<CCValAssign, 16> RVLocs;
7791   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7792                  *DAG.getContext());
7793   CCInfo.AnalyzeReturn(Outs,
7794                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7795                            ? RetCC_PPC_Cold
7796                            : RetCC_PPC);
7797 
7798   SDValue Flag;
7799   SmallVector<SDValue, 4> RetOps(1, Chain);
7800 
7801   // Copy the result values into the output registers.
7802   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7803     CCValAssign &VA = RVLocs[i];
7804     assert(VA.isRegLoc() && "Can only return in registers!");
7805 
7806     SDValue Arg = OutVals[RealResIdx];
7807 
7808     switch (VA.getLocInfo()) {
7809     default: llvm_unreachable("Unknown loc info!");
7810     case CCValAssign::Full: break;
7811     case CCValAssign::AExt:
7812       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7813       break;
7814     case CCValAssign::ZExt:
7815       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7816       break;
7817     case CCValAssign::SExt:
7818       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7819       break;
7820     }
7821     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7822       bool isLittleEndian = Subtarget.isLittleEndian();
7823       // Legalize ret f64 -> ret 2 x i32.
7824       SDValue SVal =
7825           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7826                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7827       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7828       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7829       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7830                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7831       Flag = Chain.getValue(1);
7832       VA = RVLocs[++i]; // skip ahead to next loc
7833       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7834     } else
7835       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7836     Flag = Chain.getValue(1);
7837     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7838   }
7839 
7840   RetOps[0] = Chain;  // Update chain.
7841 
7842   // Add the flag if we have it.
7843   if (Flag.getNode())
7844     RetOps.push_back(Flag);
7845 
7846   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7847 }
7848 
7849 SDValue
7850 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7851                                                 SelectionDAG &DAG) const {
7852   SDLoc dl(Op);
7853 
7854   // Get the correct type for integers.
7855   EVT IntVT = Op.getValueType();
7856 
7857   // Get the inputs.
7858   SDValue Chain = Op.getOperand(0);
7859   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7860   // Build a DYNAREAOFFSET node.
7861   SDValue Ops[2] = {Chain, FPSIdx};
7862   SDVTList VTs = DAG.getVTList(IntVT);
7863   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7864 }
7865 
7866 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7867                                              SelectionDAG &DAG) const {
7868   // When we pop the dynamic allocation we need to restore the SP link.
7869   SDLoc dl(Op);
7870 
7871   // Get the correct type for pointers.
7872   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7873 
7874   // Construct the stack pointer operand.
7875   bool isPPC64 = Subtarget.isPPC64();
7876   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7877   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7878 
7879   // Get the operands for the STACKRESTORE.
7880   SDValue Chain = Op.getOperand(0);
7881   SDValue SaveSP = Op.getOperand(1);
7882 
7883   // Load the old link SP.
7884   SDValue LoadLinkSP =
7885       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7886 
7887   // Restore the stack pointer.
7888   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7889 
7890   // Store the old link SP.
7891   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7892 }
7893 
7894 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7895   MachineFunction &MF = DAG.getMachineFunction();
7896   bool isPPC64 = Subtarget.isPPC64();
7897   EVT PtrVT = getPointerTy(MF.getDataLayout());
7898 
7899   // Get current frame pointer save index.  The users of this index will be
7900   // primarily DYNALLOC instructions.
7901   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7902   int RASI = FI->getReturnAddrSaveIndex();
7903 
7904   // If the frame pointer save index hasn't been defined yet.
7905   if (!RASI) {
7906     // Find out what the fix offset of the frame pointer save area.
7907     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7908     // Allocate the frame index for frame pointer save area.
7909     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7910     // Save the result.
7911     FI->setReturnAddrSaveIndex(RASI);
7912   }
7913   return DAG.getFrameIndex(RASI, PtrVT);
7914 }
7915 
7916 SDValue
7917 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7918   MachineFunction &MF = DAG.getMachineFunction();
7919   bool isPPC64 = Subtarget.isPPC64();
7920   EVT PtrVT = getPointerTy(MF.getDataLayout());
7921 
7922   // Get current frame pointer save index.  The users of this index will be
7923   // primarily DYNALLOC instructions.
7924   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7925   int FPSI = FI->getFramePointerSaveIndex();
7926 
7927   // If the frame pointer save index hasn't been defined yet.
7928   if (!FPSI) {
7929     // Find out what the fix offset of the frame pointer save area.
7930     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7931     // Allocate the frame index for frame pointer save area.
7932     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7933     // Save the result.
7934     FI->setFramePointerSaveIndex(FPSI);
7935   }
7936   return DAG.getFrameIndex(FPSI, PtrVT);
7937 }
7938 
7939 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7940                                                    SelectionDAG &DAG) const {
7941   MachineFunction &MF = DAG.getMachineFunction();
7942   // Get the inputs.
7943   SDValue Chain = Op.getOperand(0);
7944   SDValue Size  = Op.getOperand(1);
7945   SDLoc dl(Op);
7946 
7947   // Get the correct type for pointers.
7948   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7949   // Negate the size.
7950   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7951                                 DAG.getConstant(0, dl, PtrVT), Size);
7952   // Construct a node for the frame pointer save index.
7953   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7954   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7955   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7956   if (hasInlineStackProbe(MF))
7957     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7958   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7959 }
7960 
7961 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7962                                                      SelectionDAG &DAG) const {
7963   MachineFunction &MF = DAG.getMachineFunction();
7964 
7965   bool isPPC64 = Subtarget.isPPC64();
7966   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7967 
7968   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7969   return DAG.getFrameIndex(FI, PtrVT);
7970 }
7971 
7972 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7973                                                SelectionDAG &DAG) const {
7974   SDLoc DL(Op);
7975   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7976                      DAG.getVTList(MVT::i32, MVT::Other),
7977                      Op.getOperand(0), Op.getOperand(1));
7978 }
7979 
7980 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7981                                                 SelectionDAG &DAG) const {
7982   SDLoc DL(Op);
7983   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7984                      Op.getOperand(0), Op.getOperand(1));
7985 }
7986 
7987 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7988   if (Op.getValueType().isVector())
7989     return LowerVectorLoad(Op, DAG);
7990 
7991   assert(Op.getValueType() == MVT::i1 &&
7992          "Custom lowering only for i1 loads");
7993 
7994   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7995 
7996   SDLoc dl(Op);
7997   LoadSDNode *LD = cast<LoadSDNode>(Op);
7998 
7999   SDValue Chain = LD->getChain();
8000   SDValue BasePtr = LD->getBasePtr();
8001   MachineMemOperand *MMO = LD->getMemOperand();
8002 
8003   SDValue NewLD =
8004       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
8005                      BasePtr, MVT::i8, MMO);
8006   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
8007 
8008   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
8009   return DAG.getMergeValues(Ops, dl);
8010 }
8011 
8012 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8013   if (Op.getOperand(1).getValueType().isVector())
8014     return LowerVectorStore(Op, DAG);
8015 
8016   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
8017          "Custom lowering only for i1 stores");
8018 
8019   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
8020 
8021   SDLoc dl(Op);
8022   StoreSDNode *ST = cast<StoreSDNode>(Op);
8023 
8024   SDValue Chain = ST->getChain();
8025   SDValue BasePtr = ST->getBasePtr();
8026   SDValue Value = ST->getValue();
8027   MachineMemOperand *MMO = ST->getMemOperand();
8028 
8029   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
8030                       Value);
8031   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
8032 }
8033 
8034 // FIXME: Remove this once the ANDI glue bug is fixed:
8035 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8036   assert(Op.getValueType() == MVT::i1 &&
8037          "Custom lowering only for i1 results");
8038 
8039   SDLoc DL(Op);
8040   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
8041 }
8042 
8043 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
8044                                                SelectionDAG &DAG) const {
8045 
8046   // Implements a vector truncate that fits in a vector register as a shuffle.
8047   // We want to legalize vector truncates down to where the source fits in
8048   // a vector register (and target is therefore smaller than vector register
8049   // size).  At that point legalization will try to custom lower the sub-legal
8050   // result and get here - where we can contain the truncate as a single target
8051   // operation.
8052 
8053   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
8054   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
8055   //
8056   // We will implement it for big-endian ordering as this (where x denotes
8057   // undefined):
8058   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
8059   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
8060   //
8061   // The same operation in little-endian ordering will be:
8062   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
8063   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
8064 
8065   EVT TrgVT = Op.getValueType();
8066   assert(TrgVT.isVector() && "Vector type expected.");
8067   unsigned TrgNumElts = TrgVT.getVectorNumElements();
8068   EVT EltVT = TrgVT.getVectorElementType();
8069   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
8070       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
8071       !isPowerOf2_32(EltVT.getSizeInBits()))
8072     return SDValue();
8073 
8074   SDValue N1 = Op.getOperand(0);
8075   EVT SrcVT = N1.getValueType();
8076   unsigned SrcSize = SrcVT.getSizeInBits();
8077   if (SrcSize > 256 ||
8078       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
8079       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
8080     return SDValue();
8081   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
8082     return SDValue();
8083 
8084   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8085   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8086 
8087   SDLoc DL(Op);
8088   SDValue Op1, Op2;
8089   if (SrcSize == 256) {
8090     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
8091     EVT SplitVT =
8092         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
8093     unsigned SplitNumElts = SplitVT.getVectorNumElements();
8094     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
8095                       DAG.getConstant(0, DL, VecIdxTy));
8096     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
8097                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
8098   }
8099   else {
8100     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
8101     Op2 = DAG.getUNDEF(WideVT);
8102   }
8103 
8104   // First list the elements we want to keep.
8105   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
8106   SmallVector<int, 16> ShuffV;
8107   if (Subtarget.isLittleEndian())
8108     for (unsigned i = 0; i < TrgNumElts; ++i)
8109       ShuffV.push_back(i * SizeMult);
8110   else
8111     for (unsigned i = 1; i <= TrgNumElts; ++i)
8112       ShuffV.push_back(i * SizeMult - 1);
8113 
8114   // Populate the remaining elements with undefs.
8115   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
8116     // ShuffV.push_back(i + WideNumElts);
8117     ShuffV.push_back(WideNumElts + 1);
8118 
8119   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
8120   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
8121   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
8122 }
8123 
8124 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
8125 /// possible.
8126 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
8127   // Not FP, or using SPE? Not a fsel.
8128   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
8129       !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE())
8130     return Op;
8131 
8132   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
8133 
8134   EVT ResVT = Op.getValueType();
8135   EVT CmpVT = Op.getOperand(0).getValueType();
8136   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8137   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
8138   SDLoc dl(Op);
8139   SDNodeFlags Flags = Op.getNode()->getFlags();
8140 
8141   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
8142   // presence of infinities.
8143   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
8144     switch (CC) {
8145     default:
8146       break;
8147     case ISD::SETOGT:
8148     case ISD::SETGT:
8149       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
8150     case ISD::SETOLT:
8151     case ISD::SETLT:
8152       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
8153     }
8154   }
8155 
8156   // We might be able to do better than this under some circumstances, but in
8157   // general, fsel-based lowering of select is a finite-math-only optimization.
8158   // For more information, see section F.3 of the 2.06 ISA specification.
8159   // With ISA 3.0
8160   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
8161       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
8162     return Op;
8163 
8164   // If the RHS of the comparison is a 0.0, we don't need to do the
8165   // subtraction at all.
8166   SDValue Sel1;
8167   if (isFloatingPointZero(RHS))
8168     switch (CC) {
8169     default: break;       // SETUO etc aren't handled by fsel.
8170     case ISD::SETNE:
8171       std::swap(TV, FV);
8172       LLVM_FALLTHROUGH;
8173     case ISD::SETEQ:
8174       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8175         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8176       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8177       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8178         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8179       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8180                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
8181     case ISD::SETULT:
8182     case ISD::SETLT:
8183       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8184       LLVM_FALLTHROUGH;
8185     case ISD::SETOGE:
8186     case ISD::SETGE:
8187       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8188         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8189       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8190     case ISD::SETUGT:
8191     case ISD::SETGT:
8192       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8193       LLVM_FALLTHROUGH;
8194     case ISD::SETOLE:
8195     case ISD::SETLE:
8196       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8197         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8198       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8199                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
8200     }
8201 
8202   SDValue Cmp;
8203   switch (CC) {
8204   default: break;       // SETUO etc aren't handled by fsel.
8205   case ISD::SETNE:
8206     std::swap(TV, FV);
8207     LLVM_FALLTHROUGH;
8208   case ISD::SETEQ:
8209     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8210     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8211       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8212     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8213     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8214       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8215     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8216                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8217   case ISD::SETULT:
8218   case ISD::SETLT:
8219     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8220     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8221       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8222     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8223   case ISD::SETOGE:
8224   case ISD::SETGE:
8225     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8226     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8227       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8228     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8229   case ISD::SETUGT:
8230   case ISD::SETGT:
8231     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8232     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8233       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8234     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8235   case ISD::SETOLE:
8236   case ISD::SETLE:
8237     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8238     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8239       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8240     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8241   }
8242   return Op;
8243 }
8244 
8245 static unsigned getPPCStrictOpcode(unsigned Opc) {
8246   switch (Opc) {
8247   default:
8248     llvm_unreachable("No strict version of this opcode!");
8249   case PPCISD::FCTIDZ:
8250     return PPCISD::STRICT_FCTIDZ;
8251   case PPCISD::FCTIWZ:
8252     return PPCISD::STRICT_FCTIWZ;
8253   case PPCISD::FCTIDUZ:
8254     return PPCISD::STRICT_FCTIDUZ;
8255   case PPCISD::FCTIWUZ:
8256     return PPCISD::STRICT_FCTIWUZ;
8257   case PPCISD::FCFID:
8258     return PPCISD::STRICT_FCFID;
8259   case PPCISD::FCFIDU:
8260     return PPCISD::STRICT_FCFIDU;
8261   case PPCISD::FCFIDS:
8262     return PPCISD::STRICT_FCFIDS;
8263   case PPCISD::FCFIDUS:
8264     return PPCISD::STRICT_FCFIDUS;
8265   }
8266 }
8267 
8268 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
8269                               const PPCSubtarget &Subtarget) {
8270   SDLoc dl(Op);
8271   bool IsStrict = Op->isStrictFPOpcode();
8272   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8273                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8274 
8275   // TODO: Any other flags to propagate?
8276   SDNodeFlags Flags;
8277   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8278 
8279   // For strict nodes, source is the second operand.
8280   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8281   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8282   assert(Src.getValueType().isFloatingPoint());
8283   if (Src.getValueType() == MVT::f32) {
8284     if (IsStrict) {
8285       Src =
8286           DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
8287                       DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
8288       Chain = Src.getValue(1);
8289     } else
8290       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8291   }
8292   SDValue Conv;
8293   unsigned Opc = ISD::DELETED_NODE;
8294   switch (Op.getSimpleValueType().SimpleTy) {
8295   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8296   case MVT::i32:
8297     Opc = IsSigned ? PPCISD::FCTIWZ
8298                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8299     break;
8300   case MVT::i64:
8301     assert((IsSigned || Subtarget.hasFPCVT()) &&
8302            "i64 FP_TO_UINT is supported only with FPCVT");
8303     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8304   }
8305   if (IsStrict) {
8306     Opc = getPPCStrictOpcode(Opc);
8307     Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
8308                        {Chain, Src}, Flags);
8309   } else {
8310     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8311   }
8312   return Conv;
8313 }
8314 
8315 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8316                                                SelectionDAG &DAG,
8317                                                const SDLoc &dl) const {
8318   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8319   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8320                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8321   bool IsStrict = Op->isStrictFPOpcode();
8322 
8323   // Convert the FP value to an int value through memory.
8324   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8325                   (IsSigned || Subtarget.hasFPCVT());
8326   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8327   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8328   MachinePointerInfo MPI =
8329       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8330 
8331   // Emit a store to the stack slot.
8332   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8333   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8334   if (i32Stack) {
8335     MachineFunction &MF = DAG.getMachineFunction();
8336     Alignment = Align(4);
8337     MachineMemOperand *MMO =
8338         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8339     SDValue Ops[] = { Chain, Tmp, FIPtr };
8340     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8341               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8342   } else
8343     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8344 
8345   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8346   // add in a bias on big endian.
8347   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8348     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8349                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8350     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8351   }
8352 
8353   RLI.Chain = Chain;
8354   RLI.Ptr = FIPtr;
8355   RLI.MPI = MPI;
8356   RLI.Alignment = Alignment;
8357 }
8358 
8359 /// Custom lowers floating point to integer conversions to use
8360 /// the direct move instructions available in ISA 2.07 to avoid the
8361 /// need for load/store combinations.
8362 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8363                                                     SelectionDAG &DAG,
8364                                                     const SDLoc &dl) const {
8365   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8366   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8367   if (Op->isStrictFPOpcode())
8368     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8369   else
8370     return Mov;
8371 }
8372 
8373 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8374                                           const SDLoc &dl) const {
8375   bool IsStrict = Op->isStrictFPOpcode();
8376   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8377                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8378   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8379   EVT SrcVT = Src.getValueType();
8380   EVT DstVT = Op.getValueType();
8381 
8382   // FP to INT conversions are legal for f128.
8383   if (SrcVT == MVT::f128)
8384     return Op;
8385 
8386   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8387   // PPC (the libcall is not available).
8388   if (SrcVT == MVT::ppcf128) {
8389     if (DstVT == MVT::i32) {
8390       // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8391       // set other fast-math flags to FP operations in both strict and
8392       // non-strict cases. (FP_TO_SINT, FSUB)
8393       SDNodeFlags Flags;
8394       Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8395 
8396       if (IsSigned) {
8397         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8398                                  DAG.getIntPtrConstant(0, dl));
8399         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8400                                  DAG.getIntPtrConstant(1, dl));
8401 
8402         // Add the two halves of the long double in round-to-zero mode, and use
8403         // a smaller FP_TO_SINT.
8404         if (IsStrict) {
8405           SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8406                                     DAG.getVTList(MVT::f64, MVT::Other),
8407                                     {Op.getOperand(0), Lo, Hi}, Flags);
8408           return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8409                              DAG.getVTList(MVT::i32, MVT::Other),
8410                              {Res.getValue(1), Res}, Flags);
8411         } else {
8412           SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8413           return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8414         }
8415       } else {
8416         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8417         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8418         SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8419         SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8420         if (IsStrict) {
8421           // Sel = Src < 0x80000000
8422           // FltOfs = select Sel, 0.0, 0x80000000
8423           // IntOfs = select Sel, 0, 0x80000000
8424           // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8425           SDValue Chain = Op.getOperand(0);
8426           EVT SetCCVT =
8427               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8428           EVT DstSetCCVT =
8429               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8430           SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8431                                      Chain, true);
8432           Chain = Sel.getValue(1);
8433 
8434           SDValue FltOfs = DAG.getSelect(
8435               dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8436           Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8437 
8438           SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8439                                     DAG.getVTList(SrcVT, MVT::Other),
8440                                     {Chain, Src, FltOfs}, Flags);
8441           Chain = Val.getValue(1);
8442           SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8443                                      DAG.getVTList(DstVT, MVT::Other),
8444                                      {Chain, Val}, Flags);
8445           Chain = SInt.getValue(1);
8446           SDValue IntOfs = DAG.getSelect(
8447               dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8448           SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8449           return DAG.getMergeValues({Result, Chain}, dl);
8450         } else {
8451           // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8452           // FIXME: generated code sucks.
8453           SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8454           True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8455           True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8456           SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8457           return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8458         }
8459       }
8460     }
8461 
8462     return SDValue();
8463   }
8464 
8465   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8466     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8467 
8468   ReuseLoadInfo RLI;
8469   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8470 
8471   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8472                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8473 }
8474 
8475 // We're trying to insert a regular store, S, and then a load, L. If the
8476 // incoming value, O, is a load, we might just be able to have our load use the
8477 // address used by O. However, we don't know if anything else will store to
8478 // that address before we can load from it. To prevent this situation, we need
8479 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8480 // the same chain operand as O, we create a token factor from the chain results
8481 // of O and L, and we replace all uses of O's chain result with that token
8482 // factor (see spliceIntoChain below for this last part).
8483 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8484                                             ReuseLoadInfo &RLI,
8485                                             SelectionDAG &DAG,
8486                                             ISD::LoadExtType ET) const {
8487   // Conservatively skip reusing for constrained FP nodes.
8488   if (Op->isStrictFPOpcode())
8489     return false;
8490 
8491   SDLoc dl(Op);
8492   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8493                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8494   if (ET == ISD::NON_EXTLOAD &&
8495       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8496       isOperationLegalOrCustom(Op.getOpcode(),
8497                                Op.getOperand(0).getValueType())) {
8498 
8499     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8500     return true;
8501   }
8502 
8503   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8504   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8505       LD->isNonTemporal())
8506     return false;
8507   if (LD->getMemoryVT() != MemVT)
8508     return false;
8509 
8510   // If the result of the load is an illegal type, then we can't build a
8511   // valid chain for reuse since the legalised loads and token factor node that
8512   // ties the legalised loads together uses a different output chain then the
8513   // illegal load.
8514   if (!isTypeLegal(LD->getValueType(0)))
8515     return false;
8516 
8517   RLI.Ptr = LD->getBasePtr();
8518   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8519     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8520            "Non-pre-inc AM on PPC?");
8521     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8522                           LD->getOffset());
8523   }
8524 
8525   RLI.Chain = LD->getChain();
8526   RLI.MPI = LD->getPointerInfo();
8527   RLI.IsDereferenceable = LD->isDereferenceable();
8528   RLI.IsInvariant = LD->isInvariant();
8529   RLI.Alignment = LD->getAlign();
8530   RLI.AAInfo = LD->getAAInfo();
8531   RLI.Ranges = LD->getRanges();
8532 
8533   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8534   return true;
8535 }
8536 
8537 // Given the head of the old chain, ResChain, insert a token factor containing
8538 // it and NewResChain, and make users of ResChain now be users of that token
8539 // factor.
8540 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8541 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8542                                         SDValue NewResChain,
8543                                         SelectionDAG &DAG) const {
8544   if (!ResChain)
8545     return;
8546 
8547   SDLoc dl(NewResChain);
8548 
8549   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8550                            NewResChain, DAG.getUNDEF(MVT::Other));
8551   assert(TF.getNode() != NewResChain.getNode() &&
8552          "A new TF really is required here");
8553 
8554   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8555   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8556 }
8557 
8558 /// Analyze profitability of direct move
8559 /// prefer float load to int load plus direct move
8560 /// when there is no integer use of int load
8561 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8562   SDNode *Origin = Op.getOperand(0).getNode();
8563   if (Origin->getOpcode() != ISD::LOAD)
8564     return true;
8565 
8566   // If there is no LXSIBZX/LXSIHZX, like Power8,
8567   // prefer direct move if the memory size is 1 or 2 bytes.
8568   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8569   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8570     return true;
8571 
8572   for (SDNode::use_iterator UI = Origin->use_begin(),
8573                             UE = Origin->use_end();
8574        UI != UE; ++UI) {
8575 
8576     // Only look at the users of the loaded value.
8577     if (UI.getUse().get().getResNo() != 0)
8578       continue;
8579 
8580     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8581         UI->getOpcode() != ISD::UINT_TO_FP &&
8582         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8583         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8584       return true;
8585   }
8586 
8587   return false;
8588 }
8589 
8590 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8591                               const PPCSubtarget &Subtarget,
8592                               SDValue Chain = SDValue()) {
8593   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8594                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8595   SDLoc dl(Op);
8596 
8597   // TODO: Any other flags to propagate?
8598   SDNodeFlags Flags;
8599   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8600 
8601   // If we have FCFIDS, then use it when converting to single-precision.
8602   // Otherwise, convert to double-precision and then round.
8603   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8604   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8605                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8606   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8607   if (Op->isStrictFPOpcode()) {
8608     if (!Chain)
8609       Chain = Op.getOperand(0);
8610     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8611                        DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8612   } else
8613     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8614 }
8615 
8616 /// Custom lowers integer to floating point conversions to use
8617 /// the direct move instructions available in ISA 2.07 to avoid the
8618 /// need for load/store combinations.
8619 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8620                                                     SelectionDAG &DAG,
8621                                                     const SDLoc &dl) const {
8622   assert((Op.getValueType() == MVT::f32 ||
8623           Op.getValueType() == MVT::f64) &&
8624          "Invalid floating point type as target of conversion");
8625   assert(Subtarget.hasFPCVT() &&
8626          "Int to FP conversions with direct moves require FPCVT");
8627   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8628   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8629   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8630                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8631   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8632   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8633   return convertIntToFP(Op, Mov, DAG, Subtarget);
8634 }
8635 
8636 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8637 
8638   EVT VecVT = Vec.getValueType();
8639   assert(VecVT.isVector() && "Expected a vector type.");
8640   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8641 
8642   EVT EltVT = VecVT.getVectorElementType();
8643   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8644   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8645 
8646   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8647   SmallVector<SDValue, 16> Ops(NumConcat);
8648   Ops[0] = Vec;
8649   SDValue UndefVec = DAG.getUNDEF(VecVT);
8650   for (unsigned i = 1; i < NumConcat; ++i)
8651     Ops[i] = UndefVec;
8652 
8653   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8654 }
8655 
8656 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8657                                                 const SDLoc &dl) const {
8658   bool IsStrict = Op->isStrictFPOpcode();
8659   unsigned Opc = Op.getOpcode();
8660   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8661   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8662           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8663          "Unexpected conversion type");
8664   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8665          "Supports conversions to v2f64/v4f32 only.");
8666 
8667   // TODO: Any other flags to propagate?
8668   SDNodeFlags Flags;
8669   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8670 
8671   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8672   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8673 
8674   SDValue Wide = widenVec(DAG, Src, dl);
8675   EVT WideVT = Wide.getValueType();
8676   unsigned WideNumElts = WideVT.getVectorNumElements();
8677   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8678 
8679   SmallVector<int, 16> ShuffV;
8680   for (unsigned i = 0; i < WideNumElts; ++i)
8681     ShuffV.push_back(i + WideNumElts);
8682 
8683   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8684   int SaveElts = FourEltRes ? 4 : 2;
8685   if (Subtarget.isLittleEndian())
8686     for (int i = 0; i < SaveElts; i++)
8687       ShuffV[i * Stride] = i;
8688   else
8689     for (int i = 1; i <= SaveElts; i++)
8690       ShuffV[i * Stride - 1] = i - 1;
8691 
8692   SDValue ShuffleSrc2 =
8693       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8694   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8695 
8696   SDValue Extend;
8697   if (SignedConv) {
8698     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8699     EVT ExtVT = Src.getValueType();
8700     if (Subtarget.hasP9Altivec())
8701       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8702                                IntermediateVT.getVectorNumElements());
8703 
8704     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8705                          DAG.getValueType(ExtVT));
8706   } else
8707     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8708 
8709   if (IsStrict)
8710     return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8711                        {Op.getOperand(0), Extend}, Flags);
8712 
8713   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8714 }
8715 
8716 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8717                                           SelectionDAG &DAG) const {
8718   SDLoc dl(Op);
8719   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8720                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8721   bool IsStrict = Op->isStrictFPOpcode();
8722   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8723   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8724 
8725   // TODO: Any other flags to propagate?
8726   SDNodeFlags Flags;
8727   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8728 
8729   EVT InVT = Src.getValueType();
8730   EVT OutVT = Op.getValueType();
8731   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8732       isOperationCustom(Op.getOpcode(), InVT))
8733     return LowerINT_TO_FPVector(Op, DAG, dl);
8734 
8735   // Conversions to f128 are legal.
8736   if (Op.getValueType() == MVT::f128)
8737     return Op;
8738 
8739   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8740   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8741     return SDValue();
8742 
8743   if (Src.getValueType() == MVT::i1) {
8744     SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8745                               DAG.getConstantFP(1.0, dl, Op.getValueType()),
8746                               DAG.getConstantFP(0.0, dl, Op.getValueType()));
8747     if (IsStrict)
8748       return DAG.getMergeValues({Sel, Chain}, dl);
8749     else
8750       return Sel;
8751   }
8752 
8753   // If we have direct moves, we can do all the conversion, skip the store/load
8754   // however, without FPCVT we can't do most conversions.
8755   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8756       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8757     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8758 
8759   assert((IsSigned || Subtarget.hasFPCVT()) &&
8760          "UINT_TO_FP is supported only with FPCVT");
8761 
8762   if (Src.getValueType() == MVT::i64) {
8763     SDValue SINT = Src;
8764     // When converting to single-precision, we actually need to convert
8765     // to double-precision first and then round to single-precision.
8766     // To avoid double-rounding effects during that operation, we have
8767     // to prepare the input operand.  Bits that might be truncated when
8768     // converting to double-precision are replaced by a bit that won't
8769     // be lost at this stage, but is below the single-precision rounding
8770     // position.
8771     //
8772     // However, if -enable-unsafe-fp-math is in effect, accept double
8773     // rounding to avoid the extra overhead.
8774     if (Op.getValueType() == MVT::f32 &&
8775         !Subtarget.hasFPCVT() &&
8776         !DAG.getTarget().Options.UnsafeFPMath) {
8777 
8778       // Twiddle input to make sure the low 11 bits are zero.  (If this
8779       // is the case, we are guaranteed the value will fit into the 53 bit
8780       // mantissa of an IEEE double-precision value without rounding.)
8781       // If any of those low 11 bits were not zero originally, make sure
8782       // bit 12 (value 2048) is set instead, so that the final rounding
8783       // to single-precision gets the correct result.
8784       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8785                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8786       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8787                           Round, DAG.getConstant(2047, dl, MVT::i64));
8788       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8789       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8790                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8791 
8792       // However, we cannot use that value unconditionally: if the magnitude
8793       // of the input value is small, the bit-twiddling we did above might
8794       // end up visibly changing the output.  Fortunately, in that case, we
8795       // don't need to twiddle bits since the original input will convert
8796       // exactly to double-precision floating-point already.  Therefore,
8797       // construct a conditional to use the original value if the top 11
8798       // bits are all sign-bit copies, and use the rounded value computed
8799       // above otherwise.
8800       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8801                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8802       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8803                          Cond, DAG.getConstant(1, dl, MVT::i64));
8804       Cond = DAG.getSetCC(
8805           dl,
8806           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8807           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8808 
8809       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8810     }
8811 
8812     ReuseLoadInfo RLI;
8813     SDValue Bits;
8814 
8815     MachineFunction &MF = DAG.getMachineFunction();
8816     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8817       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8818                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8819       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8820     } else if (Subtarget.hasLFIWAX() &&
8821                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8822       MachineMemOperand *MMO =
8823         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8824                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8825       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8826       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8827                                      DAG.getVTList(MVT::f64, MVT::Other),
8828                                      Ops, MVT::i32, MMO);
8829       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8830     } else if (Subtarget.hasFPCVT() &&
8831                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8832       MachineMemOperand *MMO =
8833         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8834                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8835       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8836       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8837                                      DAG.getVTList(MVT::f64, MVT::Other),
8838                                      Ops, MVT::i32, MMO);
8839       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8840     } else if (((Subtarget.hasLFIWAX() &&
8841                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8842                 (Subtarget.hasFPCVT() &&
8843                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8844                SINT.getOperand(0).getValueType() == MVT::i32) {
8845       MachineFrameInfo &MFI = MF.getFrameInfo();
8846       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8847 
8848       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8849       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8850 
8851       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8852                                    MachinePointerInfo::getFixedStack(
8853                                        DAG.getMachineFunction(), FrameIdx));
8854       Chain = Store;
8855 
8856       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8857              "Expected an i32 store");
8858 
8859       RLI.Ptr = FIdx;
8860       RLI.Chain = Chain;
8861       RLI.MPI =
8862           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8863       RLI.Alignment = Align(4);
8864 
8865       MachineMemOperand *MMO =
8866         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8867                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8868       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8869       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8870                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8871                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8872                                      Ops, MVT::i32, MMO);
8873       Chain = Bits.getValue(1);
8874     } else
8875       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8876 
8877     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8878     if (IsStrict)
8879       Chain = FP.getValue(1);
8880 
8881     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8882       if (IsStrict)
8883         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8884                          DAG.getVTList(MVT::f32, MVT::Other),
8885                          {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8886       else
8887         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8888                          DAG.getIntPtrConstant(0, dl));
8889     }
8890     return FP;
8891   }
8892 
8893   assert(Src.getValueType() == MVT::i32 &&
8894          "Unhandled INT_TO_FP type in custom expander!");
8895   // Since we only generate this in 64-bit mode, we can take advantage of
8896   // 64-bit registers.  In particular, sign extend the input value into the
8897   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8898   // then lfd it and fcfid it.
8899   MachineFunction &MF = DAG.getMachineFunction();
8900   MachineFrameInfo &MFI = MF.getFrameInfo();
8901   EVT PtrVT = getPointerTy(MF.getDataLayout());
8902 
8903   SDValue Ld;
8904   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8905     ReuseLoadInfo RLI;
8906     bool ReusingLoad;
8907     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8908       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8909       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8910 
8911       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8912                                    MachinePointerInfo::getFixedStack(
8913                                        DAG.getMachineFunction(), FrameIdx));
8914       Chain = Store;
8915 
8916       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8917              "Expected an i32 store");
8918 
8919       RLI.Ptr = FIdx;
8920       RLI.Chain = Chain;
8921       RLI.MPI =
8922           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8923       RLI.Alignment = Align(4);
8924     }
8925 
8926     MachineMemOperand *MMO =
8927       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8928                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8929     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8930     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8931                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8932                                  MVT::i32, MMO);
8933     Chain = Ld.getValue(1);
8934     if (ReusingLoad)
8935       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8936   } else {
8937     assert(Subtarget.isPPC64() &&
8938            "i32->FP without LFIWAX supported only on PPC64");
8939 
8940     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8941     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8942 
8943     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8944 
8945     // STD the extended value into the stack slot.
8946     SDValue Store = DAG.getStore(
8947         Chain, dl, Ext64, FIdx,
8948         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8949     Chain = Store;
8950 
8951     // Load the value as a double.
8952     Ld = DAG.getLoad(
8953         MVT::f64, dl, Chain, FIdx,
8954         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8955     Chain = Ld.getValue(1);
8956   }
8957 
8958   // FCFID it and return it.
8959   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8960   if (IsStrict)
8961     Chain = FP.getValue(1);
8962   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8963     if (IsStrict)
8964       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8965                        DAG.getVTList(MVT::f32, MVT::Other),
8966                        {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8967     else
8968       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8969                        DAG.getIntPtrConstant(0, dl));
8970   }
8971   return FP;
8972 }
8973 
8974 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8975                                             SelectionDAG &DAG) const {
8976   SDLoc dl(Op);
8977   /*
8978    The rounding mode is in bits 30:31 of FPSR, and has the following
8979    settings:
8980      00 Round to nearest
8981      01 Round to 0
8982      10 Round to +inf
8983      11 Round to -inf
8984 
8985   FLT_ROUNDS, on the other hand, expects the following:
8986     -1 Undefined
8987      0 Round to 0
8988      1 Round to nearest
8989      2 Round to +inf
8990      3 Round to -inf
8991 
8992   To perform the conversion, we do:
8993     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8994   */
8995 
8996   MachineFunction &MF = DAG.getMachineFunction();
8997   EVT VT = Op.getValueType();
8998   EVT PtrVT = getPointerTy(MF.getDataLayout());
8999 
9000   // Save FP Control Word to register
9001   SDValue Chain = Op.getOperand(0);
9002   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
9003   Chain = MFFS.getValue(1);
9004 
9005   SDValue CWD;
9006   if (isTypeLegal(MVT::i64)) {
9007     CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
9008                       DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
9009   } else {
9010     // Save FP register to stack slot
9011     int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
9012     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
9013     Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
9014 
9015     // Load FP Control Word from low 32 bits of stack slot.
9016     assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) &&
9017            "Stack slot adjustment is valid only on big endian subtargets!");
9018     SDValue Four = DAG.getConstant(4, dl, PtrVT);
9019     SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
9020     CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
9021     Chain = CWD.getValue(1);
9022   }
9023 
9024   // Transform as necessary
9025   SDValue CWD1 =
9026     DAG.getNode(ISD::AND, dl, MVT::i32,
9027                 CWD, DAG.getConstant(3, dl, MVT::i32));
9028   SDValue CWD2 =
9029     DAG.getNode(ISD::SRL, dl, MVT::i32,
9030                 DAG.getNode(ISD::AND, dl, MVT::i32,
9031                             DAG.getNode(ISD::XOR, dl, MVT::i32,
9032                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
9033                             DAG.getConstant(3, dl, MVT::i32)),
9034                 DAG.getConstant(1, dl, MVT::i32));
9035 
9036   SDValue RetVal =
9037     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
9038 
9039   RetVal =
9040       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
9041                   dl, VT, RetVal);
9042 
9043   return DAG.getMergeValues({RetVal, Chain}, dl);
9044 }
9045 
9046 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
9047   EVT VT = Op.getValueType();
9048   unsigned BitWidth = VT.getSizeInBits();
9049   SDLoc dl(Op);
9050   assert(Op.getNumOperands() == 3 &&
9051          VT == Op.getOperand(1).getValueType() &&
9052          "Unexpected SHL!");
9053 
9054   // Expand into a bunch of logical ops.  Note that these ops
9055   // depend on the PPC behavior for oversized shift amounts.
9056   SDValue Lo = Op.getOperand(0);
9057   SDValue Hi = Op.getOperand(1);
9058   SDValue Amt = Op.getOperand(2);
9059   EVT AmtVT = Amt.getValueType();
9060 
9061   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
9062                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
9063   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
9064   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
9065   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
9066   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
9067                              DAG.getConstant(-BitWidth, dl, AmtVT));
9068   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
9069   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
9070   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
9071   SDValue OutOps[] = { OutLo, OutHi };
9072   return DAG.getMergeValues(OutOps, dl);
9073 }
9074 
9075 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
9076   EVT VT = Op.getValueType();
9077   SDLoc dl(Op);
9078   unsigned BitWidth = VT.getSizeInBits();
9079   assert(Op.getNumOperands() == 3 &&
9080          VT == Op.getOperand(1).getValueType() &&
9081          "Unexpected SRL!");
9082 
9083   // Expand into a bunch of logical ops.  Note that these ops
9084   // depend on the PPC behavior for oversized shift amounts.
9085   SDValue Lo = Op.getOperand(0);
9086   SDValue Hi = Op.getOperand(1);
9087   SDValue Amt = Op.getOperand(2);
9088   EVT AmtVT = Amt.getValueType();
9089 
9090   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
9091                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
9092   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
9093   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
9094   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
9095   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
9096                              DAG.getConstant(-BitWidth, dl, AmtVT));
9097   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
9098   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
9099   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
9100   SDValue OutOps[] = { OutLo, OutHi };
9101   return DAG.getMergeValues(OutOps, dl);
9102 }
9103 
9104 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
9105   SDLoc dl(Op);
9106   EVT VT = Op.getValueType();
9107   unsigned BitWidth = VT.getSizeInBits();
9108   assert(Op.getNumOperands() == 3 &&
9109          VT == Op.getOperand(1).getValueType() &&
9110          "Unexpected SRA!");
9111 
9112   // Expand into a bunch of logical ops, followed by a select_cc.
9113   SDValue Lo = Op.getOperand(0);
9114   SDValue Hi = Op.getOperand(1);
9115   SDValue Amt = Op.getOperand(2);
9116   EVT AmtVT = Amt.getValueType();
9117 
9118   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
9119                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
9120   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
9121   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
9122   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
9123   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
9124                              DAG.getConstant(-BitWidth, dl, AmtVT));
9125   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
9126   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
9127   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
9128                                   Tmp4, Tmp6, ISD::SETLE);
9129   SDValue OutOps[] = { OutLo, OutHi };
9130   return DAG.getMergeValues(OutOps, dl);
9131 }
9132 
9133 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
9134                                             SelectionDAG &DAG) const {
9135   SDLoc dl(Op);
9136   EVT VT = Op.getValueType();
9137   unsigned BitWidth = VT.getSizeInBits();
9138 
9139   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
9140   SDValue X = Op.getOperand(0);
9141   SDValue Y = Op.getOperand(1);
9142   SDValue Z = Op.getOperand(2);
9143   EVT AmtVT = Z.getValueType();
9144 
9145   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
9146   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
9147   // This is simpler than TargetLowering::expandFunnelShift because we can rely
9148   // on PowerPC shift by BW being well defined.
9149   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
9150                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
9151   SDValue SubZ =
9152       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
9153   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
9154   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
9155   return DAG.getNode(ISD::OR, dl, VT, X, Y);
9156 }
9157 
9158 //===----------------------------------------------------------------------===//
9159 // Vector related lowering.
9160 //
9161 
9162 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
9163 /// element size of SplatSize. Cast the result to VT.
9164 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
9165                                       SelectionDAG &DAG, const SDLoc &dl) {
9166   static const MVT VTys[] = { // canonical VT to use for each size.
9167     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
9168   };
9169 
9170   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
9171 
9172   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
9173   if (Val == ((1LU << (SplatSize * 8)) - 1)) {
9174     SplatSize = 1;
9175     Val = 0xFF;
9176   }
9177 
9178   EVT CanonicalVT = VTys[SplatSize-1];
9179 
9180   // Build a canonical splat for this value.
9181   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
9182 }
9183 
9184 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
9185 /// specified intrinsic ID.
9186 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
9187                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
9188   if (DestVT == MVT::Other) DestVT = Op.getValueType();
9189   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9190                      DAG.getConstant(IID, dl, MVT::i32), Op);
9191 }
9192 
9193 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
9194 /// specified intrinsic ID.
9195 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
9196                                 SelectionDAG &DAG, const SDLoc &dl,
9197                                 EVT DestVT = MVT::Other) {
9198   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
9199   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9200                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
9201 }
9202 
9203 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
9204 /// specified intrinsic ID.
9205 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
9206                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
9207                                 EVT DestVT = MVT::Other) {
9208   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
9209   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9210                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
9211 }
9212 
9213 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
9214 /// amount.  The result has the specified value type.
9215 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
9216                            SelectionDAG &DAG, const SDLoc &dl) {
9217   // Force LHS/RHS to be the right type.
9218   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
9219   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
9220 
9221   int Ops[16];
9222   for (unsigned i = 0; i != 16; ++i)
9223     Ops[i] = i + Amt;
9224   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
9225   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9226 }
9227 
9228 /// Do we have an efficient pattern in a .td file for this node?
9229 ///
9230 /// \param V - pointer to the BuildVectorSDNode being matched
9231 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
9232 ///
9233 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
9234 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
9235 /// the opposite is true (expansion is beneficial) are:
9236 /// - The node builds a vector out of integers that are not 32 or 64-bits
9237 /// - The node builds a vector out of constants
9238 /// - The node is a "load-and-splat"
9239 /// In all other cases, we will choose to keep the BUILD_VECTOR.
9240 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
9241                                             bool HasDirectMove,
9242                                             bool HasP8Vector) {
9243   EVT VecVT = V->getValueType(0);
9244   bool RightType = VecVT == MVT::v2f64 ||
9245     (HasP8Vector && VecVT == MVT::v4f32) ||
9246     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
9247   if (!RightType)
9248     return false;
9249 
9250   bool IsSplat = true;
9251   bool IsLoad = false;
9252   SDValue Op0 = V->getOperand(0);
9253 
9254   // This function is called in a block that confirms the node is not a constant
9255   // splat. So a constant BUILD_VECTOR here means the vector is built out of
9256   // different constants.
9257   if (V->isConstant())
9258     return false;
9259   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9260     if (V->getOperand(i).isUndef())
9261       return false;
9262     // We want to expand nodes that represent load-and-splat even if the
9263     // loaded value is a floating point truncation or conversion to int.
9264     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9265         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9266          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9267         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9268          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9269         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9270          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9271       IsLoad = true;
9272     // If the operands are different or the input is not a load and has more
9273     // uses than just this BV node, then it isn't a splat.
9274     if (V->getOperand(i) != Op0 ||
9275         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9276       IsSplat = false;
9277   }
9278   return !(IsSplat && IsLoad);
9279 }
9280 
9281 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9282 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9283 
9284   SDLoc dl(Op);
9285   SDValue Op0 = Op->getOperand(0);
9286 
9287   if ((Op.getValueType() != MVT::f128) ||
9288       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9289       (Op0.getOperand(0).getValueType() != MVT::i64) ||
9290       (Op0.getOperand(1).getValueType() != MVT::i64))
9291     return SDValue();
9292 
9293   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9294                      Op0.getOperand(1));
9295 }
9296 
9297 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9298   const SDValue *InputLoad = &Op;
9299   if (InputLoad->getOpcode() == ISD::BITCAST)
9300     InputLoad = &InputLoad->getOperand(0);
9301   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9302       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9303     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9304     InputLoad = &InputLoad->getOperand(0);
9305   }
9306   if (InputLoad->getOpcode() != ISD::LOAD)
9307     return nullptr;
9308   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9309   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9310 }
9311 
9312 // Convert the argument APFloat to a single precision APFloat if there is no
9313 // loss in information during the conversion to single precision APFloat and the
9314 // resulting number is not a denormal number. Return true if successful.
9315 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9316   APFloat APFloatToConvert = ArgAPFloat;
9317   bool LosesInfo = true;
9318   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9319                            &LosesInfo);
9320   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9321   if (Success)
9322     ArgAPFloat = APFloatToConvert;
9323   return Success;
9324 }
9325 
9326 // Bitcast the argument APInt to a double and convert it to a single precision
9327 // APFloat, bitcast the APFloat to an APInt and assign it to the original
9328 // argument if there is no loss in information during the conversion from
9329 // double to single precision APFloat and the resulting number is not a denormal
9330 // number. Return true if successful.
9331 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9332   double DpValue = ArgAPInt.bitsToDouble();
9333   APFloat APFloatDp(DpValue);
9334   bool Success = convertToNonDenormSingle(APFloatDp);
9335   if (Success)
9336     ArgAPInt = APFloatDp.bitcastToAPInt();
9337   return Success;
9338 }
9339 
9340 // If this is a case we can't handle, return null and let the default
9341 // expansion code take care of it.  If we CAN select this case, and if it
9342 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9343 // this case more efficiently than a constant pool load, lower it to the
9344 // sequence of ops that should be used.
9345 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9346                                              SelectionDAG &DAG) const {
9347   SDLoc dl(Op);
9348   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9349   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9350 
9351   // Check if this is a splat of a constant value.
9352   APInt APSplatBits, APSplatUndef;
9353   unsigned SplatBitSize;
9354   bool HasAnyUndefs;
9355   bool BVNIsConstantSplat =
9356       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9357                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9358 
9359   // If it is a splat of a double, check if we can shrink it to a 32 bit
9360   // non-denormal float which when converted back to double gives us the same
9361   // double. This is to exploit the XXSPLTIDP instruction.
9362   if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() &&
9363       (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) &&
9364       convertToNonDenormSingle(APSplatBits)) {
9365     SDValue SplatNode = DAG.getNode(
9366         PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9367         DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9368     return DAG.getBitcast(Op.getValueType(), SplatNode);
9369   }
9370 
9371   if (!BVNIsConstantSplat || SplatBitSize > 32) {
9372 
9373     bool IsPermutedLoad = false;
9374     const SDValue *InputLoad =
9375         getNormalLoadInput(Op.getOperand(0), IsPermutedLoad);
9376     // Handle load-and-splat patterns as we have instructions that will do this
9377     // in one go.
9378     if (InputLoad && DAG.isSplatValue(Op, true)) {
9379       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9380 
9381       // We have handling for 4 and 8 byte elements.
9382       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9383 
9384       // Checking for a single use of this load, we have to check for vector
9385       // width (128 bits) / ElementSize uses (since each operand of the
9386       // BUILD_VECTOR is a separate use of the value.
9387       unsigned NumUsesOfInputLD = 128 / ElementSize;
9388       for (SDValue BVInOp : Op->ops())
9389         if (BVInOp.isUndef())
9390           NumUsesOfInputLD--;
9391       assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
9392       if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
9393           ((Subtarget.hasVSX() && ElementSize == 64) ||
9394            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9395         SDValue Ops[] = {
9396           LD->getChain(),    // Chain
9397           LD->getBasePtr(),  // Ptr
9398           DAG.getValueType(Op.getValueType()) // VT
9399         };
9400         SDValue LdSplt = DAG.getMemIntrinsicNode(
9401             PPCISD::LD_SPLAT, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
9402             Ops, LD->getMemoryVT(), LD->getMemOperand());
9403         // Replace all uses of the output chain of the original load with the
9404         // output chain of the new load.
9405         DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
9406                                       LdSplt.getValue(1));
9407         return LdSplt;
9408       }
9409     }
9410 
9411     // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
9412     // 32-bits can be lowered to VSX instructions under certain conditions.
9413     // Without VSX, there is no pattern more efficient than expanding the node.
9414     if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
9415         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9416                                         Subtarget.hasP8Vector()))
9417       return Op;
9418     return SDValue();
9419   }
9420 
9421   uint64_t SplatBits = APSplatBits.getZExtValue();
9422   uint64_t SplatUndef = APSplatUndef.getZExtValue();
9423   unsigned SplatSize = SplatBitSize / 8;
9424 
9425   // First, handle single instruction cases.
9426 
9427   // All zeros?
9428   if (SplatBits == 0) {
9429     // Canonicalize all zero vectors to be v4i32.
9430     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9431       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9432       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9433     }
9434     return Op;
9435   }
9436 
9437   // We have XXSPLTIW for constant splats four bytes wide.
9438   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9439   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9440   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9441   // turned into a 4-byte splat of 0xABABABAB.
9442   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9443     return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
9444                                   Op.getValueType(), DAG, dl);
9445 
9446   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9447     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9448                                   dl);
9449 
9450   // We have XXSPLTIB for constant splats one byte wide.
9451   if (Subtarget.hasP9Vector() && SplatSize == 1)
9452     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9453                                   dl);
9454 
9455   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9456   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9457                     (32-SplatBitSize));
9458   if (SextVal >= -16 && SextVal <= 15)
9459     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9460                                   dl);
9461 
9462   // Two instruction sequences.
9463 
9464   // If this value is in the range [-32,30] and is even, use:
9465   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9466   // If this value is in the range [17,31] and is odd, use:
9467   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9468   // If this value is in the range [-31,-17] and is odd, use:
9469   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9470   // Note the last two are three-instruction sequences.
9471   if (SextVal >= -32 && SextVal <= 31) {
9472     // To avoid having these optimizations undone by constant folding,
9473     // we convert to a pseudo that will be expanded later into one of
9474     // the above forms.
9475     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9476     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9477               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9478     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9479     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9480     if (VT == Op.getValueType())
9481       return RetVal;
9482     else
9483       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9484   }
9485 
9486   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9487   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9488   // for fneg/fabs.
9489   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9490     // Make -1 and vspltisw -1:
9491     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9492 
9493     // Make the VSLW intrinsic, computing 0x8000_0000.
9494     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9495                                    OnesV, DAG, dl);
9496 
9497     // xor by OnesV to invert it.
9498     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9499     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9500   }
9501 
9502   // Check to see if this is a wide variety of vsplti*, binop self cases.
9503   static const signed char SplatCsts[] = {
9504     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9505     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9506   };
9507 
9508   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9509     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9510     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9511     int i = SplatCsts[idx];
9512 
9513     // Figure out what shift amount will be used by altivec if shifted by i in
9514     // this splat size.
9515     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9516 
9517     // vsplti + shl self.
9518     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9519       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9520       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9521         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9522         Intrinsic::ppc_altivec_vslw
9523       };
9524       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9525       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9526     }
9527 
9528     // vsplti + srl self.
9529     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9530       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9531       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9532         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9533         Intrinsic::ppc_altivec_vsrw
9534       };
9535       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9536       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9537     }
9538 
9539     // vsplti + sra self.
9540     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9541       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9542       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9543         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9544         Intrinsic::ppc_altivec_vsraw
9545       };
9546       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9547       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9548     }
9549 
9550     // vsplti + rol self.
9551     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9552                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9553       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9554       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9555         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9556         Intrinsic::ppc_altivec_vrlw
9557       };
9558       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9559       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9560     }
9561 
9562     // t = vsplti c, result = vsldoi t, t, 1
9563     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9564       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9565       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9566       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9567     }
9568     // t = vsplti c, result = vsldoi t, t, 2
9569     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9570       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9571       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9572       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9573     }
9574     // t = vsplti c, result = vsldoi t, t, 3
9575     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9576       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9577       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9578       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9579     }
9580   }
9581 
9582   return SDValue();
9583 }
9584 
9585 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9586 /// the specified operations to build the shuffle.
9587 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9588                                       SDValue RHS, SelectionDAG &DAG,
9589                                       const SDLoc &dl) {
9590   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9591   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9592   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9593 
9594   enum {
9595     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9596     OP_VMRGHW,
9597     OP_VMRGLW,
9598     OP_VSPLTISW0,
9599     OP_VSPLTISW1,
9600     OP_VSPLTISW2,
9601     OP_VSPLTISW3,
9602     OP_VSLDOI4,
9603     OP_VSLDOI8,
9604     OP_VSLDOI12
9605   };
9606 
9607   if (OpNum == OP_COPY) {
9608     if (LHSID == (1*9+2)*9+3) return LHS;
9609     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9610     return RHS;
9611   }
9612 
9613   SDValue OpLHS, OpRHS;
9614   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9615   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9616 
9617   int ShufIdxs[16];
9618   switch (OpNum) {
9619   default: llvm_unreachable("Unknown i32 permute!");
9620   case OP_VMRGHW:
9621     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9622     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9623     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9624     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9625     break;
9626   case OP_VMRGLW:
9627     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9628     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9629     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9630     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9631     break;
9632   case OP_VSPLTISW0:
9633     for (unsigned i = 0; i != 16; ++i)
9634       ShufIdxs[i] = (i&3)+0;
9635     break;
9636   case OP_VSPLTISW1:
9637     for (unsigned i = 0; i != 16; ++i)
9638       ShufIdxs[i] = (i&3)+4;
9639     break;
9640   case OP_VSPLTISW2:
9641     for (unsigned i = 0; i != 16; ++i)
9642       ShufIdxs[i] = (i&3)+8;
9643     break;
9644   case OP_VSPLTISW3:
9645     for (unsigned i = 0; i != 16; ++i)
9646       ShufIdxs[i] = (i&3)+12;
9647     break;
9648   case OP_VSLDOI4:
9649     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9650   case OP_VSLDOI8:
9651     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9652   case OP_VSLDOI12:
9653     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9654   }
9655   EVT VT = OpLHS.getValueType();
9656   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9657   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9658   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9659   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9660 }
9661 
9662 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9663 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9664 /// SDValue.
9665 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9666                                            SelectionDAG &DAG) const {
9667   const unsigned BytesInVector = 16;
9668   bool IsLE = Subtarget.isLittleEndian();
9669   SDLoc dl(N);
9670   SDValue V1 = N->getOperand(0);
9671   SDValue V2 = N->getOperand(1);
9672   unsigned ShiftElts = 0, InsertAtByte = 0;
9673   bool Swap = false;
9674 
9675   // Shifts required to get the byte we want at element 7.
9676   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9677                                    0, 15, 14, 13, 12, 11, 10, 9};
9678   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9679                                 1, 2,  3,  4,  5,  6,  7,  8};
9680 
9681   ArrayRef<int> Mask = N->getMask();
9682   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9683 
9684   // For each mask element, find out if we're just inserting something
9685   // from V2 into V1 or vice versa.
9686   // Possible permutations inserting an element from V2 into V1:
9687   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9688   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9689   //   ...
9690   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9691   // Inserting from V1 into V2 will be similar, except mask range will be
9692   // [16,31].
9693 
9694   bool FoundCandidate = false;
9695   // If both vector operands for the shuffle are the same vector, the mask
9696   // will contain only elements from the first one and the second one will be
9697   // undef.
9698   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9699   // Go through the mask of half-words to find an element that's being moved
9700   // from one vector to the other.
9701   for (unsigned i = 0; i < BytesInVector; ++i) {
9702     unsigned CurrentElement = Mask[i];
9703     // If 2nd operand is undefined, we should only look for element 7 in the
9704     // Mask.
9705     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9706       continue;
9707 
9708     bool OtherElementsInOrder = true;
9709     // Examine the other elements in the Mask to see if they're in original
9710     // order.
9711     for (unsigned j = 0; j < BytesInVector; ++j) {
9712       if (j == i)
9713         continue;
9714       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9715       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9716       // in which we always assume we're always picking from the 1st operand.
9717       int MaskOffset =
9718           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9719       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9720         OtherElementsInOrder = false;
9721         break;
9722       }
9723     }
9724     // If other elements are in original order, we record the number of shifts
9725     // we need to get the element we want into element 7. Also record which byte
9726     // in the vector we should insert into.
9727     if (OtherElementsInOrder) {
9728       // If 2nd operand is undefined, we assume no shifts and no swapping.
9729       if (V2.isUndef()) {
9730         ShiftElts = 0;
9731         Swap = false;
9732       } else {
9733         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9734         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9735                          : BigEndianShifts[CurrentElement & 0xF];
9736         Swap = CurrentElement < BytesInVector;
9737       }
9738       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9739       FoundCandidate = true;
9740       break;
9741     }
9742   }
9743 
9744   if (!FoundCandidate)
9745     return SDValue();
9746 
9747   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9748   // optionally with VECSHL if shift is required.
9749   if (Swap)
9750     std::swap(V1, V2);
9751   if (V2.isUndef())
9752     V2 = V1;
9753   if (ShiftElts) {
9754     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9755                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9756     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9757                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9758   }
9759   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9760                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9761 }
9762 
9763 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9764 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9765 /// SDValue.
9766 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9767                                            SelectionDAG &DAG) const {
9768   const unsigned NumHalfWords = 8;
9769   const unsigned BytesInVector = NumHalfWords * 2;
9770   // Check that the shuffle is on half-words.
9771   if (!isNByteElemShuffleMask(N, 2, 1))
9772     return SDValue();
9773 
9774   bool IsLE = Subtarget.isLittleEndian();
9775   SDLoc dl(N);
9776   SDValue V1 = N->getOperand(0);
9777   SDValue V2 = N->getOperand(1);
9778   unsigned ShiftElts = 0, InsertAtByte = 0;
9779   bool Swap = false;
9780 
9781   // Shifts required to get the half-word we want at element 3.
9782   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9783   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9784 
9785   uint32_t Mask = 0;
9786   uint32_t OriginalOrderLow = 0x1234567;
9787   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9788   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9789   // 32-bit space, only need 4-bit nibbles per element.
9790   for (unsigned i = 0; i < NumHalfWords; ++i) {
9791     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9792     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9793   }
9794 
9795   // For each mask element, find out if we're just inserting something
9796   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9797   // from V2 into V1:
9798   //   X, 1, 2, 3, 4, 5, 6, 7
9799   //   0, X, 2, 3, 4, 5, 6, 7
9800   //   0, 1, X, 3, 4, 5, 6, 7
9801   //   0, 1, 2, X, 4, 5, 6, 7
9802   //   0, 1, 2, 3, X, 5, 6, 7
9803   //   0, 1, 2, 3, 4, X, 6, 7
9804   //   0, 1, 2, 3, 4, 5, X, 7
9805   //   0, 1, 2, 3, 4, 5, 6, X
9806   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9807 
9808   bool FoundCandidate = false;
9809   // Go through the mask of half-words to find an element that's being moved
9810   // from one vector to the other.
9811   for (unsigned i = 0; i < NumHalfWords; ++i) {
9812     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9813     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9814     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9815     uint32_t TargetOrder = 0x0;
9816 
9817     // If both vector operands for the shuffle are the same vector, the mask
9818     // will contain only elements from the first one and the second one will be
9819     // undef.
9820     if (V2.isUndef()) {
9821       ShiftElts = 0;
9822       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9823       TargetOrder = OriginalOrderLow;
9824       Swap = false;
9825       // Skip if not the correct element or mask of other elements don't equal
9826       // to our expected order.
9827       if (MaskOneElt == VINSERTHSrcElem &&
9828           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9829         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9830         FoundCandidate = true;
9831         break;
9832       }
9833     } else { // If both operands are defined.
9834       // Target order is [8,15] if the current mask is between [0,7].
9835       TargetOrder =
9836           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9837       // Skip if mask of other elements don't equal our expected order.
9838       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9839         // We only need the last 3 bits for the number of shifts.
9840         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9841                          : BigEndianShifts[MaskOneElt & 0x7];
9842         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9843         Swap = MaskOneElt < NumHalfWords;
9844         FoundCandidate = true;
9845         break;
9846       }
9847     }
9848   }
9849 
9850   if (!FoundCandidate)
9851     return SDValue();
9852 
9853   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9854   // optionally with VECSHL if shift is required.
9855   if (Swap)
9856     std::swap(V1, V2);
9857   if (V2.isUndef())
9858     V2 = V1;
9859   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9860   if (ShiftElts) {
9861     // Double ShiftElts because we're left shifting on v16i8 type.
9862     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9863                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9864     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9865     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9866                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9867     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9868   }
9869   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9870   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9871                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9872   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9873 }
9874 
9875 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9876 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9877 /// return the default SDValue.
9878 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9879                                               SelectionDAG &DAG) const {
9880   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9881   // to v16i8. Peek through the bitcasts to get the actual operands.
9882   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9883   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9884 
9885   auto ShuffleMask = SVN->getMask();
9886   SDValue VecShuffle(SVN, 0);
9887   SDLoc DL(SVN);
9888 
9889   // Check that we have a four byte shuffle.
9890   if (!isNByteElemShuffleMask(SVN, 4, 1))
9891     return SDValue();
9892 
9893   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9894   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9895     std::swap(LHS, RHS);
9896     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9897     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9898   }
9899 
9900   // Ensure that the RHS is a vector of constants.
9901   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9902   if (!BVN)
9903     return SDValue();
9904 
9905   // Check if RHS is a splat of 4-bytes (or smaller).
9906   APInt APSplatValue, APSplatUndef;
9907   unsigned SplatBitSize;
9908   bool HasAnyUndefs;
9909   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9910                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9911       SplatBitSize > 32)
9912     return SDValue();
9913 
9914   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9915   // The instruction splats a constant C into two words of the source vector
9916   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9917   // Thus we check that the shuffle mask is the equivalent  of
9918   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9919   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9920   // within each word are consecutive, so we only need to check the first byte.
9921   SDValue Index;
9922   bool IsLE = Subtarget.isLittleEndian();
9923   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9924       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9925        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9926     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9927   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9928            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9929             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9930     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9931   else
9932     return SDValue();
9933 
9934   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9935   // for XXSPLTI32DX.
9936   unsigned SplatVal = APSplatValue.getZExtValue();
9937   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9938     SplatVal |= (SplatVal << SplatBitSize);
9939 
9940   SDValue SplatNode = DAG.getNode(
9941       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9942       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9943   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9944 }
9945 
9946 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9947 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9948 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9949 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9950 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9951   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9952   assert(Op.getValueType() == MVT::v1i128 &&
9953          "Only set v1i128 as custom, other type shouldn't reach here!");
9954   SDLoc dl(Op);
9955   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9956   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9957   unsigned SHLAmt = N1.getConstantOperandVal(0);
9958   if (SHLAmt % 8 == 0) {
9959     SmallVector<int, 16> Mask(16, 0);
9960     std::iota(Mask.begin(), Mask.end(), 0);
9961     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9962     if (SDValue Shuffle =
9963             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9964                                  DAG.getUNDEF(MVT::v16i8), Mask))
9965       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9966   }
9967   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9968   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9969                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9970   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9971                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9972   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9973   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9974 }
9975 
9976 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9977 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9978 /// return the code it can be lowered into.  Worst case, it can always be
9979 /// lowered into a vperm.
9980 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9981                                                SelectionDAG &DAG) const {
9982   SDLoc dl(Op);
9983   SDValue V1 = Op.getOperand(0);
9984   SDValue V2 = Op.getOperand(1);
9985   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9986 
9987   // Any nodes that were combined in the target-independent combiner prior
9988   // to vector legalization will not be sent to the target combine. Try to
9989   // combine it here.
9990   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9991     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9992       return NewShuffle;
9993     Op = NewShuffle;
9994     SVOp = cast<ShuffleVectorSDNode>(Op);
9995     V1 = Op.getOperand(0);
9996     V2 = Op.getOperand(1);
9997   }
9998   EVT VT = Op.getValueType();
9999   bool isLittleEndian = Subtarget.isLittleEndian();
10000 
10001   unsigned ShiftElts, InsertAtByte;
10002   bool Swap = false;
10003 
10004   // If this is a load-and-splat, we can do that with a single instruction
10005   // in some cases. However if the load has multiple uses, we don't want to
10006   // combine it because that will just produce multiple loads.
10007   bool IsPermutedLoad = false;
10008   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
10009   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
10010       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
10011       InputLoad->hasOneUse()) {
10012     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
10013     int SplatIdx =
10014       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
10015 
10016     // The splat index for permuted loads will be in the left half of the vector
10017     // which is strictly wider than the loaded value by 8 bytes. So we need to
10018     // adjust the splat index to point to the correct address in memory.
10019     if (IsPermutedLoad) {
10020       assert(isLittleEndian && "Unexpected permuted load on big endian target");
10021       SplatIdx += IsFourByte ? 2 : 1;
10022       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
10023              "Splat of a value outside of the loaded memory");
10024     }
10025 
10026     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
10027     // For 4-byte load-and-splat, we need Power9.
10028     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
10029       uint64_t Offset = 0;
10030       if (IsFourByte)
10031         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
10032       else
10033         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
10034 
10035       SDValue BasePtr = LD->getBasePtr();
10036       if (Offset != 0)
10037         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
10038                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
10039       SDValue Ops[] = {
10040         LD->getChain(),    // Chain
10041         BasePtr,           // BasePtr
10042         DAG.getValueType(Op.getValueType()) // VT
10043       };
10044       SDVTList VTL =
10045         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
10046       SDValue LdSplt =
10047         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
10048                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
10049       DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
10050       if (LdSplt.getValueType() != SVOp->getValueType(0))
10051         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
10052       return LdSplt;
10053     }
10054   }
10055   if (Subtarget.hasP9Vector() &&
10056       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
10057                            isLittleEndian)) {
10058     if (Swap)
10059       std::swap(V1, V2);
10060     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10061     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
10062     if (ShiftElts) {
10063       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
10064                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
10065       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
10066                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10067       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
10068     }
10069     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
10070                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
10071     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
10072   }
10073 
10074   if (Subtarget.hasPrefixInstrs()) {
10075     SDValue SplatInsertNode;
10076     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
10077       return SplatInsertNode;
10078   }
10079 
10080   if (Subtarget.hasP9Altivec()) {
10081     SDValue NewISDNode;
10082     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
10083       return NewISDNode;
10084 
10085     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
10086       return NewISDNode;
10087   }
10088 
10089   if (Subtarget.hasVSX() &&
10090       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
10091     if (Swap)
10092       std::swap(V1, V2);
10093     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10094     SDValue Conv2 =
10095         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
10096 
10097     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
10098                               DAG.getConstant(ShiftElts, dl, MVT::i32));
10099     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
10100   }
10101 
10102   if (Subtarget.hasVSX() &&
10103     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
10104     if (Swap)
10105       std::swap(V1, V2);
10106     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10107     SDValue Conv2 =
10108         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
10109 
10110     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
10111                               DAG.getConstant(ShiftElts, dl, MVT::i32));
10112     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
10113   }
10114 
10115   if (Subtarget.hasP9Vector()) {
10116      if (PPC::isXXBRHShuffleMask(SVOp)) {
10117       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10118       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
10119       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
10120     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
10121       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10122       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
10123       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
10124     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
10125       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10126       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
10127       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
10128     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
10129       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
10130       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
10131       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
10132     }
10133   }
10134 
10135   if (Subtarget.hasVSX()) {
10136     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
10137       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
10138 
10139       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10140       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
10141                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
10142       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
10143     }
10144 
10145     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
10146     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
10147       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
10148       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
10149       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
10150     }
10151   }
10152 
10153   // Cases that are handled by instructions that take permute immediates
10154   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
10155   // selected by the instruction selector.
10156   if (V2.isUndef()) {
10157     if (PPC::isSplatShuffleMask(SVOp, 1) ||
10158         PPC::isSplatShuffleMask(SVOp, 2) ||
10159         PPC::isSplatShuffleMask(SVOp, 4) ||
10160         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
10161         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
10162         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
10163         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
10164         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
10165         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
10166         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
10167         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
10168         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
10169         (Subtarget.hasP8Altivec() && (
10170          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
10171          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
10172          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
10173       return Op;
10174     }
10175   }
10176 
10177   // Altivec has a variety of "shuffle immediates" that take two vector inputs
10178   // and produce a fixed permutation.  If any of these match, do not lower to
10179   // VPERM.
10180   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
10181   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10182       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10183       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
10184       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10185       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10186       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10187       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10188       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10189       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10190       (Subtarget.hasP8Altivec() && (
10191        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10192        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
10193        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
10194     return Op;
10195 
10196   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
10197   // perfect shuffle table to emit an optimal matching sequence.
10198   ArrayRef<int> PermMask = SVOp->getMask();
10199 
10200   unsigned PFIndexes[4];
10201   bool isFourElementShuffle = true;
10202   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
10203     unsigned EltNo = 8;   // Start out undef.
10204     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
10205       if (PermMask[i*4+j] < 0)
10206         continue;   // Undef, ignore it.
10207 
10208       unsigned ByteSource = PermMask[i*4+j];
10209       if ((ByteSource & 3) != j) {
10210         isFourElementShuffle = false;
10211         break;
10212       }
10213 
10214       if (EltNo == 8) {
10215         EltNo = ByteSource/4;
10216       } else if (EltNo != ByteSource/4) {
10217         isFourElementShuffle = false;
10218         break;
10219       }
10220     }
10221     PFIndexes[i] = EltNo;
10222   }
10223 
10224   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
10225   // perfect shuffle vector to determine if it is cost effective to do this as
10226   // discrete instructions, or whether we should use a vperm.
10227   // For now, we skip this for little endian until such time as we have a
10228   // little-endian perfect shuffle table.
10229   if (isFourElementShuffle && !isLittleEndian) {
10230     // Compute the index in the perfect shuffle table.
10231     unsigned PFTableIndex =
10232       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
10233 
10234     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10235     unsigned Cost  = (PFEntry >> 30);
10236 
10237     // Determining when to avoid vperm is tricky.  Many things affect the cost
10238     // of vperm, particularly how many times the perm mask needs to be computed.
10239     // For example, if the perm mask can be hoisted out of a loop or is already
10240     // used (perhaps because there are multiple permutes with the same shuffle
10241     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
10242     // the loop requires an extra register.
10243     //
10244     // As a compromise, we only emit discrete instructions if the shuffle can be
10245     // generated in 3 or fewer operations.  When we have loop information
10246     // available, if this block is within a loop, we should avoid using vperm
10247     // for 3-operation perms and use a constant pool load instead.
10248     if (Cost < 3)
10249       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10250   }
10251 
10252   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10253   // vector that will get spilled to the constant pool.
10254   if (V2.isUndef()) V2 = V1;
10255 
10256   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10257   // that it is in input element units, not in bytes.  Convert now.
10258 
10259   // For little endian, the order of the input vectors is reversed, and
10260   // the permutation mask is complemented with respect to 31.  This is
10261   // necessary to produce proper semantics with the big-endian-biased vperm
10262   // instruction.
10263   EVT EltVT = V1.getValueType().getVectorElementType();
10264   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
10265 
10266   SmallVector<SDValue, 16> ResultMask;
10267   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10268     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10269 
10270     for (unsigned j = 0; j != BytesPerElement; ++j)
10271       if (isLittleEndian)
10272         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
10273                                              dl, MVT::i32));
10274       else
10275         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
10276                                              MVT::i32));
10277   }
10278 
10279   ShufflesHandledWithVPERM++;
10280   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10281   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
10282   LLVM_DEBUG(SVOp->dump());
10283   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
10284   LLVM_DEBUG(VPermMask.dump());
10285 
10286   if (isLittleEndian)
10287     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10288                        V2, V1, VPermMask);
10289   else
10290     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10291                        V1, V2, VPermMask);
10292 }
10293 
10294 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10295 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10296 /// information about the intrinsic.
10297 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10298                                  bool &isDot, const PPCSubtarget &Subtarget) {
10299   unsigned IntrinsicID =
10300       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10301   CompareOpc = -1;
10302   isDot = false;
10303   switch (IntrinsicID) {
10304   default:
10305     return false;
10306   // Comparison predicates.
10307   case Intrinsic::ppc_altivec_vcmpbfp_p:
10308     CompareOpc = 966;
10309     isDot = true;
10310     break;
10311   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10312     CompareOpc = 198;
10313     isDot = true;
10314     break;
10315   case Intrinsic::ppc_altivec_vcmpequb_p:
10316     CompareOpc = 6;
10317     isDot = true;
10318     break;
10319   case Intrinsic::ppc_altivec_vcmpequh_p:
10320     CompareOpc = 70;
10321     isDot = true;
10322     break;
10323   case Intrinsic::ppc_altivec_vcmpequw_p:
10324     CompareOpc = 134;
10325     isDot = true;
10326     break;
10327   case Intrinsic::ppc_altivec_vcmpequd_p:
10328     if (Subtarget.hasP8Altivec()) {
10329       CompareOpc = 199;
10330       isDot = true;
10331     } else
10332       return false;
10333     break;
10334   case Intrinsic::ppc_altivec_vcmpneb_p:
10335   case Intrinsic::ppc_altivec_vcmpneh_p:
10336   case Intrinsic::ppc_altivec_vcmpnew_p:
10337   case Intrinsic::ppc_altivec_vcmpnezb_p:
10338   case Intrinsic::ppc_altivec_vcmpnezh_p:
10339   case Intrinsic::ppc_altivec_vcmpnezw_p:
10340     if (Subtarget.hasP9Altivec()) {
10341       switch (IntrinsicID) {
10342       default:
10343         llvm_unreachable("Unknown comparison intrinsic.");
10344       case Intrinsic::ppc_altivec_vcmpneb_p:
10345         CompareOpc = 7;
10346         break;
10347       case Intrinsic::ppc_altivec_vcmpneh_p:
10348         CompareOpc = 71;
10349         break;
10350       case Intrinsic::ppc_altivec_vcmpnew_p:
10351         CompareOpc = 135;
10352         break;
10353       case Intrinsic::ppc_altivec_vcmpnezb_p:
10354         CompareOpc = 263;
10355         break;
10356       case Intrinsic::ppc_altivec_vcmpnezh_p:
10357         CompareOpc = 327;
10358         break;
10359       case Intrinsic::ppc_altivec_vcmpnezw_p:
10360         CompareOpc = 391;
10361         break;
10362       }
10363       isDot = true;
10364     } else
10365       return false;
10366     break;
10367   case Intrinsic::ppc_altivec_vcmpgefp_p:
10368     CompareOpc = 454;
10369     isDot = true;
10370     break;
10371   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10372     CompareOpc = 710;
10373     isDot = true;
10374     break;
10375   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10376     CompareOpc = 774;
10377     isDot = true;
10378     break;
10379   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10380     CompareOpc = 838;
10381     isDot = true;
10382     break;
10383   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10384     CompareOpc = 902;
10385     isDot = true;
10386     break;
10387   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10388     if (Subtarget.hasP8Altivec()) {
10389       CompareOpc = 967;
10390       isDot = true;
10391     } else
10392       return false;
10393     break;
10394   case Intrinsic::ppc_altivec_vcmpgtub_p:
10395     CompareOpc = 518;
10396     isDot = true;
10397     break;
10398   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10399     CompareOpc = 582;
10400     isDot = true;
10401     break;
10402   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10403     CompareOpc = 646;
10404     isDot = true;
10405     break;
10406   case Intrinsic::ppc_altivec_vcmpgtud_p:
10407     if (Subtarget.hasP8Altivec()) {
10408       CompareOpc = 711;
10409       isDot = true;
10410     } else
10411       return false;
10412     break;
10413 
10414   case Intrinsic::ppc_altivec_vcmpequq:
10415   case Intrinsic::ppc_altivec_vcmpgtsq:
10416   case Intrinsic::ppc_altivec_vcmpgtuq:
10417     if (!Subtarget.isISA3_1())
10418       return false;
10419     switch (IntrinsicID) {
10420     default:
10421       llvm_unreachable("Unknown comparison intrinsic.");
10422     case Intrinsic::ppc_altivec_vcmpequq:
10423       CompareOpc = 455;
10424       break;
10425     case Intrinsic::ppc_altivec_vcmpgtsq:
10426       CompareOpc = 903;
10427       break;
10428     case Intrinsic::ppc_altivec_vcmpgtuq:
10429       CompareOpc = 647;
10430       break;
10431     }
10432     break;
10433 
10434   // VSX predicate comparisons use the same infrastructure
10435   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10436   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10437   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10438   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10439   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10440   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10441     if (Subtarget.hasVSX()) {
10442       switch (IntrinsicID) {
10443       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10444         CompareOpc = 99;
10445         break;
10446       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10447         CompareOpc = 115;
10448         break;
10449       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10450         CompareOpc = 107;
10451         break;
10452       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10453         CompareOpc = 67;
10454         break;
10455       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10456         CompareOpc = 83;
10457         break;
10458       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10459         CompareOpc = 75;
10460         break;
10461       }
10462       isDot = true;
10463     } else
10464       return false;
10465     break;
10466 
10467   // Normal Comparisons.
10468   case Intrinsic::ppc_altivec_vcmpbfp:
10469     CompareOpc = 966;
10470     break;
10471   case Intrinsic::ppc_altivec_vcmpeqfp:
10472     CompareOpc = 198;
10473     break;
10474   case Intrinsic::ppc_altivec_vcmpequb:
10475     CompareOpc = 6;
10476     break;
10477   case Intrinsic::ppc_altivec_vcmpequh:
10478     CompareOpc = 70;
10479     break;
10480   case Intrinsic::ppc_altivec_vcmpequw:
10481     CompareOpc = 134;
10482     break;
10483   case Intrinsic::ppc_altivec_vcmpequd:
10484     if (Subtarget.hasP8Altivec())
10485       CompareOpc = 199;
10486     else
10487       return false;
10488     break;
10489   case Intrinsic::ppc_altivec_vcmpneb:
10490   case Intrinsic::ppc_altivec_vcmpneh:
10491   case Intrinsic::ppc_altivec_vcmpnew:
10492   case Intrinsic::ppc_altivec_vcmpnezb:
10493   case Intrinsic::ppc_altivec_vcmpnezh:
10494   case Intrinsic::ppc_altivec_vcmpnezw:
10495     if (Subtarget.hasP9Altivec())
10496       switch (IntrinsicID) {
10497       default:
10498         llvm_unreachable("Unknown comparison intrinsic.");
10499       case Intrinsic::ppc_altivec_vcmpneb:
10500         CompareOpc = 7;
10501         break;
10502       case Intrinsic::ppc_altivec_vcmpneh:
10503         CompareOpc = 71;
10504         break;
10505       case Intrinsic::ppc_altivec_vcmpnew:
10506         CompareOpc = 135;
10507         break;
10508       case Intrinsic::ppc_altivec_vcmpnezb:
10509         CompareOpc = 263;
10510         break;
10511       case Intrinsic::ppc_altivec_vcmpnezh:
10512         CompareOpc = 327;
10513         break;
10514       case Intrinsic::ppc_altivec_vcmpnezw:
10515         CompareOpc = 391;
10516         break;
10517       }
10518     else
10519       return false;
10520     break;
10521   case Intrinsic::ppc_altivec_vcmpgefp:
10522     CompareOpc = 454;
10523     break;
10524   case Intrinsic::ppc_altivec_vcmpgtfp:
10525     CompareOpc = 710;
10526     break;
10527   case Intrinsic::ppc_altivec_vcmpgtsb:
10528     CompareOpc = 774;
10529     break;
10530   case Intrinsic::ppc_altivec_vcmpgtsh:
10531     CompareOpc = 838;
10532     break;
10533   case Intrinsic::ppc_altivec_vcmpgtsw:
10534     CompareOpc = 902;
10535     break;
10536   case Intrinsic::ppc_altivec_vcmpgtsd:
10537     if (Subtarget.hasP8Altivec())
10538       CompareOpc = 967;
10539     else
10540       return false;
10541     break;
10542   case Intrinsic::ppc_altivec_vcmpgtub:
10543     CompareOpc = 518;
10544     break;
10545   case Intrinsic::ppc_altivec_vcmpgtuh:
10546     CompareOpc = 582;
10547     break;
10548   case Intrinsic::ppc_altivec_vcmpgtuw:
10549     CompareOpc = 646;
10550     break;
10551   case Intrinsic::ppc_altivec_vcmpgtud:
10552     if (Subtarget.hasP8Altivec())
10553       CompareOpc = 711;
10554     else
10555       return false;
10556     break;
10557   case Intrinsic::ppc_altivec_vcmpequq_p:
10558   case Intrinsic::ppc_altivec_vcmpgtsq_p:
10559   case Intrinsic::ppc_altivec_vcmpgtuq_p:
10560     if (!Subtarget.isISA3_1())
10561       return false;
10562     switch (IntrinsicID) {
10563     default:
10564       llvm_unreachable("Unknown comparison intrinsic.");
10565     case Intrinsic::ppc_altivec_vcmpequq_p:
10566       CompareOpc = 455;
10567       break;
10568     case Intrinsic::ppc_altivec_vcmpgtsq_p:
10569       CompareOpc = 903;
10570       break;
10571     case Intrinsic::ppc_altivec_vcmpgtuq_p:
10572       CompareOpc = 647;
10573       break;
10574     }
10575     isDot = true;
10576     break;
10577   }
10578   return true;
10579 }
10580 
10581 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10582 /// lower, do it, otherwise return null.
10583 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10584                                                    SelectionDAG &DAG) const {
10585   unsigned IntrinsicID =
10586     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10587 
10588   SDLoc dl(Op);
10589 
10590   switch (IntrinsicID) {
10591   case Intrinsic::thread_pointer:
10592     // Reads the thread pointer register, used for __builtin_thread_pointer.
10593     if (Subtarget.isPPC64())
10594       return DAG.getRegister(PPC::X13, MVT::i64);
10595     return DAG.getRegister(PPC::R2, MVT::i32);
10596 
10597   case Intrinsic::ppc_mma_disassemble_acc:
10598   case Intrinsic::ppc_mma_disassemble_pair: {
10599     int NumVecs = 2;
10600     SDValue WideVec = Op.getOperand(1);
10601     if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
10602       NumVecs = 4;
10603       WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
10604     }
10605     SmallVector<SDValue, 4> RetOps;
10606     for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
10607       SDValue Extract = DAG.getNode(
10608           PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
10609           DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
10610                                                      : VecNo,
10611                           dl, MVT::i64));
10612       RetOps.push_back(Extract);
10613     }
10614     return DAG.getMergeValues(RetOps, dl);
10615   }
10616   }
10617 
10618   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10619   // opcode number of the comparison.
10620   int CompareOpc;
10621   bool isDot;
10622   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10623     return SDValue();    // Don't custom lower most intrinsics.
10624 
10625   // If this is a non-dot comparison, make the VCMP node and we are done.
10626   if (!isDot) {
10627     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10628                               Op.getOperand(1), Op.getOperand(2),
10629                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10630     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10631   }
10632 
10633   // Create the PPCISD altivec 'dot' comparison node.
10634   SDValue Ops[] = {
10635     Op.getOperand(2),  // LHS
10636     Op.getOperand(3),  // RHS
10637     DAG.getConstant(CompareOpc, dl, MVT::i32)
10638   };
10639   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10640   SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
10641 
10642   // Now that we have the comparison, emit a copy from the CR to a GPR.
10643   // This is flagged to the above dot comparison.
10644   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10645                                 DAG.getRegister(PPC::CR6, MVT::i32),
10646                                 CompNode.getValue(1));
10647 
10648   // Unpack the result based on how the target uses it.
10649   unsigned BitNo;   // Bit # of CR6.
10650   bool InvertBit;   // Invert result?
10651   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10652   default:  // Can't happen, don't crash on invalid number though.
10653   case 0:   // Return the value of the EQ bit of CR6.
10654     BitNo = 0; InvertBit = false;
10655     break;
10656   case 1:   // Return the inverted value of the EQ bit of CR6.
10657     BitNo = 0; InvertBit = true;
10658     break;
10659   case 2:   // Return the value of the LT bit of CR6.
10660     BitNo = 2; InvertBit = false;
10661     break;
10662   case 3:   // Return the inverted value of the LT bit of CR6.
10663     BitNo = 2; InvertBit = true;
10664     break;
10665   }
10666 
10667   // Shift the bit into the low position.
10668   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10669                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10670   // Isolate the bit.
10671   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10672                       DAG.getConstant(1, dl, MVT::i32));
10673 
10674   // If we are supposed to, toggle the bit.
10675   if (InvertBit)
10676     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10677                         DAG.getConstant(1, dl, MVT::i32));
10678   return Flags;
10679 }
10680 
10681 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10682                                                SelectionDAG &DAG) const {
10683   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10684   // the beginning of the argument list.
10685   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10686   SDLoc DL(Op);
10687   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10688   case Intrinsic::ppc_cfence: {
10689     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10690     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10691     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10692                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10693                                                   Op.getOperand(ArgStart + 1)),
10694                                       Op.getOperand(0)),
10695                    0);
10696   }
10697   default:
10698     break;
10699   }
10700   return SDValue();
10701 }
10702 
10703 // Lower scalar BSWAP64 to xxbrd.
10704 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10705   SDLoc dl(Op);
10706   // MTVSRDD
10707   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10708                    Op.getOperand(0));
10709   // XXBRD
10710   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10711   // MFVSRD
10712   int VectorIndex = 0;
10713   if (Subtarget.isLittleEndian())
10714     VectorIndex = 1;
10715   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10716                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10717   return Op;
10718 }
10719 
10720 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10721 // compared to a value that is atomically loaded (atomic loads zero-extend).
10722 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10723                                                 SelectionDAG &DAG) const {
10724   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10725          "Expecting an atomic compare-and-swap here.");
10726   SDLoc dl(Op);
10727   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10728   EVT MemVT = AtomicNode->getMemoryVT();
10729   if (MemVT.getSizeInBits() >= 32)
10730     return Op;
10731 
10732   SDValue CmpOp = Op.getOperand(2);
10733   // If this is already correctly zero-extended, leave it alone.
10734   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10735   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10736     return Op;
10737 
10738   // Clear the high bits of the compare operand.
10739   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10740   SDValue NewCmpOp =
10741     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10742                 DAG.getConstant(MaskVal, dl, MVT::i32));
10743 
10744   // Replace the existing compare operand with the properly zero-extended one.
10745   SmallVector<SDValue, 4> Ops;
10746   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10747     Ops.push_back(AtomicNode->getOperand(i));
10748   Ops[2] = NewCmpOp;
10749   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10750   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10751   auto NodeTy =
10752     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10753   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10754 }
10755 
10756 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10757                                                  SelectionDAG &DAG) const {
10758   SDLoc dl(Op);
10759   // Create a stack slot that is 16-byte aligned.
10760   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10761   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10762   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10763   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10764 
10765   // Store the input value into Value#0 of the stack slot.
10766   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10767                                MachinePointerInfo());
10768   // Load it out.
10769   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10770 }
10771 
10772 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10773                                                   SelectionDAG &DAG) const {
10774   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10775          "Should only be called for ISD::INSERT_VECTOR_ELT");
10776 
10777   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10778   // We have legal lowering for constant indices but not for variable ones.
10779   if (!C)
10780     return SDValue();
10781 
10782   EVT VT = Op.getValueType();
10783   SDLoc dl(Op);
10784   SDValue V1 = Op.getOperand(0);
10785   SDValue V2 = Op.getOperand(1);
10786   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10787   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10788     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10789     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10790     unsigned InsertAtElement = C->getZExtValue();
10791     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10792     if (Subtarget.isLittleEndian()) {
10793       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10794     }
10795     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10796                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10797   }
10798   return Op;
10799 }
10800 
10801 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10802                                            SelectionDAG &DAG) const {
10803   SDLoc dl(Op);
10804   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10805   SDValue LoadChain = LN->getChain();
10806   SDValue BasePtr = LN->getBasePtr();
10807   EVT VT = Op.getValueType();
10808 
10809   if (VT != MVT::v256i1 && VT != MVT::v512i1)
10810     return Op;
10811 
10812   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10813   // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
10814   // 2 or 4 vsx registers.
10815   assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
10816          "Type unsupported without MMA");
10817   assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10818          "Type unsupported without paired vector support");
10819   Align Alignment = LN->getAlign();
10820   SmallVector<SDValue, 4> Loads;
10821   SmallVector<SDValue, 4> LoadChains;
10822   unsigned NumVecs = VT.getSizeInBits() / 128;
10823   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10824     SDValue Load =
10825         DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
10826                     LN->getPointerInfo().getWithOffset(Idx * 16),
10827                     commonAlignment(Alignment, Idx * 16),
10828                     LN->getMemOperand()->getFlags(), LN->getAAInfo());
10829     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10830                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10831     Loads.push_back(Load);
10832     LoadChains.push_back(Load.getValue(1));
10833   }
10834   if (Subtarget.isLittleEndian()) {
10835     std::reverse(Loads.begin(), Loads.end());
10836     std::reverse(LoadChains.begin(), LoadChains.end());
10837   }
10838   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10839   SDValue Value =
10840       DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
10841                   dl, VT, Loads);
10842   SDValue RetOps[] = {Value, TF};
10843   return DAG.getMergeValues(RetOps, dl);
10844 }
10845 
10846 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10847                                             SelectionDAG &DAG) const {
10848   SDLoc dl(Op);
10849   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10850   SDValue StoreChain = SN->getChain();
10851   SDValue BasePtr = SN->getBasePtr();
10852   SDValue Value = SN->getValue();
10853   EVT StoreVT = Value.getValueType();
10854 
10855   if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
10856     return Op;
10857 
10858   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10859   // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
10860   // underlying registers individually.
10861   assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
10862          "Type unsupported without MMA");
10863   assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10864          "Type unsupported without paired vector support");
10865   Align Alignment = SN->getAlign();
10866   SmallVector<SDValue, 4> Stores;
10867   unsigned NumVecs = 2;
10868   if (StoreVT == MVT::v512i1) {
10869     Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
10870     NumVecs = 4;
10871   }
10872   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10873     unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
10874     SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
10875                               DAG.getConstant(VecNum, dl, MVT::i64));
10876     SDValue Store =
10877         DAG.getStore(StoreChain, dl, Elt, BasePtr,
10878                      SN->getPointerInfo().getWithOffset(Idx * 16),
10879                      commonAlignment(Alignment, Idx * 16),
10880                      SN->getMemOperand()->getFlags(), SN->getAAInfo());
10881     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10882                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10883     Stores.push_back(Store);
10884   }
10885   SDValue TF = DAG.getTokenFactor(dl, Stores);
10886   return TF;
10887 }
10888 
10889 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10890   SDLoc dl(Op);
10891   if (Op.getValueType() == MVT::v4i32) {
10892     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10893 
10894     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10895     // +16 as shift amt.
10896     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10897     SDValue RHSSwap =   // = vrlw RHS, 16
10898       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10899 
10900     // Shrinkify inputs to v8i16.
10901     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10902     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10903     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10904 
10905     // Low parts multiplied together, generating 32-bit results (we ignore the
10906     // top parts).
10907     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10908                                         LHS, RHS, DAG, dl, MVT::v4i32);
10909 
10910     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10911                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10912     // Shift the high parts up 16 bits.
10913     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10914                               Neg16, DAG, dl);
10915     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10916   } else if (Op.getValueType() == MVT::v16i8) {
10917     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10918     bool isLittleEndian = Subtarget.isLittleEndian();
10919 
10920     // Multiply the even 8-bit parts, producing 16-bit sums.
10921     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10922                                            LHS, RHS, DAG, dl, MVT::v8i16);
10923     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10924 
10925     // Multiply the odd 8-bit parts, producing 16-bit sums.
10926     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10927                                           LHS, RHS, DAG, dl, MVT::v8i16);
10928     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10929 
10930     // Merge the results together.  Because vmuleub and vmuloub are
10931     // instructions with a big-endian bias, we must reverse the
10932     // element numbering and reverse the meaning of "odd" and "even"
10933     // when generating little endian code.
10934     int Ops[16];
10935     for (unsigned i = 0; i != 8; ++i) {
10936       if (isLittleEndian) {
10937         Ops[i*2  ] = 2*i;
10938         Ops[i*2+1] = 2*i+16;
10939       } else {
10940         Ops[i*2  ] = 2*i+1;
10941         Ops[i*2+1] = 2*i+1+16;
10942       }
10943     }
10944     if (isLittleEndian)
10945       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10946     else
10947       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10948   } else {
10949     llvm_unreachable("Unknown mul to lower!");
10950   }
10951 }
10952 
10953 // Custom lowering for fpext vf32 to v2f64
10954 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10955 
10956   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10957          "Should only be called for ISD::FP_EXTEND");
10958 
10959   // FIXME: handle extends from half precision float vectors on P9.
10960   // We only want to custom lower an extend from v2f32 to v2f64.
10961   if (Op.getValueType() != MVT::v2f64 ||
10962       Op.getOperand(0).getValueType() != MVT::v2f32)
10963     return SDValue();
10964 
10965   SDLoc dl(Op);
10966   SDValue Op0 = Op.getOperand(0);
10967 
10968   switch (Op0.getOpcode()) {
10969   default:
10970     return SDValue();
10971   case ISD::EXTRACT_SUBVECTOR: {
10972     assert(Op0.getNumOperands() == 2 &&
10973            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10974            "Node should have 2 operands with second one being a constant!");
10975 
10976     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10977       return SDValue();
10978 
10979     // Custom lower is only done for high or low doubleword.
10980     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10981     if (Idx % 2 != 0)
10982       return SDValue();
10983 
10984     // Since input is v4f32, at this point Idx is either 0 or 2.
10985     // Shift to get the doubleword position we want.
10986     int DWord = Idx >> 1;
10987 
10988     // High and low word positions are different on little endian.
10989     if (Subtarget.isLittleEndian())
10990       DWord ^= 0x1;
10991 
10992     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10993                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10994   }
10995   case ISD::FADD:
10996   case ISD::FMUL:
10997   case ISD::FSUB: {
10998     SDValue NewLoad[2];
10999     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
11000       // Ensure both input are loads.
11001       SDValue LdOp = Op0.getOperand(i);
11002       if (LdOp.getOpcode() != ISD::LOAD)
11003         return SDValue();
11004       // Generate new load node.
11005       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
11006       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11007       NewLoad[i] = DAG.getMemIntrinsicNode(
11008           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11009           LD->getMemoryVT(), LD->getMemOperand());
11010     }
11011     SDValue NewOp =
11012         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
11013                     NewLoad[1], Op0.getNode()->getFlags());
11014     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
11015                        DAG.getConstant(0, dl, MVT::i32));
11016   }
11017   case ISD::LOAD: {
11018     LoadSDNode *LD = cast<LoadSDNode>(Op0);
11019     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11020     SDValue NewLd = DAG.getMemIntrinsicNode(
11021         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11022         LD->getMemoryVT(), LD->getMemOperand());
11023     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
11024                        DAG.getConstant(0, dl, MVT::i32));
11025   }
11026   }
11027   llvm_unreachable("ERROR:Should return for all cases within swtich.");
11028 }
11029 
11030 /// LowerOperation - Provide custom lowering hooks for some operations.
11031 ///
11032 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11033   switch (Op.getOpcode()) {
11034   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
11035   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11036   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11037   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11038   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11039   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11040   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11041   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11042   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11043 
11044   // Variable argument lowering.
11045   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11046   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11047   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11048 
11049   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
11050   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11051   case ISD::GET_DYNAMIC_AREA_OFFSET:
11052     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
11053 
11054   // Exception handling lowering.
11055   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
11056   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11057   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11058 
11059   case ISD::LOAD:               return LowerLOAD(Op, DAG);
11060   case ISD::STORE:              return LowerSTORE(Op, DAG);
11061   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
11062   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
11063   case ISD::STRICT_FP_TO_UINT:
11064   case ISD::STRICT_FP_TO_SINT:
11065   case ISD::FP_TO_UINT:
11066   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
11067   case ISD::STRICT_UINT_TO_FP:
11068   case ISD::STRICT_SINT_TO_FP:
11069   case ISD::UINT_TO_FP:
11070   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
11071   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11072 
11073   // Lower 64-bit shifts.
11074   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
11075   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
11076   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
11077 
11078   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
11079   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
11080 
11081   // Vector-related lowering.
11082   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11083   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11084   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11085   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11086   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11087   case ISD::MUL:                return LowerMUL(Op, DAG);
11088   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
11089   case ISD::ROTL:               return LowerROTL(Op, DAG);
11090 
11091   // For counter-based loop handling.
11092   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
11093 
11094   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11095 
11096   // Frame & Return address.
11097   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11098   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11099 
11100   case ISD::INTRINSIC_VOID:
11101     return LowerINTRINSIC_VOID(Op, DAG);
11102   case ISD::BSWAP:
11103     return LowerBSWAP(Op, DAG);
11104   case ISD::ATOMIC_CMP_SWAP:
11105     return LowerATOMIC_CMP_SWAP(Op, DAG);
11106   }
11107 }
11108 
11109 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
11110                                            SmallVectorImpl<SDValue>&Results,
11111                                            SelectionDAG &DAG) const {
11112   SDLoc dl(N);
11113   switch (N->getOpcode()) {
11114   default:
11115     llvm_unreachable("Do not know how to custom type legalize this operation!");
11116   case ISD::READCYCLECOUNTER: {
11117     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11118     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
11119 
11120     Results.push_back(
11121         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
11122     Results.push_back(RTB.getValue(2));
11123     break;
11124   }
11125   case ISD::INTRINSIC_W_CHAIN: {
11126     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
11127         Intrinsic::loop_decrement)
11128       break;
11129 
11130     assert(N->getValueType(0) == MVT::i1 &&
11131            "Unexpected result type for CTR decrement intrinsic");
11132     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11133                                  N->getValueType(0));
11134     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
11135     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
11136                                  N->getOperand(1));
11137 
11138     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
11139     Results.push_back(NewInt.getValue(1));
11140     break;
11141   }
11142   case ISD::VAARG: {
11143     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
11144       return;
11145 
11146     EVT VT = N->getValueType(0);
11147 
11148     if (VT == MVT::i64) {
11149       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
11150 
11151       Results.push_back(NewNode);
11152       Results.push_back(NewNode.getValue(1));
11153     }
11154     return;
11155   }
11156   case ISD::STRICT_FP_TO_SINT:
11157   case ISD::STRICT_FP_TO_UINT:
11158   case ISD::FP_TO_SINT:
11159   case ISD::FP_TO_UINT:
11160     // LowerFP_TO_INT() can only handle f32 and f64.
11161     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
11162         MVT::ppcf128)
11163       return;
11164     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
11165     return;
11166   case ISD::TRUNCATE: {
11167     if (!N->getValueType(0).isVector())
11168       return;
11169     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
11170     if (Lowered)
11171       Results.push_back(Lowered);
11172     return;
11173   }
11174   case ISD::FSHL:
11175   case ISD::FSHR:
11176     // Don't handle funnel shifts here.
11177     return;
11178   case ISD::BITCAST:
11179     // Don't handle bitcast here.
11180     return;
11181   case ISD::FP_EXTEND:
11182     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
11183     if (Lowered)
11184       Results.push_back(Lowered);
11185     return;
11186   }
11187 }
11188 
11189 //===----------------------------------------------------------------------===//
11190 //  Other Lowering Code
11191 //===----------------------------------------------------------------------===//
11192 
11193 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
11194   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11195   Function *Func = Intrinsic::getDeclaration(M, Id);
11196   return Builder.CreateCall(Func, {});
11197 }
11198 
11199 // The mappings for emitLeading/TrailingFence is taken from
11200 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11201 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11202                                                  Instruction *Inst,
11203                                                  AtomicOrdering Ord) const {
11204   if (Ord == AtomicOrdering::SequentiallyConsistent)
11205     return callIntrinsic(Builder, Intrinsic::ppc_sync);
11206   if (isReleaseOrStronger(Ord))
11207     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11208   return nullptr;
11209 }
11210 
11211 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11212                                                   Instruction *Inst,
11213                                                   AtomicOrdering Ord) const {
11214   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11215     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11216     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11217     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11218     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11219       return Builder.CreateCall(
11220           Intrinsic::getDeclaration(
11221               Builder.GetInsertBlock()->getParent()->getParent(),
11222               Intrinsic::ppc_cfence, {Inst->getType()}),
11223           {Inst});
11224     // FIXME: Can use isync for rmw operation.
11225     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11226   }
11227   return nullptr;
11228 }
11229 
11230 MachineBasicBlock *
11231 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11232                                     unsigned AtomicSize,
11233                                     unsigned BinOpcode,
11234                                     unsigned CmpOpcode,
11235                                     unsigned CmpPred) const {
11236   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11237   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11238 
11239   auto LoadMnemonic = PPC::LDARX;
11240   auto StoreMnemonic = PPC::STDCX;
11241   switch (AtomicSize) {
11242   default:
11243     llvm_unreachable("Unexpected size of atomic entity");
11244   case 1:
11245     LoadMnemonic = PPC::LBARX;
11246     StoreMnemonic = PPC::STBCX;
11247     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11248     break;
11249   case 2:
11250     LoadMnemonic = PPC::LHARX;
11251     StoreMnemonic = PPC::STHCX;
11252     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11253     break;
11254   case 4:
11255     LoadMnemonic = PPC::LWARX;
11256     StoreMnemonic = PPC::STWCX;
11257     break;
11258   case 8:
11259     LoadMnemonic = PPC::LDARX;
11260     StoreMnemonic = PPC::STDCX;
11261     break;
11262   }
11263 
11264   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11265   MachineFunction *F = BB->getParent();
11266   MachineFunction::iterator It = ++BB->getIterator();
11267 
11268   Register dest = MI.getOperand(0).getReg();
11269   Register ptrA = MI.getOperand(1).getReg();
11270   Register ptrB = MI.getOperand(2).getReg();
11271   Register incr = MI.getOperand(3).getReg();
11272   DebugLoc dl = MI.getDebugLoc();
11273 
11274   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11275   MachineBasicBlock *loop2MBB =
11276     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11277   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11278   F->insert(It, loopMBB);
11279   if (CmpOpcode)
11280     F->insert(It, loop2MBB);
11281   F->insert(It, exitMBB);
11282   exitMBB->splice(exitMBB->begin(), BB,
11283                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11284   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11285 
11286   MachineRegisterInfo &RegInfo = F->getRegInfo();
11287   Register TmpReg = (!BinOpcode) ? incr :
11288     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11289                                            : &PPC::GPRCRegClass);
11290 
11291   //  thisMBB:
11292   //   ...
11293   //   fallthrough --> loopMBB
11294   BB->addSuccessor(loopMBB);
11295 
11296   //  loopMBB:
11297   //   l[wd]arx dest, ptr
11298   //   add r0, dest, incr
11299   //   st[wd]cx. r0, ptr
11300   //   bne- loopMBB
11301   //   fallthrough --> exitMBB
11302 
11303   // For max/min...
11304   //  loopMBB:
11305   //   l[wd]arx dest, ptr
11306   //   cmpl?[wd] incr, dest
11307   //   bgt exitMBB
11308   //  loop2MBB:
11309   //   st[wd]cx. dest, ptr
11310   //   bne- loopMBB
11311   //   fallthrough --> exitMBB
11312 
11313   BB = loopMBB;
11314   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11315     .addReg(ptrA).addReg(ptrB);
11316   if (BinOpcode)
11317     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11318   if (CmpOpcode) {
11319     // Signed comparisons of byte or halfword values must be sign-extended.
11320     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11321       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11322       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11323               ExtReg).addReg(dest);
11324       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11325         .addReg(incr).addReg(ExtReg);
11326     } else
11327       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11328         .addReg(incr).addReg(dest);
11329 
11330     BuildMI(BB, dl, TII->get(PPC::BCC))
11331       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11332     BB->addSuccessor(loop2MBB);
11333     BB->addSuccessor(exitMBB);
11334     BB = loop2MBB;
11335   }
11336   BuildMI(BB, dl, TII->get(StoreMnemonic))
11337     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11338   BuildMI(BB, dl, TII->get(PPC::BCC))
11339     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11340   BB->addSuccessor(loopMBB);
11341   BB->addSuccessor(exitMBB);
11342 
11343   //  exitMBB:
11344   //   ...
11345   BB = exitMBB;
11346   return BB;
11347 }
11348 
11349 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11350     MachineInstr &MI, MachineBasicBlock *BB,
11351     bool is8bit, // operation
11352     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11353   // If we support part-word atomic mnemonics, just use them
11354   if (Subtarget.hasPartwordAtomics())
11355     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11356                             CmpPred);
11357 
11358   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11359   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11360   // In 64 bit mode we have to use 64 bits for addresses, even though the
11361   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11362   // registers without caring whether they're 32 or 64, but here we're
11363   // doing actual arithmetic on the addresses.
11364   bool is64bit = Subtarget.isPPC64();
11365   bool isLittleEndian = Subtarget.isLittleEndian();
11366   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11367 
11368   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11369   MachineFunction *F = BB->getParent();
11370   MachineFunction::iterator It = ++BB->getIterator();
11371 
11372   Register dest = MI.getOperand(0).getReg();
11373   Register ptrA = MI.getOperand(1).getReg();
11374   Register ptrB = MI.getOperand(2).getReg();
11375   Register incr = MI.getOperand(3).getReg();
11376   DebugLoc dl = MI.getDebugLoc();
11377 
11378   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11379   MachineBasicBlock *loop2MBB =
11380       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11381   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11382   F->insert(It, loopMBB);
11383   if (CmpOpcode)
11384     F->insert(It, loop2MBB);
11385   F->insert(It, exitMBB);
11386   exitMBB->splice(exitMBB->begin(), BB,
11387                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11388   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11389 
11390   MachineRegisterInfo &RegInfo = F->getRegInfo();
11391   const TargetRegisterClass *RC =
11392       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11393   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11394 
11395   Register PtrReg = RegInfo.createVirtualRegister(RC);
11396   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11397   Register ShiftReg =
11398       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11399   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11400   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11401   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11402   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11403   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11404   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11405   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11406   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11407   Register Ptr1Reg;
11408   Register TmpReg =
11409       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11410 
11411   //  thisMBB:
11412   //   ...
11413   //   fallthrough --> loopMBB
11414   BB->addSuccessor(loopMBB);
11415 
11416   // The 4-byte load must be aligned, while a char or short may be
11417   // anywhere in the word.  Hence all this nasty bookkeeping code.
11418   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11419   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11420   //   xori shift, shift1, 24 [16]
11421   //   rlwinm ptr, ptr1, 0, 0, 29
11422   //   slw incr2, incr, shift
11423   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11424   //   slw mask, mask2, shift
11425   //  loopMBB:
11426   //   lwarx tmpDest, ptr
11427   //   add tmp, tmpDest, incr2
11428   //   andc tmp2, tmpDest, mask
11429   //   and tmp3, tmp, mask
11430   //   or tmp4, tmp3, tmp2
11431   //   stwcx. tmp4, ptr
11432   //   bne- loopMBB
11433   //   fallthrough --> exitMBB
11434   //   srw dest, tmpDest, shift
11435   if (ptrA != ZeroReg) {
11436     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11437     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11438         .addReg(ptrA)
11439         .addReg(ptrB);
11440   } else {
11441     Ptr1Reg = ptrB;
11442   }
11443   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11444   // mode.
11445   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11446       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11447       .addImm(3)
11448       .addImm(27)
11449       .addImm(is8bit ? 28 : 27);
11450   if (!isLittleEndian)
11451     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11452         .addReg(Shift1Reg)
11453         .addImm(is8bit ? 24 : 16);
11454   if (is64bit)
11455     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11456         .addReg(Ptr1Reg)
11457         .addImm(0)
11458         .addImm(61);
11459   else
11460     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11461         .addReg(Ptr1Reg)
11462         .addImm(0)
11463         .addImm(0)
11464         .addImm(29);
11465   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11466   if (is8bit)
11467     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11468   else {
11469     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11470     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11471         .addReg(Mask3Reg)
11472         .addImm(65535);
11473   }
11474   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11475       .addReg(Mask2Reg)
11476       .addReg(ShiftReg);
11477 
11478   BB = loopMBB;
11479   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11480       .addReg(ZeroReg)
11481       .addReg(PtrReg);
11482   if (BinOpcode)
11483     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11484         .addReg(Incr2Reg)
11485         .addReg(TmpDestReg);
11486   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11487       .addReg(TmpDestReg)
11488       .addReg(MaskReg);
11489   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11490   if (CmpOpcode) {
11491     // For unsigned comparisons, we can directly compare the shifted values.
11492     // For signed comparisons we shift and sign extend.
11493     Register SReg = RegInfo.createVirtualRegister(GPRC);
11494     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11495         .addReg(TmpDestReg)
11496         .addReg(MaskReg);
11497     unsigned ValueReg = SReg;
11498     unsigned CmpReg = Incr2Reg;
11499     if (CmpOpcode == PPC::CMPW) {
11500       ValueReg = RegInfo.createVirtualRegister(GPRC);
11501       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11502           .addReg(SReg)
11503           .addReg(ShiftReg);
11504       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11505       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11506           .addReg(ValueReg);
11507       ValueReg = ValueSReg;
11508       CmpReg = incr;
11509     }
11510     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11511         .addReg(CmpReg)
11512         .addReg(ValueReg);
11513     BuildMI(BB, dl, TII->get(PPC::BCC))
11514         .addImm(CmpPred)
11515         .addReg(PPC::CR0)
11516         .addMBB(exitMBB);
11517     BB->addSuccessor(loop2MBB);
11518     BB->addSuccessor(exitMBB);
11519     BB = loop2MBB;
11520   }
11521   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11522   BuildMI(BB, dl, TII->get(PPC::STWCX))
11523       .addReg(Tmp4Reg)
11524       .addReg(ZeroReg)
11525       .addReg(PtrReg);
11526   BuildMI(BB, dl, TII->get(PPC::BCC))
11527       .addImm(PPC::PRED_NE)
11528       .addReg(PPC::CR0)
11529       .addMBB(loopMBB);
11530   BB->addSuccessor(loopMBB);
11531   BB->addSuccessor(exitMBB);
11532 
11533   //  exitMBB:
11534   //   ...
11535   BB = exitMBB;
11536   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11537       .addReg(TmpDestReg)
11538       .addReg(ShiftReg);
11539   return BB;
11540 }
11541 
11542 llvm::MachineBasicBlock *
11543 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11544                                     MachineBasicBlock *MBB) const {
11545   DebugLoc DL = MI.getDebugLoc();
11546   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11547   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11548 
11549   MachineFunction *MF = MBB->getParent();
11550   MachineRegisterInfo &MRI = MF->getRegInfo();
11551 
11552   const BasicBlock *BB = MBB->getBasicBlock();
11553   MachineFunction::iterator I = ++MBB->getIterator();
11554 
11555   Register DstReg = MI.getOperand(0).getReg();
11556   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11557   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11558   Register mainDstReg = MRI.createVirtualRegister(RC);
11559   Register restoreDstReg = MRI.createVirtualRegister(RC);
11560 
11561   MVT PVT = getPointerTy(MF->getDataLayout());
11562   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11563          "Invalid Pointer Size!");
11564   // For v = setjmp(buf), we generate
11565   //
11566   // thisMBB:
11567   //  SjLjSetup mainMBB
11568   //  bl mainMBB
11569   //  v_restore = 1
11570   //  b sinkMBB
11571   //
11572   // mainMBB:
11573   //  buf[LabelOffset] = LR
11574   //  v_main = 0
11575   //
11576   // sinkMBB:
11577   //  v = phi(main, restore)
11578   //
11579 
11580   MachineBasicBlock *thisMBB = MBB;
11581   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11582   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11583   MF->insert(I, mainMBB);
11584   MF->insert(I, sinkMBB);
11585 
11586   MachineInstrBuilder MIB;
11587 
11588   // Transfer the remainder of BB and its successor edges to sinkMBB.
11589   sinkMBB->splice(sinkMBB->begin(), MBB,
11590                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11591   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11592 
11593   // Note that the structure of the jmp_buf used here is not compatible
11594   // with that used by libc, and is not designed to be. Specifically, it
11595   // stores only those 'reserved' registers that LLVM does not otherwise
11596   // understand how to spill. Also, by convention, by the time this
11597   // intrinsic is called, Clang has already stored the frame address in the
11598   // first slot of the buffer and stack address in the third. Following the
11599   // X86 target code, we'll store the jump address in the second slot. We also
11600   // need to save the TOC pointer (R2) to handle jumps between shared
11601   // libraries, and that will be stored in the fourth slot. The thread
11602   // identifier (R13) is not affected.
11603 
11604   // thisMBB:
11605   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11606   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11607   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11608 
11609   // Prepare IP either in reg.
11610   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11611   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11612   Register BufReg = MI.getOperand(1).getReg();
11613 
11614   if (Subtarget.is64BitELFABI()) {
11615     setUsesTOCBasePtr(*MBB->getParent());
11616     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11617               .addReg(PPC::X2)
11618               .addImm(TOCOffset)
11619               .addReg(BufReg)
11620               .cloneMemRefs(MI);
11621   }
11622 
11623   // Naked functions never have a base pointer, and so we use r1. For all
11624   // other functions, this decision must be delayed until during PEI.
11625   unsigned BaseReg;
11626   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11627     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11628   else
11629     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11630 
11631   MIB = BuildMI(*thisMBB, MI, DL,
11632                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11633             .addReg(BaseReg)
11634             .addImm(BPOffset)
11635             .addReg(BufReg)
11636             .cloneMemRefs(MI);
11637 
11638   // Setup
11639   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11640   MIB.addRegMask(TRI->getNoPreservedMask());
11641 
11642   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11643 
11644   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11645           .addMBB(mainMBB);
11646   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11647 
11648   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11649   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11650 
11651   // mainMBB:
11652   //  mainDstReg = 0
11653   MIB =
11654       BuildMI(mainMBB, DL,
11655               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11656 
11657   // Store IP
11658   if (Subtarget.isPPC64()) {
11659     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11660             .addReg(LabelReg)
11661             .addImm(LabelOffset)
11662             .addReg(BufReg);
11663   } else {
11664     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11665             .addReg(LabelReg)
11666             .addImm(LabelOffset)
11667             .addReg(BufReg);
11668   }
11669   MIB.cloneMemRefs(MI);
11670 
11671   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11672   mainMBB->addSuccessor(sinkMBB);
11673 
11674   // sinkMBB:
11675   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11676           TII->get(PPC::PHI), DstReg)
11677     .addReg(mainDstReg).addMBB(mainMBB)
11678     .addReg(restoreDstReg).addMBB(thisMBB);
11679 
11680   MI.eraseFromParent();
11681   return sinkMBB;
11682 }
11683 
11684 MachineBasicBlock *
11685 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11686                                      MachineBasicBlock *MBB) const {
11687   DebugLoc DL = MI.getDebugLoc();
11688   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11689 
11690   MachineFunction *MF = MBB->getParent();
11691   MachineRegisterInfo &MRI = MF->getRegInfo();
11692 
11693   MVT PVT = getPointerTy(MF->getDataLayout());
11694   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11695          "Invalid Pointer Size!");
11696 
11697   const TargetRegisterClass *RC =
11698     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11699   Register Tmp = MRI.createVirtualRegister(RC);
11700   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11701   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11702   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11703   unsigned BP =
11704       (PVT == MVT::i64)
11705           ? PPC::X30
11706           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11707                                                               : PPC::R30);
11708 
11709   MachineInstrBuilder MIB;
11710 
11711   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11712   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11713   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11714   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11715 
11716   Register BufReg = MI.getOperand(0).getReg();
11717 
11718   // Reload FP (the jumped-to function may not have had a
11719   // frame pointer, and if so, then its r31 will be restored
11720   // as necessary).
11721   if (PVT == MVT::i64) {
11722     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11723             .addImm(0)
11724             .addReg(BufReg);
11725   } else {
11726     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11727             .addImm(0)
11728             .addReg(BufReg);
11729   }
11730   MIB.cloneMemRefs(MI);
11731 
11732   // Reload IP
11733   if (PVT == MVT::i64) {
11734     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11735             .addImm(LabelOffset)
11736             .addReg(BufReg);
11737   } else {
11738     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11739             .addImm(LabelOffset)
11740             .addReg(BufReg);
11741   }
11742   MIB.cloneMemRefs(MI);
11743 
11744   // Reload SP
11745   if (PVT == MVT::i64) {
11746     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11747             .addImm(SPOffset)
11748             .addReg(BufReg);
11749   } else {
11750     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11751             .addImm(SPOffset)
11752             .addReg(BufReg);
11753   }
11754   MIB.cloneMemRefs(MI);
11755 
11756   // Reload BP
11757   if (PVT == MVT::i64) {
11758     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11759             .addImm(BPOffset)
11760             .addReg(BufReg);
11761   } else {
11762     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11763             .addImm(BPOffset)
11764             .addReg(BufReg);
11765   }
11766   MIB.cloneMemRefs(MI);
11767 
11768   // Reload TOC
11769   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11770     setUsesTOCBasePtr(*MBB->getParent());
11771     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11772               .addImm(TOCOffset)
11773               .addReg(BufReg)
11774               .cloneMemRefs(MI);
11775   }
11776 
11777   // Jump
11778   BuildMI(*MBB, MI, DL,
11779           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11780   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11781 
11782   MI.eraseFromParent();
11783   return MBB;
11784 }
11785 
11786 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11787   // If the function specifically requests inline stack probes, emit them.
11788   if (MF.getFunction().hasFnAttribute("probe-stack"))
11789     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11790            "inline-asm";
11791   return false;
11792 }
11793 
11794 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11795   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11796   unsigned StackAlign = TFI->getStackAlignment();
11797   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11798          "Unexpected stack alignment");
11799   // The default stack probe size is 4096 if the function has no
11800   // stack-probe-size attribute.
11801   unsigned StackProbeSize = 4096;
11802   const Function &Fn = MF.getFunction();
11803   if (Fn.hasFnAttribute("stack-probe-size"))
11804     Fn.getFnAttribute("stack-probe-size")
11805         .getValueAsString()
11806         .getAsInteger(0, StackProbeSize);
11807   // Round down to the stack alignment.
11808   StackProbeSize &= ~(StackAlign - 1);
11809   return StackProbeSize ? StackProbeSize : StackAlign;
11810 }
11811 
11812 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11813 // into three phases. In the first phase, it uses pseudo instruction
11814 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11815 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11816 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11817 // MaxCallFrameSize so that it can calculate correct data area pointer.
11818 MachineBasicBlock *
11819 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11820                                     MachineBasicBlock *MBB) const {
11821   const bool isPPC64 = Subtarget.isPPC64();
11822   MachineFunction *MF = MBB->getParent();
11823   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11824   DebugLoc DL = MI.getDebugLoc();
11825   const unsigned ProbeSize = getStackProbeSize(*MF);
11826   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11827   MachineRegisterInfo &MRI = MF->getRegInfo();
11828   // The CFG of probing stack looks as
11829   //         +-----+
11830   //         | MBB |
11831   //         +--+--+
11832   //            |
11833   //       +----v----+
11834   //  +--->+ TestMBB +---+
11835   //  |    +----+----+   |
11836   //  |         |        |
11837   //  |   +-----v----+   |
11838   //  +---+ BlockMBB |   |
11839   //      +----------+   |
11840   //                     |
11841   //       +---------+   |
11842   //       | TailMBB +<--+
11843   //       +---------+
11844   // In MBB, calculate previous frame pointer and final stack pointer.
11845   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11846   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11847   // TailMBB is spliced via \p MI.
11848   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11849   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11850   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11851 
11852   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11853   MF->insert(MBBIter, TestMBB);
11854   MF->insert(MBBIter, BlockMBB);
11855   MF->insert(MBBIter, TailMBB);
11856 
11857   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11858   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11859 
11860   Register DstReg = MI.getOperand(0).getReg();
11861   Register NegSizeReg = MI.getOperand(1).getReg();
11862   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11863   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11864   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11865   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11866 
11867   // Since value of NegSizeReg might be realigned in prologepilog, insert a
11868   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
11869   // NegSize.
11870   unsigned ProbeOpc;
11871   if (!MRI.hasOneNonDBGUse(NegSizeReg))
11872     ProbeOpc =
11873         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
11874   else
11875     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
11876     // and NegSizeReg will be allocated in the same phyreg to avoid
11877     // redundant copy when NegSizeReg has only one use which is current MI and
11878     // will be replaced by PREPARE_PROBED_ALLOCA then.
11879     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
11880                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
11881   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
11882       .addDef(ActualNegSizeReg)
11883       .addReg(NegSizeReg)
11884       .add(MI.getOperand(2))
11885       .add(MI.getOperand(3));
11886 
11887   // Calculate final stack pointer, which equals to SP + ActualNegSize.
11888   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
11889           FinalStackPtr)
11890       .addReg(SPReg)
11891       .addReg(ActualNegSizeReg);
11892 
11893   // Materialize a scratch register for update.
11894   int64_t NegProbeSize = -(int64_t)ProbeSize;
11895   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
11896   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11897   if (!isInt<16>(NegProbeSize)) {
11898     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11899     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
11900         .addImm(NegProbeSize >> 16);
11901     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
11902             ScratchReg)
11903         .addReg(TempReg)
11904         .addImm(NegProbeSize & 0xFFFF);
11905   } else
11906     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
11907         .addImm(NegProbeSize);
11908 
11909   {
11910     // Probing leading residual part.
11911     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11912     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
11913         .addReg(ActualNegSizeReg)
11914         .addReg(ScratchReg);
11915     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11916     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
11917         .addReg(Div)
11918         .addReg(ScratchReg);
11919     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11920     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
11921         .addReg(Mul)
11922         .addReg(ActualNegSizeReg);
11923     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11924         .addReg(FramePointer)
11925         .addReg(SPReg)
11926         .addReg(NegMod);
11927   }
11928 
11929   {
11930     // Remaining part should be multiple of ProbeSize.
11931     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
11932     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
11933         .addReg(SPReg)
11934         .addReg(FinalStackPtr);
11935     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
11936         .addImm(PPC::PRED_EQ)
11937         .addReg(CmpResult)
11938         .addMBB(TailMBB);
11939     TestMBB->addSuccessor(BlockMBB);
11940     TestMBB->addSuccessor(TailMBB);
11941   }
11942 
11943   {
11944     // Touch the block.
11945     // |P...|P...|P...
11946     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11947         .addReg(FramePointer)
11948         .addReg(SPReg)
11949         .addReg(ScratchReg);
11950     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
11951     BlockMBB->addSuccessor(TestMBB);
11952   }
11953 
11954   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
11955   // DYNAREAOFFSET pseudo instruction to get the future result.
11956   Register MaxCallFrameSizeReg =
11957       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11958   BuildMI(TailMBB, DL,
11959           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
11960           MaxCallFrameSizeReg)
11961       .add(MI.getOperand(2))
11962       .add(MI.getOperand(3));
11963   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
11964       .addReg(SPReg)
11965       .addReg(MaxCallFrameSizeReg);
11966 
11967   // Splice instructions after MI to TailMBB.
11968   TailMBB->splice(TailMBB->end(), MBB,
11969                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11970   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
11971   MBB->addSuccessor(TestMBB);
11972 
11973   // Delete the pseudo instruction.
11974   MI.eraseFromParent();
11975 
11976   ++NumDynamicAllocaProbed;
11977   return TailMBB;
11978 }
11979 
11980 MachineBasicBlock *
11981 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11982                                                MachineBasicBlock *BB) const {
11983   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11984       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11985     if (Subtarget.is64BitELFABI() &&
11986         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11987         !Subtarget.isUsingPCRelativeCalls()) {
11988       // Call lowering should have added an r2 operand to indicate a dependence
11989       // on the TOC base pointer value. It can't however, because there is no
11990       // way to mark the dependence as implicit there, and so the stackmap code
11991       // will confuse it with a regular operand. Instead, add the dependence
11992       // here.
11993       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11994     }
11995 
11996     return emitPatchPoint(MI, BB);
11997   }
11998 
11999   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
12000       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
12001     return emitEHSjLjSetJmp(MI, BB);
12002   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
12003              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
12004     return emitEHSjLjLongJmp(MI, BB);
12005   }
12006 
12007   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12008 
12009   // To "insert" these instructions we actually have to insert their
12010   // control-flow patterns.
12011   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12012   MachineFunction::iterator It = ++BB->getIterator();
12013 
12014   MachineFunction *F = BB->getParent();
12015 
12016   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12017       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
12018       MI.getOpcode() == PPC::SELECT_I8) {
12019     SmallVector<MachineOperand, 2> Cond;
12020     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12021         MI.getOpcode() == PPC::SELECT_CC_I8)
12022       Cond.push_back(MI.getOperand(4));
12023     else
12024       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
12025     Cond.push_back(MI.getOperand(1));
12026 
12027     DebugLoc dl = MI.getDebugLoc();
12028     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
12029                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
12030   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
12031              MI.getOpcode() == PPC::SELECT_CC_F8 ||
12032              MI.getOpcode() == PPC::SELECT_CC_F16 ||
12033              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
12034              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
12035              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
12036              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
12037              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
12038              MI.getOpcode() == PPC::SELECT_CC_SPE ||
12039              MI.getOpcode() == PPC::SELECT_F4 ||
12040              MI.getOpcode() == PPC::SELECT_F8 ||
12041              MI.getOpcode() == PPC::SELECT_F16 ||
12042              MI.getOpcode() == PPC::SELECT_SPE ||
12043              MI.getOpcode() == PPC::SELECT_SPE4 ||
12044              MI.getOpcode() == PPC::SELECT_VRRC ||
12045              MI.getOpcode() == PPC::SELECT_VSFRC ||
12046              MI.getOpcode() == PPC::SELECT_VSSRC ||
12047              MI.getOpcode() == PPC::SELECT_VSRC) {
12048     // The incoming instruction knows the destination vreg to set, the
12049     // condition code register to branch on, the true/false values to
12050     // select between, and a branch opcode to use.
12051 
12052     //  thisMBB:
12053     //  ...
12054     //   TrueVal = ...
12055     //   cmpTY ccX, r1, r2
12056     //   bCC copy1MBB
12057     //   fallthrough --> copy0MBB
12058     MachineBasicBlock *thisMBB = BB;
12059     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12060     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12061     DebugLoc dl = MI.getDebugLoc();
12062     F->insert(It, copy0MBB);
12063     F->insert(It, sinkMBB);
12064 
12065     // Transfer the remainder of BB and its successor edges to sinkMBB.
12066     sinkMBB->splice(sinkMBB->begin(), BB,
12067                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12068     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12069 
12070     // Next, add the true and fallthrough blocks as its successors.
12071     BB->addSuccessor(copy0MBB);
12072     BB->addSuccessor(sinkMBB);
12073 
12074     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
12075         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
12076         MI.getOpcode() == PPC::SELECT_F16 ||
12077         MI.getOpcode() == PPC::SELECT_SPE4 ||
12078         MI.getOpcode() == PPC::SELECT_SPE ||
12079         MI.getOpcode() == PPC::SELECT_VRRC ||
12080         MI.getOpcode() == PPC::SELECT_VSFRC ||
12081         MI.getOpcode() == PPC::SELECT_VSSRC ||
12082         MI.getOpcode() == PPC::SELECT_VSRC) {
12083       BuildMI(BB, dl, TII->get(PPC::BC))
12084           .addReg(MI.getOperand(1).getReg())
12085           .addMBB(sinkMBB);
12086     } else {
12087       unsigned SelectPred = MI.getOperand(4).getImm();
12088       BuildMI(BB, dl, TII->get(PPC::BCC))
12089           .addImm(SelectPred)
12090           .addReg(MI.getOperand(1).getReg())
12091           .addMBB(sinkMBB);
12092     }
12093 
12094     //  copy0MBB:
12095     //   %FalseValue = ...
12096     //   # fallthrough to sinkMBB
12097     BB = copy0MBB;
12098 
12099     // Update machine-CFG edges
12100     BB->addSuccessor(sinkMBB);
12101 
12102     //  sinkMBB:
12103     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12104     //  ...
12105     BB = sinkMBB;
12106     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
12107         .addReg(MI.getOperand(3).getReg())
12108         .addMBB(copy0MBB)
12109         .addReg(MI.getOperand(2).getReg())
12110         .addMBB(thisMBB);
12111   } else if (MI.getOpcode() == PPC::ReadTB) {
12112     // To read the 64-bit time-base register on a 32-bit target, we read the
12113     // two halves. Should the counter have wrapped while it was being read, we
12114     // need to try again.
12115     // ...
12116     // readLoop:
12117     // mfspr Rx,TBU # load from TBU
12118     // mfspr Ry,TB  # load from TB
12119     // mfspr Rz,TBU # load from TBU
12120     // cmpw crX,Rx,Rz # check if 'old'='new'
12121     // bne readLoop   # branch if they're not equal
12122     // ...
12123 
12124     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
12125     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12126     DebugLoc dl = MI.getDebugLoc();
12127     F->insert(It, readMBB);
12128     F->insert(It, sinkMBB);
12129 
12130     // Transfer the remainder of BB and its successor edges to sinkMBB.
12131     sinkMBB->splice(sinkMBB->begin(), BB,
12132                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12133     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12134 
12135     BB->addSuccessor(readMBB);
12136     BB = readMBB;
12137 
12138     MachineRegisterInfo &RegInfo = F->getRegInfo();
12139     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
12140     Register LoReg = MI.getOperand(0).getReg();
12141     Register HiReg = MI.getOperand(1).getReg();
12142 
12143     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
12144     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
12145     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
12146 
12147     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12148 
12149     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
12150         .addReg(HiReg)
12151         .addReg(ReadAgainReg);
12152     BuildMI(BB, dl, TII->get(PPC::BCC))
12153         .addImm(PPC::PRED_NE)
12154         .addReg(CmpReg)
12155         .addMBB(readMBB);
12156 
12157     BB->addSuccessor(readMBB);
12158     BB->addSuccessor(sinkMBB);
12159   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
12160     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
12161   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
12162     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
12163   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
12164     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
12165   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
12166     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
12167 
12168   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
12169     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
12170   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
12171     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
12172   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
12173     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
12174   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
12175     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
12176 
12177   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
12178     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
12179   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
12180     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
12181   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
12182     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
12183   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
12184     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
12185 
12186   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
12187     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
12188   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
12189     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
12190   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
12191     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
12192   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
12193     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
12194 
12195   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
12196     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
12197   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
12198     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
12199   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
12200     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
12201   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
12202     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
12203 
12204   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
12205     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
12206   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
12207     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
12208   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
12209     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
12210   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
12211     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
12212 
12213   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
12214     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
12215   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
12216     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
12217   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
12218     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
12219   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
12220     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
12221 
12222   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
12223     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
12224   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
12225     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
12226   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
12227     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
12228   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
12229     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
12230 
12231   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
12232     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
12233   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
12234     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
12235   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
12236     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
12237   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
12238     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
12239 
12240   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
12241     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
12242   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
12243     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
12244   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
12245     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
12246   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
12247     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
12248 
12249   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
12250     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
12251   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
12252     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
12253   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
12254     BB = EmitAtomicBinary(MI, BB, 4, 0);
12255   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
12256     BB = EmitAtomicBinary(MI, BB, 8, 0);
12257   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
12258            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
12259            (Subtarget.hasPartwordAtomics() &&
12260             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
12261            (Subtarget.hasPartwordAtomics() &&
12262             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
12263     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
12264 
12265     auto LoadMnemonic = PPC::LDARX;
12266     auto StoreMnemonic = PPC::STDCX;
12267     switch (MI.getOpcode()) {
12268     default:
12269       llvm_unreachable("Compare and swap of unknown size");
12270     case PPC::ATOMIC_CMP_SWAP_I8:
12271       LoadMnemonic = PPC::LBARX;
12272       StoreMnemonic = PPC::STBCX;
12273       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12274       break;
12275     case PPC::ATOMIC_CMP_SWAP_I16:
12276       LoadMnemonic = PPC::LHARX;
12277       StoreMnemonic = PPC::STHCX;
12278       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12279       break;
12280     case PPC::ATOMIC_CMP_SWAP_I32:
12281       LoadMnemonic = PPC::LWARX;
12282       StoreMnemonic = PPC::STWCX;
12283       break;
12284     case PPC::ATOMIC_CMP_SWAP_I64:
12285       LoadMnemonic = PPC::LDARX;
12286       StoreMnemonic = PPC::STDCX;
12287       break;
12288     }
12289     Register dest = MI.getOperand(0).getReg();
12290     Register ptrA = MI.getOperand(1).getReg();
12291     Register ptrB = MI.getOperand(2).getReg();
12292     Register oldval = MI.getOperand(3).getReg();
12293     Register newval = MI.getOperand(4).getReg();
12294     DebugLoc dl = MI.getDebugLoc();
12295 
12296     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12297     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12298     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12299     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12300     F->insert(It, loop1MBB);
12301     F->insert(It, loop2MBB);
12302     F->insert(It, midMBB);
12303     F->insert(It, exitMBB);
12304     exitMBB->splice(exitMBB->begin(), BB,
12305                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12306     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12307 
12308     //  thisMBB:
12309     //   ...
12310     //   fallthrough --> loopMBB
12311     BB->addSuccessor(loop1MBB);
12312 
12313     // loop1MBB:
12314     //   l[bhwd]arx dest, ptr
12315     //   cmp[wd] dest, oldval
12316     //   bne- midMBB
12317     // loop2MBB:
12318     //   st[bhwd]cx. newval, ptr
12319     //   bne- loopMBB
12320     //   b exitBB
12321     // midMBB:
12322     //   st[bhwd]cx. dest, ptr
12323     // exitBB:
12324     BB = loop1MBB;
12325     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12326     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12327         .addReg(oldval)
12328         .addReg(dest);
12329     BuildMI(BB, dl, TII->get(PPC::BCC))
12330         .addImm(PPC::PRED_NE)
12331         .addReg(PPC::CR0)
12332         .addMBB(midMBB);
12333     BB->addSuccessor(loop2MBB);
12334     BB->addSuccessor(midMBB);
12335 
12336     BB = loop2MBB;
12337     BuildMI(BB, dl, TII->get(StoreMnemonic))
12338         .addReg(newval)
12339         .addReg(ptrA)
12340         .addReg(ptrB);
12341     BuildMI(BB, dl, TII->get(PPC::BCC))
12342         .addImm(PPC::PRED_NE)
12343         .addReg(PPC::CR0)
12344         .addMBB(loop1MBB);
12345     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12346     BB->addSuccessor(loop1MBB);
12347     BB->addSuccessor(exitMBB);
12348 
12349     BB = midMBB;
12350     BuildMI(BB, dl, TII->get(StoreMnemonic))
12351         .addReg(dest)
12352         .addReg(ptrA)
12353         .addReg(ptrB);
12354     BB->addSuccessor(exitMBB);
12355 
12356     //  exitMBB:
12357     //   ...
12358     BB = exitMBB;
12359   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12360              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12361     // We must use 64-bit registers for addresses when targeting 64-bit,
12362     // since we're actually doing arithmetic on them.  Other registers
12363     // can be 32-bit.
12364     bool is64bit = Subtarget.isPPC64();
12365     bool isLittleEndian = Subtarget.isLittleEndian();
12366     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12367 
12368     Register dest = MI.getOperand(0).getReg();
12369     Register ptrA = MI.getOperand(1).getReg();
12370     Register ptrB = MI.getOperand(2).getReg();
12371     Register oldval = MI.getOperand(3).getReg();
12372     Register newval = MI.getOperand(4).getReg();
12373     DebugLoc dl = MI.getDebugLoc();
12374 
12375     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12376     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12377     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12378     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12379     F->insert(It, loop1MBB);
12380     F->insert(It, loop2MBB);
12381     F->insert(It, midMBB);
12382     F->insert(It, exitMBB);
12383     exitMBB->splice(exitMBB->begin(), BB,
12384                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12385     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12386 
12387     MachineRegisterInfo &RegInfo = F->getRegInfo();
12388     const TargetRegisterClass *RC =
12389         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12390     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12391 
12392     Register PtrReg = RegInfo.createVirtualRegister(RC);
12393     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12394     Register ShiftReg =
12395         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12396     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12397     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12398     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12399     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12400     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12401     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12402     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12403     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12404     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12405     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12406     Register Ptr1Reg;
12407     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12408     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12409     //  thisMBB:
12410     //   ...
12411     //   fallthrough --> loopMBB
12412     BB->addSuccessor(loop1MBB);
12413 
12414     // The 4-byte load must be aligned, while a char or short may be
12415     // anywhere in the word.  Hence all this nasty bookkeeping code.
12416     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12417     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12418     //   xori shift, shift1, 24 [16]
12419     //   rlwinm ptr, ptr1, 0, 0, 29
12420     //   slw newval2, newval, shift
12421     //   slw oldval2, oldval,shift
12422     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12423     //   slw mask, mask2, shift
12424     //   and newval3, newval2, mask
12425     //   and oldval3, oldval2, mask
12426     // loop1MBB:
12427     //   lwarx tmpDest, ptr
12428     //   and tmp, tmpDest, mask
12429     //   cmpw tmp, oldval3
12430     //   bne- midMBB
12431     // loop2MBB:
12432     //   andc tmp2, tmpDest, mask
12433     //   or tmp4, tmp2, newval3
12434     //   stwcx. tmp4, ptr
12435     //   bne- loop1MBB
12436     //   b exitBB
12437     // midMBB:
12438     //   stwcx. tmpDest, ptr
12439     // exitBB:
12440     //   srw dest, tmpDest, shift
12441     if (ptrA != ZeroReg) {
12442       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12443       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12444           .addReg(ptrA)
12445           .addReg(ptrB);
12446     } else {
12447       Ptr1Reg = ptrB;
12448     }
12449 
12450     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12451     // mode.
12452     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12453         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12454         .addImm(3)
12455         .addImm(27)
12456         .addImm(is8bit ? 28 : 27);
12457     if (!isLittleEndian)
12458       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12459           .addReg(Shift1Reg)
12460           .addImm(is8bit ? 24 : 16);
12461     if (is64bit)
12462       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12463           .addReg(Ptr1Reg)
12464           .addImm(0)
12465           .addImm(61);
12466     else
12467       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12468           .addReg(Ptr1Reg)
12469           .addImm(0)
12470           .addImm(0)
12471           .addImm(29);
12472     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12473         .addReg(newval)
12474         .addReg(ShiftReg);
12475     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12476         .addReg(oldval)
12477         .addReg(ShiftReg);
12478     if (is8bit)
12479       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12480     else {
12481       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12482       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12483           .addReg(Mask3Reg)
12484           .addImm(65535);
12485     }
12486     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12487         .addReg(Mask2Reg)
12488         .addReg(ShiftReg);
12489     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12490         .addReg(NewVal2Reg)
12491         .addReg(MaskReg);
12492     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12493         .addReg(OldVal2Reg)
12494         .addReg(MaskReg);
12495 
12496     BB = loop1MBB;
12497     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12498         .addReg(ZeroReg)
12499         .addReg(PtrReg);
12500     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12501         .addReg(TmpDestReg)
12502         .addReg(MaskReg);
12503     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12504         .addReg(TmpReg)
12505         .addReg(OldVal3Reg);
12506     BuildMI(BB, dl, TII->get(PPC::BCC))
12507         .addImm(PPC::PRED_NE)
12508         .addReg(PPC::CR0)
12509         .addMBB(midMBB);
12510     BB->addSuccessor(loop2MBB);
12511     BB->addSuccessor(midMBB);
12512 
12513     BB = loop2MBB;
12514     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12515         .addReg(TmpDestReg)
12516         .addReg(MaskReg);
12517     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12518         .addReg(Tmp2Reg)
12519         .addReg(NewVal3Reg);
12520     BuildMI(BB, dl, TII->get(PPC::STWCX))
12521         .addReg(Tmp4Reg)
12522         .addReg(ZeroReg)
12523         .addReg(PtrReg);
12524     BuildMI(BB, dl, TII->get(PPC::BCC))
12525         .addImm(PPC::PRED_NE)
12526         .addReg(PPC::CR0)
12527         .addMBB(loop1MBB);
12528     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12529     BB->addSuccessor(loop1MBB);
12530     BB->addSuccessor(exitMBB);
12531 
12532     BB = midMBB;
12533     BuildMI(BB, dl, TII->get(PPC::STWCX))
12534         .addReg(TmpDestReg)
12535         .addReg(ZeroReg)
12536         .addReg(PtrReg);
12537     BB->addSuccessor(exitMBB);
12538 
12539     //  exitMBB:
12540     //   ...
12541     BB = exitMBB;
12542     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12543         .addReg(TmpReg)
12544         .addReg(ShiftReg);
12545   } else if (MI.getOpcode() == PPC::FADDrtz) {
12546     // This pseudo performs an FADD with rounding mode temporarily forced
12547     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12548     // is not modeled at the SelectionDAG level.
12549     Register Dest = MI.getOperand(0).getReg();
12550     Register Src1 = MI.getOperand(1).getReg();
12551     Register Src2 = MI.getOperand(2).getReg();
12552     DebugLoc dl = MI.getDebugLoc();
12553 
12554     MachineRegisterInfo &RegInfo = F->getRegInfo();
12555     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12556 
12557     // Save FPSCR value.
12558     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12559 
12560     // Set rounding mode to round-to-zero.
12561     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12562         .addImm(31)
12563         .addReg(PPC::RM, RegState::ImplicitDefine);
12564 
12565     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12566         .addImm(30)
12567         .addReg(PPC::RM, RegState::ImplicitDefine);
12568 
12569     // Perform addition.
12570     auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
12571                    .addReg(Src1)
12572                    .addReg(Src2);
12573     if (MI.getFlag(MachineInstr::NoFPExcept))
12574       MIB.setMIFlag(MachineInstr::NoFPExcept);
12575 
12576     // Restore FPSCR value.
12577     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12578   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12579              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12580              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12581              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12582     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12583                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12584                           ? PPC::ANDI8_rec
12585                           : PPC::ANDI_rec;
12586     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12587                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12588 
12589     MachineRegisterInfo &RegInfo = F->getRegInfo();
12590     Register Dest = RegInfo.createVirtualRegister(
12591         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12592 
12593     DebugLoc Dl = MI.getDebugLoc();
12594     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12595         .addReg(MI.getOperand(1).getReg())
12596         .addImm(1);
12597     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12598             MI.getOperand(0).getReg())
12599         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12600   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12601     DebugLoc Dl = MI.getDebugLoc();
12602     MachineRegisterInfo &RegInfo = F->getRegInfo();
12603     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12604     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12605     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12606             MI.getOperand(0).getReg())
12607         .addReg(CRReg);
12608   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12609     DebugLoc Dl = MI.getDebugLoc();
12610     unsigned Imm = MI.getOperand(1).getImm();
12611     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12612     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12613             MI.getOperand(0).getReg())
12614         .addReg(PPC::CR0EQ);
12615   } else if (MI.getOpcode() == PPC::SETRNDi) {
12616     DebugLoc dl = MI.getDebugLoc();
12617     Register OldFPSCRReg = MI.getOperand(0).getReg();
12618 
12619     // Save FPSCR value.
12620     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12621 
12622     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12623     // the following settings:
12624     //   00 Round to nearest
12625     //   01 Round to 0
12626     //   10 Round to +inf
12627     //   11 Round to -inf
12628 
12629     // When the operand is immediate, using the two least significant bits of
12630     // the immediate to set the bits 62:63 of FPSCR.
12631     unsigned Mode = MI.getOperand(1).getImm();
12632     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12633         .addImm(31)
12634         .addReg(PPC::RM, RegState::ImplicitDefine);
12635 
12636     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12637         .addImm(30)
12638         .addReg(PPC::RM, RegState::ImplicitDefine);
12639   } else if (MI.getOpcode() == PPC::SETRND) {
12640     DebugLoc dl = MI.getDebugLoc();
12641 
12642     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12643     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12644     // If the target doesn't have DirectMove, we should use stack to do the
12645     // conversion, because the target doesn't have the instructions like mtvsrd
12646     // or mfvsrd to do this conversion directly.
12647     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12648       if (Subtarget.hasDirectMove()) {
12649         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12650           .addReg(SrcReg);
12651       } else {
12652         // Use stack to do the register copy.
12653         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12654         MachineRegisterInfo &RegInfo = F->getRegInfo();
12655         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12656         if (RC == &PPC::F8RCRegClass) {
12657           // Copy register from F8RCRegClass to G8RCRegclass.
12658           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12659                  "Unsupported RegClass.");
12660 
12661           StoreOp = PPC::STFD;
12662           LoadOp = PPC::LD;
12663         } else {
12664           // Copy register from G8RCRegClass to F8RCRegclass.
12665           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12666                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12667                  "Unsupported RegClass.");
12668         }
12669 
12670         MachineFrameInfo &MFI = F->getFrameInfo();
12671         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12672 
12673         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12674             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12675             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12676             MFI.getObjectAlign(FrameIdx));
12677 
12678         // Store the SrcReg into the stack.
12679         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12680           .addReg(SrcReg)
12681           .addImm(0)
12682           .addFrameIndex(FrameIdx)
12683           .addMemOperand(MMOStore);
12684 
12685         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12686             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12687             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12688             MFI.getObjectAlign(FrameIdx));
12689 
12690         // Load from the stack where SrcReg is stored, and save to DestReg,
12691         // so we have done the RegClass conversion from RegClass::SrcReg to
12692         // RegClass::DestReg.
12693         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12694           .addImm(0)
12695           .addFrameIndex(FrameIdx)
12696           .addMemOperand(MMOLoad);
12697       }
12698     };
12699 
12700     Register OldFPSCRReg = MI.getOperand(0).getReg();
12701 
12702     // Save FPSCR value.
12703     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12704 
12705     // When the operand is gprc register, use two least significant bits of the
12706     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12707     //
12708     // copy OldFPSCRTmpReg, OldFPSCRReg
12709     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12710     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12711     // copy NewFPSCRReg, NewFPSCRTmpReg
12712     // mtfsf 255, NewFPSCRReg
12713     MachineOperand SrcOp = MI.getOperand(1);
12714     MachineRegisterInfo &RegInfo = F->getRegInfo();
12715     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12716 
12717     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12718 
12719     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12720     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12721 
12722     // The first operand of INSERT_SUBREG should be a register which has
12723     // subregisters, we only care about its RegClass, so we should use an
12724     // IMPLICIT_DEF register.
12725     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12726     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12727       .addReg(ImDefReg)
12728       .add(SrcOp)
12729       .addImm(1);
12730 
12731     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12732     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12733       .addReg(OldFPSCRTmpReg)
12734       .addReg(ExtSrcReg)
12735       .addImm(0)
12736       .addImm(62);
12737 
12738     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12739     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12740 
12741     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12742     // bits of FPSCR.
12743     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12744       .addImm(255)
12745       .addReg(NewFPSCRReg)
12746       .addImm(0)
12747       .addImm(0);
12748   } else if (MI.getOpcode() == PPC::SETFLM) {
12749     DebugLoc Dl = MI.getDebugLoc();
12750 
12751     // Result of setflm is previous FPSCR content, so we need to save it first.
12752     Register OldFPSCRReg = MI.getOperand(0).getReg();
12753     BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12754 
12755     // Put bits in 32:63 to FPSCR.
12756     Register NewFPSCRReg = MI.getOperand(1).getReg();
12757     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12758         .addImm(255)
12759         .addReg(NewFPSCRReg)
12760         .addImm(0)
12761         .addImm(0);
12762   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12763              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12764     return emitProbedAlloca(MI, BB);
12765   } else {
12766     llvm_unreachable("Unexpected instr type to insert");
12767   }
12768 
12769   MI.eraseFromParent(); // The pseudo instruction is gone now.
12770   return BB;
12771 }
12772 
12773 //===----------------------------------------------------------------------===//
12774 // Target Optimization Hooks
12775 //===----------------------------------------------------------------------===//
12776 
12777 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12778   // For the estimates, convergence is quadratic, so we essentially double the
12779   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12780   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12781   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12782   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12783   if (VT.getScalarType() == MVT::f64)
12784     RefinementSteps++;
12785   return RefinementSteps;
12786 }
12787 
12788 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
12789                                             const DenormalMode &Mode) const {
12790   // We only have VSX Vector Test for software Square Root.
12791   EVT VT = Op.getValueType();
12792   if (!isTypeLegal(MVT::i1) ||
12793       (VT != MVT::f64 &&
12794        ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
12795     return SDValue();
12796 
12797   SDLoc DL(Op);
12798   // The output register of FTSQRT is CR field.
12799   SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
12800   // ftsqrt BF,FRB
12801   // Let e_b be the unbiased exponent of the double-precision
12802   // floating-point operand in register FRB.
12803   // fe_flag is set to 1 if either of the following conditions occurs.
12804   //   - The double-precision floating-point operand in register FRB is a zero,
12805   //     a NaN, or an infinity, or a negative value.
12806   //   - e_b is less than or equal to -970.
12807   // Otherwise fe_flag is set to 0.
12808   // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
12809   // not eligible for iteration. (zero/negative/infinity/nan or unbiased
12810   // exponent is less than -970)
12811   SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
12812   return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
12813                                     FTSQRT, SRIdxVal),
12814                  0);
12815 }
12816 
12817 SDValue
12818 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
12819                                                SelectionDAG &DAG) const {
12820   // We only have VSX Vector Square Root.
12821   EVT VT = Op.getValueType();
12822   if (VT != MVT::f64 &&
12823       ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
12824     return TargetLowering::getSqrtResultForDenormInput(Op, DAG);
12825 
12826   return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
12827 }
12828 
12829 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12830                                            int Enabled, int &RefinementSteps,
12831                                            bool &UseOneConstNR,
12832                                            bool Reciprocal) const {
12833   EVT VT = Operand.getValueType();
12834   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12835       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12836       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12837       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12838     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12839       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12840 
12841     // The Newton-Raphson computation with a single constant does not provide
12842     // enough accuracy on some CPUs.
12843     UseOneConstNR = !Subtarget.needsTwoConstNR();
12844     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12845   }
12846   return SDValue();
12847 }
12848 
12849 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12850                                             int Enabled,
12851                                             int &RefinementSteps) const {
12852   EVT VT = Operand.getValueType();
12853   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12854       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12855       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12856       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12857     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12858       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12859     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12860   }
12861   return SDValue();
12862 }
12863 
12864 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12865   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12866   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12867   // enabled for division), this functionality is redundant with the default
12868   // combiner logic (once the division -> reciprocal/multiply transformation
12869   // has taken place). As a result, this matters more for older cores than for
12870   // newer ones.
12871 
12872   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12873   // reciprocal if there are two or more FDIVs (for embedded cores with only
12874   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12875   switch (Subtarget.getCPUDirective()) {
12876   default:
12877     return 3;
12878   case PPC::DIR_440:
12879   case PPC::DIR_A2:
12880   case PPC::DIR_E500:
12881   case PPC::DIR_E500mc:
12882   case PPC::DIR_E5500:
12883     return 2;
12884   }
12885 }
12886 
12887 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12888 // collapsed, and so we need to look through chains of them.
12889 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12890                                      int64_t& Offset, SelectionDAG &DAG) {
12891   if (DAG.isBaseWithConstantOffset(Loc)) {
12892     Base = Loc.getOperand(0);
12893     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12894 
12895     // The base might itself be a base plus an offset, and if so, accumulate
12896     // that as well.
12897     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12898   }
12899 }
12900 
12901 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12902                             unsigned Bytes, int Dist,
12903                             SelectionDAG &DAG) {
12904   if (VT.getSizeInBits() / 8 != Bytes)
12905     return false;
12906 
12907   SDValue BaseLoc = Base->getBasePtr();
12908   if (Loc.getOpcode() == ISD::FrameIndex) {
12909     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12910       return false;
12911     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12912     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12913     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12914     int FS  = MFI.getObjectSize(FI);
12915     int BFS = MFI.getObjectSize(BFI);
12916     if (FS != BFS || FS != (int)Bytes) return false;
12917     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12918   }
12919 
12920   SDValue Base1 = Loc, Base2 = BaseLoc;
12921   int64_t Offset1 = 0, Offset2 = 0;
12922   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12923   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12924   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12925     return true;
12926 
12927   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12928   const GlobalValue *GV1 = nullptr;
12929   const GlobalValue *GV2 = nullptr;
12930   Offset1 = 0;
12931   Offset2 = 0;
12932   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12933   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12934   if (isGA1 && isGA2 && GV1 == GV2)
12935     return Offset1 == (Offset2 + Dist*Bytes);
12936   return false;
12937 }
12938 
12939 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12940 // not enforce equality of the chain operands.
12941 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12942                             unsigned Bytes, int Dist,
12943                             SelectionDAG &DAG) {
12944   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12945     EVT VT = LS->getMemoryVT();
12946     SDValue Loc = LS->getBasePtr();
12947     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12948   }
12949 
12950   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12951     EVT VT;
12952     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12953     default: return false;
12954     case Intrinsic::ppc_altivec_lvx:
12955     case Intrinsic::ppc_altivec_lvxl:
12956     case Intrinsic::ppc_vsx_lxvw4x:
12957     case Intrinsic::ppc_vsx_lxvw4x_be:
12958       VT = MVT::v4i32;
12959       break;
12960     case Intrinsic::ppc_vsx_lxvd2x:
12961     case Intrinsic::ppc_vsx_lxvd2x_be:
12962       VT = MVT::v2f64;
12963       break;
12964     case Intrinsic::ppc_altivec_lvebx:
12965       VT = MVT::i8;
12966       break;
12967     case Intrinsic::ppc_altivec_lvehx:
12968       VT = MVT::i16;
12969       break;
12970     case Intrinsic::ppc_altivec_lvewx:
12971       VT = MVT::i32;
12972       break;
12973     }
12974 
12975     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12976   }
12977 
12978   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12979     EVT VT;
12980     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12981     default: return false;
12982     case Intrinsic::ppc_altivec_stvx:
12983     case Intrinsic::ppc_altivec_stvxl:
12984     case Intrinsic::ppc_vsx_stxvw4x:
12985       VT = MVT::v4i32;
12986       break;
12987     case Intrinsic::ppc_vsx_stxvd2x:
12988       VT = MVT::v2f64;
12989       break;
12990     case Intrinsic::ppc_vsx_stxvw4x_be:
12991       VT = MVT::v4i32;
12992       break;
12993     case Intrinsic::ppc_vsx_stxvd2x_be:
12994       VT = MVT::v2f64;
12995       break;
12996     case Intrinsic::ppc_altivec_stvebx:
12997       VT = MVT::i8;
12998       break;
12999     case Intrinsic::ppc_altivec_stvehx:
13000       VT = MVT::i16;
13001       break;
13002     case Intrinsic::ppc_altivec_stvewx:
13003       VT = MVT::i32;
13004       break;
13005     }
13006 
13007     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
13008   }
13009 
13010   return false;
13011 }
13012 
13013 // Return true is there is a nearyby consecutive load to the one provided
13014 // (regardless of alignment). We search up and down the chain, looking though
13015 // token factors and other loads (but nothing else). As a result, a true result
13016 // indicates that it is safe to create a new consecutive load adjacent to the
13017 // load provided.
13018 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
13019   SDValue Chain = LD->getChain();
13020   EVT VT = LD->getMemoryVT();
13021 
13022   SmallSet<SDNode *, 16> LoadRoots;
13023   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
13024   SmallSet<SDNode *, 16> Visited;
13025 
13026   // First, search up the chain, branching to follow all token-factor operands.
13027   // If we find a consecutive load, then we're done, otherwise, record all
13028   // nodes just above the top-level loads and token factors.
13029   while (!Queue.empty()) {
13030     SDNode *ChainNext = Queue.pop_back_val();
13031     if (!Visited.insert(ChainNext).second)
13032       continue;
13033 
13034     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
13035       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13036         return true;
13037 
13038       if (!Visited.count(ChainLD->getChain().getNode()))
13039         Queue.push_back(ChainLD->getChain().getNode());
13040     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
13041       for (const SDUse &O : ChainNext->ops())
13042         if (!Visited.count(O.getNode()))
13043           Queue.push_back(O.getNode());
13044     } else
13045       LoadRoots.insert(ChainNext);
13046   }
13047 
13048   // Second, search down the chain, starting from the top-level nodes recorded
13049   // in the first phase. These top-level nodes are the nodes just above all
13050   // loads and token factors. Starting with their uses, recursively look though
13051   // all loads (just the chain uses) and token factors to find a consecutive
13052   // load.
13053   Visited.clear();
13054   Queue.clear();
13055 
13056   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
13057        IE = LoadRoots.end(); I != IE; ++I) {
13058     Queue.push_back(*I);
13059 
13060     while (!Queue.empty()) {
13061       SDNode *LoadRoot = Queue.pop_back_val();
13062       if (!Visited.insert(LoadRoot).second)
13063         continue;
13064 
13065       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
13066         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13067           return true;
13068 
13069       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
13070            UE = LoadRoot->use_end(); UI != UE; ++UI)
13071         if (((isa<MemSDNode>(*UI) &&
13072             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
13073             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
13074           Queue.push_back(*UI);
13075     }
13076   }
13077 
13078   return false;
13079 }
13080 
13081 /// This function is called when we have proved that a SETCC node can be replaced
13082 /// by subtraction (and other supporting instructions) so that the result of
13083 /// comparison is kept in a GPR instead of CR. This function is purely for
13084 /// codegen purposes and has some flags to guide the codegen process.
13085 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
13086                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
13087   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13088 
13089   // Zero extend the operands to the largest legal integer. Originally, they
13090   // must be of a strictly smaller size.
13091   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
13092                          DAG.getConstant(Size, DL, MVT::i32));
13093   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
13094                          DAG.getConstant(Size, DL, MVT::i32));
13095 
13096   // Swap if needed. Depends on the condition code.
13097   if (Swap)
13098     std::swap(Op0, Op1);
13099 
13100   // Subtract extended integers.
13101   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
13102 
13103   // Move the sign bit to the least significant position and zero out the rest.
13104   // Now the least significant bit carries the result of original comparison.
13105   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
13106                              DAG.getConstant(Size - 1, DL, MVT::i32));
13107   auto Final = Shifted;
13108 
13109   // Complement the result if needed. Based on the condition code.
13110   if (Complement)
13111     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
13112                         DAG.getConstant(1, DL, MVT::i64));
13113 
13114   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
13115 }
13116 
13117 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
13118                                                   DAGCombinerInfo &DCI) const {
13119   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13120 
13121   SelectionDAG &DAG = DCI.DAG;
13122   SDLoc DL(N);
13123 
13124   // Size of integers being compared has a critical role in the following
13125   // analysis, so we prefer to do this when all types are legal.
13126   if (!DCI.isAfterLegalizeDAG())
13127     return SDValue();
13128 
13129   // If all users of SETCC extend its value to a legal integer type
13130   // then we replace SETCC with a subtraction
13131   for (SDNode::use_iterator UI = N->use_begin(),
13132        UE = N->use_end(); UI != UE; ++UI) {
13133     if (UI->getOpcode() != ISD::ZERO_EXTEND)
13134       return SDValue();
13135   }
13136 
13137   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13138   auto OpSize = N->getOperand(0).getValueSizeInBits();
13139 
13140   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
13141 
13142   if (OpSize < Size) {
13143     switch (CC) {
13144     default: break;
13145     case ISD::SETULT:
13146       return generateEquivalentSub(N, Size, false, false, DL, DAG);
13147     case ISD::SETULE:
13148       return generateEquivalentSub(N, Size, true, true, DL, DAG);
13149     case ISD::SETUGT:
13150       return generateEquivalentSub(N, Size, false, true, DL, DAG);
13151     case ISD::SETUGE:
13152       return generateEquivalentSub(N, Size, true, false, DL, DAG);
13153     }
13154   }
13155 
13156   return SDValue();
13157 }
13158 
13159 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
13160                                                   DAGCombinerInfo &DCI) const {
13161   SelectionDAG &DAG = DCI.DAG;
13162   SDLoc dl(N);
13163 
13164   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
13165   // If we're tracking CR bits, we need to be careful that we don't have:
13166   //   trunc(binary-ops(zext(x), zext(y)))
13167   // or
13168   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
13169   // such that we're unnecessarily moving things into GPRs when it would be
13170   // better to keep them in CR bits.
13171 
13172   // Note that trunc here can be an actual i1 trunc, or can be the effective
13173   // truncation that comes from a setcc or select_cc.
13174   if (N->getOpcode() == ISD::TRUNCATE &&
13175       N->getValueType(0) != MVT::i1)
13176     return SDValue();
13177 
13178   if (N->getOperand(0).getValueType() != MVT::i32 &&
13179       N->getOperand(0).getValueType() != MVT::i64)
13180     return SDValue();
13181 
13182   if (N->getOpcode() == ISD::SETCC ||
13183       N->getOpcode() == ISD::SELECT_CC) {
13184     // If we're looking at a comparison, then we need to make sure that the
13185     // high bits (all except for the first) don't matter the result.
13186     ISD::CondCode CC =
13187       cast<CondCodeSDNode>(N->getOperand(
13188         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
13189     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
13190 
13191     if (ISD::isSignedIntSetCC(CC)) {
13192       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
13193           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
13194         return SDValue();
13195     } else if (ISD::isUnsignedIntSetCC(CC)) {
13196       if (!DAG.MaskedValueIsZero(N->getOperand(0),
13197                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
13198           !DAG.MaskedValueIsZero(N->getOperand(1),
13199                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
13200         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
13201                                              : SDValue());
13202     } else {
13203       // This is neither a signed nor an unsigned comparison, just make sure
13204       // that the high bits are equal.
13205       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
13206       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
13207 
13208       // We don't really care about what is known about the first bit (if
13209       // anything), so clear it in all masks prior to comparing them.
13210       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
13211       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
13212 
13213       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
13214         return SDValue();
13215     }
13216   }
13217 
13218   // We now know that the higher-order bits are irrelevant, we just need to
13219   // make sure that all of the intermediate operations are bit operations, and
13220   // all inputs are extensions.
13221   if (N->getOperand(0).getOpcode() != ISD::AND &&
13222       N->getOperand(0).getOpcode() != ISD::OR  &&
13223       N->getOperand(0).getOpcode() != ISD::XOR &&
13224       N->getOperand(0).getOpcode() != ISD::SELECT &&
13225       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
13226       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
13227       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
13228       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
13229       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
13230     return SDValue();
13231 
13232   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
13233       N->getOperand(1).getOpcode() != ISD::AND &&
13234       N->getOperand(1).getOpcode() != ISD::OR  &&
13235       N->getOperand(1).getOpcode() != ISD::XOR &&
13236       N->getOperand(1).getOpcode() != ISD::SELECT &&
13237       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
13238       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
13239       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
13240       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
13241       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
13242     return SDValue();
13243 
13244   SmallVector<SDValue, 4> Inputs;
13245   SmallVector<SDValue, 8> BinOps, PromOps;
13246   SmallPtrSet<SDNode *, 16> Visited;
13247 
13248   for (unsigned i = 0; i < 2; ++i) {
13249     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13250           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13251           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13252           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13253         isa<ConstantSDNode>(N->getOperand(i)))
13254       Inputs.push_back(N->getOperand(i));
13255     else
13256       BinOps.push_back(N->getOperand(i));
13257 
13258     if (N->getOpcode() == ISD::TRUNCATE)
13259       break;
13260   }
13261 
13262   // Visit all inputs, collect all binary operations (and, or, xor and
13263   // select) that are all fed by extensions.
13264   while (!BinOps.empty()) {
13265     SDValue BinOp = BinOps.back();
13266     BinOps.pop_back();
13267 
13268     if (!Visited.insert(BinOp.getNode()).second)
13269       continue;
13270 
13271     PromOps.push_back(BinOp);
13272 
13273     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13274       // The condition of the select is not promoted.
13275       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13276         continue;
13277       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13278         continue;
13279 
13280       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13281             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13282             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13283            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13284           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13285         Inputs.push_back(BinOp.getOperand(i));
13286       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13287                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13288                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13289                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13290                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
13291                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13292                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13293                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13294                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
13295         BinOps.push_back(BinOp.getOperand(i));
13296       } else {
13297         // We have an input that is not an extension or another binary
13298         // operation; we'll abort this transformation.
13299         return SDValue();
13300       }
13301     }
13302   }
13303 
13304   // Make sure that this is a self-contained cluster of operations (which
13305   // is not quite the same thing as saying that everything has only one
13306   // use).
13307   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13308     if (isa<ConstantSDNode>(Inputs[i]))
13309       continue;
13310 
13311     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13312                               UE = Inputs[i].getNode()->use_end();
13313          UI != UE; ++UI) {
13314       SDNode *User = *UI;
13315       if (User != N && !Visited.count(User))
13316         return SDValue();
13317 
13318       // Make sure that we're not going to promote the non-output-value
13319       // operand(s) or SELECT or SELECT_CC.
13320       // FIXME: Although we could sometimes handle this, and it does occur in
13321       // practice that one of the condition inputs to the select is also one of
13322       // the outputs, we currently can't deal with this.
13323       if (User->getOpcode() == ISD::SELECT) {
13324         if (User->getOperand(0) == Inputs[i])
13325           return SDValue();
13326       } else if (User->getOpcode() == ISD::SELECT_CC) {
13327         if (User->getOperand(0) == Inputs[i] ||
13328             User->getOperand(1) == Inputs[i])
13329           return SDValue();
13330       }
13331     }
13332   }
13333 
13334   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13335     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13336                               UE = PromOps[i].getNode()->use_end();
13337          UI != UE; ++UI) {
13338       SDNode *User = *UI;
13339       if (User != N && !Visited.count(User))
13340         return SDValue();
13341 
13342       // Make sure that we're not going to promote the non-output-value
13343       // operand(s) or SELECT or SELECT_CC.
13344       // FIXME: Although we could sometimes handle this, and it does occur in
13345       // practice that one of the condition inputs to the select is also one of
13346       // the outputs, we currently can't deal with this.
13347       if (User->getOpcode() == ISD::SELECT) {
13348         if (User->getOperand(0) == PromOps[i])
13349           return SDValue();
13350       } else if (User->getOpcode() == ISD::SELECT_CC) {
13351         if (User->getOperand(0) == PromOps[i] ||
13352             User->getOperand(1) == PromOps[i])
13353           return SDValue();
13354       }
13355     }
13356   }
13357 
13358   // Replace all inputs with the extension operand.
13359   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13360     // Constants may have users outside the cluster of to-be-promoted nodes,
13361     // and so we need to replace those as we do the promotions.
13362     if (isa<ConstantSDNode>(Inputs[i]))
13363       continue;
13364     else
13365       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13366   }
13367 
13368   std::list<HandleSDNode> PromOpHandles;
13369   for (auto &PromOp : PromOps)
13370     PromOpHandles.emplace_back(PromOp);
13371 
13372   // Replace all operations (these are all the same, but have a different
13373   // (i1) return type). DAG.getNode will validate that the types of
13374   // a binary operator match, so go through the list in reverse so that
13375   // we've likely promoted both operands first. Any intermediate truncations or
13376   // extensions disappear.
13377   while (!PromOpHandles.empty()) {
13378     SDValue PromOp = PromOpHandles.back().getValue();
13379     PromOpHandles.pop_back();
13380 
13381     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13382         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13383         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13384         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13385       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13386           PromOp.getOperand(0).getValueType() != MVT::i1) {
13387         // The operand is not yet ready (see comment below).
13388         PromOpHandles.emplace_front(PromOp);
13389         continue;
13390       }
13391 
13392       SDValue RepValue = PromOp.getOperand(0);
13393       if (isa<ConstantSDNode>(RepValue))
13394         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13395 
13396       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13397       continue;
13398     }
13399 
13400     unsigned C;
13401     switch (PromOp.getOpcode()) {
13402     default:             C = 0; break;
13403     case ISD::SELECT:    C = 1; break;
13404     case ISD::SELECT_CC: C = 2; break;
13405     }
13406 
13407     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13408          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13409         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13410          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13411       // The to-be-promoted operands of this node have not yet been
13412       // promoted (this should be rare because we're going through the
13413       // list backward, but if one of the operands has several users in
13414       // this cluster of to-be-promoted nodes, it is possible).
13415       PromOpHandles.emplace_front(PromOp);
13416       continue;
13417     }
13418 
13419     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13420                                 PromOp.getNode()->op_end());
13421 
13422     // If there are any constant inputs, make sure they're replaced now.
13423     for (unsigned i = 0; i < 2; ++i)
13424       if (isa<ConstantSDNode>(Ops[C+i]))
13425         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13426 
13427     DAG.ReplaceAllUsesOfValueWith(PromOp,
13428       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13429   }
13430 
13431   // Now we're left with the initial truncation itself.
13432   if (N->getOpcode() == ISD::TRUNCATE)
13433     return N->getOperand(0);
13434 
13435   // Otherwise, this is a comparison. The operands to be compared have just
13436   // changed type (to i1), but everything else is the same.
13437   return SDValue(N, 0);
13438 }
13439 
13440 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13441                                                   DAGCombinerInfo &DCI) const {
13442   SelectionDAG &DAG = DCI.DAG;
13443   SDLoc dl(N);
13444 
13445   // If we're tracking CR bits, we need to be careful that we don't have:
13446   //   zext(binary-ops(trunc(x), trunc(y)))
13447   // or
13448   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13449   // such that we're unnecessarily moving things into CR bits that can more
13450   // efficiently stay in GPRs. Note that if we're not certain that the high
13451   // bits are set as required by the final extension, we still may need to do
13452   // some masking to get the proper behavior.
13453 
13454   // This same functionality is important on PPC64 when dealing with
13455   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13456   // the return values of functions. Because it is so similar, it is handled
13457   // here as well.
13458 
13459   if (N->getValueType(0) != MVT::i32 &&
13460       N->getValueType(0) != MVT::i64)
13461     return SDValue();
13462 
13463   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13464         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13465     return SDValue();
13466 
13467   if (N->getOperand(0).getOpcode() != ISD::AND &&
13468       N->getOperand(0).getOpcode() != ISD::OR  &&
13469       N->getOperand(0).getOpcode() != ISD::XOR &&
13470       N->getOperand(0).getOpcode() != ISD::SELECT &&
13471       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13472     return SDValue();
13473 
13474   SmallVector<SDValue, 4> Inputs;
13475   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13476   SmallPtrSet<SDNode *, 16> Visited;
13477 
13478   // Visit all inputs, collect all binary operations (and, or, xor and
13479   // select) that are all fed by truncations.
13480   while (!BinOps.empty()) {
13481     SDValue BinOp = BinOps.back();
13482     BinOps.pop_back();
13483 
13484     if (!Visited.insert(BinOp.getNode()).second)
13485       continue;
13486 
13487     PromOps.push_back(BinOp);
13488 
13489     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13490       // The condition of the select is not promoted.
13491       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13492         continue;
13493       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13494         continue;
13495 
13496       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13497           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13498         Inputs.push_back(BinOp.getOperand(i));
13499       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13500                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13501                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13502                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13503                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13504         BinOps.push_back(BinOp.getOperand(i));
13505       } else {
13506         // We have an input that is not a truncation or another binary
13507         // operation; we'll abort this transformation.
13508         return SDValue();
13509       }
13510     }
13511   }
13512 
13513   // The operands of a select that must be truncated when the select is
13514   // promoted because the operand is actually part of the to-be-promoted set.
13515   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13516 
13517   // Make sure that this is a self-contained cluster of operations (which
13518   // is not quite the same thing as saying that everything has only one
13519   // use).
13520   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13521     if (isa<ConstantSDNode>(Inputs[i]))
13522       continue;
13523 
13524     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13525                               UE = Inputs[i].getNode()->use_end();
13526          UI != UE; ++UI) {
13527       SDNode *User = *UI;
13528       if (User != N && !Visited.count(User))
13529         return SDValue();
13530 
13531       // If we're going to promote the non-output-value operand(s) or SELECT or
13532       // SELECT_CC, record them for truncation.
13533       if (User->getOpcode() == ISD::SELECT) {
13534         if (User->getOperand(0) == Inputs[i])
13535           SelectTruncOp[0].insert(std::make_pair(User,
13536                                     User->getOperand(0).getValueType()));
13537       } else if (User->getOpcode() == ISD::SELECT_CC) {
13538         if (User->getOperand(0) == Inputs[i])
13539           SelectTruncOp[0].insert(std::make_pair(User,
13540                                     User->getOperand(0).getValueType()));
13541         if (User->getOperand(1) == Inputs[i])
13542           SelectTruncOp[1].insert(std::make_pair(User,
13543                                     User->getOperand(1).getValueType()));
13544       }
13545     }
13546   }
13547 
13548   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13549     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13550                               UE = PromOps[i].getNode()->use_end();
13551          UI != UE; ++UI) {
13552       SDNode *User = *UI;
13553       if (User != N && !Visited.count(User))
13554         return SDValue();
13555 
13556       // If we're going to promote the non-output-value operand(s) or SELECT or
13557       // SELECT_CC, record them for truncation.
13558       if (User->getOpcode() == ISD::SELECT) {
13559         if (User->getOperand(0) == PromOps[i])
13560           SelectTruncOp[0].insert(std::make_pair(User,
13561                                     User->getOperand(0).getValueType()));
13562       } else if (User->getOpcode() == ISD::SELECT_CC) {
13563         if (User->getOperand(0) == PromOps[i])
13564           SelectTruncOp[0].insert(std::make_pair(User,
13565                                     User->getOperand(0).getValueType()));
13566         if (User->getOperand(1) == PromOps[i])
13567           SelectTruncOp[1].insert(std::make_pair(User,
13568                                     User->getOperand(1).getValueType()));
13569       }
13570     }
13571   }
13572 
13573   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13574   bool ReallyNeedsExt = false;
13575   if (N->getOpcode() != ISD::ANY_EXTEND) {
13576     // If all of the inputs are not already sign/zero extended, then
13577     // we'll still need to do that at the end.
13578     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13579       if (isa<ConstantSDNode>(Inputs[i]))
13580         continue;
13581 
13582       unsigned OpBits =
13583         Inputs[i].getOperand(0).getValueSizeInBits();
13584       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13585 
13586       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13587            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13588                                   APInt::getHighBitsSet(OpBits,
13589                                                         OpBits-PromBits))) ||
13590           (N->getOpcode() == ISD::SIGN_EXTEND &&
13591            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13592              (OpBits-(PromBits-1)))) {
13593         ReallyNeedsExt = true;
13594         break;
13595       }
13596     }
13597   }
13598 
13599   // Replace all inputs, either with the truncation operand, or a
13600   // truncation or extension to the final output type.
13601   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13602     // Constant inputs need to be replaced with the to-be-promoted nodes that
13603     // use them because they might have users outside of the cluster of
13604     // promoted nodes.
13605     if (isa<ConstantSDNode>(Inputs[i]))
13606       continue;
13607 
13608     SDValue InSrc = Inputs[i].getOperand(0);
13609     if (Inputs[i].getValueType() == N->getValueType(0))
13610       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13611     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13612       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13613         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13614     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13615       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13616         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13617     else
13618       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13619         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13620   }
13621 
13622   std::list<HandleSDNode> PromOpHandles;
13623   for (auto &PromOp : PromOps)
13624     PromOpHandles.emplace_back(PromOp);
13625 
13626   // Replace all operations (these are all the same, but have a different
13627   // (promoted) return type). DAG.getNode will validate that the types of
13628   // a binary operator match, so go through the list in reverse so that
13629   // we've likely promoted both operands first.
13630   while (!PromOpHandles.empty()) {
13631     SDValue PromOp = PromOpHandles.back().getValue();
13632     PromOpHandles.pop_back();
13633 
13634     unsigned C;
13635     switch (PromOp.getOpcode()) {
13636     default:             C = 0; break;
13637     case ISD::SELECT:    C = 1; break;
13638     case ISD::SELECT_CC: C = 2; break;
13639     }
13640 
13641     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13642          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13643         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13644          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13645       // The to-be-promoted operands of this node have not yet been
13646       // promoted (this should be rare because we're going through the
13647       // list backward, but if one of the operands has several users in
13648       // this cluster of to-be-promoted nodes, it is possible).
13649       PromOpHandles.emplace_front(PromOp);
13650       continue;
13651     }
13652 
13653     // For SELECT and SELECT_CC nodes, we do a similar check for any
13654     // to-be-promoted comparison inputs.
13655     if (PromOp.getOpcode() == ISD::SELECT ||
13656         PromOp.getOpcode() == ISD::SELECT_CC) {
13657       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13658            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13659           (SelectTruncOp[1].count(PromOp.getNode()) &&
13660            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13661         PromOpHandles.emplace_front(PromOp);
13662         continue;
13663       }
13664     }
13665 
13666     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13667                                 PromOp.getNode()->op_end());
13668 
13669     // If this node has constant inputs, then they'll need to be promoted here.
13670     for (unsigned i = 0; i < 2; ++i) {
13671       if (!isa<ConstantSDNode>(Ops[C+i]))
13672         continue;
13673       if (Ops[C+i].getValueType() == N->getValueType(0))
13674         continue;
13675 
13676       if (N->getOpcode() == ISD::SIGN_EXTEND)
13677         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13678       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13679         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13680       else
13681         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13682     }
13683 
13684     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13685     // truncate them again to the original value type.
13686     if (PromOp.getOpcode() == ISD::SELECT ||
13687         PromOp.getOpcode() == ISD::SELECT_CC) {
13688       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13689       if (SI0 != SelectTruncOp[0].end())
13690         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13691       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13692       if (SI1 != SelectTruncOp[1].end())
13693         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13694     }
13695 
13696     DAG.ReplaceAllUsesOfValueWith(PromOp,
13697       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13698   }
13699 
13700   // Now we're left with the initial extension itself.
13701   if (!ReallyNeedsExt)
13702     return N->getOperand(0);
13703 
13704   // To zero extend, just mask off everything except for the first bit (in the
13705   // i1 case).
13706   if (N->getOpcode() == ISD::ZERO_EXTEND)
13707     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13708                        DAG.getConstant(APInt::getLowBitsSet(
13709                                          N->getValueSizeInBits(0), PromBits),
13710                                        dl, N->getValueType(0)));
13711 
13712   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13713          "Invalid extension type");
13714   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13715   SDValue ShiftCst =
13716       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13717   return DAG.getNode(
13718       ISD::SRA, dl, N->getValueType(0),
13719       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13720       ShiftCst);
13721 }
13722 
13723 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13724                                         DAGCombinerInfo &DCI) const {
13725   assert(N->getOpcode() == ISD::SETCC &&
13726          "Should be called with a SETCC node");
13727 
13728   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13729   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13730     SDValue LHS = N->getOperand(0);
13731     SDValue RHS = N->getOperand(1);
13732 
13733     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13734     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13735         LHS.hasOneUse())
13736       std::swap(LHS, RHS);
13737 
13738     // x == 0-y --> x+y == 0
13739     // x != 0-y --> x+y != 0
13740     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13741         RHS.hasOneUse()) {
13742       SDLoc DL(N);
13743       SelectionDAG &DAG = DCI.DAG;
13744       EVT VT = N->getValueType(0);
13745       EVT OpVT = LHS.getValueType();
13746       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13747       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13748     }
13749   }
13750 
13751   return DAGCombineTruncBoolExt(N, DCI);
13752 }
13753 
13754 // Is this an extending load from an f32 to an f64?
13755 static bool isFPExtLoad(SDValue Op) {
13756   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13757     return LD->getExtensionType() == ISD::EXTLOAD &&
13758       Op.getValueType() == MVT::f64;
13759   return false;
13760 }
13761 
13762 /// Reduces the number of fp-to-int conversion when building a vector.
13763 ///
13764 /// If this vector is built out of floating to integer conversions,
13765 /// transform it to a vector built out of floating point values followed by a
13766 /// single floating to integer conversion of the vector.
13767 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13768 /// becomes (fptosi (build_vector ($A, $B, ...)))
13769 SDValue PPCTargetLowering::
13770 combineElementTruncationToVectorTruncation(SDNode *N,
13771                                            DAGCombinerInfo &DCI) const {
13772   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13773          "Should be called with a BUILD_VECTOR node");
13774 
13775   SelectionDAG &DAG = DCI.DAG;
13776   SDLoc dl(N);
13777 
13778   SDValue FirstInput = N->getOperand(0);
13779   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13780          "The input operand must be an fp-to-int conversion.");
13781 
13782   // This combine happens after legalization so the fp_to_[su]i nodes are
13783   // already converted to PPCSISD nodes.
13784   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13785   if (FirstConversion == PPCISD::FCTIDZ ||
13786       FirstConversion == PPCISD::FCTIDUZ ||
13787       FirstConversion == PPCISD::FCTIWZ ||
13788       FirstConversion == PPCISD::FCTIWUZ) {
13789     bool IsSplat = true;
13790     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13791       FirstConversion == PPCISD::FCTIWUZ;
13792     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13793     SmallVector<SDValue, 4> Ops;
13794     EVT TargetVT = N->getValueType(0);
13795     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13796       SDValue NextOp = N->getOperand(i);
13797       if (NextOp.getOpcode() != PPCISD::MFVSR)
13798         return SDValue();
13799       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13800       if (NextConversion != FirstConversion)
13801         return SDValue();
13802       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13803       // This is not valid if the input was originally double precision. It is
13804       // also not profitable to do unless this is an extending load in which
13805       // case doing this combine will allow us to combine consecutive loads.
13806       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13807         return SDValue();
13808       if (N->getOperand(i) != FirstInput)
13809         IsSplat = false;
13810     }
13811 
13812     // If this is a splat, we leave it as-is since there will be only a single
13813     // fp-to-int conversion followed by a splat of the integer. This is better
13814     // for 32-bit and smaller ints and neutral for 64-bit ints.
13815     if (IsSplat)
13816       return SDValue();
13817 
13818     // Now that we know we have the right type of node, get its operands
13819     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13820       SDValue In = N->getOperand(i).getOperand(0);
13821       if (Is32Bit) {
13822         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13823         // here, we know that all inputs are extending loads so this is safe).
13824         if (In.isUndef())
13825           Ops.push_back(DAG.getUNDEF(SrcVT));
13826         else {
13827           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13828                                       MVT::f32, In.getOperand(0),
13829                                       DAG.getIntPtrConstant(1, dl));
13830           Ops.push_back(Trunc);
13831         }
13832       } else
13833         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13834     }
13835 
13836     unsigned Opcode;
13837     if (FirstConversion == PPCISD::FCTIDZ ||
13838         FirstConversion == PPCISD::FCTIWZ)
13839       Opcode = ISD::FP_TO_SINT;
13840     else
13841       Opcode = ISD::FP_TO_UINT;
13842 
13843     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13844     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13845     return DAG.getNode(Opcode, dl, TargetVT, BV);
13846   }
13847   return SDValue();
13848 }
13849 
13850 /// Reduce the number of loads when building a vector.
13851 ///
13852 /// Building a vector out of multiple loads can be converted to a load
13853 /// of the vector type if the loads are consecutive. If the loads are
13854 /// consecutive but in descending order, a shuffle is added at the end
13855 /// to reorder the vector.
13856 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13857   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13858          "Should be called with a BUILD_VECTOR node");
13859 
13860   SDLoc dl(N);
13861 
13862   // Return early for non byte-sized type, as they can't be consecutive.
13863   if (!N->getValueType(0).getVectorElementType().isByteSized())
13864     return SDValue();
13865 
13866   bool InputsAreConsecutiveLoads = true;
13867   bool InputsAreReverseConsecutive = true;
13868   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13869   SDValue FirstInput = N->getOperand(0);
13870   bool IsRoundOfExtLoad = false;
13871 
13872   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13873       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13874     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13875     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13876   }
13877   // Not a build vector of (possibly fp_rounded) loads.
13878   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13879       N->getNumOperands() == 1)
13880     return SDValue();
13881 
13882   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13883     // If any inputs are fp_round(extload), they all must be.
13884     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13885       return SDValue();
13886 
13887     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13888       N->getOperand(i);
13889     if (NextInput.getOpcode() != ISD::LOAD)
13890       return SDValue();
13891 
13892     SDValue PreviousInput =
13893       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13894     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13895     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13896 
13897     // If any inputs are fp_round(extload), they all must be.
13898     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13899       return SDValue();
13900 
13901     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13902       InputsAreConsecutiveLoads = false;
13903     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13904       InputsAreReverseConsecutive = false;
13905 
13906     // Exit early if the loads are neither consecutive nor reverse consecutive.
13907     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13908       return SDValue();
13909   }
13910 
13911   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13912          "The loads cannot be both consecutive and reverse consecutive.");
13913 
13914   SDValue FirstLoadOp =
13915     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13916   SDValue LastLoadOp =
13917     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13918                        N->getOperand(N->getNumOperands()-1);
13919 
13920   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13921   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13922   if (InputsAreConsecutiveLoads) {
13923     assert(LD1 && "Input needs to be a LoadSDNode.");
13924     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13925                        LD1->getBasePtr(), LD1->getPointerInfo(),
13926                        LD1->getAlignment());
13927   }
13928   if (InputsAreReverseConsecutive) {
13929     assert(LDL && "Input needs to be a LoadSDNode.");
13930     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13931                                LDL->getBasePtr(), LDL->getPointerInfo(),
13932                                LDL->getAlignment());
13933     SmallVector<int, 16> Ops;
13934     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13935       Ops.push_back(i);
13936 
13937     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13938                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13939   }
13940   return SDValue();
13941 }
13942 
13943 // This function adds the required vector_shuffle needed to get
13944 // the elements of the vector extract in the correct position
13945 // as specified by the CorrectElems encoding.
13946 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13947                                       SDValue Input, uint64_t Elems,
13948                                       uint64_t CorrectElems) {
13949   SDLoc dl(N);
13950 
13951   unsigned NumElems = Input.getValueType().getVectorNumElements();
13952   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13953 
13954   // Knowing the element indices being extracted from the original
13955   // vector and the order in which they're being inserted, just put
13956   // them at element indices required for the instruction.
13957   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13958     if (DAG.getDataLayout().isLittleEndian())
13959       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13960     else
13961       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13962     CorrectElems = CorrectElems >> 8;
13963     Elems = Elems >> 8;
13964   }
13965 
13966   SDValue Shuffle =
13967       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13968                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13969 
13970   EVT VT = N->getValueType(0);
13971   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13972 
13973   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13974                                Input.getValueType().getVectorElementType(),
13975                                VT.getVectorNumElements());
13976   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13977                      DAG.getValueType(ExtVT));
13978 }
13979 
13980 // Look for build vector patterns where input operands come from sign
13981 // extended vector_extract elements of specific indices. If the correct indices
13982 // aren't used, add a vector shuffle to fix up the indices and create
13983 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13984 // during instruction selection.
13985 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13986   // This array encodes the indices that the vector sign extend instructions
13987   // extract from when extending from one type to another for both BE and LE.
13988   // The right nibble of each byte corresponds to the LE incides.
13989   // and the left nibble of each byte corresponds to the BE incides.
13990   // For example: 0x3074B8FC  byte->word
13991   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13992   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13993   // For example: 0x000070F8  byte->double word
13994   // For LE: the allowed indices are: 0x0,0x8
13995   // For BE: the allowed indices are: 0x7,0xF
13996   uint64_t TargetElems[] = {
13997       0x3074B8FC, // b->w
13998       0x000070F8, // b->d
13999       0x10325476, // h->w
14000       0x00003074, // h->d
14001       0x00001032, // w->d
14002   };
14003 
14004   uint64_t Elems = 0;
14005   int Index;
14006   SDValue Input;
14007 
14008   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
14009     if (!Op)
14010       return false;
14011     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
14012         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
14013       return false;
14014 
14015     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
14016     // of the right width.
14017     SDValue Extract = Op.getOperand(0);
14018     if (Extract.getOpcode() == ISD::ANY_EXTEND)
14019       Extract = Extract.getOperand(0);
14020     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14021       return false;
14022 
14023     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
14024     if (!ExtOp)
14025       return false;
14026 
14027     Index = ExtOp->getZExtValue();
14028     if (Input && Input != Extract.getOperand(0))
14029       return false;
14030 
14031     if (!Input)
14032       Input = Extract.getOperand(0);
14033 
14034     Elems = Elems << 8;
14035     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
14036     Elems |= Index;
14037 
14038     return true;
14039   };
14040 
14041   // If the build vector operands aren't sign extended vector extracts,
14042   // of the same input vector, then return.
14043   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14044     if (!isSExtOfVecExtract(N->getOperand(i))) {
14045       return SDValue();
14046     }
14047   }
14048 
14049   // If the vector extract indicies are not correct, add the appropriate
14050   // vector_shuffle.
14051   int TgtElemArrayIdx;
14052   int InputSize = Input.getValueType().getScalarSizeInBits();
14053   int OutputSize = N->getValueType(0).getScalarSizeInBits();
14054   if (InputSize + OutputSize == 40)
14055     TgtElemArrayIdx = 0;
14056   else if (InputSize + OutputSize == 72)
14057     TgtElemArrayIdx = 1;
14058   else if (InputSize + OutputSize == 48)
14059     TgtElemArrayIdx = 2;
14060   else if (InputSize + OutputSize == 80)
14061     TgtElemArrayIdx = 3;
14062   else if (InputSize + OutputSize == 96)
14063     TgtElemArrayIdx = 4;
14064   else
14065     return SDValue();
14066 
14067   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
14068   CorrectElems = DAG.getDataLayout().isLittleEndian()
14069                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
14070                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
14071   if (Elems != CorrectElems) {
14072     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
14073   }
14074 
14075   // Regular lowering will catch cases where a shuffle is not needed.
14076   return SDValue();
14077 }
14078 
14079 // Look for the pattern of a load from a narrow width to i128, feeding
14080 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
14081 // (LXVRZX). This node represents a zero extending load that will be matched
14082 // to the Load VSX Vector Rightmost instructions.
14083 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
14084   SDLoc DL(N);
14085 
14086   // This combine is only eligible for a BUILD_VECTOR of v1i128.
14087   if (N->getValueType(0) != MVT::v1i128)
14088     return SDValue();
14089 
14090   SDValue Operand = N->getOperand(0);
14091   // Proceed with the transformation if the operand to the BUILD_VECTOR
14092   // is a load instruction.
14093   if (Operand.getOpcode() != ISD::LOAD)
14094     return SDValue();
14095 
14096   LoadSDNode *LD = dyn_cast<LoadSDNode>(Operand);
14097   EVT MemoryType = LD->getMemoryVT();
14098 
14099   // This transformation is only valid if the we are loading either a byte,
14100   // halfword, word, or doubleword.
14101   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
14102                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
14103 
14104   // Ensure that the load from the narrow width is being zero extended to i128.
14105   if (!ValidLDType ||
14106       (LD->getExtensionType() != ISD::ZEXTLOAD &&
14107        LD->getExtensionType() != ISD::EXTLOAD))
14108     return SDValue();
14109 
14110   SDValue LoadOps[] = {
14111       LD->getChain(), LD->getBasePtr(),
14112       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
14113 
14114   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
14115                                  DAG.getVTList(MVT::v1i128, MVT::Other),
14116                                  LoadOps, MemoryType, LD->getMemOperand());
14117 }
14118 
14119 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
14120                                                  DAGCombinerInfo &DCI) const {
14121   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14122          "Should be called with a BUILD_VECTOR node");
14123 
14124   SelectionDAG &DAG = DCI.DAG;
14125   SDLoc dl(N);
14126 
14127   if (!Subtarget.hasVSX())
14128     return SDValue();
14129 
14130   // The target independent DAG combiner will leave a build_vector of
14131   // float-to-int conversions intact. We can generate MUCH better code for
14132   // a float-to-int conversion of a vector of floats.
14133   SDValue FirstInput = N->getOperand(0);
14134   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
14135     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
14136     if (Reduced)
14137       return Reduced;
14138   }
14139 
14140   // If we're building a vector out of consecutive loads, just load that
14141   // vector type.
14142   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
14143   if (Reduced)
14144     return Reduced;
14145 
14146   // If we're building a vector out of extended elements from another vector
14147   // we have P9 vector integer extend instructions. The code assumes legal
14148   // input types (i.e. it can't handle things like v4i16) so do not run before
14149   // legalization.
14150   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
14151     Reduced = combineBVOfVecSExt(N, DAG);
14152     if (Reduced)
14153       return Reduced;
14154   }
14155 
14156   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
14157   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
14158   // is a load from <valid narrow width> to i128.
14159   if (Subtarget.isISA3_1()) {
14160     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
14161     if (BVOfZLoad)
14162       return BVOfZLoad;
14163   }
14164 
14165   if (N->getValueType(0) != MVT::v2f64)
14166     return SDValue();
14167 
14168   // Looking for:
14169   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
14170   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
14171       FirstInput.getOpcode() != ISD::UINT_TO_FP)
14172     return SDValue();
14173   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
14174       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
14175     return SDValue();
14176   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
14177     return SDValue();
14178 
14179   SDValue Ext1 = FirstInput.getOperand(0);
14180   SDValue Ext2 = N->getOperand(1).getOperand(0);
14181   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14182      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14183     return SDValue();
14184 
14185   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
14186   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
14187   if (!Ext1Op || !Ext2Op)
14188     return SDValue();
14189   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
14190       Ext1.getOperand(0) != Ext2.getOperand(0))
14191     return SDValue();
14192 
14193   int FirstElem = Ext1Op->getZExtValue();
14194   int SecondElem = Ext2Op->getZExtValue();
14195   int SubvecIdx;
14196   if (FirstElem == 0 && SecondElem == 1)
14197     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
14198   else if (FirstElem == 2 && SecondElem == 3)
14199     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
14200   else
14201     return SDValue();
14202 
14203   SDValue SrcVec = Ext1.getOperand(0);
14204   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
14205     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
14206   return DAG.getNode(NodeType, dl, MVT::v2f64,
14207                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
14208 }
14209 
14210 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
14211                                               DAGCombinerInfo &DCI) const {
14212   assert((N->getOpcode() == ISD::SINT_TO_FP ||
14213           N->getOpcode() == ISD::UINT_TO_FP) &&
14214          "Need an int -> FP conversion node here");
14215 
14216   if (useSoftFloat() || !Subtarget.has64BitSupport())
14217     return SDValue();
14218 
14219   SelectionDAG &DAG = DCI.DAG;
14220   SDLoc dl(N);
14221   SDValue Op(N, 0);
14222 
14223   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
14224   // from the hardware.
14225   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
14226     return SDValue();
14227   if (!Op.getOperand(0).getValueType().isSimple())
14228     return SDValue();
14229   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
14230       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
14231     return SDValue();
14232 
14233   SDValue FirstOperand(Op.getOperand(0));
14234   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
14235     (FirstOperand.getValueType() == MVT::i8 ||
14236      FirstOperand.getValueType() == MVT::i16);
14237   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
14238     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
14239     bool DstDouble = Op.getValueType() == MVT::f64;
14240     unsigned ConvOp = Signed ?
14241       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
14242       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
14243     SDValue WidthConst =
14244       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
14245                             dl, false);
14246     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
14247     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
14248     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
14249                                          DAG.getVTList(MVT::f64, MVT::Other),
14250                                          Ops, MVT::i8, LDN->getMemOperand());
14251 
14252     // For signed conversion, we need to sign-extend the value in the VSR
14253     if (Signed) {
14254       SDValue ExtOps[] = { Ld, WidthConst };
14255       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
14256       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
14257     } else
14258       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
14259   }
14260 
14261 
14262   // For i32 intermediate values, unfortunately, the conversion functions
14263   // leave the upper 32 bits of the value are undefined. Within the set of
14264   // scalar instructions, we have no method for zero- or sign-extending the
14265   // value. Thus, we cannot handle i32 intermediate values here.
14266   if (Op.getOperand(0).getValueType() == MVT::i32)
14267     return SDValue();
14268 
14269   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
14270          "UINT_TO_FP is supported only with FPCVT");
14271 
14272   // If we have FCFIDS, then use it when converting to single-precision.
14273   // Otherwise, convert to double-precision and then round.
14274   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14275                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
14276                                                             : PPCISD::FCFIDS)
14277                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
14278                                                             : PPCISD::FCFID);
14279   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14280                   ? MVT::f32
14281                   : MVT::f64;
14282 
14283   // If we're converting from a float, to an int, and back to a float again,
14284   // then we don't need the store/load pair at all.
14285   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
14286        Subtarget.hasFPCVT()) ||
14287       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
14288     SDValue Src = Op.getOperand(0).getOperand(0);
14289     if (Src.getValueType() == MVT::f32) {
14290       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
14291       DCI.AddToWorklist(Src.getNode());
14292     } else if (Src.getValueType() != MVT::f64) {
14293       // Make sure that we don't pick up a ppc_fp128 source value.
14294       return SDValue();
14295     }
14296 
14297     unsigned FCTOp =
14298       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
14299                                                         PPCISD::FCTIDUZ;
14300 
14301     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
14302     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
14303 
14304     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
14305       FP = DAG.getNode(ISD::FP_ROUND, dl,
14306                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
14307       DCI.AddToWorklist(FP.getNode());
14308     }
14309 
14310     return FP;
14311   }
14312 
14313   return SDValue();
14314 }
14315 
14316 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
14317 // builtins) into loads with swaps.
14318 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
14319                                               DAGCombinerInfo &DCI) const {
14320   SelectionDAG &DAG = DCI.DAG;
14321   SDLoc dl(N);
14322   SDValue Chain;
14323   SDValue Base;
14324   MachineMemOperand *MMO;
14325 
14326   switch (N->getOpcode()) {
14327   default:
14328     llvm_unreachable("Unexpected opcode for little endian VSX load");
14329   case ISD::LOAD: {
14330     LoadSDNode *LD = cast<LoadSDNode>(N);
14331     Chain = LD->getChain();
14332     Base = LD->getBasePtr();
14333     MMO = LD->getMemOperand();
14334     // If the MMO suggests this isn't a load of a full vector, leave
14335     // things alone.  For a built-in, we have to make the change for
14336     // correctness, so if there is a size problem that will be a bug.
14337     if (MMO->getSize() < 16)
14338       return SDValue();
14339     break;
14340   }
14341   case ISD::INTRINSIC_W_CHAIN: {
14342     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14343     Chain = Intrin->getChain();
14344     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
14345     // us what we want. Get operand 2 instead.
14346     Base = Intrin->getOperand(2);
14347     MMO = Intrin->getMemOperand();
14348     break;
14349   }
14350   }
14351 
14352   MVT VecTy = N->getValueType(0).getSimpleVT();
14353 
14354   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
14355   // aligned and the type is a vector with elements up to 4 bytes
14356   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14357       VecTy.getScalarSizeInBits() <= 32) {
14358     return SDValue();
14359   }
14360 
14361   SDValue LoadOps[] = { Chain, Base };
14362   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14363                                          DAG.getVTList(MVT::v2f64, MVT::Other),
14364                                          LoadOps, MVT::v2f64, MMO);
14365 
14366   DCI.AddToWorklist(Load.getNode());
14367   Chain = Load.getValue(1);
14368   SDValue Swap = DAG.getNode(
14369       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14370   DCI.AddToWorklist(Swap.getNode());
14371 
14372   // Add a bitcast if the resulting load type doesn't match v2f64.
14373   if (VecTy != MVT::v2f64) {
14374     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14375     DCI.AddToWorklist(N.getNode());
14376     // Package {bitcast value, swap's chain} to match Load's shape.
14377     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14378                        N, Swap.getValue(1));
14379   }
14380 
14381   return Swap;
14382 }
14383 
14384 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14385 // builtins) into stores with swaps.
14386 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14387                                                DAGCombinerInfo &DCI) const {
14388   SelectionDAG &DAG = DCI.DAG;
14389   SDLoc dl(N);
14390   SDValue Chain;
14391   SDValue Base;
14392   unsigned SrcOpnd;
14393   MachineMemOperand *MMO;
14394 
14395   switch (N->getOpcode()) {
14396   default:
14397     llvm_unreachable("Unexpected opcode for little endian VSX store");
14398   case ISD::STORE: {
14399     StoreSDNode *ST = cast<StoreSDNode>(N);
14400     Chain = ST->getChain();
14401     Base = ST->getBasePtr();
14402     MMO = ST->getMemOperand();
14403     SrcOpnd = 1;
14404     // If the MMO suggests this isn't a store of a full vector, leave
14405     // things alone.  For a built-in, we have to make the change for
14406     // correctness, so if there is a size problem that will be a bug.
14407     if (MMO->getSize() < 16)
14408       return SDValue();
14409     break;
14410   }
14411   case ISD::INTRINSIC_VOID: {
14412     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14413     Chain = Intrin->getChain();
14414     // Intrin->getBasePtr() oddly does not get what we want.
14415     Base = Intrin->getOperand(3);
14416     MMO = Intrin->getMemOperand();
14417     SrcOpnd = 2;
14418     break;
14419   }
14420   }
14421 
14422   SDValue Src = N->getOperand(SrcOpnd);
14423   MVT VecTy = Src.getValueType().getSimpleVT();
14424 
14425   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14426   // aligned and the type is a vector with elements up to 4 bytes
14427   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14428       VecTy.getScalarSizeInBits() <= 32) {
14429     return SDValue();
14430   }
14431 
14432   // All stores are done as v2f64 and possible bit cast.
14433   if (VecTy != MVT::v2f64) {
14434     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14435     DCI.AddToWorklist(Src.getNode());
14436   }
14437 
14438   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14439                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14440   DCI.AddToWorklist(Swap.getNode());
14441   Chain = Swap.getValue(1);
14442   SDValue StoreOps[] = { Chain, Swap, Base };
14443   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14444                                           DAG.getVTList(MVT::Other),
14445                                           StoreOps, VecTy, MMO);
14446   DCI.AddToWorklist(Store.getNode());
14447   return Store;
14448 }
14449 
14450 // Handle DAG combine for STORE (FP_TO_INT F).
14451 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14452                                                DAGCombinerInfo &DCI) const {
14453 
14454   SelectionDAG &DAG = DCI.DAG;
14455   SDLoc dl(N);
14456   unsigned Opcode = N->getOperand(1).getOpcode();
14457 
14458   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14459          && "Not a FP_TO_INT Instruction!");
14460 
14461   SDValue Val = N->getOperand(1).getOperand(0);
14462   EVT Op1VT = N->getOperand(1).getValueType();
14463   EVT ResVT = Val.getValueType();
14464 
14465   if (!isTypeLegal(ResVT))
14466     return SDValue();
14467 
14468   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14469   bool ValidTypeForStoreFltAsInt =
14470         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14471          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14472 
14473   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14474       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14475     return SDValue();
14476 
14477   // Extend f32 values to f64
14478   if (ResVT.getScalarSizeInBits() == 32) {
14479     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14480     DCI.AddToWorklist(Val.getNode());
14481   }
14482 
14483   // Set signed or unsigned conversion opcode.
14484   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14485                           PPCISD::FP_TO_SINT_IN_VSR :
14486                           PPCISD::FP_TO_UINT_IN_VSR;
14487 
14488   Val = DAG.getNode(ConvOpcode,
14489                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14490   DCI.AddToWorklist(Val.getNode());
14491 
14492   // Set number of bytes being converted.
14493   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14494   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14495                     DAG.getIntPtrConstant(ByteSize, dl, false),
14496                     DAG.getValueType(Op1VT) };
14497 
14498   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14499           DAG.getVTList(MVT::Other), Ops,
14500           cast<StoreSDNode>(N)->getMemoryVT(),
14501           cast<StoreSDNode>(N)->getMemOperand());
14502 
14503   DCI.AddToWorklist(Val.getNode());
14504   return Val;
14505 }
14506 
14507 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14508   // Check that the source of the element keeps flipping
14509   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14510   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14511   for (int i = 1, e = Mask.size(); i < e; i++) {
14512     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14513       return false;
14514     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14515       return false;
14516     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14517   }
14518   return true;
14519 }
14520 
14521 static bool isSplatBV(SDValue Op) {
14522   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14523     return false;
14524   SDValue FirstOp;
14525 
14526   // Find first non-undef input.
14527   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14528     FirstOp = Op.getOperand(i);
14529     if (!FirstOp.isUndef())
14530       break;
14531   }
14532 
14533   // All inputs are undef or the same as the first non-undef input.
14534   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14535     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14536       return false;
14537   return true;
14538 }
14539 
14540 static SDValue isScalarToVec(SDValue Op) {
14541   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14542     return Op;
14543   if (Op.getOpcode() != ISD::BITCAST)
14544     return SDValue();
14545   Op = Op.getOperand(0);
14546   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14547     return Op;
14548   return SDValue();
14549 }
14550 
14551 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14552                                             int LHSMaxIdx, int RHSMinIdx,
14553                                             int RHSMaxIdx, int HalfVec) {
14554   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14555     int Idx = ShuffV[i];
14556     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14557       ShuffV[i] += HalfVec;
14558   }
14559   return;
14560 }
14561 
14562 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14563 // the original is:
14564 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14565 // In such a case, just change the shuffle mask to extract the element
14566 // from the permuted index.
14567 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) {
14568   SDLoc dl(OrigSToV);
14569   EVT VT = OrigSToV.getValueType();
14570   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14571          "Expecting a SCALAR_TO_VECTOR here");
14572   SDValue Input = OrigSToV.getOperand(0);
14573 
14574   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14575     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14576     SDValue OrigVector = Input.getOperand(0);
14577 
14578     // Can't handle non-const element indices or different vector types
14579     // for the input to the extract and the output of the scalar_to_vector.
14580     if (Idx && VT == OrigVector.getValueType()) {
14581       SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1);
14582       NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue();
14583       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14584     }
14585   }
14586   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14587                      OrigSToV.getOperand(0));
14588 }
14589 
14590 // On little endian subtargets, combine shuffles such as:
14591 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14592 // into:
14593 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14594 // because the latter can be matched to a single instruction merge.
14595 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14596 // to put the value into element zero. Adjust the shuffle mask so that the
14597 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14598 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14599                                                 SelectionDAG &DAG) const {
14600   SDValue LHS = SVN->getOperand(0);
14601   SDValue RHS = SVN->getOperand(1);
14602   auto Mask = SVN->getMask();
14603   int NumElts = LHS.getValueType().getVectorNumElements();
14604   SDValue Res(SVN, 0);
14605   SDLoc dl(SVN);
14606 
14607   // None of these combines are useful on big endian systems since the ISA
14608   // already has a big endian bias.
14609   if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14610     return Res;
14611 
14612   // If this is not a shuffle of a shuffle and the first element comes from
14613   // the second vector, canonicalize to the commuted form. This will make it
14614   // more likely to match one of the single instruction patterns.
14615   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14616       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14617     std::swap(LHS, RHS);
14618     Res = DAG.getCommutedVectorShuffle(*SVN);
14619     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14620   }
14621 
14622   // Adjust the shuffle mask if either input vector comes from a
14623   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14624   // form (to prevent the need for a swap).
14625   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14626   SDValue SToVLHS = isScalarToVec(LHS);
14627   SDValue SToVRHS = isScalarToVec(RHS);
14628   if (SToVLHS || SToVRHS) {
14629     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14630                             : SToVRHS.getValueType().getVectorNumElements();
14631     int NumEltsOut = ShuffV.size();
14632 
14633     // Initially assume that neither input is permuted. These will be adjusted
14634     // accordingly if either input is.
14635     int LHSMaxIdx = -1;
14636     int RHSMinIdx = -1;
14637     int RHSMaxIdx = -1;
14638     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14639 
14640     // Get the permuted scalar to vector nodes for the source(s) that come from
14641     // ISD::SCALAR_TO_VECTOR.
14642     if (SToVLHS) {
14643       // Set up the values for the shuffle vector fixup.
14644       LHSMaxIdx = NumEltsOut / NumEltsIn;
14645       SToVLHS = getSToVPermuted(SToVLHS, DAG);
14646       if (SToVLHS.getValueType() != LHS.getValueType())
14647         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14648       LHS = SToVLHS;
14649     }
14650     if (SToVRHS) {
14651       RHSMinIdx = NumEltsOut;
14652       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14653       SToVRHS = getSToVPermuted(SToVRHS, DAG);
14654       if (SToVRHS.getValueType() != RHS.getValueType())
14655         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14656       RHS = SToVRHS;
14657     }
14658 
14659     // Fix up the shuffle mask to reflect where the desired element actually is.
14660     // The minimum and maximum indices that correspond to element zero for both
14661     // the LHS and RHS are computed and will control which shuffle mask entries
14662     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14663     // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by
14664     // HalfVec to refer to the corresponding element in the permuted vector.
14665     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14666                                     HalfVec);
14667     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14668 
14669     // We may have simplified away the shuffle. We won't be able to do anything
14670     // further with it here.
14671     if (!isa<ShuffleVectorSDNode>(Res))
14672       return Res;
14673     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14674   }
14675 
14676   // The common case after we commuted the shuffle is that the RHS is a splat
14677   // and we have elements coming in from the splat at indices that are not
14678   // conducive to using a merge.
14679   // Example:
14680   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14681   if (!isSplatBV(RHS))
14682     return Res;
14683 
14684   // We are looking for a mask such that all even elements are from
14685   // one vector and all odd elements from the other.
14686   if (!isAlternatingShuffMask(Mask, NumElts))
14687     return Res;
14688 
14689   // Adjust the mask so we are pulling in the same index from the splat
14690   // as the index from the interesting vector in consecutive elements.
14691   // Example (even elements from first vector):
14692   // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14693   if (Mask[0] < NumElts)
14694     for (int i = 1, e = Mask.size(); i < e; i += 2)
14695       ShuffV[i] = (ShuffV[i - 1] + NumElts);
14696   // Example (odd elements from first vector):
14697   // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14698   else
14699     for (int i = 0, e = Mask.size(); i < e; i += 2)
14700       ShuffV[i] = (ShuffV[i + 1] + NumElts);
14701 
14702   // If the RHS has undefs, we need to remove them since we may have created
14703   // a shuffle that adds those instead of the splat value.
14704   SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue();
14705   RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal);
14706 
14707   Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14708   return Res;
14709 }
14710 
14711 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14712                                                 LSBaseSDNode *LSBase,
14713                                                 DAGCombinerInfo &DCI) const {
14714   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14715         "Not a reverse memop pattern!");
14716 
14717   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14718     auto Mask = SVN->getMask();
14719     int i = 0;
14720     auto I = Mask.rbegin();
14721     auto E = Mask.rend();
14722 
14723     for (; I != E; ++I) {
14724       if (*I != i)
14725         return false;
14726       i++;
14727     }
14728     return true;
14729   };
14730 
14731   SelectionDAG &DAG = DCI.DAG;
14732   EVT VT = SVN->getValueType(0);
14733 
14734   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14735     return SDValue();
14736 
14737   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14738   // See comment in PPCVSXSwapRemoval.cpp.
14739   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14740   if (!Subtarget.hasP9Vector())
14741     return SDValue();
14742 
14743   if(!IsElementReverse(SVN))
14744     return SDValue();
14745 
14746   if (LSBase->getOpcode() == ISD::LOAD) {
14747     SDLoc dl(SVN);
14748     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14749     return DAG.getMemIntrinsicNode(
14750         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14751         LSBase->getMemoryVT(), LSBase->getMemOperand());
14752   }
14753 
14754   if (LSBase->getOpcode() == ISD::STORE) {
14755     SDLoc dl(LSBase);
14756     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14757                           LSBase->getBasePtr()};
14758     return DAG.getMemIntrinsicNode(
14759         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14760         LSBase->getMemoryVT(), LSBase->getMemOperand());
14761   }
14762 
14763   llvm_unreachable("Expected a load or store node here");
14764 }
14765 
14766 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14767                                              DAGCombinerInfo &DCI) const {
14768   SelectionDAG &DAG = DCI.DAG;
14769   SDLoc dl(N);
14770   switch (N->getOpcode()) {
14771   default: break;
14772   case ISD::ADD:
14773     return combineADD(N, DCI);
14774   case ISD::SHL:
14775     return combineSHL(N, DCI);
14776   case ISD::SRA:
14777     return combineSRA(N, DCI);
14778   case ISD::SRL:
14779     return combineSRL(N, DCI);
14780   case ISD::MUL:
14781     return combineMUL(N, DCI);
14782   case ISD::FMA:
14783   case PPCISD::FNMSUB:
14784     return combineFMALike(N, DCI);
14785   case PPCISD::SHL:
14786     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14787         return N->getOperand(0);
14788     break;
14789   case PPCISD::SRL:
14790     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14791         return N->getOperand(0);
14792     break;
14793   case PPCISD::SRA:
14794     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14795       if (C->isNullValue() ||   //  0 >>s V -> 0.
14796           C->isAllOnesValue())    // -1 >>s V -> -1.
14797         return N->getOperand(0);
14798     }
14799     break;
14800   case ISD::SIGN_EXTEND:
14801   case ISD::ZERO_EXTEND:
14802   case ISD::ANY_EXTEND:
14803     return DAGCombineExtBoolTrunc(N, DCI);
14804   case ISD::TRUNCATE:
14805     return combineTRUNCATE(N, DCI);
14806   case ISD::SETCC:
14807     if (SDValue CSCC = combineSetCC(N, DCI))
14808       return CSCC;
14809     LLVM_FALLTHROUGH;
14810   case ISD::SELECT_CC:
14811     return DAGCombineTruncBoolExt(N, DCI);
14812   case ISD::SINT_TO_FP:
14813   case ISD::UINT_TO_FP:
14814     return combineFPToIntToFP(N, DCI);
14815   case ISD::VECTOR_SHUFFLE:
14816     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14817       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14818       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14819     }
14820     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14821   case ISD::STORE: {
14822 
14823     EVT Op1VT = N->getOperand(1).getValueType();
14824     unsigned Opcode = N->getOperand(1).getOpcode();
14825 
14826     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14827       SDValue Val= combineStoreFPToInt(N, DCI);
14828       if (Val)
14829         return Val;
14830     }
14831 
14832     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14833       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14834       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14835       if (Val)
14836         return Val;
14837     }
14838 
14839     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14840     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14841         N->getOperand(1).getNode()->hasOneUse() &&
14842         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14843          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14844 
14845       // STBRX can only handle simple types and it makes no sense to store less
14846       // two bytes in byte-reversed order.
14847       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14848       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14849         break;
14850 
14851       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14852       // Do an any-extend to 32-bits if this is a half-word input.
14853       if (BSwapOp.getValueType() == MVT::i16)
14854         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14855 
14856       // If the type of BSWAP operand is wider than stored memory width
14857       // it need to be shifted to the right side before STBRX.
14858       if (Op1VT.bitsGT(mVT)) {
14859         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14860         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14861                               DAG.getConstant(Shift, dl, MVT::i32));
14862         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14863         if (Op1VT == MVT::i64)
14864           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14865       }
14866 
14867       SDValue Ops[] = {
14868         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14869       };
14870       return
14871         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14872                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14873                                 cast<StoreSDNode>(N)->getMemOperand());
14874     }
14875 
14876     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14877     // So it can increase the chance of CSE constant construction.
14878     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14879         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14880       // Need to sign-extended to 64-bits to handle negative values.
14881       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14882       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14883                                     MemVT.getSizeInBits());
14884       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14885 
14886       // DAG.getTruncStore() can't be used here because it doesn't accept
14887       // the general (base + offset) addressing mode.
14888       // So we use UpdateNodeOperands and setTruncatingStore instead.
14889       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14890                              N->getOperand(3));
14891       cast<StoreSDNode>(N)->setTruncatingStore(true);
14892       return SDValue(N, 0);
14893     }
14894 
14895     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14896     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14897     if (Op1VT.isSimple()) {
14898       MVT StoreVT = Op1VT.getSimpleVT();
14899       if (Subtarget.needsSwapsForVSXMemOps() &&
14900           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14901            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14902         return expandVSXStoreForLE(N, DCI);
14903     }
14904     break;
14905   }
14906   case ISD::LOAD: {
14907     LoadSDNode *LD = cast<LoadSDNode>(N);
14908     EVT VT = LD->getValueType(0);
14909 
14910     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14911     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14912     if (VT.isSimple()) {
14913       MVT LoadVT = VT.getSimpleVT();
14914       if (Subtarget.needsSwapsForVSXMemOps() &&
14915           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14916            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14917         return expandVSXLoadForLE(N, DCI);
14918     }
14919 
14920     // We sometimes end up with a 64-bit integer load, from which we extract
14921     // two single-precision floating-point numbers. This happens with
14922     // std::complex<float>, and other similar structures, because of the way we
14923     // canonicalize structure copies. However, if we lack direct moves,
14924     // then the final bitcasts from the extracted integer values to the
14925     // floating-point numbers turn into store/load pairs. Even with direct moves,
14926     // just loading the two floating-point numbers is likely better.
14927     auto ReplaceTwoFloatLoad = [&]() {
14928       if (VT != MVT::i64)
14929         return false;
14930 
14931       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14932           LD->isVolatile())
14933         return false;
14934 
14935       //  We're looking for a sequence like this:
14936       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14937       //      t16: i64 = srl t13, Constant:i32<32>
14938       //    t17: i32 = truncate t16
14939       //  t18: f32 = bitcast t17
14940       //    t19: i32 = truncate t13
14941       //  t20: f32 = bitcast t19
14942 
14943       if (!LD->hasNUsesOfValue(2, 0))
14944         return false;
14945 
14946       auto UI = LD->use_begin();
14947       while (UI.getUse().getResNo() != 0) ++UI;
14948       SDNode *Trunc = *UI++;
14949       while (UI.getUse().getResNo() != 0) ++UI;
14950       SDNode *RightShift = *UI;
14951       if (Trunc->getOpcode() != ISD::TRUNCATE)
14952         std::swap(Trunc, RightShift);
14953 
14954       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14955           Trunc->getValueType(0) != MVT::i32 ||
14956           !Trunc->hasOneUse())
14957         return false;
14958       if (RightShift->getOpcode() != ISD::SRL ||
14959           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14960           RightShift->getConstantOperandVal(1) != 32 ||
14961           !RightShift->hasOneUse())
14962         return false;
14963 
14964       SDNode *Trunc2 = *RightShift->use_begin();
14965       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14966           Trunc2->getValueType(0) != MVT::i32 ||
14967           !Trunc2->hasOneUse())
14968         return false;
14969 
14970       SDNode *Bitcast = *Trunc->use_begin();
14971       SDNode *Bitcast2 = *Trunc2->use_begin();
14972 
14973       if (Bitcast->getOpcode() != ISD::BITCAST ||
14974           Bitcast->getValueType(0) != MVT::f32)
14975         return false;
14976       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14977           Bitcast2->getValueType(0) != MVT::f32)
14978         return false;
14979 
14980       if (Subtarget.isLittleEndian())
14981         std::swap(Bitcast, Bitcast2);
14982 
14983       // Bitcast has the second float (in memory-layout order) and Bitcast2
14984       // has the first one.
14985 
14986       SDValue BasePtr = LD->getBasePtr();
14987       if (LD->isIndexed()) {
14988         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14989                "Non-pre-inc AM on PPC?");
14990         BasePtr =
14991           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14992                       LD->getOffset());
14993       }
14994 
14995       auto MMOFlags =
14996           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14997       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14998                                       LD->getPointerInfo(), LD->getAlignment(),
14999                                       MMOFlags, LD->getAAInfo());
15000       SDValue AddPtr =
15001         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
15002                     BasePtr, DAG.getIntPtrConstant(4, dl));
15003       SDValue FloatLoad2 = DAG.getLoad(
15004           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
15005           LD->getPointerInfo().getWithOffset(4),
15006           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
15007 
15008       if (LD->isIndexed()) {
15009         // Note that DAGCombine should re-form any pre-increment load(s) from
15010         // what is produced here if that makes sense.
15011         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
15012       }
15013 
15014       DCI.CombineTo(Bitcast2, FloatLoad);
15015       DCI.CombineTo(Bitcast, FloatLoad2);
15016 
15017       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
15018                                     SDValue(FloatLoad2.getNode(), 1));
15019       return true;
15020     };
15021 
15022     if (ReplaceTwoFloatLoad())
15023       return SDValue(N, 0);
15024 
15025     EVT MemVT = LD->getMemoryVT();
15026     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
15027     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
15028     if (LD->isUnindexed() && VT.isVector() &&
15029         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
15030           // P8 and later hardware should just use LOAD.
15031           !Subtarget.hasP8Vector() &&
15032           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
15033            VT == MVT::v4f32))) &&
15034         LD->getAlign() < ABIAlignment) {
15035       // This is a type-legal unaligned Altivec load.
15036       SDValue Chain = LD->getChain();
15037       SDValue Ptr = LD->getBasePtr();
15038       bool isLittleEndian = Subtarget.isLittleEndian();
15039 
15040       // This implements the loading of unaligned vectors as described in
15041       // the venerable Apple Velocity Engine overview. Specifically:
15042       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
15043       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
15044       //
15045       // The general idea is to expand a sequence of one or more unaligned
15046       // loads into an alignment-based permutation-control instruction (lvsl
15047       // or lvsr), a series of regular vector loads (which always truncate
15048       // their input address to an aligned address), and a series of
15049       // permutations.  The results of these permutations are the requested
15050       // loaded values.  The trick is that the last "extra" load is not taken
15051       // from the address you might suspect (sizeof(vector) bytes after the
15052       // last requested load), but rather sizeof(vector) - 1 bytes after the
15053       // last requested vector. The point of this is to avoid a page fault if
15054       // the base address happened to be aligned. This works because if the
15055       // base address is aligned, then adding less than a full vector length
15056       // will cause the last vector in the sequence to be (re)loaded.
15057       // Otherwise, the next vector will be fetched as you might suspect was
15058       // necessary.
15059 
15060       // We might be able to reuse the permutation generation from
15061       // a different base address offset from this one by an aligned amount.
15062       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
15063       // optimization later.
15064       Intrinsic::ID Intr, IntrLD, IntrPerm;
15065       MVT PermCntlTy, PermTy, LDTy;
15066       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15067                             : Intrinsic::ppc_altivec_lvsl;
15068       IntrLD = Intrinsic::ppc_altivec_lvx;
15069       IntrPerm = Intrinsic::ppc_altivec_vperm;
15070       PermCntlTy = MVT::v16i8;
15071       PermTy = MVT::v4i32;
15072       LDTy = MVT::v4i32;
15073 
15074       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
15075 
15076       // Create the new MMO for the new base load. It is like the original MMO,
15077       // but represents an area in memory almost twice the vector size centered
15078       // on the original address. If the address is unaligned, we might start
15079       // reading up to (sizeof(vector)-1) bytes below the address of the
15080       // original unaligned load.
15081       MachineFunction &MF = DAG.getMachineFunction();
15082       MachineMemOperand *BaseMMO =
15083         MF.getMachineMemOperand(LD->getMemOperand(),
15084                                 -(long)MemVT.getStoreSize()+1,
15085                                 2*MemVT.getStoreSize()-1);
15086 
15087       // Create the new base load.
15088       SDValue LDXIntID =
15089           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
15090       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
15091       SDValue BaseLoad =
15092         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15093                                 DAG.getVTList(PermTy, MVT::Other),
15094                                 BaseLoadOps, LDTy, BaseMMO);
15095 
15096       // Note that the value of IncOffset (which is provided to the next
15097       // load's pointer info offset value, and thus used to calculate the
15098       // alignment), and the value of IncValue (which is actually used to
15099       // increment the pointer value) are different! This is because we
15100       // require the next load to appear to be aligned, even though it
15101       // is actually offset from the base pointer by a lesser amount.
15102       int IncOffset = VT.getSizeInBits() / 8;
15103       int IncValue = IncOffset;
15104 
15105       // Walk (both up and down) the chain looking for another load at the real
15106       // (aligned) offset (the alignment of the other load does not matter in
15107       // this case). If found, then do not use the offset reduction trick, as
15108       // that will prevent the loads from being later combined (as they would
15109       // otherwise be duplicates).
15110       if (!findConsecutiveLoad(LD, DAG))
15111         --IncValue;
15112 
15113       SDValue Increment =
15114           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
15115       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15116 
15117       MachineMemOperand *ExtraMMO =
15118         MF.getMachineMemOperand(LD->getMemOperand(),
15119                                 1, 2*MemVT.getStoreSize()-1);
15120       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
15121       SDValue ExtraLoad =
15122         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15123                                 DAG.getVTList(PermTy, MVT::Other),
15124                                 ExtraLoadOps, LDTy, ExtraMMO);
15125 
15126       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15127         BaseLoad.getValue(1), ExtraLoad.getValue(1));
15128 
15129       // Because vperm has a big-endian bias, we must reverse the order
15130       // of the input vectors and complement the permute control vector
15131       // when generating little endian code.  We have already handled the
15132       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
15133       // and ExtraLoad here.
15134       SDValue Perm;
15135       if (isLittleEndian)
15136         Perm = BuildIntrinsicOp(IntrPerm,
15137                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
15138       else
15139         Perm = BuildIntrinsicOp(IntrPerm,
15140                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
15141 
15142       if (VT != PermTy)
15143         Perm = Subtarget.hasAltivec()
15144                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
15145                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
15146                                  DAG.getTargetConstant(1, dl, MVT::i64));
15147                                // second argument is 1 because this rounding
15148                                // is always exact.
15149 
15150       // The output of the permutation is our loaded result, the TokenFactor is
15151       // our new chain.
15152       DCI.CombineTo(N, Perm, TF);
15153       return SDValue(N, 0);
15154     }
15155     }
15156     break;
15157     case ISD::INTRINSIC_WO_CHAIN: {
15158       bool isLittleEndian = Subtarget.isLittleEndian();
15159       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15160       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15161                                            : Intrinsic::ppc_altivec_lvsl);
15162       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
15163         SDValue Add = N->getOperand(1);
15164 
15165         int Bits = 4 /* 16 byte alignment */;
15166 
15167         if (DAG.MaskedValueIsZero(Add->getOperand(1),
15168                                   APInt::getAllOnesValue(Bits /* alignment */)
15169                                       .zext(Add.getScalarValueSizeInBits()))) {
15170           SDNode *BasePtr = Add->getOperand(0).getNode();
15171           for (SDNode::use_iterator UI = BasePtr->use_begin(),
15172                                     UE = BasePtr->use_end();
15173                UI != UE; ++UI) {
15174             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15175                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
15176                     IID) {
15177               // We've found another LVSL/LVSR, and this address is an aligned
15178               // multiple of that one. The results will be the same, so use the
15179               // one we've just found instead.
15180 
15181               return SDValue(*UI, 0);
15182             }
15183           }
15184         }
15185 
15186         if (isa<ConstantSDNode>(Add->getOperand(1))) {
15187           SDNode *BasePtr = Add->getOperand(0).getNode();
15188           for (SDNode::use_iterator UI = BasePtr->use_begin(),
15189                UE = BasePtr->use_end(); UI != UE; ++UI) {
15190             if (UI->getOpcode() == ISD::ADD &&
15191                 isa<ConstantSDNode>(UI->getOperand(1)) &&
15192                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
15193                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
15194                 (1ULL << Bits) == 0) {
15195               SDNode *OtherAdd = *UI;
15196               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
15197                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
15198                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15199                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
15200                   return SDValue(*VI, 0);
15201                 }
15202               }
15203             }
15204           }
15205         }
15206       }
15207 
15208       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
15209       // Expose the vabsduw/h/b opportunity for down stream
15210       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
15211           (IID == Intrinsic::ppc_altivec_vmaxsw ||
15212            IID == Intrinsic::ppc_altivec_vmaxsh ||
15213            IID == Intrinsic::ppc_altivec_vmaxsb)) {
15214         SDValue V1 = N->getOperand(1);
15215         SDValue V2 = N->getOperand(2);
15216         if ((V1.getSimpleValueType() == MVT::v4i32 ||
15217              V1.getSimpleValueType() == MVT::v8i16 ||
15218              V1.getSimpleValueType() == MVT::v16i8) &&
15219             V1.getSimpleValueType() == V2.getSimpleValueType()) {
15220           // (0-a, a)
15221           if (V1.getOpcode() == ISD::SUB &&
15222               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
15223               V1.getOperand(1) == V2) {
15224             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
15225           }
15226           // (a, 0-a)
15227           if (V2.getOpcode() == ISD::SUB &&
15228               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
15229               V2.getOperand(1) == V1) {
15230             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15231           }
15232           // (x-y, y-x)
15233           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
15234               V1.getOperand(0) == V2.getOperand(1) &&
15235               V1.getOperand(1) == V2.getOperand(0)) {
15236             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15237           }
15238         }
15239       }
15240     }
15241 
15242     break;
15243   case ISD::INTRINSIC_W_CHAIN:
15244     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15245     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15246     if (Subtarget.needsSwapsForVSXMemOps()) {
15247       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15248       default:
15249         break;
15250       case Intrinsic::ppc_vsx_lxvw4x:
15251       case Intrinsic::ppc_vsx_lxvd2x:
15252         return expandVSXLoadForLE(N, DCI);
15253       }
15254     }
15255     break;
15256   case ISD::INTRINSIC_VOID:
15257     // For little endian, VSX stores require generating xxswapd/stxvd2x.
15258     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15259     if (Subtarget.needsSwapsForVSXMemOps()) {
15260       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15261       default:
15262         break;
15263       case Intrinsic::ppc_vsx_stxvw4x:
15264       case Intrinsic::ppc_vsx_stxvd2x:
15265         return expandVSXStoreForLE(N, DCI);
15266       }
15267     }
15268     break;
15269   case ISD::BSWAP:
15270     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
15271     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
15272         N->getOperand(0).hasOneUse() &&
15273         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
15274          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
15275           N->getValueType(0) == MVT::i64))) {
15276       SDValue Load = N->getOperand(0);
15277       LoadSDNode *LD = cast<LoadSDNode>(Load);
15278       // Create the byte-swapping load.
15279       SDValue Ops[] = {
15280         LD->getChain(),    // Chain
15281         LD->getBasePtr(),  // Ptr
15282         DAG.getValueType(N->getValueType(0)) // VT
15283       };
15284       SDValue BSLoad =
15285         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
15286                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
15287                                               MVT::i64 : MVT::i32, MVT::Other),
15288                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
15289 
15290       // If this is an i16 load, insert the truncate.
15291       SDValue ResVal = BSLoad;
15292       if (N->getValueType(0) == MVT::i16)
15293         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
15294 
15295       // First, combine the bswap away.  This makes the value produced by the
15296       // load dead.
15297       DCI.CombineTo(N, ResVal);
15298 
15299       // Next, combine the load away, we give it a bogus result value but a real
15300       // chain result.  The result value is dead because the bswap is dead.
15301       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
15302 
15303       // Return N so it doesn't get rechecked!
15304       return SDValue(N, 0);
15305     }
15306     break;
15307   case PPCISD::VCMP:
15308     // If a VCMP_rec node already exists with exactly the same operands as this
15309     // node, use its result instead of this node (VCMP_rec computes both a CR6
15310     // and a normal output).
15311     //
15312     if (!N->getOperand(0).hasOneUse() &&
15313         !N->getOperand(1).hasOneUse() &&
15314         !N->getOperand(2).hasOneUse()) {
15315 
15316       // Scan all of the users of the LHS, looking for VCMP_rec's that match.
15317       SDNode *VCMPrecNode = nullptr;
15318 
15319       SDNode *LHSN = N->getOperand(0).getNode();
15320       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
15321            UI != E; ++UI)
15322         if (UI->getOpcode() == PPCISD::VCMP_rec &&
15323             UI->getOperand(1) == N->getOperand(1) &&
15324             UI->getOperand(2) == N->getOperand(2) &&
15325             UI->getOperand(0) == N->getOperand(0)) {
15326           VCMPrecNode = *UI;
15327           break;
15328         }
15329 
15330       // If there is no VCMP_rec node, or if the flag value has a single use,
15331       // don't transform this.
15332       if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
15333         break;
15334 
15335       // Look at the (necessarily single) use of the flag value.  If it has a
15336       // chain, this transformation is more complex.  Note that multiple things
15337       // could use the value result, which we should ignore.
15338       SDNode *FlagUser = nullptr;
15339       for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
15340            FlagUser == nullptr; ++UI) {
15341         assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
15342         SDNode *User = *UI;
15343         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
15344           if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
15345             FlagUser = User;
15346             break;
15347           }
15348         }
15349       }
15350 
15351       // If the user is a MFOCRF instruction, we know this is safe.
15352       // Otherwise we give up for right now.
15353       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
15354         return SDValue(VCMPrecNode, 0);
15355     }
15356     break;
15357   case ISD::BRCOND: {
15358     SDValue Cond = N->getOperand(1);
15359     SDValue Target = N->getOperand(2);
15360 
15361     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15362         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15363           Intrinsic::loop_decrement) {
15364 
15365       // We now need to make the intrinsic dead (it cannot be instruction
15366       // selected).
15367       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15368       assert(Cond.getNode()->hasOneUse() &&
15369              "Counter decrement has more than one use");
15370 
15371       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15372                          N->getOperand(0), Target);
15373     }
15374   }
15375   break;
15376   case ISD::BR_CC: {
15377     // If this is a branch on an altivec predicate comparison, lower this so
15378     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15379     // lowering is done pre-legalize, because the legalizer lowers the predicate
15380     // compare down to code that is difficult to reassemble.
15381     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15382     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15383 
15384     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15385     // value. If so, pass-through the AND to get to the intrinsic.
15386     if (LHS.getOpcode() == ISD::AND &&
15387         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15388         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15389           Intrinsic::loop_decrement &&
15390         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15391         !isNullConstant(LHS.getOperand(1)))
15392       LHS = LHS.getOperand(0);
15393 
15394     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15395         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15396           Intrinsic::loop_decrement &&
15397         isa<ConstantSDNode>(RHS)) {
15398       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15399              "Counter decrement comparison is not EQ or NE");
15400 
15401       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15402       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15403                     (CC == ISD::SETNE && !Val);
15404 
15405       // We now need to make the intrinsic dead (it cannot be instruction
15406       // selected).
15407       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15408       assert(LHS.getNode()->hasOneUse() &&
15409              "Counter decrement has more than one use");
15410 
15411       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15412                          N->getOperand(0), N->getOperand(4));
15413     }
15414 
15415     int CompareOpc;
15416     bool isDot;
15417 
15418     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15419         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15420         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15421       assert(isDot && "Can't compare against a vector result!");
15422 
15423       // If this is a comparison against something other than 0/1, then we know
15424       // that the condition is never/always true.
15425       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15426       if (Val != 0 && Val != 1) {
15427         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15428           return N->getOperand(0);
15429         // Always !=, turn it into an unconditional branch.
15430         return DAG.getNode(ISD::BR, dl, MVT::Other,
15431                            N->getOperand(0), N->getOperand(4));
15432       }
15433 
15434       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15435 
15436       // Create the PPCISD altivec 'dot' comparison node.
15437       SDValue Ops[] = {
15438         LHS.getOperand(2),  // LHS of compare
15439         LHS.getOperand(3),  // RHS of compare
15440         DAG.getConstant(CompareOpc, dl, MVT::i32)
15441       };
15442       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15443       SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
15444 
15445       // Unpack the result based on how the target uses it.
15446       PPC::Predicate CompOpc;
15447       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15448       default:  // Can't happen, don't crash on invalid number though.
15449       case 0:   // Branch on the value of the EQ bit of CR6.
15450         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15451         break;
15452       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15453         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15454         break;
15455       case 2:   // Branch on the value of the LT bit of CR6.
15456         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15457         break;
15458       case 3:   // Branch on the inverted value of the LT bit of CR6.
15459         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15460         break;
15461       }
15462 
15463       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15464                          DAG.getConstant(CompOpc, dl, MVT::i32),
15465                          DAG.getRegister(PPC::CR6, MVT::i32),
15466                          N->getOperand(4), CompNode.getValue(1));
15467     }
15468     break;
15469   }
15470   case ISD::BUILD_VECTOR:
15471     return DAGCombineBuildVector(N, DCI);
15472   case ISD::ABS:
15473     return combineABS(N, DCI);
15474   case ISD::VSELECT:
15475     return combineVSelect(N, DCI);
15476   }
15477 
15478   return SDValue();
15479 }
15480 
15481 SDValue
15482 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15483                                  SelectionDAG &DAG,
15484                                  SmallVectorImpl<SDNode *> &Created) const {
15485   // fold (sdiv X, pow2)
15486   EVT VT = N->getValueType(0);
15487   if (VT == MVT::i64 && !Subtarget.isPPC64())
15488     return SDValue();
15489   if ((VT != MVT::i32 && VT != MVT::i64) ||
15490       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
15491     return SDValue();
15492 
15493   SDLoc DL(N);
15494   SDValue N0 = N->getOperand(0);
15495 
15496   bool IsNegPow2 = (-Divisor).isPowerOf2();
15497   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15498   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15499 
15500   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15501   Created.push_back(Op.getNode());
15502 
15503   if (IsNegPow2) {
15504     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15505     Created.push_back(Op.getNode());
15506   }
15507 
15508   return Op;
15509 }
15510 
15511 //===----------------------------------------------------------------------===//
15512 // Inline Assembly Support
15513 //===----------------------------------------------------------------------===//
15514 
15515 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15516                                                       KnownBits &Known,
15517                                                       const APInt &DemandedElts,
15518                                                       const SelectionDAG &DAG,
15519                                                       unsigned Depth) const {
15520   Known.resetAll();
15521   switch (Op.getOpcode()) {
15522   default: break;
15523   case PPCISD::LBRX: {
15524     // lhbrx is known to have the top bits cleared out.
15525     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15526       Known.Zero = 0xFFFF0000;
15527     break;
15528   }
15529   case ISD::INTRINSIC_WO_CHAIN: {
15530     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15531     default: break;
15532     case Intrinsic::ppc_altivec_vcmpbfp_p:
15533     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15534     case Intrinsic::ppc_altivec_vcmpequb_p:
15535     case Intrinsic::ppc_altivec_vcmpequh_p:
15536     case Intrinsic::ppc_altivec_vcmpequw_p:
15537     case Intrinsic::ppc_altivec_vcmpequd_p:
15538     case Intrinsic::ppc_altivec_vcmpequq_p:
15539     case Intrinsic::ppc_altivec_vcmpgefp_p:
15540     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15541     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15542     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15543     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15544     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15545     case Intrinsic::ppc_altivec_vcmpgtsq_p:
15546     case Intrinsic::ppc_altivec_vcmpgtub_p:
15547     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15548     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15549     case Intrinsic::ppc_altivec_vcmpgtud_p:
15550     case Intrinsic::ppc_altivec_vcmpgtuq_p:
15551       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15552       break;
15553     }
15554   }
15555   }
15556 }
15557 
15558 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15559   switch (Subtarget.getCPUDirective()) {
15560   default: break;
15561   case PPC::DIR_970:
15562   case PPC::DIR_PWR4:
15563   case PPC::DIR_PWR5:
15564   case PPC::DIR_PWR5X:
15565   case PPC::DIR_PWR6:
15566   case PPC::DIR_PWR6X:
15567   case PPC::DIR_PWR7:
15568   case PPC::DIR_PWR8:
15569   case PPC::DIR_PWR9:
15570   case PPC::DIR_PWR10:
15571   case PPC::DIR_PWR_FUTURE: {
15572     if (!ML)
15573       break;
15574 
15575     if (!DisableInnermostLoopAlign32) {
15576       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15577       // so that we can decrease cache misses and branch-prediction misses.
15578       // Actual alignment of the loop will depend on the hotness check and other
15579       // logic in alignBlocks.
15580       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15581         return Align(32);
15582     }
15583 
15584     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15585 
15586     // For small loops (between 5 and 8 instructions), align to a 32-byte
15587     // boundary so that the entire loop fits in one instruction-cache line.
15588     uint64_t LoopSize = 0;
15589     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15590       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15591         LoopSize += TII->getInstSizeInBytes(*J);
15592         if (LoopSize > 32)
15593           break;
15594       }
15595 
15596     if (LoopSize > 16 && LoopSize <= 32)
15597       return Align(32);
15598 
15599     break;
15600   }
15601   }
15602 
15603   return TargetLowering::getPrefLoopAlignment(ML);
15604 }
15605 
15606 /// getConstraintType - Given a constraint, return the type of
15607 /// constraint it is for this target.
15608 PPCTargetLowering::ConstraintType
15609 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15610   if (Constraint.size() == 1) {
15611     switch (Constraint[0]) {
15612     default: break;
15613     case 'b':
15614     case 'r':
15615     case 'f':
15616     case 'd':
15617     case 'v':
15618     case 'y':
15619       return C_RegisterClass;
15620     case 'Z':
15621       // FIXME: While Z does indicate a memory constraint, it specifically
15622       // indicates an r+r address (used in conjunction with the 'y' modifier
15623       // in the replacement string). Currently, we're forcing the base
15624       // register to be r0 in the asm printer (which is interpreted as zero)
15625       // and forming the complete address in the second register. This is
15626       // suboptimal.
15627       return C_Memory;
15628     }
15629   } else if (Constraint == "wc") { // individual CR bits.
15630     return C_RegisterClass;
15631   } else if (Constraint == "wa" || Constraint == "wd" ||
15632              Constraint == "wf" || Constraint == "ws" ||
15633              Constraint == "wi" || Constraint == "ww") {
15634     return C_RegisterClass; // VSX registers.
15635   }
15636   return TargetLowering::getConstraintType(Constraint);
15637 }
15638 
15639 /// Examine constraint type and operand type and determine a weight value.
15640 /// This object must already have been set up with the operand type
15641 /// and the current alternative constraint selected.
15642 TargetLowering::ConstraintWeight
15643 PPCTargetLowering::getSingleConstraintMatchWeight(
15644     AsmOperandInfo &info, const char *constraint) const {
15645   ConstraintWeight weight = CW_Invalid;
15646   Value *CallOperandVal = info.CallOperandVal;
15647     // If we don't have a value, we can't do a match,
15648     // but allow it at the lowest weight.
15649   if (!CallOperandVal)
15650     return CW_Default;
15651   Type *type = CallOperandVal->getType();
15652 
15653   // Look at the constraint type.
15654   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15655     return CW_Register; // an individual CR bit.
15656   else if ((StringRef(constraint) == "wa" ||
15657             StringRef(constraint) == "wd" ||
15658             StringRef(constraint) == "wf") &&
15659            type->isVectorTy())
15660     return CW_Register;
15661   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15662     return CW_Register; // just hold 64-bit integers data.
15663   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15664     return CW_Register;
15665   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15666     return CW_Register;
15667 
15668   switch (*constraint) {
15669   default:
15670     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15671     break;
15672   case 'b':
15673     if (type->isIntegerTy())
15674       weight = CW_Register;
15675     break;
15676   case 'f':
15677     if (type->isFloatTy())
15678       weight = CW_Register;
15679     break;
15680   case 'd':
15681     if (type->isDoubleTy())
15682       weight = CW_Register;
15683     break;
15684   case 'v':
15685     if (type->isVectorTy())
15686       weight = CW_Register;
15687     break;
15688   case 'y':
15689     weight = CW_Register;
15690     break;
15691   case 'Z':
15692     weight = CW_Memory;
15693     break;
15694   }
15695   return weight;
15696 }
15697 
15698 std::pair<unsigned, const TargetRegisterClass *>
15699 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15700                                                 StringRef Constraint,
15701                                                 MVT VT) const {
15702   if (Constraint.size() == 1) {
15703     // GCC RS6000 Constraint Letters
15704     switch (Constraint[0]) {
15705     case 'b':   // R1-R31
15706       if (VT == MVT::i64 && Subtarget.isPPC64())
15707         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15708       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15709     case 'r':   // R0-R31
15710       if (VT == MVT::i64 && Subtarget.isPPC64())
15711         return std::make_pair(0U, &PPC::G8RCRegClass);
15712       return std::make_pair(0U, &PPC::GPRCRegClass);
15713     // 'd' and 'f' constraints are both defined to be "the floating point
15714     // registers", where one is for 32-bit and the other for 64-bit. We don't
15715     // really care overly much here so just give them all the same reg classes.
15716     case 'd':
15717     case 'f':
15718       if (Subtarget.hasSPE()) {
15719         if (VT == MVT::f32 || VT == MVT::i32)
15720           return std::make_pair(0U, &PPC::GPRCRegClass);
15721         if (VT == MVT::f64 || VT == MVT::i64)
15722           return std::make_pair(0U, &PPC::SPERCRegClass);
15723       } else {
15724         if (VT == MVT::f32 || VT == MVT::i32)
15725           return std::make_pair(0U, &PPC::F4RCRegClass);
15726         if (VT == MVT::f64 || VT == MVT::i64)
15727           return std::make_pair(0U, &PPC::F8RCRegClass);
15728       }
15729       break;
15730     case 'v':
15731       if (Subtarget.hasAltivec())
15732         return std::make_pair(0U, &PPC::VRRCRegClass);
15733       break;
15734     case 'y':   // crrc
15735       return std::make_pair(0U, &PPC::CRRCRegClass);
15736     }
15737   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15738     // An individual CR bit.
15739     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15740   } else if ((Constraint == "wa" || Constraint == "wd" ||
15741              Constraint == "wf" || Constraint == "wi") &&
15742              Subtarget.hasVSX()) {
15743     return std::make_pair(0U, &PPC::VSRCRegClass);
15744   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15745     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15746       return std::make_pair(0U, &PPC::VSSRCRegClass);
15747     else
15748       return std::make_pair(0U, &PPC::VSFRCRegClass);
15749   }
15750 
15751   // If we name a VSX register, we can't defer to the base class because it
15752   // will not recognize the correct register (their names will be VSL{0-31}
15753   // and V{0-31} so they won't match). So we match them here.
15754   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15755     int VSNum = atoi(Constraint.data() + 3);
15756     assert(VSNum >= 0 && VSNum <= 63 &&
15757            "Attempted to access a vsr out of range");
15758     if (VSNum < 32)
15759       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15760     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15761   }
15762   std::pair<unsigned, const TargetRegisterClass *> R =
15763       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15764 
15765   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15766   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15767   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15768   // register.
15769   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15770   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15771   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15772       PPC::GPRCRegClass.contains(R.first))
15773     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15774                             PPC::sub_32, &PPC::G8RCRegClass),
15775                           &PPC::G8RCRegClass);
15776 
15777   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15778   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15779     R.first = PPC::CR0;
15780     R.second = &PPC::CRRCRegClass;
15781   }
15782 
15783   return R;
15784 }
15785 
15786 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15787 /// vector.  If it is invalid, don't add anything to Ops.
15788 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15789                                                      std::string &Constraint,
15790                                                      std::vector<SDValue>&Ops,
15791                                                      SelectionDAG &DAG) const {
15792   SDValue Result;
15793 
15794   // Only support length 1 constraints.
15795   if (Constraint.length() > 1) return;
15796 
15797   char Letter = Constraint[0];
15798   switch (Letter) {
15799   default: break;
15800   case 'I':
15801   case 'J':
15802   case 'K':
15803   case 'L':
15804   case 'M':
15805   case 'N':
15806   case 'O':
15807   case 'P': {
15808     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15809     if (!CST) return; // Must be an immediate to match.
15810     SDLoc dl(Op);
15811     int64_t Value = CST->getSExtValue();
15812     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15813                          // numbers are printed as such.
15814     switch (Letter) {
15815     default: llvm_unreachable("Unknown constraint letter!");
15816     case 'I':  // "I" is a signed 16-bit constant.
15817       if (isInt<16>(Value))
15818         Result = DAG.getTargetConstant(Value, dl, TCVT);
15819       break;
15820     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15821       if (isShiftedUInt<16, 16>(Value))
15822         Result = DAG.getTargetConstant(Value, dl, TCVT);
15823       break;
15824     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15825       if (isShiftedInt<16, 16>(Value))
15826         Result = DAG.getTargetConstant(Value, dl, TCVT);
15827       break;
15828     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15829       if (isUInt<16>(Value))
15830         Result = DAG.getTargetConstant(Value, dl, TCVT);
15831       break;
15832     case 'M':  // "M" is a constant that is greater than 31.
15833       if (Value > 31)
15834         Result = DAG.getTargetConstant(Value, dl, TCVT);
15835       break;
15836     case 'N':  // "N" is a positive constant that is an exact power of two.
15837       if (Value > 0 && isPowerOf2_64(Value))
15838         Result = DAG.getTargetConstant(Value, dl, TCVT);
15839       break;
15840     case 'O':  // "O" is the constant zero.
15841       if (Value == 0)
15842         Result = DAG.getTargetConstant(Value, dl, TCVT);
15843       break;
15844     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15845       if (isInt<16>(-Value))
15846         Result = DAG.getTargetConstant(Value, dl, TCVT);
15847       break;
15848     }
15849     break;
15850   }
15851   }
15852 
15853   if (Result.getNode()) {
15854     Ops.push_back(Result);
15855     return;
15856   }
15857 
15858   // Handle standard constraint letters.
15859   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15860 }
15861 
15862 // isLegalAddressingMode - Return true if the addressing mode represented
15863 // by AM is legal for this target, for a load/store of the specified type.
15864 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15865                                               const AddrMode &AM, Type *Ty,
15866                                               unsigned AS,
15867                                               Instruction *I) const {
15868   // Vector type r+i form is supported since power9 as DQ form. We don't check
15869   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
15870   // imm form is preferred and the offset can be adjusted to use imm form later
15871   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
15872   // max offset to check legal addressing mode, we should be a little aggressive
15873   // to contain other offsets for that LSRUse.
15874   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
15875     return false;
15876 
15877   // PPC allows a sign-extended 16-bit immediate field.
15878   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15879     return false;
15880 
15881   // No global is ever allowed as a base.
15882   if (AM.BaseGV)
15883     return false;
15884 
15885   // PPC only support r+r,
15886   switch (AM.Scale) {
15887   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15888     break;
15889   case 1:
15890     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15891       return false;
15892     // Otherwise we have r+r or r+i.
15893     break;
15894   case 2:
15895     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15896       return false;
15897     // Allow 2*r as r+r.
15898     break;
15899   default:
15900     // No other scales are supported.
15901     return false;
15902   }
15903 
15904   return true;
15905 }
15906 
15907 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15908                                            SelectionDAG &DAG) const {
15909   MachineFunction &MF = DAG.getMachineFunction();
15910   MachineFrameInfo &MFI = MF.getFrameInfo();
15911   MFI.setReturnAddressIsTaken(true);
15912 
15913   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15914     return SDValue();
15915 
15916   SDLoc dl(Op);
15917   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15918 
15919   // Make sure the function does not optimize away the store of the RA to
15920   // the stack.
15921   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15922   FuncInfo->setLRStoreRequired();
15923   bool isPPC64 = Subtarget.isPPC64();
15924   auto PtrVT = getPointerTy(MF.getDataLayout());
15925 
15926   if (Depth > 0) {
15927     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15928     SDValue Offset =
15929         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15930                         isPPC64 ? MVT::i64 : MVT::i32);
15931     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15932                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15933                        MachinePointerInfo());
15934   }
15935 
15936   // Just load the return address off the stack.
15937   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15938   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15939                      MachinePointerInfo());
15940 }
15941 
15942 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15943                                           SelectionDAG &DAG) const {
15944   SDLoc dl(Op);
15945   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15946 
15947   MachineFunction &MF = DAG.getMachineFunction();
15948   MachineFrameInfo &MFI = MF.getFrameInfo();
15949   MFI.setFrameAddressIsTaken(true);
15950 
15951   EVT PtrVT = getPointerTy(MF.getDataLayout());
15952   bool isPPC64 = PtrVT == MVT::i64;
15953 
15954   // Naked functions never have a frame pointer, and so we use r1. For all
15955   // other functions, this decision must be delayed until during PEI.
15956   unsigned FrameReg;
15957   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15958     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15959   else
15960     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15961 
15962   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15963                                          PtrVT);
15964   while (Depth--)
15965     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15966                             FrameAddr, MachinePointerInfo());
15967   return FrameAddr;
15968 }
15969 
15970 // FIXME? Maybe this could be a TableGen attribute on some registers and
15971 // this table could be generated automatically from RegInfo.
15972 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15973                                               const MachineFunction &MF) const {
15974   bool isPPC64 = Subtarget.isPPC64();
15975 
15976   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15977   if (!is64Bit && VT != LLT::scalar(32))
15978     report_fatal_error("Invalid register global variable type");
15979 
15980   Register Reg = StringSwitch<Register>(RegName)
15981                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15982                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15983                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15984                      .Default(Register());
15985 
15986   if (Reg)
15987     return Reg;
15988   report_fatal_error("Invalid register name global variable");
15989 }
15990 
15991 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15992   // 32-bit SVR4 ABI access everything as got-indirect.
15993   if (Subtarget.is32BitELFABI())
15994     return true;
15995 
15996   // AIX accesses everything indirectly through the TOC, which is similar to
15997   // the GOT.
15998   if (Subtarget.isAIXABI())
15999     return true;
16000 
16001   CodeModel::Model CModel = getTargetMachine().getCodeModel();
16002   // If it is small or large code model, module locals are accessed
16003   // indirectly by loading their address from .toc/.got.
16004   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
16005     return true;
16006 
16007   // JumpTable and BlockAddress are accessed as got-indirect.
16008   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
16009     return true;
16010 
16011   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
16012     return Subtarget.isGVIndirectSymbol(G->getGlobal());
16013 
16014   return false;
16015 }
16016 
16017 bool
16018 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
16019   // The PowerPC target isn't yet aware of offsets.
16020   return false;
16021 }
16022 
16023 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
16024                                            const CallInst &I,
16025                                            MachineFunction &MF,
16026                                            unsigned Intrinsic) const {
16027   switch (Intrinsic) {
16028   case Intrinsic::ppc_altivec_lvx:
16029   case Intrinsic::ppc_altivec_lvxl:
16030   case Intrinsic::ppc_altivec_lvebx:
16031   case Intrinsic::ppc_altivec_lvehx:
16032   case Intrinsic::ppc_altivec_lvewx:
16033   case Intrinsic::ppc_vsx_lxvd2x:
16034   case Intrinsic::ppc_vsx_lxvw4x:
16035   case Intrinsic::ppc_vsx_lxvd2x_be:
16036   case Intrinsic::ppc_vsx_lxvw4x_be:
16037   case Intrinsic::ppc_vsx_lxvl:
16038   case Intrinsic::ppc_vsx_lxvll: {
16039     EVT VT;
16040     switch (Intrinsic) {
16041     case Intrinsic::ppc_altivec_lvebx:
16042       VT = MVT::i8;
16043       break;
16044     case Intrinsic::ppc_altivec_lvehx:
16045       VT = MVT::i16;
16046       break;
16047     case Intrinsic::ppc_altivec_lvewx:
16048       VT = MVT::i32;
16049       break;
16050     case Intrinsic::ppc_vsx_lxvd2x:
16051     case Intrinsic::ppc_vsx_lxvd2x_be:
16052       VT = MVT::v2f64;
16053       break;
16054     default:
16055       VT = MVT::v4i32;
16056       break;
16057     }
16058 
16059     Info.opc = ISD::INTRINSIC_W_CHAIN;
16060     Info.memVT = VT;
16061     Info.ptrVal = I.getArgOperand(0);
16062     Info.offset = -VT.getStoreSize()+1;
16063     Info.size = 2*VT.getStoreSize()-1;
16064     Info.align = Align(1);
16065     Info.flags = MachineMemOperand::MOLoad;
16066     return true;
16067   }
16068   case Intrinsic::ppc_altivec_stvx:
16069   case Intrinsic::ppc_altivec_stvxl:
16070   case Intrinsic::ppc_altivec_stvebx:
16071   case Intrinsic::ppc_altivec_stvehx:
16072   case Intrinsic::ppc_altivec_stvewx:
16073   case Intrinsic::ppc_vsx_stxvd2x:
16074   case Intrinsic::ppc_vsx_stxvw4x:
16075   case Intrinsic::ppc_vsx_stxvd2x_be:
16076   case Intrinsic::ppc_vsx_stxvw4x_be:
16077   case Intrinsic::ppc_vsx_stxvl:
16078   case Intrinsic::ppc_vsx_stxvll: {
16079     EVT VT;
16080     switch (Intrinsic) {
16081     case Intrinsic::ppc_altivec_stvebx:
16082       VT = MVT::i8;
16083       break;
16084     case Intrinsic::ppc_altivec_stvehx:
16085       VT = MVT::i16;
16086       break;
16087     case Intrinsic::ppc_altivec_stvewx:
16088       VT = MVT::i32;
16089       break;
16090     case Intrinsic::ppc_vsx_stxvd2x:
16091     case Intrinsic::ppc_vsx_stxvd2x_be:
16092       VT = MVT::v2f64;
16093       break;
16094     default:
16095       VT = MVT::v4i32;
16096       break;
16097     }
16098 
16099     Info.opc = ISD::INTRINSIC_VOID;
16100     Info.memVT = VT;
16101     Info.ptrVal = I.getArgOperand(1);
16102     Info.offset = -VT.getStoreSize()+1;
16103     Info.size = 2*VT.getStoreSize()-1;
16104     Info.align = Align(1);
16105     Info.flags = MachineMemOperand::MOStore;
16106     return true;
16107   }
16108   default:
16109     break;
16110   }
16111 
16112   return false;
16113 }
16114 
16115 /// It returns EVT::Other if the type should be determined using generic
16116 /// target-independent logic.
16117 EVT PPCTargetLowering::getOptimalMemOpType(
16118     const MemOp &Op, const AttributeList &FuncAttributes) const {
16119   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
16120     // We should use Altivec/VSX loads and stores when available. For unaligned
16121     // addresses, unaligned VSX loads are only fast starting with the P8.
16122     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
16123         (Op.isAligned(Align(16)) ||
16124          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
16125       return MVT::v4i32;
16126   }
16127 
16128   if (Subtarget.isPPC64()) {
16129     return MVT::i64;
16130   }
16131 
16132   return MVT::i32;
16133 }
16134 
16135 /// Returns true if it is beneficial to convert a load of a constant
16136 /// to just the constant itself.
16137 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16138                                                           Type *Ty) const {
16139   assert(Ty->isIntegerTy());
16140 
16141   unsigned BitSize = Ty->getPrimitiveSizeInBits();
16142   return !(BitSize == 0 || BitSize > 64);
16143 }
16144 
16145 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16146   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16147     return false;
16148   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16149   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16150   return NumBits1 == 64 && NumBits2 == 32;
16151 }
16152 
16153 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16154   if (!VT1.isInteger() || !VT2.isInteger())
16155     return false;
16156   unsigned NumBits1 = VT1.getSizeInBits();
16157   unsigned NumBits2 = VT2.getSizeInBits();
16158   return NumBits1 == 64 && NumBits2 == 32;
16159 }
16160 
16161 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16162   // Generally speaking, zexts are not free, but they are free when they can be
16163   // folded with other operations.
16164   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
16165     EVT MemVT = LD->getMemoryVT();
16166     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
16167          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
16168         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
16169          LD->getExtensionType() == ISD::ZEXTLOAD))
16170       return true;
16171   }
16172 
16173   // FIXME: Add other cases...
16174   //  - 32-bit shifts with a zext to i64
16175   //  - zext after ctlz, bswap, etc.
16176   //  - zext after and by a constant mask
16177 
16178   return TargetLowering::isZExtFree(Val, VT2);
16179 }
16180 
16181 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
16182   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
16183          "invalid fpext types");
16184   // Extending to float128 is not free.
16185   if (DestVT == MVT::f128)
16186     return false;
16187   return true;
16188 }
16189 
16190 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16191   return isInt<16>(Imm) || isUInt<16>(Imm);
16192 }
16193 
16194 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16195   return isInt<16>(Imm) || isUInt<16>(Imm);
16196 }
16197 
16198 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
16199                                                        unsigned,
16200                                                        unsigned,
16201                                                        MachineMemOperand::Flags,
16202                                                        bool *Fast) const {
16203   if (DisablePPCUnaligned)
16204     return false;
16205 
16206   // PowerPC supports unaligned memory access for simple non-vector types.
16207   // Although accessing unaligned addresses is not as efficient as accessing
16208   // aligned addresses, it is generally more efficient than manual expansion,
16209   // and generally only traps for software emulation when crossing page
16210   // boundaries.
16211 
16212   if (!VT.isSimple())
16213     return false;
16214 
16215   if (VT.isFloatingPoint() && !VT.isVector() &&
16216       !Subtarget.allowsUnalignedFPAccess())
16217     return false;
16218 
16219   if (VT.getSimpleVT().isVector()) {
16220     if (Subtarget.hasVSX()) {
16221       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
16222           VT != MVT::v4f32 && VT != MVT::v4i32)
16223         return false;
16224     } else {
16225       return false;
16226     }
16227   }
16228 
16229   if (VT == MVT::ppcf128)
16230     return false;
16231 
16232   if (Fast)
16233     *Fast = true;
16234 
16235   return true;
16236 }
16237 
16238 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
16239                                                SDValue C) const {
16240   // Check integral scalar types.
16241   if (!VT.isScalarInteger())
16242     return false;
16243   if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
16244     if (!ConstNode->getAPIntValue().isSignedIntN(64))
16245       return false;
16246     // This transformation will generate >= 2 operations. But the following
16247     // cases will generate <= 2 instructions during ISEL. So exclude them.
16248     // 1. If the constant multiplier fits 16 bits, it can be handled by one
16249     // HW instruction, ie. MULLI
16250     // 2. If the multiplier after shifted fits 16 bits, an extra shift
16251     // instruction is needed than case 1, ie. MULLI and RLDICR
16252     int64_t Imm = ConstNode->getSExtValue();
16253     unsigned Shift = countTrailingZeros<uint64_t>(Imm);
16254     Imm >>= Shift;
16255     if (isInt<16>(Imm))
16256       return false;
16257     uint64_t UImm = static_cast<uint64_t>(Imm);
16258     if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
16259         isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
16260       return true;
16261   }
16262   return false;
16263 }
16264 
16265 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16266                                                    EVT VT) const {
16267   return isFMAFasterThanFMulAndFAdd(
16268       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
16269 }
16270 
16271 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
16272                                                    Type *Ty) const {
16273   switch (Ty->getScalarType()->getTypeID()) {
16274   case Type::FloatTyID:
16275   case Type::DoubleTyID:
16276     return true;
16277   case Type::FP128TyID:
16278     return Subtarget.hasP9Vector();
16279   default:
16280     return false;
16281   }
16282 }
16283 
16284 // FIXME: add more patterns which are not profitable to hoist.
16285 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
16286   if (!I->hasOneUse())
16287     return true;
16288 
16289   Instruction *User = I->user_back();
16290   assert(User && "A single use instruction with no uses.");
16291 
16292   switch (I->getOpcode()) {
16293   case Instruction::FMul: {
16294     // Don't break FMA, PowerPC prefers FMA.
16295     if (User->getOpcode() != Instruction::FSub &&
16296         User->getOpcode() != Instruction::FAdd)
16297       return true;
16298 
16299     const TargetOptions &Options = getTargetMachine().Options;
16300     const Function *F = I->getFunction();
16301     const DataLayout &DL = F->getParent()->getDataLayout();
16302     Type *Ty = User->getOperand(0)->getType();
16303 
16304     return !(
16305         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
16306         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
16307         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
16308   }
16309   case Instruction::Load: {
16310     // Don't break "store (load float*)" pattern, this pattern will be combined
16311     // to "store (load int32)" in later InstCombine pass. See function
16312     // combineLoadToOperationType. On PowerPC, loading a float point takes more
16313     // cycles than loading a 32 bit integer.
16314     LoadInst *LI = cast<LoadInst>(I);
16315     // For the loads that combineLoadToOperationType does nothing, like
16316     // ordered load, it should be profitable to hoist them.
16317     // For swifterror load, it can only be used for pointer to pointer type, so
16318     // later type check should get rid of this case.
16319     if (!LI->isUnordered())
16320       return true;
16321 
16322     if (User->getOpcode() != Instruction::Store)
16323       return true;
16324 
16325     if (I->getType()->getTypeID() != Type::FloatTyID)
16326       return true;
16327 
16328     return false;
16329   }
16330   default:
16331     return true;
16332   }
16333   return true;
16334 }
16335 
16336 const MCPhysReg *
16337 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
16338   // LR is a callee-save register, but we must treat it as clobbered by any call
16339   // site. Hence we include LR in the scratch registers, which are in turn added
16340   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
16341   // to CTR, which is used by any indirect call.
16342   static const MCPhysReg ScratchRegs[] = {
16343     PPC::X12, PPC::LR8, PPC::CTR8, 0
16344   };
16345 
16346   return ScratchRegs;
16347 }
16348 
16349 Register PPCTargetLowering::getExceptionPointerRegister(
16350     const Constant *PersonalityFn) const {
16351   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
16352 }
16353 
16354 Register PPCTargetLowering::getExceptionSelectorRegister(
16355     const Constant *PersonalityFn) const {
16356   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
16357 }
16358 
16359 bool
16360 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
16361                      EVT VT , unsigned DefinedValues) const {
16362   if (VT == MVT::v2i64)
16363     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
16364 
16365   if (Subtarget.hasVSX())
16366     return true;
16367 
16368   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
16369 }
16370 
16371 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16372   if (DisableILPPref || Subtarget.enableMachineScheduler())
16373     return TargetLowering::getSchedulingPreference(N);
16374 
16375   return Sched::ILP;
16376 }
16377 
16378 // Create a fast isel object.
16379 FastISel *
16380 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16381                                   const TargetLibraryInfo *LibInfo) const {
16382   return PPC::createFastISel(FuncInfo, LibInfo);
16383 }
16384 
16385 // 'Inverted' means the FMA opcode after negating one multiplicand.
16386 // For example, (fma -a b c) = (fnmsub a b c)
16387 static unsigned invertFMAOpcode(unsigned Opc) {
16388   switch (Opc) {
16389   default:
16390     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16391   case ISD::FMA:
16392     return PPCISD::FNMSUB;
16393   case PPCISD::FNMSUB:
16394     return ISD::FMA;
16395   }
16396 }
16397 
16398 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16399                                                 bool LegalOps, bool OptForSize,
16400                                                 NegatibleCost &Cost,
16401                                                 unsigned Depth) const {
16402   if (Depth > SelectionDAG::MaxRecursionDepth)
16403     return SDValue();
16404 
16405   unsigned Opc = Op.getOpcode();
16406   EVT VT = Op.getValueType();
16407   SDNodeFlags Flags = Op.getNode()->getFlags();
16408 
16409   switch (Opc) {
16410   case PPCISD::FNMSUB:
16411     if (!Op.hasOneUse() || !isTypeLegal(VT))
16412       break;
16413 
16414     const TargetOptions &Options = getTargetMachine().Options;
16415     SDValue N0 = Op.getOperand(0);
16416     SDValue N1 = Op.getOperand(1);
16417     SDValue N2 = Op.getOperand(2);
16418     SDLoc Loc(Op);
16419 
16420     NegatibleCost N2Cost = NegatibleCost::Expensive;
16421     SDValue NegN2 =
16422         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16423 
16424     if (!NegN2)
16425       return SDValue();
16426 
16427     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16428     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16429     // These transformations may change sign of zeroes. For example,
16430     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16431     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16432       // Try and choose the cheaper one to negate.
16433       NegatibleCost N0Cost = NegatibleCost::Expensive;
16434       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16435                                            N0Cost, Depth + 1);
16436 
16437       NegatibleCost N1Cost = NegatibleCost::Expensive;
16438       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16439                                            N1Cost, Depth + 1);
16440 
16441       if (NegN0 && N0Cost <= N1Cost) {
16442         Cost = std::min(N0Cost, N2Cost);
16443         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16444       } else if (NegN1) {
16445         Cost = std::min(N1Cost, N2Cost);
16446         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16447       }
16448     }
16449 
16450     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16451     if (isOperationLegal(ISD::FMA, VT)) {
16452       Cost = N2Cost;
16453       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16454     }
16455 
16456     break;
16457   }
16458 
16459   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16460                                               Cost, Depth);
16461 }
16462 
16463 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16464 bool PPCTargetLowering::useLoadStackGuardNode() const {
16465   if (!Subtarget.isTargetLinux())
16466     return TargetLowering::useLoadStackGuardNode();
16467   return true;
16468 }
16469 
16470 // Override to disable global variable loading on Linux.
16471 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16472   if (!Subtarget.isTargetLinux())
16473     return TargetLowering::insertSSPDeclarations(M);
16474 }
16475 
16476 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16477                                      bool ForCodeSize) const {
16478   if (!VT.isSimple() || !Subtarget.hasVSX())
16479     return false;
16480 
16481   switch(VT.getSimpleVT().SimpleTy) {
16482   default:
16483     // For FP types that are currently not supported by PPC backend, return
16484     // false. Examples: f16, f80.
16485     return false;
16486   case MVT::f32:
16487   case MVT::f64:
16488     if (Subtarget.hasPrefixInstrs()) {
16489       // With prefixed instructions, we can materialize anything that can be
16490       // represented with a 32-bit immediate, not just positive zero.
16491       APFloat APFloatOfImm = Imm;
16492       return convertToNonDenormSingle(APFloatOfImm);
16493     }
16494     LLVM_FALLTHROUGH;
16495   case MVT::ppcf128:
16496     return Imm.isPosZero();
16497   }
16498 }
16499 
16500 // For vector shift operation op, fold
16501 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16502 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16503                                   SelectionDAG &DAG) {
16504   SDValue N0 = N->getOperand(0);
16505   SDValue N1 = N->getOperand(1);
16506   EVT VT = N0.getValueType();
16507   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16508   unsigned Opcode = N->getOpcode();
16509   unsigned TargetOpcode;
16510 
16511   switch (Opcode) {
16512   default:
16513     llvm_unreachable("Unexpected shift operation");
16514   case ISD::SHL:
16515     TargetOpcode = PPCISD::SHL;
16516     break;
16517   case ISD::SRL:
16518     TargetOpcode = PPCISD::SRL;
16519     break;
16520   case ISD::SRA:
16521     TargetOpcode = PPCISD::SRA;
16522     break;
16523   }
16524 
16525   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16526       N1->getOpcode() == ISD::AND)
16527     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16528       if (Mask->getZExtValue() == OpSizeInBits - 1)
16529         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16530 
16531   return SDValue();
16532 }
16533 
16534 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16535   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16536     return Value;
16537 
16538   SDValue N0 = N->getOperand(0);
16539   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16540   if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
16541       N0.getOpcode() != ISD::SIGN_EXTEND ||
16542       N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
16543       N->getValueType(0) != MVT::i64)
16544     return SDValue();
16545 
16546   // We can't save an operation here if the value is already extended, and
16547   // the existing shift is easier to combine.
16548   SDValue ExtsSrc = N0.getOperand(0);
16549   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16550       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16551     return SDValue();
16552 
16553   SDLoc DL(N0);
16554   SDValue ShiftBy = SDValue(CN1, 0);
16555   // We want the shift amount to be i32 on the extswli, but the shift could
16556   // have an i64.
16557   if (ShiftBy.getValueType() == MVT::i64)
16558     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16559 
16560   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16561                          ShiftBy);
16562 }
16563 
16564 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16565   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16566     return Value;
16567 
16568   return SDValue();
16569 }
16570 
16571 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16572   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16573     return Value;
16574 
16575   return SDValue();
16576 }
16577 
16578 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16579 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16580 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16581 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16582 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16583                                  const PPCSubtarget &Subtarget) {
16584   if (!Subtarget.isPPC64())
16585     return SDValue();
16586 
16587   SDValue LHS = N->getOperand(0);
16588   SDValue RHS = N->getOperand(1);
16589 
16590   auto isZextOfCompareWithConstant = [](SDValue Op) {
16591     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16592         Op.getValueType() != MVT::i64)
16593       return false;
16594 
16595     SDValue Cmp = Op.getOperand(0);
16596     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16597         Cmp.getOperand(0).getValueType() != MVT::i64)
16598       return false;
16599 
16600     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
16601       int64_t NegConstant = 0 - Constant->getSExtValue();
16602       // Due to the limitations of the addi instruction,
16603       // -C is required to be [-32768, 32767].
16604       return isInt<16>(NegConstant);
16605     }
16606 
16607     return false;
16608   };
16609 
16610   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
16611   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16612 
16613   // If there is a pattern, canonicalize a zext operand to the RHS.
16614   if (LHSHasPattern && !RHSHasPattern)
16615     std::swap(LHS, RHS);
16616   else if (!LHSHasPattern && !RHSHasPattern)
16617     return SDValue();
16618 
16619   SDLoc DL(N);
16620   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16621   SDValue Cmp = RHS.getOperand(0);
16622   SDValue Z = Cmp.getOperand(0);
16623   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
16624 
16625   assert(Constant && "Constant Should not be a null pointer.");
16626   int64_t NegConstant = 0 - Constant->getSExtValue();
16627 
16628   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16629   default: break;
16630   case ISD::SETNE: {
16631     //                                 when C == 0
16632     //                             --> addze X, (addic Z, -1).carry
16633     //                            /
16634     // add X, (zext(setne Z, C))--
16635     //                            \    when -32768 <= -C <= 32767 && C != 0
16636     //                             --> addze X, (addic (addi Z, -C), -1).carry
16637     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16638                               DAG.getConstant(NegConstant, DL, MVT::i64));
16639     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16640     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16641                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16642     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16643                        SDValue(Addc.getNode(), 1));
16644     }
16645   case ISD::SETEQ: {
16646     //                                 when C == 0
16647     //                             --> addze X, (subfic Z, 0).carry
16648     //                            /
16649     // add X, (zext(sete  Z, C))--
16650     //                            \    when -32768 <= -C <= 32767 && C != 0
16651     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16652     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16653                               DAG.getConstant(NegConstant, DL, MVT::i64));
16654     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16655     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16656                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16657     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16658                        SDValue(Subc.getNode(), 1));
16659     }
16660   }
16661 
16662   return SDValue();
16663 }
16664 
16665 // Transform
16666 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16667 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16668 // In this case both C1 and C2 must be known constants.
16669 // C1+C2 must fit into a 34 bit signed integer.
16670 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16671                                           const PPCSubtarget &Subtarget) {
16672   if (!Subtarget.isUsingPCRelativeCalls())
16673     return SDValue();
16674 
16675   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16676   // If we find that node try to cast the Global Address and the Constant.
16677   SDValue LHS = N->getOperand(0);
16678   SDValue RHS = N->getOperand(1);
16679 
16680   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16681     std::swap(LHS, RHS);
16682 
16683   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16684     return SDValue();
16685 
16686   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16687   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16688   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16689 
16690   // Check that both casts succeeded.
16691   if (!GSDN || !ConstNode)
16692     return SDValue();
16693 
16694   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16695   SDLoc DL(GSDN);
16696 
16697   // The signed int offset needs to fit in 34 bits.
16698   if (!isInt<34>(NewOffset))
16699     return SDValue();
16700 
16701   // The new global address is a copy of the old global address except
16702   // that it has the updated Offset.
16703   SDValue GA =
16704       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16705                                  NewOffset, GSDN->getTargetFlags());
16706   SDValue MatPCRel =
16707       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16708   return MatPCRel;
16709 }
16710 
16711 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16712   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16713     return Value;
16714 
16715   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16716     return Value;
16717 
16718   return SDValue();
16719 }
16720 
16721 // Detect TRUNCATE operations on bitcasts of float128 values.
16722 // What we are looking for here is the situtation where we extract a subset
16723 // of bits from a 128 bit float.
16724 // This can be of two forms:
16725 // 1) BITCAST of f128 feeding TRUNCATE
16726 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16727 // The reason this is required is because we do not have a legal i128 type
16728 // and so we want to prevent having to store the f128 and then reload part
16729 // of it.
16730 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16731                                            DAGCombinerInfo &DCI) const {
16732   // If we are using CRBits then try that first.
16733   if (Subtarget.useCRBits()) {
16734     // Check if CRBits did anything and return that if it did.
16735     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16736       return CRTruncValue;
16737   }
16738 
16739   SDLoc dl(N);
16740   SDValue Op0 = N->getOperand(0);
16741 
16742   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
16743   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
16744     EVT VT = N->getValueType(0);
16745     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16746       return SDValue();
16747     SDValue Sub = Op0.getOperand(0);
16748     if (Sub.getOpcode() == ISD::SUB) {
16749       SDValue SubOp0 = Sub.getOperand(0);
16750       SDValue SubOp1 = Sub.getOperand(1);
16751       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16752           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16753         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16754                                SubOp1.getOperand(0),
16755                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16756       }
16757     }
16758   }
16759 
16760   // Looking for a truncate of i128 to i64.
16761   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16762     return SDValue();
16763 
16764   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16765 
16766   // SRL feeding TRUNCATE.
16767   if (Op0.getOpcode() == ISD::SRL) {
16768     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16769     // The right shift has to be by 64 bits.
16770     if (!ConstNode || ConstNode->getZExtValue() != 64)
16771       return SDValue();
16772 
16773     // Switch the element number to extract.
16774     EltToExtract = EltToExtract ? 0 : 1;
16775     // Update Op0 past the SRL.
16776     Op0 = Op0.getOperand(0);
16777   }
16778 
16779   // BITCAST feeding a TRUNCATE possibly via SRL.
16780   if (Op0.getOpcode() == ISD::BITCAST &&
16781       Op0.getValueType() == MVT::i128 &&
16782       Op0.getOperand(0).getValueType() == MVT::f128) {
16783     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16784     return DCI.DAG.getNode(
16785         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16786         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16787   }
16788   return SDValue();
16789 }
16790 
16791 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16792   SelectionDAG &DAG = DCI.DAG;
16793 
16794   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16795   if (!ConstOpOrElement)
16796     return SDValue();
16797 
16798   // An imul is usually smaller than the alternative sequence for legal type.
16799   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16800       isOperationLegal(ISD::MUL, N->getValueType(0)))
16801     return SDValue();
16802 
16803   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16804     switch (this->Subtarget.getCPUDirective()) {
16805     default:
16806       // TODO: enhance the condition for subtarget before pwr8
16807       return false;
16808     case PPC::DIR_PWR8:
16809       //  type        mul     add    shl
16810       // scalar        4       1      1
16811       // vector        7       2      2
16812       return true;
16813     case PPC::DIR_PWR9:
16814     case PPC::DIR_PWR10:
16815     case PPC::DIR_PWR_FUTURE:
16816       //  type        mul     add    shl
16817       // scalar        5       2      2
16818       // vector        7       2      2
16819 
16820       // The cycle RATIO of related operations are showed as a table above.
16821       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16822       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16823       // are 4, it is always profitable; but for 3 instrs patterns
16824       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16825       // So we should only do it for vector type.
16826       return IsAddOne && IsNeg ? VT.isVector() : true;
16827     }
16828   };
16829 
16830   EVT VT = N->getValueType(0);
16831   SDLoc DL(N);
16832 
16833   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16834   bool IsNeg = MulAmt.isNegative();
16835   APInt MulAmtAbs = MulAmt.abs();
16836 
16837   if ((MulAmtAbs - 1).isPowerOf2()) {
16838     // (mul x, 2^N + 1) => (add (shl x, N), x)
16839     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16840 
16841     if (!IsProfitable(IsNeg, true, VT))
16842       return SDValue();
16843 
16844     SDValue Op0 = N->getOperand(0);
16845     SDValue Op1 =
16846         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16847                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16848     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16849 
16850     if (!IsNeg)
16851       return Res;
16852 
16853     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16854   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16855     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16856     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16857 
16858     if (!IsProfitable(IsNeg, false, VT))
16859       return SDValue();
16860 
16861     SDValue Op0 = N->getOperand(0);
16862     SDValue Op1 =
16863         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16864                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16865 
16866     if (!IsNeg)
16867       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16868     else
16869       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16870 
16871   } else {
16872     return SDValue();
16873   }
16874 }
16875 
16876 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16877 // in combiner since we need to check SD flags and other subtarget features.
16878 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16879                                           DAGCombinerInfo &DCI) const {
16880   SDValue N0 = N->getOperand(0);
16881   SDValue N1 = N->getOperand(1);
16882   SDValue N2 = N->getOperand(2);
16883   SDNodeFlags Flags = N->getFlags();
16884   EVT VT = N->getValueType(0);
16885   SelectionDAG &DAG = DCI.DAG;
16886   const TargetOptions &Options = getTargetMachine().Options;
16887   unsigned Opc = N->getOpcode();
16888   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16889   bool LegalOps = !DCI.isBeforeLegalizeOps();
16890   SDLoc Loc(N);
16891 
16892   if (!isOperationLegal(ISD::FMA, VT))
16893     return SDValue();
16894 
16895   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16896   // since (fnmsub a b c)=-0 while c-ab=+0.
16897   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16898     return SDValue();
16899 
16900   // (fma (fneg a) b c) => (fnmsub a b c)
16901   // (fnmsub (fneg a) b c) => (fma a b c)
16902   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16903     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16904 
16905   // (fma a (fneg b) c) => (fnmsub a b c)
16906   // (fnmsub a (fneg b) c) => (fma a b c)
16907   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16908     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16909 
16910   return SDValue();
16911 }
16912 
16913 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16914   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16915   if (!Subtarget.is64BitELFABI())
16916     return false;
16917 
16918   // If not a tail call then no need to proceed.
16919   if (!CI->isTailCall())
16920     return false;
16921 
16922   // If sibling calls have been disabled and tail-calls aren't guaranteed
16923   // there is no reason to duplicate.
16924   auto &TM = getTargetMachine();
16925   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16926     return false;
16927 
16928   // Can't tail call a function called indirectly, or if it has variadic args.
16929   const Function *Callee = CI->getCalledFunction();
16930   if (!Callee || Callee->isVarArg())
16931     return false;
16932 
16933   // Make sure the callee and caller calling conventions are eligible for tco.
16934   const Function *Caller = CI->getParent()->getParent();
16935   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16936                                            CI->getCallingConv()))
16937       return false;
16938 
16939   // If the function is local then we have a good chance at tail-calling it
16940   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16941 }
16942 
16943 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16944   if (!Subtarget.hasVSX())
16945     return false;
16946   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16947     return true;
16948   return VT == MVT::f32 || VT == MVT::f64 ||
16949     VT == MVT::v4f32 || VT == MVT::v2f64;
16950 }
16951 
16952 bool PPCTargetLowering::
16953 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16954   const Value *Mask = AndI.getOperand(1);
16955   // If the mask is suitable for andi. or andis. we should sink the and.
16956   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16957     // Can't handle constants wider than 64-bits.
16958     if (CI->getBitWidth() > 64)
16959       return false;
16960     int64_t ConstVal = CI->getZExtValue();
16961     return isUInt<16>(ConstVal) ||
16962       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16963   }
16964 
16965   // For non-constant masks, we can always use the record-form and.
16966   return true;
16967 }
16968 
16969 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16970 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16971 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16972 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16973 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16974 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16975   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16976   assert(Subtarget.hasP9Altivec() &&
16977          "Only combine this when P9 altivec supported!");
16978   EVT VT = N->getValueType(0);
16979   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16980     return SDValue();
16981 
16982   SelectionDAG &DAG = DCI.DAG;
16983   SDLoc dl(N);
16984   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16985     // Even for signed integers, if it's known to be positive (as signed
16986     // integer) due to zero-extended inputs.
16987     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16988     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16989     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16990          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16991         (SubOpcd1 == ISD::ZERO_EXTEND ||
16992          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16993       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16994                          N->getOperand(0)->getOperand(0),
16995                          N->getOperand(0)->getOperand(1),
16996                          DAG.getTargetConstant(0, dl, MVT::i32));
16997     }
16998 
16999     // For type v4i32, it can be optimized with xvnegsp + vabsduw
17000     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
17001         N->getOperand(0).hasOneUse()) {
17002       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17003                          N->getOperand(0)->getOperand(0),
17004                          N->getOperand(0)->getOperand(1),
17005                          DAG.getTargetConstant(1, dl, MVT::i32));
17006     }
17007   }
17008 
17009   return SDValue();
17010 }
17011 
17012 // For type v4i32/v8ii16/v16i8, transform
17013 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
17014 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
17015 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
17016 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
17017 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
17018                                           DAGCombinerInfo &DCI) const {
17019   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
17020   assert(Subtarget.hasP9Altivec() &&
17021          "Only combine this when P9 altivec supported!");
17022 
17023   SelectionDAG &DAG = DCI.DAG;
17024   SDLoc dl(N);
17025   SDValue Cond = N->getOperand(0);
17026   SDValue TrueOpnd = N->getOperand(1);
17027   SDValue FalseOpnd = N->getOperand(2);
17028   EVT VT = N->getOperand(1).getValueType();
17029 
17030   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
17031       FalseOpnd.getOpcode() != ISD::SUB)
17032     return SDValue();
17033 
17034   // ABSD only available for type v4i32/v8i16/v16i8
17035   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17036     return SDValue();
17037 
17038   // At least to save one more dependent computation
17039   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
17040     return SDValue();
17041 
17042   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17043 
17044   // Can only handle unsigned comparison here
17045   switch (CC) {
17046   default:
17047     return SDValue();
17048   case ISD::SETUGT:
17049   case ISD::SETUGE:
17050     break;
17051   case ISD::SETULT:
17052   case ISD::SETULE:
17053     std::swap(TrueOpnd, FalseOpnd);
17054     break;
17055   }
17056 
17057   SDValue CmpOpnd1 = Cond.getOperand(0);
17058   SDValue CmpOpnd2 = Cond.getOperand(1);
17059 
17060   // SETCC CmpOpnd1 CmpOpnd2 cond
17061   // TrueOpnd = CmpOpnd1 - CmpOpnd2
17062   // FalseOpnd = CmpOpnd2 - CmpOpnd1
17063   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
17064       TrueOpnd.getOperand(1) == CmpOpnd2 &&
17065       FalseOpnd.getOperand(0) == CmpOpnd2 &&
17066       FalseOpnd.getOperand(1) == CmpOpnd1) {
17067     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
17068                        CmpOpnd1, CmpOpnd2,
17069                        DAG.getTargetConstant(0, dl, MVT::i32));
17070   }
17071 
17072   return SDValue();
17073 }
17074