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     } else {
238       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom);
239       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom);
240       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
241       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
242     }
243 
244     // PowerPC does not support direct load/store of condition registers.
245     setOperationAction(ISD::LOAD, MVT::i1, Custom);
246     setOperationAction(ISD::STORE, MVT::i1, Custom);
247 
248     // FIXME: Remove this once the ANDI glue bug is fixed:
249     if (ANDIGlueBug)
250       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
251 
252     for (MVT VT : MVT::integer_valuetypes()) {
253       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
254       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
255       setTruncStoreAction(VT, MVT::i1, Expand);
256     }
257 
258     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
259   }
260 
261   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
262   // PPC (the libcall is not available).
263   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
264   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
265   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom);
266   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom);
267 
268   // We do not currently implement these libm ops for PowerPC.
269   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
270   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
271   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
272   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
273   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
274   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
275 
276   // PowerPC has no SREM/UREM instructions unless we are on P9
277   // On P9 we may use a hardware instruction to compute the remainder.
278   // When the result of both the remainder and the division is required it is
279   // more efficient to compute the remainder from the result of the division
280   // rather than use the remainder instruction. The instructions are legalized
281   // directly because the DivRemPairsPass performs the transformation at the IR
282   // level.
283   if (Subtarget.isISA3_0()) {
284     setOperationAction(ISD::SREM, MVT::i32, Legal);
285     setOperationAction(ISD::UREM, MVT::i32, Legal);
286     setOperationAction(ISD::SREM, MVT::i64, Legal);
287     setOperationAction(ISD::UREM, MVT::i64, Legal);
288   } else {
289     setOperationAction(ISD::SREM, MVT::i32, Expand);
290     setOperationAction(ISD::UREM, MVT::i32, Expand);
291     setOperationAction(ISD::SREM, MVT::i64, Expand);
292     setOperationAction(ISD::UREM, MVT::i64, Expand);
293   }
294 
295   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
296   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
297   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
298   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
299   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
300   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
301   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
302   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
303   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
304 
305   // Handle constrained floating-point operations of scalar.
306   // TODO: Handle SPE specific operation.
307   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
308   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
309   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
310   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
311   setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
312   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
313 
314   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
315   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
316   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
317   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
318   setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
319   if (Subtarget.hasVSX()) {
320     setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal);
321     setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal);
322   }
323 
324   if (Subtarget.hasFSQRT()) {
325     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
326     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
327   }
328 
329   if (Subtarget.hasFPRND()) {
330     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
331     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
332     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
333     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
334 
335     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
336     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
337     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
338     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
339   }
340 
341   // We don't support sin/cos/sqrt/fmod/pow
342   setOperationAction(ISD::FSIN , MVT::f64, Expand);
343   setOperationAction(ISD::FCOS , MVT::f64, Expand);
344   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
345   setOperationAction(ISD::FREM , MVT::f64, Expand);
346   setOperationAction(ISD::FPOW , MVT::f64, Expand);
347   setOperationAction(ISD::FSIN , MVT::f32, Expand);
348   setOperationAction(ISD::FCOS , MVT::f32, Expand);
349   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
350   setOperationAction(ISD::FREM , MVT::f32, Expand);
351   setOperationAction(ISD::FPOW , MVT::f32, Expand);
352   if (Subtarget.hasSPE()) {
353     setOperationAction(ISD::FMA  , MVT::f64, Expand);
354     setOperationAction(ISD::FMA  , MVT::f32, Expand);
355   } else {
356     setOperationAction(ISD::FMA  , MVT::f64, Legal);
357     setOperationAction(ISD::FMA  , MVT::f32, Legal);
358   }
359 
360   if (Subtarget.hasSPE())
361     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
362 
363   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
364 
365   // If we're enabling GP optimizations, use hardware square root
366   if (!Subtarget.hasFSQRT() &&
367       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
368         Subtarget.hasFRE()))
369     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
370 
371   if (!Subtarget.hasFSQRT() &&
372       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
373         Subtarget.hasFRES()))
374     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
375 
376   if (Subtarget.hasFCPSGN()) {
377     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
378     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
379   } else {
380     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
381     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
382   }
383 
384   if (Subtarget.hasFPRND()) {
385     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
386     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
387     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
388     setOperationAction(ISD::FROUND, MVT::f64, Legal);
389 
390     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
391     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
392     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
393     setOperationAction(ISD::FROUND, MVT::f32, Legal);
394   }
395 
396   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
397   // to speed up scalar BSWAP64.
398   // CTPOP or CTTZ were introduced in P8/P9 respectively
399   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
400   if (Subtarget.hasP9Vector())
401     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
402   else
403     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
404   if (Subtarget.isISA3_0()) {
405     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
406     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
407   } else {
408     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
409     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
410   }
411 
412   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
413     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
414     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
415   } else {
416     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
417     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
418   }
419 
420   // PowerPC does not have ROTR
421   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
422   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
423 
424   if (!Subtarget.useCRBits()) {
425     // PowerPC does not have Select
426     setOperationAction(ISD::SELECT, MVT::i32, Expand);
427     setOperationAction(ISD::SELECT, MVT::i64, Expand);
428     setOperationAction(ISD::SELECT, MVT::f32, Expand);
429     setOperationAction(ISD::SELECT, MVT::f64, Expand);
430   }
431 
432   // PowerPC wants to turn select_cc of FP into fsel when possible.
433   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
434   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
435 
436   // PowerPC wants to optimize integer setcc a bit
437   if (!Subtarget.useCRBits())
438     setOperationAction(ISD::SETCC, MVT::i32, Custom);
439 
440   if (Subtarget.hasFPU()) {
441     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
442     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
443     setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
444 
445     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
446     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
447     setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
448   }
449 
450   // PowerPC does not have BRCOND which requires SetCC
451   if (!Subtarget.useCRBits())
452     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
453 
454   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
455 
456   if (Subtarget.hasSPE()) {
457     // SPE has built-in conversions
458     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
459     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
460     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
461     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
462     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
463     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
464   } else {
465     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
466     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
467     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
468 
469     // PowerPC does not have [U|S]INT_TO_FP
470     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand);
471     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand);
472     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
473     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
474   }
475 
476   if (Subtarget.hasDirectMove() && isPPC64) {
477     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
478     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
479     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
480     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
481     if (TM.Options.UnsafeFPMath) {
482       setOperationAction(ISD::LRINT, MVT::f64, Legal);
483       setOperationAction(ISD::LRINT, MVT::f32, Legal);
484       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
485       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
486       setOperationAction(ISD::LROUND, MVT::f64, Legal);
487       setOperationAction(ISD::LROUND, MVT::f32, Legal);
488       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
489       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
490     }
491   } else {
492     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
493     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
494     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
495     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
496   }
497 
498   // We cannot sextinreg(i1).  Expand to shifts.
499   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
500 
501   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
502   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
503   // support continuation, user-level threading, and etc.. As a result, no
504   // other SjLj exception interfaces are implemented and please don't build
505   // your own exception handling based on them.
506   // LLVM/Clang supports zero-cost DWARF exception handling.
507   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
508   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
509 
510   // We want to legalize GlobalAddress and ConstantPool nodes into the
511   // appropriate instructions to materialize the address.
512   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
513   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
514   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
515   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
516   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
517   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
518   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
519   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
520   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
521   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
522 
523   // TRAP is legal.
524   setOperationAction(ISD::TRAP, MVT::Other, Legal);
525 
526   // TRAMPOLINE is custom lowered.
527   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
528   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
529 
530   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
531   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
532 
533   if (Subtarget.is64BitELFABI()) {
534     // VAARG always uses double-word chunks, so promote anything smaller.
535     setOperationAction(ISD::VAARG, MVT::i1, Promote);
536     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
537     setOperationAction(ISD::VAARG, MVT::i8, Promote);
538     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
539     setOperationAction(ISD::VAARG, MVT::i16, Promote);
540     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
541     setOperationAction(ISD::VAARG, MVT::i32, Promote);
542     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
543     setOperationAction(ISD::VAARG, MVT::Other, Expand);
544   } else if (Subtarget.is32BitELFABI()) {
545     // VAARG is custom lowered with the 32-bit SVR4 ABI.
546     setOperationAction(ISD::VAARG, MVT::Other, Custom);
547     setOperationAction(ISD::VAARG, MVT::i64, Custom);
548   } else
549     setOperationAction(ISD::VAARG, MVT::Other, Expand);
550 
551   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
552   if (Subtarget.is32BitELFABI())
553     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
554   else
555     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
556 
557   // Use the default implementation.
558   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
559   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
560   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
561   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
562   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
563   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
564   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
565   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
566   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
567 
568   // We want to custom lower some of our intrinsics.
569   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
570 
571   // To handle counter-based loop conditions.
572   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
573 
574   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
575   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
576   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
577   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
578 
579   // Comparisons that require checking two conditions.
580   if (Subtarget.hasSPE()) {
581     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
582     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
583     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
584     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
585   }
586   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
587   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
588   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
589   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
590   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
591   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
592   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
593   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
594   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
595   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
596   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
597   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
598 
599   if (Subtarget.has64BitSupport()) {
600     // They also have instructions for converting between i64 and fp.
601     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
602     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
603     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
604     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
605     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
606     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
607     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
608     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
609     // This is just the low 32 bits of a (signed) fp->i64 conversion.
610     // We cannot do this with Promote because i64 is not a legal type.
611     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
612     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
613 
614     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
615       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
616       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
617     }
618   } else {
619     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
620     if (Subtarget.hasSPE()) {
621       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
622       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
623     } else {
624       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
625       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
626     }
627   }
628 
629   // With the instructions enabled under FPCVT, we can do everything.
630   if (Subtarget.hasFPCVT()) {
631     if (Subtarget.has64BitSupport()) {
632       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
633       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
634       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
635       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
636       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
637       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
638       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
639       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
640     }
641 
642     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
643     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
644     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
645     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
646     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
647     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
648     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
649     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
650   }
651 
652   if (Subtarget.use64BitRegs()) {
653     // 64-bit PowerPC implementations can support i64 types directly
654     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
655     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
656     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
657     // 64-bit PowerPC wants to expand i128 shifts itself.
658     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
659     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
660     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
661   } else {
662     // 32-bit PowerPC wants to expand i64 shifts itself.
663     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
664     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
665     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
666   }
667 
668   // PowerPC has better expansions for funnel shifts than the generic
669   // TargetLowering::expandFunnelShift.
670   if (Subtarget.has64BitSupport()) {
671     setOperationAction(ISD::FSHL, MVT::i64, Custom);
672     setOperationAction(ISD::FSHR, MVT::i64, Custom);
673   }
674   setOperationAction(ISD::FSHL, MVT::i32, Custom);
675   setOperationAction(ISD::FSHR, MVT::i32, Custom);
676 
677   if (Subtarget.hasVSX()) {
678     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
679     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
680     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
681     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
682   }
683 
684   if (Subtarget.hasAltivec()) {
685     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
686       setOperationAction(ISD::SADDSAT, VT, Legal);
687       setOperationAction(ISD::SSUBSAT, VT, Legal);
688       setOperationAction(ISD::UADDSAT, VT, Legal);
689       setOperationAction(ISD::USUBSAT, VT, Legal);
690     }
691     // First set operation action for all vector types to expand. Then we
692     // will selectively turn on ones that can be effectively codegen'd.
693     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
694       // add/sub are legal for all supported vector VT's.
695       setOperationAction(ISD::ADD, VT, Legal);
696       setOperationAction(ISD::SUB, VT, Legal);
697 
698       // For v2i64, these are only valid with P8Vector. This is corrected after
699       // the loop.
700       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
701         setOperationAction(ISD::SMAX, VT, Legal);
702         setOperationAction(ISD::SMIN, VT, Legal);
703         setOperationAction(ISD::UMAX, VT, Legal);
704         setOperationAction(ISD::UMIN, VT, Legal);
705       }
706       else {
707         setOperationAction(ISD::SMAX, VT, Expand);
708         setOperationAction(ISD::SMIN, VT, Expand);
709         setOperationAction(ISD::UMAX, VT, Expand);
710         setOperationAction(ISD::UMIN, VT, Expand);
711       }
712 
713       if (Subtarget.hasVSX()) {
714         setOperationAction(ISD::FMAXNUM, VT, Legal);
715         setOperationAction(ISD::FMINNUM, VT, Legal);
716       }
717 
718       // Vector instructions introduced in P8
719       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
720         setOperationAction(ISD::CTPOP, VT, Legal);
721         setOperationAction(ISD::CTLZ, VT, Legal);
722       }
723       else {
724         setOperationAction(ISD::CTPOP, VT, Expand);
725         setOperationAction(ISD::CTLZ, VT, Expand);
726       }
727 
728       // Vector instructions introduced in P9
729       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
730         setOperationAction(ISD::CTTZ, VT, Legal);
731       else
732         setOperationAction(ISD::CTTZ, VT, Expand);
733 
734       // We promote all shuffles to v16i8.
735       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
736       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
737 
738       // We promote all non-typed operations to v4i32.
739       setOperationAction(ISD::AND   , VT, Promote);
740       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
741       setOperationAction(ISD::OR    , VT, Promote);
742       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
743       setOperationAction(ISD::XOR   , VT, Promote);
744       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
745       setOperationAction(ISD::LOAD  , VT, Promote);
746       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
747       setOperationAction(ISD::SELECT, VT, Promote);
748       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
749       setOperationAction(ISD::VSELECT, VT, Legal);
750       setOperationAction(ISD::SELECT_CC, VT, Promote);
751       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
752       setOperationAction(ISD::STORE, VT, Promote);
753       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
754 
755       // No other operations are legal.
756       setOperationAction(ISD::MUL , VT, Expand);
757       setOperationAction(ISD::SDIV, VT, Expand);
758       setOperationAction(ISD::SREM, VT, Expand);
759       setOperationAction(ISD::UDIV, VT, Expand);
760       setOperationAction(ISD::UREM, VT, Expand);
761       setOperationAction(ISD::FDIV, VT, Expand);
762       setOperationAction(ISD::FREM, VT, Expand);
763       setOperationAction(ISD::FNEG, VT, Expand);
764       setOperationAction(ISD::FSQRT, VT, Expand);
765       setOperationAction(ISD::FLOG, VT, Expand);
766       setOperationAction(ISD::FLOG10, VT, Expand);
767       setOperationAction(ISD::FLOG2, VT, Expand);
768       setOperationAction(ISD::FEXP, VT, Expand);
769       setOperationAction(ISD::FEXP2, VT, Expand);
770       setOperationAction(ISD::FSIN, VT, Expand);
771       setOperationAction(ISD::FCOS, VT, Expand);
772       setOperationAction(ISD::FABS, VT, Expand);
773       setOperationAction(ISD::FFLOOR, VT, Expand);
774       setOperationAction(ISD::FCEIL,  VT, Expand);
775       setOperationAction(ISD::FTRUNC, VT, Expand);
776       setOperationAction(ISD::FRINT,  VT, Expand);
777       setOperationAction(ISD::FNEARBYINT, VT, Expand);
778       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
779       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
780       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
781       setOperationAction(ISD::MULHU, VT, Expand);
782       setOperationAction(ISD::MULHS, VT, Expand);
783       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
784       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
785       setOperationAction(ISD::UDIVREM, VT, Expand);
786       setOperationAction(ISD::SDIVREM, VT, Expand);
787       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
788       setOperationAction(ISD::FPOW, VT, Expand);
789       setOperationAction(ISD::BSWAP, VT, Expand);
790       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
791       setOperationAction(ISD::ROTL, VT, Expand);
792       setOperationAction(ISD::ROTR, VT, Expand);
793 
794       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
795         setTruncStoreAction(VT, InnerVT, Expand);
796         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
797         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
798         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
799       }
800     }
801     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
802     if (!Subtarget.hasP8Vector()) {
803       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
804       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
805       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
806       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
807     }
808 
809     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
810     // with merges, splats, etc.
811     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
812 
813     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
814     // are cheap, so handle them before they get expanded to scalar.
815     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
816     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
817     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
818     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
819     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
820 
821     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
822     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
823     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
824     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
825     setOperationAction(ISD::SELECT, MVT::v4i32,
826                        Subtarget.useCRBits() ? Legal : Expand);
827     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
828     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
829     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
830     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
831     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
832     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
833     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
834     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
835     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
836     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
837     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
838     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
839     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
840 
841     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
842     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
843     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
844     if (Subtarget.hasAltivec())
845       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
846         setOperationAction(ISD::ROTL, VT, Legal);
847     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
848     if (Subtarget.hasP8Altivec())
849       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
850 
851     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
852     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
853     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
854     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
855 
856     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
857     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
858 
859     if (Subtarget.hasVSX()) {
860       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
861       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
862     }
863 
864     if (Subtarget.hasP8Altivec())
865       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
866     else
867       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
868 
869     if (Subtarget.isISA3_1()) {
870       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
871       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
872       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
873       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
874       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
875       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
876       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
877       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
878       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
879       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
880       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
881       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
882       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
883       setOperationAction(ISD::UREM, MVT::v1i128, Legal);
884       setOperationAction(ISD::SREM, MVT::v1i128, Legal);
885       setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
886       setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
887       setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
888     }
889 
890     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
891     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
892 
893     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
894     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
895 
896     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
897     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
898     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
899     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
900 
901     // Altivec does not contain unordered floating-point compare instructions
902     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
903     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
904     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
905     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
906 
907     if (Subtarget.hasVSX()) {
908       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
909       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
910       if (Subtarget.hasP8Vector()) {
911         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
912         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
913       }
914       if (Subtarget.hasDirectMove() && isPPC64) {
915         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
916         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
917         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
918         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
919         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
920         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
921         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
922         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
923       }
924       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
925 
926       // The nearbyint variants are not allowed to raise the inexact exception
927       // so we can only code-gen them with unsafe math.
928       if (TM.Options.UnsafeFPMath) {
929         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
930         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
931       }
932 
933       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
934       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
935       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
936       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
937       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
938       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
939       setOperationAction(ISD::FROUND, MVT::f64, Legal);
940       setOperationAction(ISD::FRINT, MVT::f64, Legal);
941 
942       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
943       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
944       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
945       setOperationAction(ISD::FROUND, MVT::f32, Legal);
946       setOperationAction(ISD::FRINT, MVT::f32, Legal);
947 
948       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
949       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
950 
951       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
952       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
953 
954       // Share the Altivec comparison restrictions.
955       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
956       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
957       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
958       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
959 
960       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
961       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
962 
963       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
964 
965       if (Subtarget.hasP8Vector())
966         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
967 
968       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
969 
970       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
971       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
972       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
973 
974       if (Subtarget.hasP8Altivec()) {
975         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
976         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
977         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
978 
979         // 128 bit shifts can be accomplished via 3 instructions for SHL and
980         // SRL, but not for SRA because of the instructions available:
981         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
982         // doing
983         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
984         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
985         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
986 
987         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
988       }
989       else {
990         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
991         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
992         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
993 
994         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
995 
996         // VSX v2i64 only supports non-arithmetic operations.
997         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
998         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
999       }
1000 
1001       if (Subtarget.isISA3_1())
1002         setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1003       else
1004         setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1005 
1006       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1007       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1008       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1009       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1010 
1011       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
1012 
1013       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1014       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1015       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1016       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1017       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1018       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1019       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1020       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1021 
1022       // Custom handling for partial vectors of integers converted to
1023       // floating point. We already have optimal handling for v2i32 through
1024       // the DAG combine, so those aren't necessary.
1025       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1026       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1027       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1028       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1029       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1030       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1031       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1032       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1033       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1034       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1035       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1036       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1037       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1038       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1039       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1040       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1041 
1042       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1043       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1044       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1045       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1046       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1047       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1048 
1049       if (Subtarget.hasDirectMove())
1050         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1051       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1052 
1053       // Handle constrained floating-point operations of vector.
1054       // The predictor is `hasVSX` because altivec instruction has
1055       // no exception but VSX vector instruction has.
1056       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1057       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1058       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1059       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1060       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1061       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1062       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1063       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1064       setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
1065       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1066       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1067       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1068       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1069 
1070       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1071       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1072       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1073       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1074       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1075       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1076       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1077       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1078       setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
1079       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1080       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1081       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1082       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1083 
1084       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1085     }
1086 
1087     if (Subtarget.hasP8Altivec()) {
1088       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1089       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1090     }
1091 
1092     if (Subtarget.hasP9Vector()) {
1093       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1094       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1095 
1096       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1097       // SRL, but not for SRA because of the instructions available:
1098       // VS{RL} and VS{RL}O.
1099       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1100       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1101       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1102 
1103       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1104       setOperationAction(ISD::FADD, MVT::f128, Legal);
1105       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1106       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1107       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1108       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1109       // No extending loads to f128 on PPC.
1110       for (MVT FPT : MVT::fp_valuetypes())
1111         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1112       setOperationAction(ISD::FMA, MVT::f128, Legal);
1113       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1114       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1115       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1116       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1117       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1118       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1119 
1120       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1121       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1122       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1123       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1124       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1125       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1126 
1127       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1128       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1129       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1130       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1131       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1132       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1133       // No implementation for these ops for PowerPC.
1134       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1135       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1136       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1137       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1138       setOperationAction(ISD::FREM, MVT::f128, Expand);
1139 
1140       // Handle constrained floating-point operations of fp128
1141       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1142       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1143       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1144       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1145       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1146       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1147       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1148       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1149       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1150       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1151       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1152       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1153       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1154       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1155       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1156       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1157       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1158       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1159       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1160       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1161     } else if (Subtarget.hasAltivec() && EnableSoftFP128) {
1162       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1163 
1164       for (MVT FPT : MVT::fp_valuetypes())
1165         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1166 
1167       setOperationAction(ISD::LOAD, MVT::f128, Promote);
1168       setOperationAction(ISD::STORE, MVT::f128, Promote);
1169 
1170       AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
1171       AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
1172 
1173       setOperationAction(ISD::FADD, MVT::f128, Expand);
1174       setOperationAction(ISD::FSUB, MVT::f128, Expand);
1175       setOperationAction(ISD::FMUL, MVT::f128, Expand);
1176       setOperationAction(ISD::FDIV, MVT::f128, Expand);
1177       setOperationAction(ISD::FNEG, MVT::f128, Expand);
1178       setOperationAction(ISD::FABS, MVT::f128, Expand);
1179       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1180       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1181       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1182       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1183       setOperationAction(ISD::FREM, MVT::f128, Expand);
1184       setOperationAction(ISD::FSQRT, MVT::f128, Expand);
1185       setOperationAction(ISD::FMA, MVT::f128, Expand);
1186       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
1187     }
1188 
1189     if (Subtarget.hasP9Altivec()) {
1190       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1191       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1192 
1193       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1194       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1195       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1196       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1197       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1198       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1199       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1200     }
1201   }
1202 
1203   if (Subtarget.pairedVectorMemops()) {
1204     addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1205     setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1206     setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1207   }
1208   if (Subtarget.hasMMA()) {
1209     addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1210     setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1211     setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1212     setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom);
1213   }
1214 
1215   if (Subtarget.has64BitSupport())
1216     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1217 
1218   if (Subtarget.isISA3_1())
1219     setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1220 
1221   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1222 
1223   if (!isPPC64) {
1224     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1225     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1226   }
1227 
1228   setBooleanContents(ZeroOrOneBooleanContent);
1229 
1230   if (Subtarget.hasAltivec()) {
1231     // Altivec instructions set fields to all zeros or all ones.
1232     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1233   }
1234 
1235   if (!isPPC64) {
1236     // These libcalls are not available in 32-bit.
1237     setLibcallName(RTLIB::SHL_I128, nullptr);
1238     setLibcallName(RTLIB::SRL_I128, nullptr);
1239     setLibcallName(RTLIB::SRA_I128, nullptr);
1240   }
1241 
1242   if (!isPPC64)
1243     setMaxAtomicSizeInBitsSupported(32);
1244 
1245   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1246 
1247   // We have target-specific dag combine patterns for the following nodes:
1248   setTargetDAGCombine(ISD::ADD);
1249   setTargetDAGCombine(ISD::SHL);
1250   setTargetDAGCombine(ISD::SRA);
1251   setTargetDAGCombine(ISD::SRL);
1252   setTargetDAGCombine(ISD::MUL);
1253   setTargetDAGCombine(ISD::FMA);
1254   setTargetDAGCombine(ISD::SINT_TO_FP);
1255   setTargetDAGCombine(ISD::BUILD_VECTOR);
1256   if (Subtarget.hasFPCVT())
1257     setTargetDAGCombine(ISD::UINT_TO_FP);
1258   setTargetDAGCombine(ISD::LOAD);
1259   setTargetDAGCombine(ISD::STORE);
1260   setTargetDAGCombine(ISD::BR_CC);
1261   if (Subtarget.useCRBits())
1262     setTargetDAGCombine(ISD::BRCOND);
1263   setTargetDAGCombine(ISD::BSWAP);
1264   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1265   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1266   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1267 
1268   setTargetDAGCombine(ISD::SIGN_EXTEND);
1269   setTargetDAGCombine(ISD::ZERO_EXTEND);
1270   setTargetDAGCombine(ISD::ANY_EXTEND);
1271 
1272   setTargetDAGCombine(ISD::TRUNCATE);
1273   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1274 
1275 
1276   if (Subtarget.useCRBits()) {
1277     setTargetDAGCombine(ISD::TRUNCATE);
1278     setTargetDAGCombine(ISD::SETCC);
1279     setTargetDAGCombine(ISD::SELECT_CC);
1280   }
1281 
1282   if (Subtarget.hasP9Altivec()) {
1283     setTargetDAGCombine(ISD::ABS);
1284     setTargetDAGCombine(ISD::VSELECT);
1285   }
1286 
1287   setLibcallName(RTLIB::LOG_F128, "logf128");
1288   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1289   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1290   setLibcallName(RTLIB::EXP_F128, "expf128");
1291   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1292   setLibcallName(RTLIB::SIN_F128, "sinf128");
1293   setLibcallName(RTLIB::COS_F128, "cosf128");
1294   setLibcallName(RTLIB::POW_F128, "powf128");
1295   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1296   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1297   setLibcallName(RTLIB::POWI_F128, "__powikf2");
1298   setLibcallName(RTLIB::REM_F128, "fmodf128");
1299 
1300   // With 32 condition bits, we don't need to sink (and duplicate) compares
1301   // aggressively in CodeGenPrep.
1302   if (Subtarget.useCRBits()) {
1303     setHasMultipleConditionRegisters();
1304     setJumpIsExpensive();
1305   }
1306 
1307   setMinFunctionAlignment(Align(4));
1308 
1309   switch (Subtarget.getCPUDirective()) {
1310   default: break;
1311   case PPC::DIR_970:
1312   case PPC::DIR_A2:
1313   case PPC::DIR_E500:
1314   case PPC::DIR_E500mc:
1315   case PPC::DIR_E5500:
1316   case PPC::DIR_PWR4:
1317   case PPC::DIR_PWR5:
1318   case PPC::DIR_PWR5X:
1319   case PPC::DIR_PWR6:
1320   case PPC::DIR_PWR6X:
1321   case PPC::DIR_PWR7:
1322   case PPC::DIR_PWR8:
1323   case PPC::DIR_PWR9:
1324   case PPC::DIR_PWR10:
1325   case PPC::DIR_PWR_FUTURE:
1326     setPrefLoopAlignment(Align(16));
1327     setPrefFunctionAlignment(Align(16));
1328     break;
1329   }
1330 
1331   if (Subtarget.enableMachineScheduler())
1332     setSchedulingPreference(Sched::Source);
1333   else
1334     setSchedulingPreference(Sched::Hybrid);
1335 
1336   computeRegisterProperties(STI.getRegisterInfo());
1337 
1338   // The Freescale cores do better with aggressive inlining of memcpy and
1339   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1340   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1341       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1342     MaxStoresPerMemset = 32;
1343     MaxStoresPerMemsetOptSize = 16;
1344     MaxStoresPerMemcpy = 32;
1345     MaxStoresPerMemcpyOptSize = 8;
1346     MaxStoresPerMemmove = 32;
1347     MaxStoresPerMemmoveOptSize = 8;
1348   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1349     // The A2 also benefits from (very) aggressive inlining of memcpy and
1350     // friends. The overhead of a the function call, even when warm, can be
1351     // over one hundred cycles.
1352     MaxStoresPerMemset = 128;
1353     MaxStoresPerMemcpy = 128;
1354     MaxStoresPerMemmove = 128;
1355     MaxLoadsPerMemcmp = 128;
1356   } else {
1357     MaxLoadsPerMemcmp = 8;
1358     MaxLoadsPerMemcmpOptSize = 4;
1359   }
1360 
1361   IsStrictFPEnabled = true;
1362 
1363   // Let the subtarget (CPU) decide if a predictable select is more expensive
1364   // than the corresponding branch. This information is used in CGP to decide
1365   // when to convert selects into branches.
1366   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1367 }
1368 
1369 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1370 /// the desired ByVal argument alignment.
1371 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1372   if (MaxAlign == MaxMaxAlign)
1373     return;
1374   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1375     if (MaxMaxAlign >= 32 &&
1376         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1377       MaxAlign = Align(32);
1378     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1379              MaxAlign < 16)
1380       MaxAlign = Align(16);
1381   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1382     Align EltAlign;
1383     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1384     if (EltAlign > MaxAlign)
1385       MaxAlign = EltAlign;
1386   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1387     for (auto *EltTy : STy->elements()) {
1388       Align EltAlign;
1389       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1390       if (EltAlign > MaxAlign)
1391         MaxAlign = EltAlign;
1392       if (MaxAlign == MaxMaxAlign)
1393         break;
1394     }
1395   }
1396 }
1397 
1398 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1399 /// function arguments in the caller parameter area.
1400 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1401                                                   const DataLayout &DL) const {
1402   // 16byte and wider vectors are passed on 16byte boundary.
1403   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1404   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1405   if (Subtarget.hasAltivec())
1406     getMaxByValAlign(Ty, Alignment, Align(16));
1407   return Alignment.value();
1408 }
1409 
1410 bool PPCTargetLowering::useSoftFloat() const {
1411   return Subtarget.useSoftFloat();
1412 }
1413 
1414 bool PPCTargetLowering::hasSPE() const {
1415   return Subtarget.hasSPE();
1416 }
1417 
1418 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1419   return VT.isScalarInteger();
1420 }
1421 
1422 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1423   switch ((PPCISD::NodeType)Opcode) {
1424   case PPCISD::FIRST_NUMBER:    break;
1425   case PPCISD::FSEL:            return "PPCISD::FSEL";
1426   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1427   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1428   case PPCISD::FCFID:           return "PPCISD::FCFID";
1429   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1430   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1431   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1432   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1433   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1434   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1435   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1436   case PPCISD::FP_TO_UINT_IN_VSR:
1437                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1438   case PPCISD::FP_TO_SINT_IN_VSR:
1439                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1440   case PPCISD::FRE:             return "PPCISD::FRE";
1441   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1442   case PPCISD::FTSQRT:
1443     return "PPCISD::FTSQRT";
1444   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1445   case PPCISD::VPERM:           return "PPCISD::VPERM";
1446   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1447   case PPCISD::XXSPLTI_SP_TO_DP:
1448     return "PPCISD::XXSPLTI_SP_TO_DP";
1449   case PPCISD::XXSPLTI32DX:
1450     return "PPCISD::XXSPLTI32DX";
1451   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1452   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1453   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1454   case PPCISD::CMPB:            return "PPCISD::CMPB";
1455   case PPCISD::Hi:              return "PPCISD::Hi";
1456   case PPCISD::Lo:              return "PPCISD::Lo";
1457   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1458   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1459   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1460   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1461   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1462   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1463   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1464   case PPCISD::SRL:             return "PPCISD::SRL";
1465   case PPCISD::SRA:             return "PPCISD::SRA";
1466   case PPCISD::SHL:             return "PPCISD::SHL";
1467   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1468   case PPCISD::CALL:            return "PPCISD::CALL";
1469   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1470   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1471   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1472   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1473   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1474   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1475   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1476   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1477   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1478   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1479   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1480   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1481   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1482   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1483   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1484   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1485     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1486   case PPCISD::ANDI_rec_1_EQ_BIT:
1487     return "PPCISD::ANDI_rec_1_EQ_BIT";
1488   case PPCISD::ANDI_rec_1_GT_BIT:
1489     return "PPCISD::ANDI_rec_1_GT_BIT";
1490   case PPCISD::VCMP:            return "PPCISD::VCMP";
1491   case PPCISD::VCMP_rec:        return "PPCISD::VCMP_rec";
1492   case PPCISD::LBRX:            return "PPCISD::LBRX";
1493   case PPCISD::STBRX:           return "PPCISD::STBRX";
1494   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1495   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1496   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1497   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1498   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1499   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1500   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1501   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1502   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1503   case PPCISD::ST_VSR_SCAL_INT:
1504                                 return "PPCISD::ST_VSR_SCAL_INT";
1505   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1506   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1507   case PPCISD::BDZ:             return "PPCISD::BDZ";
1508   case PPCISD::MFFS:            return "PPCISD::MFFS";
1509   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1510   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1511   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1512   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1513   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1514   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1515   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1516   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1517   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1518   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1519   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1520   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1521   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1522   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1523   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1524   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1525   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1526   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1527   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1528   case PPCISD::PADDI_DTPREL:
1529     return "PPCISD::PADDI_DTPREL";
1530   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1531   case PPCISD::SC:              return "PPCISD::SC";
1532   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1533   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1534   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1535   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1536   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1537   case PPCISD::VABSD:           return "PPCISD::VABSD";
1538   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1539   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1540   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1541   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1542   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1543   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1544   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1545   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1546     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1547   case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1548     return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1549   case PPCISD::ACC_BUILD:       return "PPCISD::ACC_BUILD";
1550   case PPCISD::PAIR_BUILD:      return "PPCISD::PAIR_BUILD";
1551   case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1552   case PPCISD::XXMFACC:         return "PPCISD::XXMFACC";
1553   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1554   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1555   case PPCISD::STRICT_FADDRTZ:
1556     return "PPCISD::STRICT_FADDRTZ";
1557   case PPCISD::STRICT_FCTIDZ:
1558     return "PPCISD::STRICT_FCTIDZ";
1559   case PPCISD::STRICT_FCTIWZ:
1560     return "PPCISD::STRICT_FCTIWZ";
1561   case PPCISD::STRICT_FCTIDUZ:
1562     return "PPCISD::STRICT_FCTIDUZ";
1563   case PPCISD::STRICT_FCTIWUZ:
1564     return "PPCISD::STRICT_FCTIWUZ";
1565   case PPCISD::STRICT_FCFID:
1566     return "PPCISD::STRICT_FCFID";
1567   case PPCISD::STRICT_FCFIDU:
1568     return "PPCISD::STRICT_FCFIDU";
1569   case PPCISD::STRICT_FCFIDS:
1570     return "PPCISD::STRICT_FCFIDS";
1571   case PPCISD::STRICT_FCFIDUS:
1572     return "PPCISD::STRICT_FCFIDUS";
1573   case PPCISD::LXVRZX:          return "PPCISD::LXVRZX";
1574   }
1575   return nullptr;
1576 }
1577 
1578 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1579                                           EVT VT) const {
1580   if (!VT.isVector())
1581     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1582 
1583   return VT.changeVectorElementTypeToInteger();
1584 }
1585 
1586 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1587   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1588   return true;
1589 }
1590 
1591 //===----------------------------------------------------------------------===//
1592 // Node matching predicates, for use by the tblgen matching code.
1593 //===----------------------------------------------------------------------===//
1594 
1595 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1596 static bool isFloatingPointZero(SDValue Op) {
1597   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1598     return CFP->getValueAPF().isZero();
1599   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1600     // Maybe this has already been legalized into the constant pool?
1601     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1602       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1603         return CFP->getValueAPF().isZero();
1604   }
1605   return false;
1606 }
1607 
1608 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1609 /// true if Op is undef or if it matches the specified value.
1610 static bool isConstantOrUndef(int Op, int Val) {
1611   return Op < 0 || Op == Val;
1612 }
1613 
1614 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1615 /// VPKUHUM instruction.
1616 /// The ShuffleKind distinguishes between big-endian operations with
1617 /// two different inputs (0), either-endian operations with two identical
1618 /// inputs (1), and little-endian operations with two different inputs (2).
1619 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1620 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1621                                SelectionDAG &DAG) {
1622   bool IsLE = DAG.getDataLayout().isLittleEndian();
1623   if (ShuffleKind == 0) {
1624     if (IsLE)
1625       return false;
1626     for (unsigned i = 0; i != 16; ++i)
1627       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1628         return false;
1629   } else if (ShuffleKind == 2) {
1630     if (!IsLE)
1631       return false;
1632     for (unsigned i = 0; i != 16; ++i)
1633       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1634         return false;
1635   } else if (ShuffleKind == 1) {
1636     unsigned j = IsLE ? 0 : 1;
1637     for (unsigned i = 0; i != 8; ++i)
1638       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1639           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1640         return false;
1641   }
1642   return true;
1643 }
1644 
1645 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1646 /// VPKUWUM instruction.
1647 /// The ShuffleKind distinguishes between big-endian operations with
1648 /// two different inputs (0), either-endian operations with two identical
1649 /// inputs (1), and little-endian operations with two different inputs (2).
1650 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1651 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1652                                SelectionDAG &DAG) {
1653   bool IsLE = DAG.getDataLayout().isLittleEndian();
1654   if (ShuffleKind == 0) {
1655     if (IsLE)
1656       return false;
1657     for (unsigned i = 0; i != 16; i += 2)
1658       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1659           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1660         return false;
1661   } else if (ShuffleKind == 2) {
1662     if (!IsLE)
1663       return false;
1664     for (unsigned i = 0; i != 16; i += 2)
1665       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1666           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1667         return false;
1668   } else if (ShuffleKind == 1) {
1669     unsigned j = IsLE ? 0 : 2;
1670     for (unsigned i = 0; i != 8; i += 2)
1671       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1672           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1673           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1674           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1675         return false;
1676   }
1677   return true;
1678 }
1679 
1680 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1681 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1682 /// current subtarget.
1683 ///
1684 /// The ShuffleKind distinguishes between big-endian operations with
1685 /// two different inputs (0), either-endian operations with two identical
1686 /// inputs (1), and little-endian operations with two different inputs (2).
1687 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1688 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1689                                SelectionDAG &DAG) {
1690   const PPCSubtarget& Subtarget =
1691       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1692   if (!Subtarget.hasP8Vector())
1693     return false;
1694 
1695   bool IsLE = DAG.getDataLayout().isLittleEndian();
1696   if (ShuffleKind == 0) {
1697     if (IsLE)
1698       return false;
1699     for (unsigned i = 0; i != 16; i += 4)
1700       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1701           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1702           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1703           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1704         return false;
1705   } else if (ShuffleKind == 2) {
1706     if (!IsLE)
1707       return false;
1708     for (unsigned i = 0; i != 16; i += 4)
1709       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1710           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1711           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1712           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1713         return false;
1714   } else if (ShuffleKind == 1) {
1715     unsigned j = IsLE ? 0 : 4;
1716     for (unsigned i = 0; i != 8; i += 4)
1717       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1718           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1719           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1720           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1721           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1722           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1723           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1724           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1725         return false;
1726   }
1727   return true;
1728 }
1729 
1730 /// isVMerge - Common function, used to match vmrg* shuffles.
1731 ///
1732 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1733                      unsigned LHSStart, unsigned RHSStart) {
1734   if (N->getValueType(0) != MVT::v16i8)
1735     return false;
1736   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1737          "Unsupported merge size!");
1738 
1739   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1740     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1741       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1742                              LHSStart+j+i*UnitSize) ||
1743           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1744                              RHSStart+j+i*UnitSize))
1745         return false;
1746     }
1747   return true;
1748 }
1749 
1750 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1751 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1752 /// The ShuffleKind distinguishes between big-endian merges with two
1753 /// different inputs (0), either-endian merges with two identical inputs (1),
1754 /// and little-endian merges with two different inputs (2).  For the latter,
1755 /// the input operands are swapped (see PPCInstrAltivec.td).
1756 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1757                              unsigned ShuffleKind, SelectionDAG &DAG) {
1758   if (DAG.getDataLayout().isLittleEndian()) {
1759     if (ShuffleKind == 1) // unary
1760       return isVMerge(N, UnitSize, 0, 0);
1761     else if (ShuffleKind == 2) // swapped
1762       return isVMerge(N, UnitSize, 0, 16);
1763     else
1764       return false;
1765   } else {
1766     if (ShuffleKind == 1) // unary
1767       return isVMerge(N, UnitSize, 8, 8);
1768     else if (ShuffleKind == 0) // normal
1769       return isVMerge(N, UnitSize, 8, 24);
1770     else
1771       return false;
1772   }
1773 }
1774 
1775 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1776 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1777 /// The ShuffleKind distinguishes between big-endian merges with two
1778 /// different inputs (0), either-endian merges with two identical inputs (1),
1779 /// and little-endian merges with two different inputs (2).  For the latter,
1780 /// the input operands are swapped (see PPCInstrAltivec.td).
1781 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1782                              unsigned ShuffleKind, SelectionDAG &DAG) {
1783   if (DAG.getDataLayout().isLittleEndian()) {
1784     if (ShuffleKind == 1) // unary
1785       return isVMerge(N, UnitSize, 8, 8);
1786     else if (ShuffleKind == 2) // swapped
1787       return isVMerge(N, UnitSize, 8, 24);
1788     else
1789       return false;
1790   } else {
1791     if (ShuffleKind == 1) // unary
1792       return isVMerge(N, UnitSize, 0, 0);
1793     else if (ShuffleKind == 0) // normal
1794       return isVMerge(N, UnitSize, 0, 16);
1795     else
1796       return false;
1797   }
1798 }
1799 
1800 /**
1801  * Common function used to match vmrgew and vmrgow shuffles
1802  *
1803  * The indexOffset determines whether to look for even or odd words in
1804  * the shuffle mask. This is based on the of the endianness of the target
1805  * machine.
1806  *   - Little Endian:
1807  *     - Use offset of 0 to check for odd elements
1808  *     - Use offset of 4 to check for even elements
1809  *   - Big Endian:
1810  *     - Use offset of 0 to check for even elements
1811  *     - Use offset of 4 to check for odd elements
1812  * A detailed description of the vector element ordering for little endian and
1813  * big endian can be found at
1814  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1815  * Targeting your applications - what little endian and big endian IBM XL C/C++
1816  * compiler differences mean to you
1817  *
1818  * The mask to the shuffle vector instruction specifies the indices of the
1819  * elements from the two input vectors to place in the result. The elements are
1820  * numbered in array-access order, starting with the first vector. These vectors
1821  * are always of type v16i8, thus each vector will contain 16 elements of size
1822  * 8. More info on the shuffle vector can be found in the
1823  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1824  * Language Reference.
1825  *
1826  * The RHSStartValue indicates whether the same input vectors are used (unary)
1827  * or two different input vectors are used, based on the following:
1828  *   - If the instruction uses the same vector for both inputs, the range of the
1829  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1830  *     be 0.
1831  *   - If the instruction has two different vectors then the range of the
1832  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1833  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1834  *     to 31 specify elements in the second vector).
1835  *
1836  * \param[in] N The shuffle vector SD Node to analyze
1837  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1838  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1839  * vector to the shuffle_vector instruction
1840  * \return true iff this shuffle vector represents an even or odd word merge
1841  */
1842 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1843                      unsigned RHSStartValue) {
1844   if (N->getValueType(0) != MVT::v16i8)
1845     return false;
1846 
1847   for (unsigned i = 0; i < 2; ++i)
1848     for (unsigned j = 0; j < 4; ++j)
1849       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1850                              i*RHSStartValue+j+IndexOffset) ||
1851           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1852                              i*RHSStartValue+j+IndexOffset+8))
1853         return false;
1854   return true;
1855 }
1856 
1857 /**
1858  * Determine if the specified shuffle mask is suitable for the vmrgew or
1859  * vmrgow instructions.
1860  *
1861  * \param[in] N The shuffle vector SD Node to analyze
1862  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1863  * \param[in] ShuffleKind Identify the type of merge:
1864  *   - 0 = big-endian merge with two different inputs;
1865  *   - 1 = either-endian merge with two identical inputs;
1866  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1867  *     little-endian merges).
1868  * \param[in] DAG The current SelectionDAG
1869  * \return true iff this shuffle mask
1870  */
1871 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1872                               unsigned ShuffleKind, SelectionDAG &DAG) {
1873   if (DAG.getDataLayout().isLittleEndian()) {
1874     unsigned indexOffset = CheckEven ? 4 : 0;
1875     if (ShuffleKind == 1) // Unary
1876       return isVMerge(N, indexOffset, 0);
1877     else if (ShuffleKind == 2) // swapped
1878       return isVMerge(N, indexOffset, 16);
1879     else
1880       return false;
1881   }
1882   else {
1883     unsigned indexOffset = CheckEven ? 0 : 4;
1884     if (ShuffleKind == 1) // Unary
1885       return isVMerge(N, indexOffset, 0);
1886     else if (ShuffleKind == 0) // Normal
1887       return isVMerge(N, indexOffset, 16);
1888     else
1889       return false;
1890   }
1891   return false;
1892 }
1893 
1894 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1895 /// amount, otherwise return -1.
1896 /// The ShuffleKind distinguishes between big-endian operations with two
1897 /// different inputs (0), either-endian operations with two identical inputs
1898 /// (1), and little-endian operations with two different inputs (2).  For the
1899 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1900 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1901                              SelectionDAG &DAG) {
1902   if (N->getValueType(0) != MVT::v16i8)
1903     return -1;
1904 
1905   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1906 
1907   // Find the first non-undef value in the shuffle mask.
1908   unsigned i;
1909   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1910     /*search*/;
1911 
1912   if (i == 16) return -1;  // all undef.
1913 
1914   // Otherwise, check to see if the rest of the elements are consecutively
1915   // numbered from this value.
1916   unsigned ShiftAmt = SVOp->getMaskElt(i);
1917   if (ShiftAmt < i) return -1;
1918 
1919   ShiftAmt -= i;
1920   bool isLE = DAG.getDataLayout().isLittleEndian();
1921 
1922   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1923     // Check the rest of the elements to see if they are consecutive.
1924     for (++i; i != 16; ++i)
1925       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1926         return -1;
1927   } else if (ShuffleKind == 1) {
1928     // Check the rest of the elements to see if they are consecutive.
1929     for (++i; i != 16; ++i)
1930       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1931         return -1;
1932   } else
1933     return -1;
1934 
1935   if (isLE)
1936     ShiftAmt = 16 - ShiftAmt;
1937 
1938   return ShiftAmt;
1939 }
1940 
1941 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1942 /// specifies a splat of a single element that is suitable for input to
1943 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1944 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1945   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1946          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1947 
1948   // The consecutive indices need to specify an element, not part of two
1949   // different elements.  So abandon ship early if this isn't the case.
1950   if (N->getMaskElt(0) % EltSize != 0)
1951     return false;
1952 
1953   // This is a splat operation if each element of the permute is the same, and
1954   // if the value doesn't reference the second vector.
1955   unsigned ElementBase = N->getMaskElt(0);
1956 
1957   // FIXME: Handle UNDEF elements too!
1958   if (ElementBase >= 16)
1959     return false;
1960 
1961   // Check that the indices are consecutive, in the case of a multi-byte element
1962   // splatted with a v16i8 mask.
1963   for (unsigned i = 1; i != EltSize; ++i)
1964     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1965       return false;
1966 
1967   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1968     if (N->getMaskElt(i) < 0) continue;
1969     for (unsigned j = 0; j != EltSize; ++j)
1970       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1971         return false;
1972   }
1973   return true;
1974 }
1975 
1976 /// Check that the mask is shuffling N byte elements. Within each N byte
1977 /// element of the mask, the indices could be either in increasing or
1978 /// decreasing order as long as they are consecutive.
1979 /// \param[in] N the shuffle vector SD Node to analyze
1980 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1981 /// Word/DoubleWord/QuadWord).
1982 /// \param[in] StepLen the delta indices number among the N byte element, if
1983 /// the mask is in increasing/decreasing order then it is 1/-1.
1984 /// \return true iff the mask is shuffling N byte elements.
1985 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1986                                    int StepLen) {
1987   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1988          "Unexpected element width.");
1989   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1990 
1991   unsigned NumOfElem = 16 / Width;
1992   unsigned MaskVal[16]; //  Width is never greater than 16
1993   for (unsigned i = 0; i < NumOfElem; ++i) {
1994     MaskVal[0] = N->getMaskElt(i * Width);
1995     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1996       return false;
1997     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1998       return false;
1999     }
2000 
2001     for (unsigned int j = 1; j < Width; ++j) {
2002       MaskVal[j] = N->getMaskElt(i * Width + j);
2003       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2004         return false;
2005       }
2006     }
2007   }
2008 
2009   return true;
2010 }
2011 
2012 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2013                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2014   if (!isNByteElemShuffleMask(N, 4, 1))
2015     return false;
2016 
2017   // Now we look at mask elements 0,4,8,12
2018   unsigned M0 = N->getMaskElt(0) / 4;
2019   unsigned M1 = N->getMaskElt(4) / 4;
2020   unsigned M2 = N->getMaskElt(8) / 4;
2021   unsigned M3 = N->getMaskElt(12) / 4;
2022   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2023   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2024 
2025   // Below, let H and L be arbitrary elements of the shuffle mask
2026   // where H is in the range [4,7] and L is in the range [0,3].
2027   // H, 1, 2, 3 or L, 5, 6, 7
2028   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2029       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2030     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2031     InsertAtByte = IsLE ? 12 : 0;
2032     Swap = M0 < 4;
2033     return true;
2034   }
2035   // 0, H, 2, 3 or 4, L, 6, 7
2036   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2037       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2038     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2039     InsertAtByte = IsLE ? 8 : 4;
2040     Swap = M1 < 4;
2041     return true;
2042   }
2043   // 0, 1, H, 3 or 4, 5, L, 7
2044   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2045       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2046     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2047     InsertAtByte = IsLE ? 4 : 8;
2048     Swap = M2 < 4;
2049     return true;
2050   }
2051   // 0, 1, 2, H or 4, 5, 6, L
2052   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2053       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2054     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2055     InsertAtByte = IsLE ? 0 : 12;
2056     Swap = M3 < 4;
2057     return true;
2058   }
2059 
2060   // If both vector operands for the shuffle are the same vector, the mask will
2061   // contain only elements from the first one and the second one will be undef.
2062   if (N->getOperand(1).isUndef()) {
2063     ShiftElts = 0;
2064     Swap = true;
2065     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2066     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2067       InsertAtByte = IsLE ? 12 : 0;
2068       return true;
2069     }
2070     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2071       InsertAtByte = IsLE ? 8 : 4;
2072       return true;
2073     }
2074     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2075       InsertAtByte = IsLE ? 4 : 8;
2076       return true;
2077     }
2078     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2079       InsertAtByte = IsLE ? 0 : 12;
2080       return true;
2081     }
2082   }
2083 
2084   return false;
2085 }
2086 
2087 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2088                                bool &Swap, bool IsLE) {
2089   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2090   // Ensure each byte index of the word is consecutive.
2091   if (!isNByteElemShuffleMask(N, 4, 1))
2092     return false;
2093 
2094   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2095   unsigned M0 = N->getMaskElt(0) / 4;
2096   unsigned M1 = N->getMaskElt(4) / 4;
2097   unsigned M2 = N->getMaskElt(8) / 4;
2098   unsigned M3 = N->getMaskElt(12) / 4;
2099 
2100   // If both vector operands for the shuffle are the same vector, the mask will
2101   // contain only elements from the first one and the second one will be undef.
2102   if (N->getOperand(1).isUndef()) {
2103     assert(M0 < 4 && "Indexing into an undef vector?");
2104     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2105       return false;
2106 
2107     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2108     Swap = false;
2109     return true;
2110   }
2111 
2112   // Ensure each word index of the ShuffleVector Mask is consecutive.
2113   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2114     return false;
2115 
2116   if (IsLE) {
2117     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2118       // Input vectors don't need to be swapped if the leading element
2119       // of the result is one of the 3 left elements of the second vector
2120       // (or if there is no shift to be done at all).
2121       Swap = false;
2122       ShiftElts = (8 - M0) % 8;
2123     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2124       // Input vectors need to be swapped if the leading element
2125       // of the result is one of the 3 left elements of the first vector
2126       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2127       Swap = true;
2128       ShiftElts = (4 - M0) % 4;
2129     }
2130 
2131     return true;
2132   } else {                                          // BE
2133     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2134       // Input vectors don't need to be swapped if the leading element
2135       // of the result is one of the 4 elements of the first vector.
2136       Swap = false;
2137       ShiftElts = M0;
2138     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2139       // Input vectors need to be swapped if the leading element
2140       // of the result is one of the 4 elements of the right vector.
2141       Swap = true;
2142       ShiftElts = M0 - 4;
2143     }
2144 
2145     return true;
2146   }
2147 }
2148 
2149 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2150   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2151 
2152   if (!isNByteElemShuffleMask(N, Width, -1))
2153     return false;
2154 
2155   for (int i = 0; i < 16; i += Width)
2156     if (N->getMaskElt(i) != i + Width - 1)
2157       return false;
2158 
2159   return true;
2160 }
2161 
2162 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2163   return isXXBRShuffleMaskHelper(N, 2);
2164 }
2165 
2166 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2167   return isXXBRShuffleMaskHelper(N, 4);
2168 }
2169 
2170 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2171   return isXXBRShuffleMaskHelper(N, 8);
2172 }
2173 
2174 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2175   return isXXBRShuffleMaskHelper(N, 16);
2176 }
2177 
2178 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2179 /// if the inputs to the instruction should be swapped and set \p DM to the
2180 /// value for the immediate.
2181 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2182 /// AND element 0 of the result comes from the first input (LE) or second input
2183 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2184 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2185 /// mask.
2186 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2187                                bool &Swap, bool IsLE) {
2188   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2189 
2190   // Ensure each byte index of the double word is consecutive.
2191   if (!isNByteElemShuffleMask(N, 8, 1))
2192     return false;
2193 
2194   unsigned M0 = N->getMaskElt(0) / 8;
2195   unsigned M1 = N->getMaskElt(8) / 8;
2196   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2197 
2198   // If both vector operands for the shuffle are the same vector, the mask will
2199   // contain only elements from the first one and the second one will be undef.
2200   if (N->getOperand(1).isUndef()) {
2201     if ((M0 | M1) < 2) {
2202       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2203       Swap = false;
2204       return true;
2205     } else
2206       return false;
2207   }
2208 
2209   if (IsLE) {
2210     if (M0 > 1 && M1 < 2) {
2211       Swap = false;
2212     } else if (M0 < 2 && M1 > 1) {
2213       M0 = (M0 + 2) % 4;
2214       M1 = (M1 + 2) % 4;
2215       Swap = true;
2216     } else
2217       return false;
2218 
2219     // Note: if control flow comes here that means Swap is already set above
2220     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2221     return true;
2222   } else { // BE
2223     if (M0 < 2 && M1 > 1) {
2224       Swap = false;
2225     } else if (M0 > 1 && M1 < 2) {
2226       M0 = (M0 + 2) % 4;
2227       M1 = (M1 + 2) % 4;
2228       Swap = true;
2229     } else
2230       return false;
2231 
2232     // Note: if control flow comes here that means Swap is already set above
2233     DM = (M0 << 1) + (M1 & 1);
2234     return true;
2235   }
2236 }
2237 
2238 
2239 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2240 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2241 /// elements are counted from the left of the vector register).
2242 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2243                                          SelectionDAG &DAG) {
2244   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2245   assert(isSplatShuffleMask(SVOp, EltSize));
2246   if (DAG.getDataLayout().isLittleEndian())
2247     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2248   else
2249     return SVOp->getMaskElt(0) / EltSize;
2250 }
2251 
2252 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2253 /// by using a vspltis[bhw] instruction of the specified element size, return
2254 /// the constant being splatted.  The ByteSize field indicates the number of
2255 /// bytes of each element [124] -> [bhw].
2256 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2257   SDValue OpVal(nullptr, 0);
2258 
2259   // If ByteSize of the splat is bigger than the element size of the
2260   // build_vector, then we have a case where we are checking for a splat where
2261   // multiple elements of the buildvector are folded together into a single
2262   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2263   unsigned EltSize = 16/N->getNumOperands();
2264   if (EltSize < ByteSize) {
2265     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2266     SDValue UniquedVals[4];
2267     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2268 
2269     // See if all of the elements in the buildvector agree across.
2270     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2271       if (N->getOperand(i).isUndef()) continue;
2272       // If the element isn't a constant, bail fully out.
2273       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2274 
2275       if (!UniquedVals[i&(Multiple-1)].getNode())
2276         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2277       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2278         return SDValue();  // no match.
2279     }
2280 
2281     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2282     // either constant or undef values that are identical for each chunk.  See
2283     // if these chunks can form into a larger vspltis*.
2284 
2285     // Check to see if all of the leading entries are either 0 or -1.  If
2286     // neither, then this won't fit into the immediate field.
2287     bool LeadingZero = true;
2288     bool LeadingOnes = true;
2289     for (unsigned i = 0; i != Multiple-1; ++i) {
2290       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2291 
2292       LeadingZero &= isNullConstant(UniquedVals[i]);
2293       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2294     }
2295     // Finally, check the least significant entry.
2296     if (LeadingZero) {
2297       if (!UniquedVals[Multiple-1].getNode())
2298         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2299       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2300       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2301         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2302     }
2303     if (LeadingOnes) {
2304       if (!UniquedVals[Multiple-1].getNode())
2305         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2306       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2307       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2308         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2309     }
2310 
2311     return SDValue();
2312   }
2313 
2314   // Check to see if this buildvec has a single non-undef value in its elements.
2315   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2316     if (N->getOperand(i).isUndef()) continue;
2317     if (!OpVal.getNode())
2318       OpVal = N->getOperand(i);
2319     else if (OpVal != N->getOperand(i))
2320       return SDValue();
2321   }
2322 
2323   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2324 
2325   unsigned ValSizeInBytes = EltSize;
2326   uint64_t Value = 0;
2327   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2328     Value = CN->getZExtValue();
2329   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2330     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2331     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2332   }
2333 
2334   // If the splat value is larger than the element value, then we can never do
2335   // this splat.  The only case that we could fit the replicated bits into our
2336   // immediate field for would be zero, and we prefer to use vxor for it.
2337   if (ValSizeInBytes < ByteSize) return SDValue();
2338 
2339   // If the element value is larger than the splat value, check if it consists
2340   // of a repeated bit pattern of size ByteSize.
2341   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2342     return SDValue();
2343 
2344   // Properly sign extend the value.
2345   int MaskVal = SignExtend32(Value, ByteSize * 8);
2346 
2347   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2348   if (MaskVal == 0) return SDValue();
2349 
2350   // Finally, if this value fits in a 5 bit sext field, return it
2351   if (SignExtend32<5>(MaskVal) == MaskVal)
2352     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2353   return SDValue();
2354 }
2355 
2356 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2357 /// amount, otherwise return -1.
2358 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2359   EVT VT = N->getValueType(0);
2360   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2361     return -1;
2362 
2363   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2364 
2365   // Find the first non-undef value in the shuffle mask.
2366   unsigned i;
2367   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2368     /*search*/;
2369 
2370   if (i == 4) return -1;  // all undef.
2371 
2372   // Otherwise, check to see if the rest of the elements are consecutively
2373   // numbered from this value.
2374   unsigned ShiftAmt = SVOp->getMaskElt(i);
2375   if (ShiftAmt < i) return -1;
2376   ShiftAmt -= i;
2377 
2378   // Check the rest of the elements to see if they are consecutive.
2379   for (++i; i != 4; ++i)
2380     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2381       return -1;
2382 
2383   return ShiftAmt;
2384 }
2385 
2386 //===----------------------------------------------------------------------===//
2387 //  Addressing Mode Selection
2388 //===----------------------------------------------------------------------===//
2389 
2390 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2391 /// or 64-bit immediate, and if the value can be accurately represented as a
2392 /// sign extension from a 16-bit value.  If so, this returns true and the
2393 /// immediate.
2394 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2395   if (!isa<ConstantSDNode>(N))
2396     return false;
2397 
2398   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2399   if (N->getValueType(0) == MVT::i32)
2400     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2401   else
2402     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2403 }
2404 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2405   return isIntS16Immediate(Op.getNode(), Imm);
2406 }
2407 
2408 
2409 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2410 /// be represented as an indexed [r+r] operation.
2411 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2412                                                SDValue &Index,
2413                                                SelectionDAG &DAG) const {
2414   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2415       UI != E; ++UI) {
2416     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2417       if (Memop->getMemoryVT() == MVT::f64) {
2418           Base = N.getOperand(0);
2419           Index = N.getOperand(1);
2420           return true;
2421       }
2422     }
2423   }
2424   return false;
2425 }
2426 
2427 /// isIntS34Immediate - This method tests if value of node given can be
2428 /// accurately represented as a sign extension from a 34-bit value.  If so,
2429 /// this returns true and the immediate.
2430 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2431   if (!isa<ConstantSDNode>(N))
2432     return false;
2433 
2434   Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2435   return isInt<34>(Imm);
2436 }
2437 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2438   return isIntS34Immediate(Op.getNode(), Imm);
2439 }
2440 
2441 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2442 /// can be represented as an indexed [r+r] operation.  Returns false if it
2443 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2444 /// non-zero and N can be represented by a base register plus a signed 16-bit
2445 /// displacement, make a more precise judgement by checking (displacement % \p
2446 /// EncodingAlignment).
2447 bool PPCTargetLowering::SelectAddressRegReg(
2448     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2449     MaybeAlign EncodingAlignment) const {
2450   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2451   // a [pc+imm].
2452   if (SelectAddressPCRel(N, Base))
2453     return false;
2454 
2455   int16_t Imm = 0;
2456   if (N.getOpcode() == ISD::ADD) {
2457     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2458     // SPE load/store can only handle 8-bit offsets.
2459     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2460         return true;
2461     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2462         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2463       return false; // r+i
2464     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2465       return false;    // r+i
2466 
2467     Base = N.getOperand(0);
2468     Index = N.getOperand(1);
2469     return true;
2470   } else if (N.getOpcode() == ISD::OR) {
2471     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2472         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2473       return false; // r+i can fold it if we can.
2474 
2475     // If this is an or of disjoint bitfields, we can codegen this as an add
2476     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2477     // disjoint.
2478     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2479 
2480     if (LHSKnown.Zero.getBoolValue()) {
2481       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2482       // If all of the bits are known zero on the LHS or RHS, the add won't
2483       // carry.
2484       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2485         Base = N.getOperand(0);
2486         Index = N.getOperand(1);
2487         return true;
2488       }
2489     }
2490   }
2491 
2492   return false;
2493 }
2494 
2495 // If we happen to be doing an i64 load or store into a stack slot that has
2496 // less than a 4-byte alignment, then the frame-index elimination may need to
2497 // use an indexed load or store instruction (because the offset may not be a
2498 // multiple of 4). The extra register needed to hold the offset comes from the
2499 // register scavenger, and it is possible that the scavenger will need to use
2500 // an emergency spill slot. As a result, we need to make sure that a spill slot
2501 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2502 // stack slot.
2503 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2504   // FIXME: This does not handle the LWA case.
2505   if (VT != MVT::i64)
2506     return;
2507 
2508   // NOTE: We'll exclude negative FIs here, which come from argument
2509   // lowering, because there are no known test cases triggering this problem
2510   // using packed structures (or similar). We can remove this exclusion if
2511   // we find such a test case. The reason why this is so test-case driven is
2512   // because this entire 'fixup' is only to prevent crashes (from the
2513   // register scavenger) on not-really-valid inputs. For example, if we have:
2514   //   %a = alloca i1
2515   //   %b = bitcast i1* %a to i64*
2516   //   store i64* a, i64 b
2517   // then the store should really be marked as 'align 1', but is not. If it
2518   // were marked as 'align 1' then the indexed form would have been
2519   // instruction-selected initially, and the problem this 'fixup' is preventing
2520   // won't happen regardless.
2521   if (FrameIdx < 0)
2522     return;
2523 
2524   MachineFunction &MF = DAG.getMachineFunction();
2525   MachineFrameInfo &MFI = MF.getFrameInfo();
2526 
2527   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2528     return;
2529 
2530   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2531   FuncInfo->setHasNonRISpills();
2532 }
2533 
2534 /// Returns true if the address N can be represented by a base register plus
2535 /// a signed 16-bit displacement [r+imm], and if it is not better
2536 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2537 /// displacements that are multiples of that value.
2538 bool PPCTargetLowering::SelectAddressRegImm(
2539     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2540     MaybeAlign EncodingAlignment) const {
2541   // FIXME dl should come from parent load or store, not from address
2542   SDLoc dl(N);
2543 
2544   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2545   // a [pc+imm].
2546   if (SelectAddressPCRel(N, Base))
2547     return false;
2548 
2549   // If this can be more profitably realized as r+r, fail.
2550   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2551     return false;
2552 
2553   if (N.getOpcode() == ISD::ADD) {
2554     int16_t imm = 0;
2555     if (isIntS16Immediate(N.getOperand(1), imm) &&
2556         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2557       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2558       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2559         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2560         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2561       } else {
2562         Base = N.getOperand(0);
2563       }
2564       return true; // [r+i]
2565     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2566       // Match LOAD (ADD (X, Lo(G))).
2567       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2568              && "Cannot handle constant offsets yet!");
2569       Disp = N.getOperand(1).getOperand(0);  // The global address.
2570       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2571              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2572              Disp.getOpcode() == ISD::TargetConstantPool ||
2573              Disp.getOpcode() == ISD::TargetJumpTable);
2574       Base = N.getOperand(0);
2575       return true;  // [&g+r]
2576     }
2577   } else if (N.getOpcode() == ISD::OR) {
2578     int16_t imm = 0;
2579     if (isIntS16Immediate(N.getOperand(1), imm) &&
2580         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2581       // If this is an or of disjoint bitfields, we can codegen this as an add
2582       // (for better address arithmetic) if the LHS and RHS of the OR are
2583       // provably disjoint.
2584       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2585 
2586       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2587         // If all of the bits are known zero on the LHS or RHS, the add won't
2588         // carry.
2589         if (FrameIndexSDNode *FI =
2590               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2591           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2592           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2593         } else {
2594           Base = N.getOperand(0);
2595         }
2596         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2597         return true;
2598       }
2599     }
2600   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2601     // Loading from a constant address.
2602 
2603     // If this address fits entirely in a 16-bit sext immediate field, codegen
2604     // this as "d, 0"
2605     int16_t Imm;
2606     if (isIntS16Immediate(CN, Imm) &&
2607         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2608       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2609       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2610                              CN->getValueType(0));
2611       return true;
2612     }
2613 
2614     // Handle 32-bit sext immediates with LIS + addr mode.
2615     if ((CN->getValueType(0) == MVT::i32 ||
2616          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2617         (!EncodingAlignment ||
2618          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2619       int Addr = (int)CN->getZExtValue();
2620 
2621       // Otherwise, break this down into an LIS + disp.
2622       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2623 
2624       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2625                                    MVT::i32);
2626       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2627       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2628       return true;
2629     }
2630   }
2631 
2632   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2633   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2634     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2635     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2636   } else
2637     Base = N;
2638   return true;      // [r+0]
2639 }
2640 
2641 /// Similar to the 16-bit case but for instructions that take a 34-bit
2642 /// displacement field (prefixed loads/stores).
2643 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp,
2644                                               SDValue &Base,
2645                                               SelectionDAG &DAG) const {
2646   // Only on 64-bit targets.
2647   if (N.getValueType() != MVT::i64)
2648     return false;
2649 
2650   SDLoc dl(N);
2651   int64_t Imm = 0;
2652 
2653   if (N.getOpcode() == ISD::ADD) {
2654     if (!isIntS34Immediate(N.getOperand(1), Imm))
2655       return false;
2656     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2657     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2658       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2659     else
2660       Base = N.getOperand(0);
2661     return true;
2662   }
2663 
2664   if (N.getOpcode() == ISD::OR) {
2665     if (!isIntS34Immediate(N.getOperand(1), Imm))
2666       return false;
2667     // If this is an or of disjoint bitfields, we can codegen this as an add
2668     // (for better address arithmetic) if the LHS and RHS of the OR are
2669     // provably disjoint.
2670     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2671     if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2672       return false;
2673     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2674       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2675     else
2676       Base = N.getOperand(0);
2677     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2678     return true;
2679   }
2680 
2681   if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2682     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2683     Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2684     return true;
2685   }
2686 
2687   return false;
2688 }
2689 
2690 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2691 /// represented as an indexed [r+r] operation.
2692 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2693                                                 SDValue &Index,
2694                                                 SelectionDAG &DAG) const {
2695   // Check to see if we can easily represent this as an [r+r] address.  This
2696   // will fail if it thinks that the address is more profitably represented as
2697   // reg+imm, e.g. where imm = 0.
2698   if (SelectAddressRegReg(N, Base, Index, DAG))
2699     return true;
2700 
2701   // If the address is the result of an add, we will utilize the fact that the
2702   // address calculation includes an implicit add.  However, we can reduce
2703   // register pressure if we do not materialize a constant just for use as the
2704   // index register.  We only get rid of the add if it is not an add of a
2705   // value and a 16-bit signed constant and both have a single use.
2706   int16_t imm = 0;
2707   if (N.getOpcode() == ISD::ADD &&
2708       (!isIntS16Immediate(N.getOperand(1), imm) ||
2709        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2710     Base = N.getOperand(0);
2711     Index = N.getOperand(1);
2712     return true;
2713   }
2714 
2715   // Otherwise, do it the hard way, using R0 as the base register.
2716   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2717                          N.getValueType());
2718   Index = N;
2719   return true;
2720 }
2721 
2722 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2723   Ty *PCRelCand = dyn_cast<Ty>(N);
2724   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2725 }
2726 
2727 /// Returns true if this address is a PC Relative address.
2728 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2729 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2730 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2731   // This is a materialize PC Relative node. Always select this as PC Relative.
2732   Base = N;
2733   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2734     return true;
2735   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2736       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2737       isValidPCRelNode<JumpTableSDNode>(N) ||
2738       isValidPCRelNode<BlockAddressSDNode>(N))
2739     return true;
2740   return false;
2741 }
2742 
2743 /// Returns true if we should use a direct load into vector instruction
2744 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2745 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2746 
2747   // If there are any other uses other than scalar to vector, then we should
2748   // keep it as a scalar load -> direct move pattern to prevent multiple
2749   // loads.
2750   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2751   if (!LD)
2752     return false;
2753 
2754   EVT MemVT = LD->getMemoryVT();
2755   if (!MemVT.isSimple())
2756     return false;
2757   switch(MemVT.getSimpleVT().SimpleTy) {
2758   case MVT::i64:
2759     break;
2760   case MVT::i32:
2761     if (!ST.hasP8Vector())
2762       return false;
2763     break;
2764   case MVT::i16:
2765   case MVT::i8:
2766     if (!ST.hasP9Vector())
2767       return false;
2768     break;
2769   default:
2770     return false;
2771   }
2772 
2773   SDValue LoadedVal(N, 0);
2774   if (!LoadedVal.hasOneUse())
2775     return false;
2776 
2777   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2778        UI != UE; ++UI)
2779     if (UI.getUse().get().getResNo() == 0 &&
2780         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2781         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2782       return false;
2783 
2784   return true;
2785 }
2786 
2787 /// getPreIndexedAddressParts - returns true by value, base pointer and
2788 /// offset pointer and addressing mode by reference if the node's address
2789 /// can be legally represented as pre-indexed load / store address.
2790 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2791                                                   SDValue &Offset,
2792                                                   ISD::MemIndexedMode &AM,
2793                                                   SelectionDAG &DAG) const {
2794   if (DisablePPCPreinc) return false;
2795 
2796   bool isLoad = true;
2797   SDValue Ptr;
2798   EVT VT;
2799   unsigned Alignment;
2800   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2801     Ptr = LD->getBasePtr();
2802     VT = LD->getMemoryVT();
2803     Alignment = LD->getAlignment();
2804   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2805     Ptr = ST->getBasePtr();
2806     VT  = ST->getMemoryVT();
2807     Alignment = ST->getAlignment();
2808     isLoad = false;
2809   } else
2810     return false;
2811 
2812   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2813   // instructions because we can fold these into a more efficient instruction
2814   // instead, (such as LXSD).
2815   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2816     return false;
2817   }
2818 
2819   // PowerPC doesn't have preinc load/store instructions for vectors
2820   if (VT.isVector())
2821     return false;
2822 
2823   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2824     // Common code will reject creating a pre-inc form if the base pointer
2825     // is a frame index, or if N is a store and the base pointer is either
2826     // the same as or a predecessor of the value being stored.  Check for
2827     // those situations here, and try with swapped Base/Offset instead.
2828     bool Swap = false;
2829 
2830     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2831       Swap = true;
2832     else if (!isLoad) {
2833       SDValue Val = cast<StoreSDNode>(N)->getValue();
2834       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2835         Swap = true;
2836     }
2837 
2838     if (Swap)
2839       std::swap(Base, Offset);
2840 
2841     AM = ISD::PRE_INC;
2842     return true;
2843   }
2844 
2845   // LDU/STU can only handle immediates that are a multiple of 4.
2846   if (VT != MVT::i64) {
2847     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2848       return false;
2849   } else {
2850     // LDU/STU need an address with at least 4-byte alignment.
2851     if (Alignment < 4)
2852       return false;
2853 
2854     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
2855       return false;
2856   }
2857 
2858   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2859     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2860     // sext i32 to i64 when addr mode is r+i.
2861     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2862         LD->getExtensionType() == ISD::SEXTLOAD &&
2863         isa<ConstantSDNode>(Offset))
2864       return false;
2865   }
2866 
2867   AM = ISD::PRE_INC;
2868   return true;
2869 }
2870 
2871 //===----------------------------------------------------------------------===//
2872 //  LowerOperation implementation
2873 //===----------------------------------------------------------------------===//
2874 
2875 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2876 /// and LoOpFlags to the target MO flags.
2877 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2878                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2879                                const GlobalValue *GV = nullptr) {
2880   HiOpFlags = PPCII::MO_HA;
2881   LoOpFlags = PPCII::MO_LO;
2882 
2883   // Don't use the pic base if not in PIC relocation model.
2884   if (IsPIC) {
2885     HiOpFlags |= PPCII::MO_PIC_FLAG;
2886     LoOpFlags |= PPCII::MO_PIC_FLAG;
2887   }
2888 }
2889 
2890 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2891                              SelectionDAG &DAG) {
2892   SDLoc DL(HiPart);
2893   EVT PtrVT = HiPart.getValueType();
2894   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2895 
2896   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2897   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2898 
2899   // With PIC, the first instruction is actually "GR+hi(&G)".
2900   if (isPIC)
2901     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2902                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2903 
2904   // Generate non-pic code that has direct accesses to the constant pool.
2905   // The address of the global is just (hi(&g)+lo(&g)).
2906   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2907 }
2908 
2909 static void setUsesTOCBasePtr(MachineFunction &MF) {
2910   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2911   FuncInfo->setUsesTOCBasePtr();
2912 }
2913 
2914 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2915   setUsesTOCBasePtr(DAG.getMachineFunction());
2916 }
2917 
2918 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2919                                        SDValue GA) const {
2920   const bool Is64Bit = Subtarget.isPPC64();
2921   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2922   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2923                         : Subtarget.isAIXABI()
2924                               ? DAG.getRegister(PPC::R2, VT)
2925                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2926   SDValue Ops[] = { GA, Reg };
2927   return DAG.getMemIntrinsicNode(
2928       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2929       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2930       MachineMemOperand::MOLoad);
2931 }
2932 
2933 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2934                                              SelectionDAG &DAG) const {
2935   EVT PtrVT = Op.getValueType();
2936   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2937   const Constant *C = CP->getConstVal();
2938 
2939   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2940   // The actual address of the GlobalValue is stored in the TOC.
2941   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2942     if (Subtarget.isUsingPCRelativeCalls()) {
2943       SDLoc DL(CP);
2944       EVT Ty = getPointerTy(DAG.getDataLayout());
2945       SDValue ConstPool = DAG.getTargetConstantPool(
2946           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2947       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2948     }
2949     setUsesTOCBasePtr(DAG);
2950     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2951     return getTOCEntry(DAG, SDLoc(CP), GA);
2952   }
2953 
2954   unsigned MOHiFlag, MOLoFlag;
2955   bool IsPIC = isPositionIndependent();
2956   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2957 
2958   if (IsPIC && Subtarget.isSVR4ABI()) {
2959     SDValue GA =
2960         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2961     return getTOCEntry(DAG, SDLoc(CP), GA);
2962   }
2963 
2964   SDValue CPIHi =
2965       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
2966   SDValue CPILo =
2967       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
2968   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2969 }
2970 
2971 // For 64-bit PowerPC, prefer the more compact relative encodings.
2972 // This trades 32 bits per jump table entry for one or two instructions
2973 // on the jump site.
2974 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2975   if (isJumpTableRelative())
2976     return MachineJumpTableInfo::EK_LabelDifference32;
2977 
2978   return TargetLowering::getJumpTableEncoding();
2979 }
2980 
2981 bool PPCTargetLowering::isJumpTableRelative() const {
2982   if (UseAbsoluteJumpTables)
2983     return false;
2984   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2985     return true;
2986   return TargetLowering::isJumpTableRelative();
2987 }
2988 
2989 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2990                                                     SelectionDAG &DAG) const {
2991   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2992     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2993 
2994   switch (getTargetMachine().getCodeModel()) {
2995   case CodeModel::Small:
2996   case CodeModel::Medium:
2997     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2998   default:
2999     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3000                        getPointerTy(DAG.getDataLayout()));
3001   }
3002 }
3003 
3004 const MCExpr *
3005 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
3006                                                 unsigned JTI,
3007                                                 MCContext &Ctx) const {
3008   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3009     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3010 
3011   switch (getTargetMachine().getCodeModel()) {
3012   case CodeModel::Small:
3013   case CodeModel::Medium:
3014     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3015   default:
3016     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3017   }
3018 }
3019 
3020 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3021   EVT PtrVT = Op.getValueType();
3022   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3023 
3024   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3025   if (Subtarget.isUsingPCRelativeCalls()) {
3026     SDLoc DL(JT);
3027     EVT Ty = getPointerTy(DAG.getDataLayout());
3028     SDValue GA =
3029         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3030     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3031     return MatAddr;
3032   }
3033 
3034   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3035   // The actual address of the GlobalValue is stored in the TOC.
3036   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3037     setUsesTOCBasePtr(DAG);
3038     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3039     return getTOCEntry(DAG, SDLoc(JT), GA);
3040   }
3041 
3042   unsigned MOHiFlag, MOLoFlag;
3043   bool IsPIC = isPositionIndependent();
3044   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3045 
3046   if (IsPIC && Subtarget.isSVR4ABI()) {
3047     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3048                                         PPCII::MO_PIC_FLAG);
3049     return getTOCEntry(DAG, SDLoc(GA), GA);
3050   }
3051 
3052   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3053   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3054   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3055 }
3056 
3057 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3058                                              SelectionDAG &DAG) const {
3059   EVT PtrVT = Op.getValueType();
3060   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3061   const BlockAddress *BA = BASDN->getBlockAddress();
3062 
3063   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3064   if (Subtarget.isUsingPCRelativeCalls()) {
3065     SDLoc DL(BASDN);
3066     EVT Ty = getPointerTy(DAG.getDataLayout());
3067     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3068                                            PPCII::MO_PCREL_FLAG);
3069     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3070     return MatAddr;
3071   }
3072 
3073   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3074   // The actual BlockAddress is stored in the TOC.
3075   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3076     setUsesTOCBasePtr(DAG);
3077     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3078     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3079   }
3080 
3081   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3082   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3083     return getTOCEntry(
3084         DAG, SDLoc(BASDN),
3085         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3086 
3087   unsigned MOHiFlag, MOLoFlag;
3088   bool IsPIC = isPositionIndependent();
3089   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3090   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3091   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3092   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3093 }
3094 
3095 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3096                                               SelectionDAG &DAG) const {
3097   // FIXME: TLS addresses currently use medium model code sequences,
3098   // which is the most useful form.  Eventually support for small and
3099   // large models could be added if users need it, at the cost of
3100   // additional complexity.
3101   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3102   if (DAG.getTarget().useEmulatedTLS())
3103     return LowerToTLSEmulatedModel(GA, DAG);
3104 
3105   SDLoc dl(GA);
3106   const GlobalValue *GV = GA->getGlobal();
3107   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3108   bool is64bit = Subtarget.isPPC64();
3109   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3110   PICLevel::Level picLevel = M->getPICLevel();
3111 
3112   const TargetMachine &TM = getTargetMachine();
3113   TLSModel::Model Model = TM.getTLSModel(GV);
3114 
3115   if (Model == TLSModel::LocalExec) {
3116     if (Subtarget.isUsingPCRelativeCalls()) {
3117       SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3118       SDValue TGA = DAG.getTargetGlobalAddress(
3119           GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3120       SDValue MatAddr =
3121           DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3122       return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3123     }
3124 
3125     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3126                                                PPCII::MO_TPREL_HA);
3127     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3128                                                PPCII::MO_TPREL_LO);
3129     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3130                              : DAG.getRegister(PPC::R2, MVT::i32);
3131 
3132     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3133     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3134   }
3135 
3136   if (Model == TLSModel::InitialExec) {
3137     bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3138     SDValue TGA = DAG.getTargetGlobalAddress(
3139         GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3140     SDValue TGATLS = DAG.getTargetGlobalAddress(
3141         GV, dl, PtrVT, 0,
3142         IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3143     SDValue TPOffset;
3144     if (IsPCRel) {
3145       SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3146       TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3147                              MachinePointerInfo());
3148     } else {
3149       SDValue GOTPtr;
3150       if (is64bit) {
3151         setUsesTOCBasePtr(DAG);
3152         SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3153         GOTPtr =
3154             DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3155       } else {
3156         if (!TM.isPositionIndependent())
3157           GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3158         else if (picLevel == PICLevel::SmallPIC)
3159           GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3160         else
3161           GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3162       }
3163       TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3164     }
3165     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3166   }
3167 
3168   if (Model == TLSModel::GeneralDynamic) {
3169     if (Subtarget.isUsingPCRelativeCalls()) {
3170       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3171                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3172       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3173     }
3174 
3175     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3176     SDValue GOTPtr;
3177     if (is64bit) {
3178       setUsesTOCBasePtr(DAG);
3179       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3180       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3181                                    GOTReg, TGA);
3182     } else {
3183       if (picLevel == PICLevel::SmallPIC)
3184         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3185       else
3186         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3187     }
3188     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3189                        GOTPtr, TGA, TGA);
3190   }
3191 
3192   if (Model == TLSModel::LocalDynamic) {
3193     if (Subtarget.isUsingPCRelativeCalls()) {
3194       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3195                                                PPCII::MO_GOT_TLSLD_PCREL_FLAG);
3196       SDValue MatPCRel =
3197           DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3198       return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3199     }
3200 
3201     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3202     SDValue GOTPtr;
3203     if (is64bit) {
3204       setUsesTOCBasePtr(DAG);
3205       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3206       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3207                            GOTReg, TGA);
3208     } else {
3209       if (picLevel == PICLevel::SmallPIC)
3210         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3211       else
3212         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3213     }
3214     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3215                                   PtrVT, GOTPtr, TGA, TGA);
3216     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3217                                       PtrVT, TLSAddr, TGA);
3218     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3219   }
3220 
3221   llvm_unreachable("Unknown TLS model!");
3222 }
3223 
3224 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3225                                               SelectionDAG &DAG) const {
3226   EVT PtrVT = Op.getValueType();
3227   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3228   SDLoc DL(GSDN);
3229   const GlobalValue *GV = GSDN->getGlobal();
3230 
3231   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3232   // The actual address of the GlobalValue is stored in the TOC.
3233   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3234     if (Subtarget.isUsingPCRelativeCalls()) {
3235       EVT Ty = getPointerTy(DAG.getDataLayout());
3236       if (isAccessedAsGotIndirect(Op)) {
3237         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3238                                                 PPCII::MO_PCREL_FLAG |
3239                                                     PPCII::MO_GOT_FLAG);
3240         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3241         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3242                                    MachinePointerInfo());
3243         return Load;
3244       } else {
3245         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3246                                                 PPCII::MO_PCREL_FLAG);
3247         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3248       }
3249     }
3250     setUsesTOCBasePtr(DAG);
3251     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3252     return getTOCEntry(DAG, DL, GA);
3253   }
3254 
3255   unsigned MOHiFlag, MOLoFlag;
3256   bool IsPIC = isPositionIndependent();
3257   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3258 
3259   if (IsPIC && Subtarget.isSVR4ABI()) {
3260     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3261                                             GSDN->getOffset(),
3262                                             PPCII::MO_PIC_FLAG);
3263     return getTOCEntry(DAG, DL, GA);
3264   }
3265 
3266   SDValue GAHi =
3267     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3268   SDValue GALo =
3269     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3270 
3271   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3272 }
3273 
3274 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3275   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3276   SDLoc dl(Op);
3277 
3278   if (Op.getValueType() == MVT::v2i64) {
3279     // When the operands themselves are v2i64 values, we need to do something
3280     // special because VSX has no underlying comparison operations for these.
3281     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3282       // Equality can be handled by casting to the legal type for Altivec
3283       // comparisons, everything else needs to be expanded.
3284       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3285         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3286                  DAG.getSetCC(dl, MVT::v4i32,
3287                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3288                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3289                    CC));
3290       }
3291 
3292       return SDValue();
3293     }
3294 
3295     // We handle most of these in the usual way.
3296     return Op;
3297   }
3298 
3299   // If we're comparing for equality to zero, expose the fact that this is
3300   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3301   // fold the new nodes.
3302   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3303     return V;
3304 
3305   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3306     // Leave comparisons against 0 and -1 alone for now, since they're usually
3307     // optimized.  FIXME: revisit this when we can custom lower all setcc
3308     // optimizations.
3309     if (C->isAllOnesValue() || C->isNullValue())
3310       return SDValue();
3311   }
3312 
3313   // If we have an integer seteq/setne, turn it into a compare against zero
3314   // by xor'ing the rhs with the lhs, which is faster than setting a
3315   // condition register, reading it back out, and masking the correct bit.  The
3316   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3317   // the result to other bit-twiddling opportunities.
3318   EVT LHSVT = Op.getOperand(0).getValueType();
3319   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3320     EVT VT = Op.getValueType();
3321     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3322                                 Op.getOperand(1));
3323     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3324   }
3325   return SDValue();
3326 }
3327 
3328 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3329   SDNode *Node = Op.getNode();
3330   EVT VT = Node->getValueType(0);
3331   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3332   SDValue InChain = Node->getOperand(0);
3333   SDValue VAListPtr = Node->getOperand(1);
3334   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3335   SDLoc dl(Node);
3336 
3337   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3338 
3339   // gpr_index
3340   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3341                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3342   InChain = GprIndex.getValue(1);
3343 
3344   if (VT == MVT::i64) {
3345     // Check if GprIndex is even
3346     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3347                                  DAG.getConstant(1, dl, MVT::i32));
3348     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3349                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3350     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3351                                           DAG.getConstant(1, dl, MVT::i32));
3352     // Align GprIndex to be even if it isn't
3353     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3354                            GprIndex);
3355   }
3356 
3357   // fpr index is 1 byte after gpr
3358   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3359                                DAG.getConstant(1, dl, MVT::i32));
3360 
3361   // fpr
3362   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3363                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3364   InChain = FprIndex.getValue(1);
3365 
3366   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3367                                        DAG.getConstant(8, dl, MVT::i32));
3368 
3369   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3370                                         DAG.getConstant(4, dl, MVT::i32));
3371 
3372   // areas
3373   SDValue OverflowArea =
3374       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3375   InChain = OverflowArea.getValue(1);
3376 
3377   SDValue RegSaveArea =
3378       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3379   InChain = RegSaveArea.getValue(1);
3380 
3381   // select overflow_area if index > 8
3382   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3383                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3384 
3385   // adjustment constant gpr_index * 4/8
3386   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3387                                     VT.isInteger() ? GprIndex : FprIndex,
3388                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3389                                                     MVT::i32));
3390 
3391   // OurReg = RegSaveArea + RegConstant
3392   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3393                                RegConstant);
3394 
3395   // Floating types are 32 bytes into RegSaveArea
3396   if (VT.isFloatingPoint())
3397     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3398                          DAG.getConstant(32, dl, MVT::i32));
3399 
3400   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3401   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3402                                    VT.isInteger() ? GprIndex : FprIndex,
3403                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3404                                                    MVT::i32));
3405 
3406   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3407                               VT.isInteger() ? VAListPtr : FprPtr,
3408                               MachinePointerInfo(SV), MVT::i8);
3409 
3410   // determine if we should load from reg_save_area or overflow_area
3411   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3412 
3413   // increase overflow_area by 4/8 if gpr/fpr > 8
3414   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3415                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3416                                           dl, MVT::i32));
3417 
3418   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3419                              OverflowAreaPlusN);
3420 
3421   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3422                               MachinePointerInfo(), MVT::i32);
3423 
3424   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3425 }
3426 
3427 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3428   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3429 
3430   // We have to copy the entire va_list struct:
3431   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3432   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3433                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3434                        false, true, false, MachinePointerInfo(),
3435                        MachinePointerInfo());
3436 }
3437 
3438 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3439                                                   SelectionDAG &DAG) const {
3440   if (Subtarget.isAIXABI())
3441     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3442 
3443   return Op.getOperand(0);
3444 }
3445 
3446 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3447                                                 SelectionDAG &DAG) const {
3448   if (Subtarget.isAIXABI())
3449     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3450 
3451   SDValue Chain = Op.getOperand(0);
3452   SDValue Trmp = Op.getOperand(1); // trampoline
3453   SDValue FPtr = Op.getOperand(2); // nested function
3454   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3455   SDLoc dl(Op);
3456 
3457   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3458   bool isPPC64 = (PtrVT == MVT::i64);
3459   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3460 
3461   TargetLowering::ArgListTy Args;
3462   TargetLowering::ArgListEntry Entry;
3463 
3464   Entry.Ty = IntPtrTy;
3465   Entry.Node = Trmp; Args.push_back(Entry);
3466 
3467   // TrampSize == (isPPC64 ? 48 : 40);
3468   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3469                                isPPC64 ? MVT::i64 : MVT::i32);
3470   Args.push_back(Entry);
3471 
3472   Entry.Node = FPtr; Args.push_back(Entry);
3473   Entry.Node = Nest; Args.push_back(Entry);
3474 
3475   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3476   TargetLowering::CallLoweringInfo CLI(DAG);
3477   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3478       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3479       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3480 
3481   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3482   return CallResult.second;
3483 }
3484 
3485 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3486   MachineFunction &MF = DAG.getMachineFunction();
3487   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3488   EVT PtrVT = getPointerTy(MF.getDataLayout());
3489 
3490   SDLoc dl(Op);
3491 
3492   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3493     // vastart just stores the address of the VarArgsFrameIndex slot into the
3494     // memory location argument.
3495     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3496     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3497     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3498                         MachinePointerInfo(SV));
3499   }
3500 
3501   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3502   // We suppose the given va_list is already allocated.
3503   //
3504   // typedef struct {
3505   //  char gpr;     /* index into the array of 8 GPRs
3506   //                 * stored in the register save area
3507   //                 * gpr=0 corresponds to r3,
3508   //                 * gpr=1 to r4, etc.
3509   //                 */
3510   //  char fpr;     /* index into the array of 8 FPRs
3511   //                 * stored in the register save area
3512   //                 * fpr=0 corresponds to f1,
3513   //                 * fpr=1 to f2, etc.
3514   //                 */
3515   //  char *overflow_arg_area;
3516   //                /* location on stack that holds
3517   //                 * the next overflow argument
3518   //                 */
3519   //  char *reg_save_area;
3520   //               /* where r3:r10 and f1:f8 (if saved)
3521   //                * are stored
3522   //                */
3523   // } va_list[1];
3524 
3525   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3526   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3527   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3528                                             PtrVT);
3529   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3530                                  PtrVT);
3531 
3532   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3533   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3534 
3535   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3536   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3537 
3538   uint64_t FPROffset = 1;
3539   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3540 
3541   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3542 
3543   // Store first byte : number of int regs
3544   SDValue firstStore =
3545       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3546                         MachinePointerInfo(SV), MVT::i8);
3547   uint64_t nextOffset = FPROffset;
3548   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3549                                   ConstFPROffset);
3550 
3551   // Store second byte : number of float regs
3552   SDValue secondStore =
3553       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3554                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3555   nextOffset += StackOffset;
3556   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3557 
3558   // Store second word : arguments given on stack
3559   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3560                                     MachinePointerInfo(SV, nextOffset));
3561   nextOffset += FrameOffset;
3562   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3563 
3564   // Store third word : arguments given in registers
3565   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3566                       MachinePointerInfo(SV, nextOffset));
3567 }
3568 
3569 /// FPR - The set of FP registers that should be allocated for arguments
3570 /// on Darwin and AIX.
3571 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3572                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3573                                 PPC::F11, PPC::F12, PPC::F13};
3574 
3575 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3576 /// the stack.
3577 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3578                                        unsigned PtrByteSize) {
3579   unsigned ArgSize = ArgVT.getStoreSize();
3580   if (Flags.isByVal())
3581     ArgSize = Flags.getByValSize();
3582 
3583   // Round up to multiples of the pointer size, except for array members,
3584   // which are always packed.
3585   if (!Flags.isInConsecutiveRegs())
3586     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3587 
3588   return ArgSize;
3589 }
3590 
3591 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3592 /// on the stack.
3593 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3594                                          ISD::ArgFlagsTy Flags,
3595                                          unsigned PtrByteSize) {
3596   Align Alignment(PtrByteSize);
3597 
3598   // Altivec parameters are padded to a 16 byte boundary.
3599   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3600       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3601       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3602       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3603     Alignment = Align(16);
3604 
3605   // ByVal parameters are aligned as requested.
3606   if (Flags.isByVal()) {
3607     auto BVAlign = Flags.getNonZeroByValAlign();
3608     if (BVAlign > PtrByteSize) {
3609       if (BVAlign.value() % PtrByteSize != 0)
3610         llvm_unreachable(
3611             "ByVal alignment is not a multiple of the pointer size");
3612 
3613       Alignment = BVAlign;
3614     }
3615   }
3616 
3617   // Array members are always packed to their original alignment.
3618   if (Flags.isInConsecutiveRegs()) {
3619     // If the array member was split into multiple registers, the first
3620     // needs to be aligned to the size of the full type.  (Except for
3621     // ppcf128, which is only aligned as its f64 components.)
3622     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3623       Alignment = Align(OrigVT.getStoreSize());
3624     else
3625       Alignment = Align(ArgVT.getStoreSize());
3626   }
3627 
3628   return Alignment;
3629 }
3630 
3631 /// CalculateStackSlotUsed - Return whether this argument will use its
3632 /// stack slot (instead of being passed in registers).  ArgOffset,
3633 /// AvailableFPRs, and AvailableVRs must hold the current argument
3634 /// position, and will be updated to account for this argument.
3635 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3636                                    unsigned PtrByteSize, unsigned LinkageSize,
3637                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3638                                    unsigned &AvailableFPRs,
3639                                    unsigned &AvailableVRs) {
3640   bool UseMemory = false;
3641 
3642   // Respect alignment of argument on the stack.
3643   Align Alignment =
3644       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3645   ArgOffset = alignTo(ArgOffset, Alignment);
3646   // If there's no space left in the argument save area, we must
3647   // use memory (this check also catches zero-sized arguments).
3648   if (ArgOffset >= LinkageSize + ParamAreaSize)
3649     UseMemory = true;
3650 
3651   // Allocate argument on the stack.
3652   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3653   if (Flags.isInConsecutiveRegsLast())
3654     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3655   // If we overran the argument save area, we must use memory
3656   // (this check catches arguments passed partially in memory)
3657   if (ArgOffset > LinkageSize + ParamAreaSize)
3658     UseMemory = true;
3659 
3660   // However, if the argument is actually passed in an FPR or a VR,
3661   // we don't use memory after all.
3662   if (!Flags.isByVal()) {
3663     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3664       if (AvailableFPRs > 0) {
3665         --AvailableFPRs;
3666         return false;
3667       }
3668     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3669         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3670         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3671         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3672       if (AvailableVRs > 0) {
3673         --AvailableVRs;
3674         return false;
3675       }
3676   }
3677 
3678   return UseMemory;
3679 }
3680 
3681 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3682 /// ensure minimum alignment required for target.
3683 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3684                                      unsigned NumBytes) {
3685   return alignTo(NumBytes, Lowering->getStackAlign());
3686 }
3687 
3688 SDValue PPCTargetLowering::LowerFormalArguments(
3689     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3690     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3691     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3692   if (Subtarget.isAIXABI())
3693     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3694                                     InVals);
3695   if (Subtarget.is64BitELFABI())
3696     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3697                                        InVals);
3698   if (Subtarget.is32BitELFABI())
3699     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3700                                        InVals);
3701 
3702   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3703                                      InVals);
3704 }
3705 
3706 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3707     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3708     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3709     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3710 
3711   // 32-bit SVR4 ABI Stack Frame Layout:
3712   //              +-----------------------------------+
3713   //        +-->  |            Back chain             |
3714   //        |     +-----------------------------------+
3715   //        |     | Floating-point register save area |
3716   //        |     +-----------------------------------+
3717   //        |     |    General register save area     |
3718   //        |     +-----------------------------------+
3719   //        |     |          CR save word             |
3720   //        |     +-----------------------------------+
3721   //        |     |         VRSAVE save word          |
3722   //        |     +-----------------------------------+
3723   //        |     |         Alignment padding         |
3724   //        |     +-----------------------------------+
3725   //        |     |     Vector register save area     |
3726   //        |     +-----------------------------------+
3727   //        |     |       Local variable space        |
3728   //        |     +-----------------------------------+
3729   //        |     |        Parameter list area        |
3730   //        |     +-----------------------------------+
3731   //        |     |           LR save word            |
3732   //        |     +-----------------------------------+
3733   // SP-->  +---  |            Back chain             |
3734   //              +-----------------------------------+
3735   //
3736   // Specifications:
3737   //   System V Application Binary Interface PowerPC Processor Supplement
3738   //   AltiVec Technology Programming Interface Manual
3739 
3740   MachineFunction &MF = DAG.getMachineFunction();
3741   MachineFrameInfo &MFI = MF.getFrameInfo();
3742   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3743 
3744   EVT PtrVT = getPointerTy(MF.getDataLayout());
3745   // Potential tail calls could cause overwriting of argument stack slots.
3746   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3747                        (CallConv == CallingConv::Fast));
3748   const Align PtrAlign(4);
3749 
3750   // Assign locations to all of the incoming arguments.
3751   SmallVector<CCValAssign, 16> ArgLocs;
3752   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3753                  *DAG.getContext());
3754 
3755   // Reserve space for the linkage area on the stack.
3756   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3757   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3758   if (useSoftFloat())
3759     CCInfo.PreAnalyzeFormalArguments(Ins);
3760 
3761   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3762   CCInfo.clearWasPPCF128();
3763 
3764   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3765     CCValAssign &VA = ArgLocs[i];
3766 
3767     // Arguments stored in registers.
3768     if (VA.isRegLoc()) {
3769       const TargetRegisterClass *RC;
3770       EVT ValVT = VA.getValVT();
3771 
3772       switch (ValVT.getSimpleVT().SimpleTy) {
3773         default:
3774           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3775         case MVT::i1:
3776         case MVT::i32:
3777           RC = &PPC::GPRCRegClass;
3778           break;
3779         case MVT::f32:
3780           if (Subtarget.hasP8Vector())
3781             RC = &PPC::VSSRCRegClass;
3782           else if (Subtarget.hasSPE())
3783             RC = &PPC::GPRCRegClass;
3784           else
3785             RC = &PPC::F4RCRegClass;
3786           break;
3787         case MVT::f64:
3788           if (Subtarget.hasVSX())
3789             RC = &PPC::VSFRCRegClass;
3790           else if (Subtarget.hasSPE())
3791             // SPE passes doubles in GPR pairs.
3792             RC = &PPC::GPRCRegClass;
3793           else
3794             RC = &PPC::F8RCRegClass;
3795           break;
3796         case MVT::v16i8:
3797         case MVT::v8i16:
3798         case MVT::v4i32:
3799           RC = &PPC::VRRCRegClass;
3800           break;
3801         case MVT::v4f32:
3802           RC = &PPC::VRRCRegClass;
3803           break;
3804         case MVT::v2f64:
3805         case MVT::v2i64:
3806           RC = &PPC::VRRCRegClass;
3807           break;
3808       }
3809 
3810       SDValue ArgValue;
3811       // Transform the arguments stored in physical registers into
3812       // virtual ones.
3813       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3814         assert(i + 1 < e && "No second half of double precision argument");
3815         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3816         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3817         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3818         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3819         if (!Subtarget.isLittleEndian())
3820           std::swap (ArgValueLo, ArgValueHi);
3821         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3822                                ArgValueHi);
3823       } else {
3824         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3825         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3826                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3827         if (ValVT == MVT::i1)
3828           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3829       }
3830 
3831       InVals.push_back(ArgValue);
3832     } else {
3833       // Argument stored in memory.
3834       assert(VA.isMemLoc());
3835 
3836       // Get the extended size of the argument type in stack
3837       unsigned ArgSize = VA.getLocVT().getStoreSize();
3838       // Get the actual size of the argument type
3839       unsigned ObjSize = VA.getValVT().getStoreSize();
3840       unsigned ArgOffset = VA.getLocMemOffset();
3841       // Stack objects in PPC32 are right justified.
3842       ArgOffset += ArgSize - ObjSize;
3843       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3844 
3845       // Create load nodes to retrieve arguments from the stack.
3846       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3847       InVals.push_back(
3848           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3849     }
3850   }
3851 
3852   // Assign locations to all of the incoming aggregate by value arguments.
3853   // Aggregates passed by value are stored in the local variable space of the
3854   // caller's stack frame, right above the parameter list area.
3855   SmallVector<CCValAssign, 16> ByValArgLocs;
3856   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3857                       ByValArgLocs, *DAG.getContext());
3858 
3859   // Reserve stack space for the allocations in CCInfo.
3860   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
3861 
3862   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3863 
3864   // Area that is at least reserved in the caller of this function.
3865   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3866   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3867 
3868   // Set the size that is at least reserved in caller of this function.  Tail
3869   // call optimized function's reserved stack space needs to be aligned so that
3870   // taking the difference between two stack areas will result in an aligned
3871   // stack.
3872   MinReservedArea =
3873       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3874   FuncInfo->setMinReservedArea(MinReservedArea);
3875 
3876   SmallVector<SDValue, 8> MemOps;
3877 
3878   // If the function takes variable number of arguments, make a frame index for
3879   // the start of the first vararg value... for expansion of llvm.va_start.
3880   if (isVarArg) {
3881     static const MCPhysReg GPArgRegs[] = {
3882       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3883       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3884     };
3885     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3886 
3887     static const MCPhysReg FPArgRegs[] = {
3888       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3889       PPC::F8
3890     };
3891     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3892 
3893     if (useSoftFloat() || hasSPE())
3894        NumFPArgRegs = 0;
3895 
3896     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3897     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3898 
3899     // Make room for NumGPArgRegs and NumFPArgRegs.
3900     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3901                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3902 
3903     FuncInfo->setVarArgsStackOffset(
3904       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3905                             CCInfo.getNextStackOffset(), true));
3906 
3907     FuncInfo->setVarArgsFrameIndex(
3908         MFI.CreateStackObject(Depth, Align(8), false));
3909     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3910 
3911     // The fixed integer arguments of a variadic function are stored to the
3912     // VarArgsFrameIndex on the stack so that they may be loaded by
3913     // dereferencing the result of va_next.
3914     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3915       // Get an existing live-in vreg, or add a new one.
3916       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3917       if (!VReg)
3918         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3919 
3920       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3921       SDValue Store =
3922           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3923       MemOps.push_back(Store);
3924       // Increment the address by four for the next argument to store
3925       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3926       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3927     }
3928 
3929     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3930     // is set.
3931     // The double arguments are stored to the VarArgsFrameIndex
3932     // on the stack.
3933     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3934       // Get an existing live-in vreg, or add a new one.
3935       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3936       if (!VReg)
3937         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3938 
3939       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3940       SDValue Store =
3941           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3942       MemOps.push_back(Store);
3943       // Increment the address by eight for the next argument to store
3944       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3945                                          PtrVT);
3946       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3947     }
3948   }
3949 
3950   if (!MemOps.empty())
3951     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3952 
3953   return Chain;
3954 }
3955 
3956 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3957 // value to MVT::i64 and then truncate to the correct register size.
3958 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3959                                              EVT ObjectVT, SelectionDAG &DAG,
3960                                              SDValue ArgVal,
3961                                              const SDLoc &dl) const {
3962   if (Flags.isSExt())
3963     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3964                          DAG.getValueType(ObjectVT));
3965   else if (Flags.isZExt())
3966     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3967                          DAG.getValueType(ObjectVT));
3968 
3969   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3970 }
3971 
3972 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3973     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3974     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3975     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3976   // TODO: add description of PPC stack frame format, or at least some docs.
3977   //
3978   bool isELFv2ABI = Subtarget.isELFv2ABI();
3979   bool isLittleEndian = Subtarget.isLittleEndian();
3980   MachineFunction &MF = DAG.getMachineFunction();
3981   MachineFrameInfo &MFI = MF.getFrameInfo();
3982   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3983 
3984   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3985          "fastcc not supported on varargs functions");
3986 
3987   EVT PtrVT = getPointerTy(MF.getDataLayout());
3988   // Potential tail calls could cause overwriting of argument stack slots.
3989   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3990                        (CallConv == CallingConv::Fast));
3991   unsigned PtrByteSize = 8;
3992   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3993 
3994   static const MCPhysReg GPR[] = {
3995     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3996     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3997   };
3998   static const MCPhysReg VR[] = {
3999     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4000     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4001   };
4002 
4003   const unsigned Num_GPR_Regs = array_lengthof(GPR);
4004   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4005   const unsigned Num_VR_Regs  = array_lengthof(VR);
4006 
4007   // Do a first pass over the arguments to determine whether the ABI
4008   // guarantees that our caller has allocated the parameter save area
4009   // on its stack frame.  In the ELFv1 ABI, this is always the case;
4010   // in the ELFv2 ABI, it is true if this is a vararg function or if
4011   // any parameter is located in a stack slot.
4012 
4013   bool HasParameterArea = !isELFv2ABI || isVarArg;
4014   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4015   unsigned NumBytes = LinkageSize;
4016   unsigned AvailableFPRs = Num_FPR_Regs;
4017   unsigned AvailableVRs = Num_VR_Regs;
4018   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4019     if (Ins[i].Flags.isNest())
4020       continue;
4021 
4022     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
4023                                PtrByteSize, LinkageSize, ParamAreaSize,
4024                                NumBytes, AvailableFPRs, AvailableVRs))
4025       HasParameterArea = true;
4026   }
4027 
4028   // Add DAG nodes to load the arguments or copy them out of registers.  On
4029   // entry to a function on PPC, the arguments start after the linkage area,
4030   // although the first ones are often in registers.
4031 
4032   unsigned ArgOffset = LinkageSize;
4033   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4034   SmallVector<SDValue, 8> MemOps;
4035   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4036   unsigned CurArgIdx = 0;
4037   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4038     SDValue ArgVal;
4039     bool needsLoad = false;
4040     EVT ObjectVT = Ins[ArgNo].VT;
4041     EVT OrigVT = Ins[ArgNo].ArgVT;
4042     unsigned ObjSize = ObjectVT.getStoreSize();
4043     unsigned ArgSize = ObjSize;
4044     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4045     if (Ins[ArgNo].isOrigArg()) {
4046       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4047       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4048     }
4049     // We re-align the argument offset for each argument, except when using the
4050     // fast calling convention, when we need to make sure we do that only when
4051     // we'll actually use a stack slot.
4052     unsigned CurArgOffset;
4053     Align Alignment;
4054     auto ComputeArgOffset = [&]() {
4055       /* Respect alignment of argument on the stack.  */
4056       Alignment =
4057           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4058       ArgOffset = alignTo(ArgOffset, Alignment);
4059       CurArgOffset = ArgOffset;
4060     };
4061 
4062     if (CallConv != CallingConv::Fast) {
4063       ComputeArgOffset();
4064 
4065       /* Compute GPR index associated with argument offset.  */
4066       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4067       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4068     }
4069 
4070     // FIXME the codegen can be much improved in some cases.
4071     // We do not have to keep everything in memory.
4072     if (Flags.isByVal()) {
4073       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4074 
4075       if (CallConv == CallingConv::Fast)
4076         ComputeArgOffset();
4077 
4078       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4079       ObjSize = Flags.getByValSize();
4080       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4081       // Empty aggregate parameters do not take up registers.  Examples:
4082       //   struct { } a;
4083       //   union  { } b;
4084       //   int c[0];
4085       // etc.  However, we have to provide a place-holder in InVals, so
4086       // pretend we have an 8-byte item at the current address for that
4087       // purpose.
4088       if (!ObjSize) {
4089         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4090         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4091         InVals.push_back(FIN);
4092         continue;
4093       }
4094 
4095       // Create a stack object covering all stack doublewords occupied
4096       // by the argument.  If the argument is (fully or partially) on
4097       // the stack, or if the argument is fully in registers but the
4098       // caller has allocated the parameter save anyway, we can refer
4099       // directly to the caller's stack frame.  Otherwise, create a
4100       // local copy in our own frame.
4101       int FI;
4102       if (HasParameterArea ||
4103           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4104         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4105       else
4106         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4107       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4108 
4109       // Handle aggregates smaller than 8 bytes.
4110       if (ObjSize < PtrByteSize) {
4111         // The value of the object is its address, which differs from the
4112         // address of the enclosing doubleword on big-endian systems.
4113         SDValue Arg = FIN;
4114         if (!isLittleEndian) {
4115           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4116           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4117         }
4118         InVals.push_back(Arg);
4119 
4120         if (GPR_idx != Num_GPR_Regs) {
4121           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4122           FuncInfo->addLiveInAttr(VReg, Flags);
4123           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4124           SDValue Store;
4125 
4126           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
4127             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
4128                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
4129             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4130                                       MachinePointerInfo(&*FuncArg), ObjType);
4131           } else {
4132             // For sizes that don't fit a truncating store (3, 5, 6, 7),
4133             // store the whole register as-is to the parameter save area
4134             // slot.
4135             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4136                                  MachinePointerInfo(&*FuncArg));
4137           }
4138 
4139           MemOps.push_back(Store);
4140         }
4141         // Whether we copied from a register or not, advance the offset
4142         // into the parameter save area by a full doubleword.
4143         ArgOffset += PtrByteSize;
4144         continue;
4145       }
4146 
4147       // The value of the object is its address, which is the address of
4148       // its first stack doubleword.
4149       InVals.push_back(FIN);
4150 
4151       // Store whatever pieces of the object are in registers to memory.
4152       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4153         if (GPR_idx == Num_GPR_Regs)
4154           break;
4155 
4156         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4157         FuncInfo->addLiveInAttr(VReg, Flags);
4158         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4159         SDValue Addr = FIN;
4160         if (j) {
4161           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4162           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4163         }
4164         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4165                                      MachinePointerInfo(&*FuncArg, j));
4166         MemOps.push_back(Store);
4167         ++GPR_idx;
4168       }
4169       ArgOffset += ArgSize;
4170       continue;
4171     }
4172 
4173     switch (ObjectVT.getSimpleVT().SimpleTy) {
4174     default: llvm_unreachable("Unhandled argument type!");
4175     case MVT::i1:
4176     case MVT::i32:
4177     case MVT::i64:
4178       if (Flags.isNest()) {
4179         // The 'nest' parameter, if any, is passed in R11.
4180         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4181         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4182 
4183         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4184           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4185 
4186         break;
4187       }
4188 
4189       // These can be scalar arguments or elements of an integer array type
4190       // passed directly.  Clang may use those instead of "byval" aggregate
4191       // types to avoid forcing arguments to memory unnecessarily.
4192       if (GPR_idx != Num_GPR_Regs) {
4193         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4194         FuncInfo->addLiveInAttr(VReg, Flags);
4195         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4196 
4197         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4198           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4199           // value to MVT::i64 and then truncate to the correct register size.
4200           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4201       } else {
4202         if (CallConv == CallingConv::Fast)
4203           ComputeArgOffset();
4204 
4205         needsLoad = true;
4206         ArgSize = PtrByteSize;
4207       }
4208       if (CallConv != CallingConv::Fast || needsLoad)
4209         ArgOffset += 8;
4210       break;
4211 
4212     case MVT::f32:
4213     case MVT::f64:
4214       // These can be scalar arguments or elements of a float array type
4215       // passed directly.  The latter are used to implement ELFv2 homogenous
4216       // float aggregates.
4217       if (FPR_idx != Num_FPR_Regs) {
4218         unsigned VReg;
4219 
4220         if (ObjectVT == MVT::f32)
4221           VReg = MF.addLiveIn(FPR[FPR_idx],
4222                               Subtarget.hasP8Vector()
4223                                   ? &PPC::VSSRCRegClass
4224                                   : &PPC::F4RCRegClass);
4225         else
4226           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4227                                                 ? &PPC::VSFRCRegClass
4228                                                 : &PPC::F8RCRegClass);
4229 
4230         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4231         ++FPR_idx;
4232       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4233         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4234         // once we support fp <-> gpr moves.
4235 
4236         // This can only ever happen in the presence of f32 array types,
4237         // since otherwise we never run out of FPRs before running out
4238         // of GPRs.
4239         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4240         FuncInfo->addLiveInAttr(VReg, Flags);
4241         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4242 
4243         if (ObjectVT == MVT::f32) {
4244           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4245             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4246                                  DAG.getConstant(32, dl, MVT::i32));
4247           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4248         }
4249 
4250         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4251       } else {
4252         if (CallConv == CallingConv::Fast)
4253           ComputeArgOffset();
4254 
4255         needsLoad = true;
4256       }
4257 
4258       // When passing an array of floats, the array occupies consecutive
4259       // space in the argument area; only round up to the next doubleword
4260       // at the end of the array.  Otherwise, each float takes 8 bytes.
4261       if (CallConv != CallingConv::Fast || needsLoad) {
4262         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4263         ArgOffset += ArgSize;
4264         if (Flags.isInConsecutiveRegsLast())
4265           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4266       }
4267       break;
4268     case MVT::v4f32:
4269     case MVT::v4i32:
4270     case MVT::v8i16:
4271     case MVT::v16i8:
4272     case MVT::v2f64:
4273     case MVT::v2i64:
4274     case MVT::v1i128:
4275     case MVT::f128:
4276       // These can be scalar arguments or elements of a vector array type
4277       // passed directly.  The latter are used to implement ELFv2 homogenous
4278       // vector aggregates.
4279       if (VR_idx != Num_VR_Regs) {
4280         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4281         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4282         ++VR_idx;
4283       } else {
4284         if (CallConv == CallingConv::Fast)
4285           ComputeArgOffset();
4286         needsLoad = true;
4287       }
4288       if (CallConv != CallingConv::Fast || needsLoad)
4289         ArgOffset += 16;
4290       break;
4291     }
4292 
4293     // We need to load the argument to a virtual register if we determined
4294     // above that we ran out of physical registers of the appropriate type.
4295     if (needsLoad) {
4296       if (ObjSize < ArgSize && !isLittleEndian)
4297         CurArgOffset += ArgSize - ObjSize;
4298       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4299       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4300       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4301     }
4302 
4303     InVals.push_back(ArgVal);
4304   }
4305 
4306   // Area that is at least reserved in the caller of this function.
4307   unsigned MinReservedArea;
4308   if (HasParameterArea)
4309     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4310   else
4311     MinReservedArea = LinkageSize;
4312 
4313   // Set the size that is at least reserved in caller of this function.  Tail
4314   // call optimized functions' reserved stack space needs to be aligned so that
4315   // taking the difference between two stack areas will result in an aligned
4316   // stack.
4317   MinReservedArea =
4318       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4319   FuncInfo->setMinReservedArea(MinReservedArea);
4320 
4321   // If the function takes variable number of arguments, make a frame index for
4322   // the start of the first vararg value... for expansion of llvm.va_start.
4323   // On ELFv2ABI spec, it writes:
4324   // C programs that are intended to be *portable* across different compilers
4325   // and architectures must use the header file <stdarg.h> to deal with variable
4326   // argument lists.
4327   if (isVarArg && MFI.hasVAStart()) {
4328     int Depth = ArgOffset;
4329 
4330     FuncInfo->setVarArgsFrameIndex(
4331       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4332     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4333 
4334     // If this function is vararg, store any remaining integer argument regs
4335     // to their spots on the stack so that they may be loaded by dereferencing
4336     // the result of va_next.
4337     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4338          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4339       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4340       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4341       SDValue Store =
4342           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4343       MemOps.push_back(Store);
4344       // Increment the address by four for the next argument to store
4345       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4346       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4347     }
4348   }
4349 
4350   if (!MemOps.empty())
4351     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4352 
4353   return Chain;
4354 }
4355 
4356 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4357     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4358     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4359     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4360   // TODO: add description of PPC stack frame format, or at least some docs.
4361   //
4362   MachineFunction &MF = DAG.getMachineFunction();
4363   MachineFrameInfo &MFI = MF.getFrameInfo();
4364   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4365 
4366   EVT PtrVT = getPointerTy(MF.getDataLayout());
4367   bool isPPC64 = PtrVT == MVT::i64;
4368   // Potential tail calls could cause overwriting of argument stack slots.
4369   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4370                        (CallConv == CallingConv::Fast));
4371   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4372   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4373   unsigned ArgOffset = LinkageSize;
4374   // Area that is at least reserved in caller of this function.
4375   unsigned MinReservedArea = ArgOffset;
4376 
4377   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4378     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4379     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4380   };
4381   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4382     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4383     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4384   };
4385   static const MCPhysReg VR[] = {
4386     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4387     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4388   };
4389 
4390   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4391   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4392   const unsigned Num_VR_Regs  = array_lengthof( VR);
4393 
4394   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4395 
4396   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4397 
4398   // In 32-bit non-varargs functions, the stack space for vectors is after the
4399   // stack space for non-vectors.  We do not use this space unless we have
4400   // too many vectors to fit in registers, something that only occurs in
4401   // constructed examples:), but we have to walk the arglist to figure
4402   // that out...for the pathological case, compute VecArgOffset as the
4403   // start of the vector parameter area.  Computing VecArgOffset is the
4404   // entire point of the following loop.
4405   unsigned VecArgOffset = ArgOffset;
4406   if (!isVarArg && !isPPC64) {
4407     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4408          ++ArgNo) {
4409       EVT ObjectVT = Ins[ArgNo].VT;
4410       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4411 
4412       if (Flags.isByVal()) {
4413         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4414         unsigned ObjSize = Flags.getByValSize();
4415         unsigned ArgSize =
4416                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4417         VecArgOffset += ArgSize;
4418         continue;
4419       }
4420 
4421       switch(ObjectVT.getSimpleVT().SimpleTy) {
4422       default: llvm_unreachable("Unhandled argument type!");
4423       case MVT::i1:
4424       case MVT::i32:
4425       case MVT::f32:
4426         VecArgOffset += 4;
4427         break;
4428       case MVT::i64:  // PPC64
4429       case MVT::f64:
4430         // FIXME: We are guaranteed to be !isPPC64 at this point.
4431         // Does MVT::i64 apply?
4432         VecArgOffset += 8;
4433         break;
4434       case MVT::v4f32:
4435       case MVT::v4i32:
4436       case MVT::v8i16:
4437       case MVT::v16i8:
4438         // Nothing to do, we're only looking at Nonvector args here.
4439         break;
4440       }
4441     }
4442   }
4443   // We've found where the vector parameter area in memory is.  Skip the
4444   // first 12 parameters; these don't use that memory.
4445   VecArgOffset = ((VecArgOffset+15)/16)*16;
4446   VecArgOffset += 12*16;
4447 
4448   // Add DAG nodes to load the arguments or copy them out of registers.  On
4449   // entry to a function on PPC, the arguments start after the linkage area,
4450   // although the first ones are often in registers.
4451 
4452   SmallVector<SDValue, 8> MemOps;
4453   unsigned nAltivecParamsAtEnd = 0;
4454   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4455   unsigned CurArgIdx = 0;
4456   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4457     SDValue ArgVal;
4458     bool needsLoad = false;
4459     EVT ObjectVT = Ins[ArgNo].VT;
4460     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4461     unsigned ArgSize = ObjSize;
4462     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4463     if (Ins[ArgNo].isOrigArg()) {
4464       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4465       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4466     }
4467     unsigned CurArgOffset = ArgOffset;
4468 
4469     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4470     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4471         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4472       if (isVarArg || isPPC64) {
4473         MinReservedArea = ((MinReservedArea+15)/16)*16;
4474         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4475                                                   Flags,
4476                                                   PtrByteSize);
4477       } else  nAltivecParamsAtEnd++;
4478     } else
4479       // Calculate min reserved area.
4480       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4481                                                 Flags,
4482                                                 PtrByteSize);
4483 
4484     // FIXME the codegen can be much improved in some cases.
4485     // We do not have to keep everything in memory.
4486     if (Flags.isByVal()) {
4487       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4488 
4489       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4490       ObjSize = Flags.getByValSize();
4491       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4492       // Objects of size 1 and 2 are right justified, everything else is
4493       // left justified.  This means the memory address is adjusted forwards.
4494       if (ObjSize==1 || ObjSize==2) {
4495         CurArgOffset = CurArgOffset + (4 - ObjSize);
4496       }
4497       // The value of the object is its address.
4498       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4499       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4500       InVals.push_back(FIN);
4501       if (ObjSize==1 || ObjSize==2) {
4502         if (GPR_idx != Num_GPR_Regs) {
4503           unsigned VReg;
4504           if (isPPC64)
4505             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4506           else
4507             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4508           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4509           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4510           SDValue Store =
4511               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4512                                 MachinePointerInfo(&*FuncArg), ObjType);
4513           MemOps.push_back(Store);
4514           ++GPR_idx;
4515         }
4516 
4517         ArgOffset += PtrByteSize;
4518 
4519         continue;
4520       }
4521       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4522         // Store whatever pieces of the object are in registers
4523         // to memory.  ArgOffset will be the address of the beginning
4524         // of the object.
4525         if (GPR_idx != Num_GPR_Regs) {
4526           unsigned VReg;
4527           if (isPPC64)
4528             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4529           else
4530             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4531           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4532           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4533           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4534           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4535                                        MachinePointerInfo(&*FuncArg, j));
4536           MemOps.push_back(Store);
4537           ++GPR_idx;
4538           ArgOffset += PtrByteSize;
4539         } else {
4540           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4541           break;
4542         }
4543       }
4544       continue;
4545     }
4546 
4547     switch (ObjectVT.getSimpleVT().SimpleTy) {
4548     default: llvm_unreachable("Unhandled argument type!");
4549     case MVT::i1:
4550     case MVT::i32:
4551       if (!isPPC64) {
4552         if (GPR_idx != Num_GPR_Regs) {
4553           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4554           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4555 
4556           if (ObjectVT == MVT::i1)
4557             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4558 
4559           ++GPR_idx;
4560         } else {
4561           needsLoad = true;
4562           ArgSize = PtrByteSize;
4563         }
4564         // All int arguments reserve stack space in the Darwin ABI.
4565         ArgOffset += PtrByteSize;
4566         break;
4567       }
4568       LLVM_FALLTHROUGH;
4569     case MVT::i64:  // PPC64
4570       if (GPR_idx != Num_GPR_Regs) {
4571         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4572         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4573 
4574         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4575           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4576           // value to MVT::i64 and then truncate to the correct register size.
4577           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4578 
4579         ++GPR_idx;
4580       } else {
4581         needsLoad = true;
4582         ArgSize = PtrByteSize;
4583       }
4584       // All int arguments reserve stack space in the Darwin ABI.
4585       ArgOffset += 8;
4586       break;
4587 
4588     case MVT::f32:
4589     case MVT::f64:
4590       // Every 4 bytes of argument space consumes one of the GPRs available for
4591       // argument passing.
4592       if (GPR_idx != Num_GPR_Regs) {
4593         ++GPR_idx;
4594         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4595           ++GPR_idx;
4596       }
4597       if (FPR_idx != Num_FPR_Regs) {
4598         unsigned VReg;
4599 
4600         if (ObjectVT == MVT::f32)
4601           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4602         else
4603           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4604 
4605         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4606         ++FPR_idx;
4607       } else {
4608         needsLoad = true;
4609       }
4610 
4611       // All FP arguments reserve stack space in the Darwin ABI.
4612       ArgOffset += isPPC64 ? 8 : ObjSize;
4613       break;
4614     case MVT::v4f32:
4615     case MVT::v4i32:
4616     case MVT::v8i16:
4617     case MVT::v16i8:
4618       // Note that vector arguments in registers don't reserve stack space,
4619       // except in varargs functions.
4620       if (VR_idx != Num_VR_Regs) {
4621         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4622         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4623         if (isVarArg) {
4624           while ((ArgOffset % 16) != 0) {
4625             ArgOffset += PtrByteSize;
4626             if (GPR_idx != Num_GPR_Regs)
4627               GPR_idx++;
4628           }
4629           ArgOffset += 16;
4630           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4631         }
4632         ++VR_idx;
4633       } else {
4634         if (!isVarArg && !isPPC64) {
4635           // Vectors go after all the nonvectors.
4636           CurArgOffset = VecArgOffset;
4637           VecArgOffset += 16;
4638         } else {
4639           // Vectors are aligned.
4640           ArgOffset = ((ArgOffset+15)/16)*16;
4641           CurArgOffset = ArgOffset;
4642           ArgOffset += 16;
4643         }
4644         needsLoad = true;
4645       }
4646       break;
4647     }
4648 
4649     // We need to load the argument to a virtual register if we determined above
4650     // that we ran out of physical registers of the appropriate type.
4651     if (needsLoad) {
4652       int FI = MFI.CreateFixedObject(ObjSize,
4653                                      CurArgOffset + (ArgSize - ObjSize),
4654                                      isImmutable);
4655       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4656       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4657     }
4658 
4659     InVals.push_back(ArgVal);
4660   }
4661 
4662   // Allow for Altivec parameters at the end, if needed.
4663   if (nAltivecParamsAtEnd) {
4664     MinReservedArea = ((MinReservedArea+15)/16)*16;
4665     MinReservedArea += 16*nAltivecParamsAtEnd;
4666   }
4667 
4668   // Area that is at least reserved in the caller of this function.
4669   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4670 
4671   // Set the size that is at least reserved in caller of this function.  Tail
4672   // call optimized functions' reserved stack space needs to be aligned so that
4673   // taking the difference between two stack areas will result in an aligned
4674   // stack.
4675   MinReservedArea =
4676       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4677   FuncInfo->setMinReservedArea(MinReservedArea);
4678 
4679   // If the function takes variable number of arguments, make a frame index for
4680   // the start of the first vararg value... for expansion of llvm.va_start.
4681   if (isVarArg) {
4682     int Depth = ArgOffset;
4683 
4684     FuncInfo->setVarArgsFrameIndex(
4685       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4686                             Depth, true));
4687     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4688 
4689     // If this function is vararg, store any remaining integer argument regs
4690     // to their spots on the stack so that they may be loaded by dereferencing
4691     // the result of va_next.
4692     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4693       unsigned VReg;
4694 
4695       if (isPPC64)
4696         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4697       else
4698         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4699 
4700       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4701       SDValue Store =
4702           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4703       MemOps.push_back(Store);
4704       // Increment the address by four for the next argument to store
4705       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4706       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4707     }
4708   }
4709 
4710   if (!MemOps.empty())
4711     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4712 
4713   return Chain;
4714 }
4715 
4716 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4717 /// adjusted to accommodate the arguments for the tailcall.
4718 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4719                                    unsigned ParamSize) {
4720 
4721   if (!isTailCall) return 0;
4722 
4723   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4724   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4725   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4726   // Remember only if the new adjustment is bigger.
4727   if (SPDiff < FI->getTailCallSPDelta())
4728     FI->setTailCallSPDelta(SPDiff);
4729 
4730   return SPDiff;
4731 }
4732 
4733 static bool isFunctionGlobalAddress(SDValue Callee);
4734 
4735 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4736                               const TargetMachine &TM) {
4737   // It does not make sense to call callsShareTOCBase() with a caller that
4738   // is PC Relative since PC Relative callers do not have a TOC.
4739 #ifndef NDEBUG
4740   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4741   assert(!STICaller->isUsingPCRelativeCalls() &&
4742          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4743 #endif
4744 
4745   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4746   // don't have enough information to determine if the caller and callee share
4747   // the same  TOC base, so we have to pessimistically assume they don't for
4748   // correctness.
4749   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4750   if (!G)
4751     return false;
4752 
4753   const GlobalValue *GV = G->getGlobal();
4754 
4755   // If the callee is preemptable, then the static linker will use a plt-stub
4756   // which saves the toc to the stack, and needs a nop after the call
4757   // instruction to convert to a toc-restore.
4758   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4759     return false;
4760 
4761   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4762   // We may need a TOC restore in the situation where the caller requires a
4763   // valid TOC but the callee is PC Relative and does not.
4764   const Function *F = dyn_cast<Function>(GV);
4765   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4766 
4767   // If we have an Alias we can try to get the function from there.
4768   if (Alias) {
4769     const GlobalObject *GlobalObj = Alias->getBaseObject();
4770     F = dyn_cast<Function>(GlobalObj);
4771   }
4772 
4773   // If we still have no valid function pointer we do not have enough
4774   // information to determine if the callee uses PC Relative calls so we must
4775   // assume that it does.
4776   if (!F)
4777     return false;
4778 
4779   // If the callee uses PC Relative we cannot guarantee that the callee won't
4780   // clobber the TOC of the caller and so we must assume that the two
4781   // functions do not share a TOC base.
4782   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4783   if (STICallee->isUsingPCRelativeCalls())
4784     return false;
4785 
4786   // The medium and large code models are expected to provide a sufficiently
4787   // large TOC to provide all data addressing needs of a module with a
4788   // single TOC.
4789   if (CodeModel::Medium == TM.getCodeModel() ||
4790       CodeModel::Large == TM.getCodeModel())
4791     return true;
4792 
4793   // Otherwise we need to ensure callee and caller are in the same section,
4794   // since the linker may allocate multiple TOCs, and we don't know which
4795   // sections will belong to the same TOC base.
4796   if (!GV->isStrongDefinitionForLinker())
4797     return false;
4798 
4799   // Any explicitly-specified sections and section prefixes must also match.
4800   // Also, if we're using -ffunction-sections, then each function is always in
4801   // a different section (the same is true for COMDAT functions).
4802   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4803       GV->getSection() != Caller->getSection())
4804     return false;
4805   if (const auto *F = dyn_cast<Function>(GV)) {
4806     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4807       return false;
4808   }
4809 
4810   return true;
4811 }
4812 
4813 static bool
4814 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4815                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4816   assert(Subtarget.is64BitELFABI());
4817 
4818   const unsigned PtrByteSize = 8;
4819   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4820 
4821   static const MCPhysReg GPR[] = {
4822     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4823     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4824   };
4825   static const MCPhysReg VR[] = {
4826     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4827     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4828   };
4829 
4830   const unsigned NumGPRs = array_lengthof(GPR);
4831   const unsigned NumFPRs = 13;
4832   const unsigned NumVRs = array_lengthof(VR);
4833   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4834 
4835   unsigned NumBytes = LinkageSize;
4836   unsigned AvailableFPRs = NumFPRs;
4837   unsigned AvailableVRs = NumVRs;
4838 
4839   for (const ISD::OutputArg& Param : Outs) {
4840     if (Param.Flags.isNest()) continue;
4841 
4842     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4843                                LinkageSize, ParamAreaSize, NumBytes,
4844                                AvailableFPRs, AvailableVRs))
4845       return true;
4846   }
4847   return false;
4848 }
4849 
4850 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4851   if (CB.arg_size() != CallerFn->arg_size())
4852     return false;
4853 
4854   auto CalleeArgIter = CB.arg_begin();
4855   auto CalleeArgEnd = CB.arg_end();
4856   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4857 
4858   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4859     const Value* CalleeArg = *CalleeArgIter;
4860     const Value* CallerArg = &(*CallerArgIter);
4861     if (CalleeArg == CallerArg)
4862       continue;
4863 
4864     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4865     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4866     //      }
4867     // 1st argument of callee is undef and has the same type as caller.
4868     if (CalleeArg->getType() == CallerArg->getType() &&
4869         isa<UndefValue>(CalleeArg))
4870       continue;
4871 
4872     return false;
4873   }
4874 
4875   return true;
4876 }
4877 
4878 // Returns true if TCO is possible between the callers and callees
4879 // calling conventions.
4880 static bool
4881 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4882                                     CallingConv::ID CalleeCC) {
4883   // Tail calls are possible with fastcc and ccc.
4884   auto isTailCallableCC  = [] (CallingConv::ID CC){
4885       return  CC == CallingConv::C || CC == CallingConv::Fast;
4886   };
4887   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4888     return false;
4889 
4890   // We can safely tail call both fastcc and ccc callees from a c calling
4891   // convention caller. If the caller is fastcc, we may have less stack space
4892   // than a non-fastcc caller with the same signature so disable tail-calls in
4893   // that case.
4894   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4895 }
4896 
4897 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4898     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4899     const SmallVectorImpl<ISD::OutputArg> &Outs,
4900     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4901   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4902 
4903   if (DisableSCO && !TailCallOpt) return false;
4904 
4905   // Variadic argument functions are not supported.
4906   if (isVarArg) return false;
4907 
4908   auto &Caller = DAG.getMachineFunction().getFunction();
4909   // Check that the calling conventions are compatible for tco.
4910   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4911     return false;
4912 
4913   // Caller contains any byval parameter is not supported.
4914   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4915     return false;
4916 
4917   // Callee contains any byval parameter is not supported, too.
4918   // Note: This is a quick work around, because in some cases, e.g.
4919   // caller's stack size > callee's stack size, we are still able to apply
4920   // sibling call optimization. For example, gcc is able to do SCO for caller1
4921   // in the following example, but not for caller2.
4922   //   struct test {
4923   //     long int a;
4924   //     char ary[56];
4925   //   } gTest;
4926   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4927   //     b->a = v.a;
4928   //     return 0;
4929   //   }
4930   //   void caller1(struct test a, struct test c, struct test *b) {
4931   //     callee(gTest, b); }
4932   //   void caller2(struct test *b) { callee(gTest, b); }
4933   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4934     return false;
4935 
4936   // If callee and caller use different calling conventions, we cannot pass
4937   // parameters on stack since offsets for the parameter area may be different.
4938   if (Caller.getCallingConv() != CalleeCC &&
4939       needStackSlotPassParameters(Subtarget, Outs))
4940     return false;
4941 
4942   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4943   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4944   // callee potentially have different TOC bases then we cannot tail call since
4945   // we need to restore the TOC pointer after the call.
4946   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4947   // We cannot guarantee this for indirect calls or calls to external functions.
4948   // When PC-Relative addressing is used, the concept of the TOC is no longer
4949   // applicable so this check is not required.
4950   // Check first for indirect calls.
4951   if (!Subtarget.isUsingPCRelativeCalls() &&
4952       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4953     return false;
4954 
4955   // Check if we share the TOC base.
4956   if (!Subtarget.isUsingPCRelativeCalls() &&
4957       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4958     return false;
4959 
4960   // TCO allows altering callee ABI, so we don't have to check further.
4961   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4962     return true;
4963 
4964   if (DisableSCO) return false;
4965 
4966   // If callee use the same argument list that caller is using, then we can
4967   // apply SCO on this case. If it is not, then we need to check if callee needs
4968   // stack for passing arguments.
4969   // PC Relative tail calls may not have a CallBase.
4970   // If there is no CallBase we cannot verify if we have the same argument
4971   // list so assume that we don't have the same argument list.
4972   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4973       needStackSlotPassParameters(Subtarget, Outs))
4974     return false;
4975   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4976     return false;
4977 
4978   return true;
4979 }
4980 
4981 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4982 /// for tail call optimization. Targets which want to do tail call
4983 /// optimization should implement this function.
4984 bool
4985 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4986                                                      CallingConv::ID CalleeCC,
4987                                                      bool isVarArg,
4988                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4989                                                      SelectionDAG& DAG) const {
4990   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4991     return false;
4992 
4993   // Variable argument functions are not supported.
4994   if (isVarArg)
4995     return false;
4996 
4997   MachineFunction &MF = DAG.getMachineFunction();
4998   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4999   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
5000     // Functions containing by val parameters are not supported.
5001     for (unsigned i = 0; i != Ins.size(); i++) {
5002        ISD::ArgFlagsTy Flags = Ins[i].Flags;
5003        if (Flags.isByVal()) return false;
5004     }
5005 
5006     // Non-PIC/GOT tail calls are supported.
5007     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
5008       return true;
5009 
5010     // At the moment we can only do local tail calls (in same module, hidden
5011     // or protected) if we are generating PIC.
5012     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
5013       return G->getGlobal()->hasHiddenVisibility()
5014           || G->getGlobal()->hasProtectedVisibility();
5015   }
5016 
5017   return false;
5018 }
5019 
5020 /// isCallCompatibleAddress - Return the immediate to use if the specified
5021 /// 32-bit value is representable in the immediate field of a BxA instruction.
5022 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
5023   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5024   if (!C) return nullptr;
5025 
5026   int Addr = C->getZExtValue();
5027   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
5028       SignExtend32<26>(Addr) != Addr)
5029     return nullptr;  // Top 6 bits have to be sext of immediate.
5030 
5031   return DAG
5032       .getConstant(
5033           (int)C->getZExtValue() >> 2, SDLoc(Op),
5034           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
5035       .getNode();
5036 }
5037 
5038 namespace {
5039 
5040 struct TailCallArgumentInfo {
5041   SDValue Arg;
5042   SDValue FrameIdxOp;
5043   int FrameIdx = 0;
5044 
5045   TailCallArgumentInfo() = default;
5046 };
5047 
5048 } // end anonymous namespace
5049 
5050 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
5051 static void StoreTailCallArgumentsToStackSlot(
5052     SelectionDAG &DAG, SDValue Chain,
5053     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
5054     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
5055   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
5056     SDValue Arg = TailCallArgs[i].Arg;
5057     SDValue FIN = TailCallArgs[i].FrameIdxOp;
5058     int FI = TailCallArgs[i].FrameIdx;
5059     // Store relative to framepointer.
5060     MemOpChains.push_back(DAG.getStore(
5061         Chain, dl, Arg, FIN,
5062         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
5063   }
5064 }
5065 
5066 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
5067 /// the appropriate stack slot for the tail call optimized function call.
5068 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
5069                                              SDValue OldRetAddr, SDValue OldFP,
5070                                              int SPDiff, const SDLoc &dl) {
5071   if (SPDiff) {
5072     // Calculate the new stack slot for the return address.
5073     MachineFunction &MF = DAG.getMachineFunction();
5074     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
5075     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
5076     bool isPPC64 = Subtarget.isPPC64();
5077     int SlotSize = isPPC64 ? 8 : 4;
5078     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
5079     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
5080                                                          NewRetAddrLoc, true);
5081     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5082     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
5083     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
5084                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
5085   }
5086   return Chain;
5087 }
5088 
5089 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5090 /// the position of the argument.
5091 static void
5092 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
5093                          SDValue Arg, int SPDiff, unsigned ArgOffset,
5094                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
5095   int Offset = ArgOffset + SPDiff;
5096   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5097   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5098   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5099   SDValue FIN = DAG.getFrameIndex(FI, VT);
5100   TailCallArgumentInfo Info;
5101   Info.Arg = Arg;
5102   Info.FrameIdxOp = FIN;
5103   Info.FrameIdx = FI;
5104   TailCallArguments.push_back(Info);
5105 }
5106 
5107 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5108 /// stack slot. Returns the chain as result and the loaded frame pointers in
5109 /// LROpOut/FPOpout. Used when tail calling.
5110 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5111     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5112     SDValue &FPOpOut, const SDLoc &dl) const {
5113   if (SPDiff) {
5114     // Load the LR and FP stack slot for later adjusting.
5115     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5116     LROpOut = getReturnAddrFrameIndex(DAG);
5117     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5118     Chain = SDValue(LROpOut.getNode(), 1);
5119   }
5120   return Chain;
5121 }
5122 
5123 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5124 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5125 /// specified by the specific parameter attribute. The copy will be passed as
5126 /// a byval function parameter.
5127 /// Sometimes what we are copying is the end of a larger object, the part that
5128 /// does not fit in registers.
5129 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5130                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5131                                          SelectionDAG &DAG, const SDLoc &dl) {
5132   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5133   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5134                        Flags.getNonZeroByValAlign(), false, false, false,
5135                        MachinePointerInfo(), MachinePointerInfo());
5136 }
5137 
5138 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5139 /// tail calls.
5140 static void LowerMemOpCallTo(
5141     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5142     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5143     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5144     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5145   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5146   if (!isTailCall) {
5147     if (isVector) {
5148       SDValue StackPtr;
5149       if (isPPC64)
5150         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5151       else
5152         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5153       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5154                            DAG.getConstant(ArgOffset, dl, PtrVT));
5155     }
5156     MemOpChains.push_back(
5157         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5158     // Calculate and remember argument location.
5159   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5160                                   TailCallArguments);
5161 }
5162 
5163 static void
5164 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5165                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5166                 SDValue FPOp,
5167                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5168   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5169   // might overwrite each other in case of tail call optimization.
5170   SmallVector<SDValue, 8> MemOpChains2;
5171   // Do not flag preceding copytoreg stuff together with the following stuff.
5172   InFlag = SDValue();
5173   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5174                                     MemOpChains2, dl);
5175   if (!MemOpChains2.empty())
5176     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5177 
5178   // Store the return address to the appropriate stack slot.
5179   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5180 
5181   // Emit callseq_end just before tailcall node.
5182   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5183                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5184   InFlag = Chain.getValue(1);
5185 }
5186 
5187 // Is this global address that of a function that can be called by name? (as
5188 // opposed to something that must hold a descriptor for an indirect call).
5189 static bool isFunctionGlobalAddress(SDValue Callee) {
5190   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5191     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5192         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5193       return false;
5194 
5195     return G->getGlobal()->getValueType()->isFunctionTy();
5196   }
5197 
5198   return false;
5199 }
5200 
5201 SDValue PPCTargetLowering::LowerCallResult(
5202     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5203     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5204     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5205   SmallVector<CCValAssign, 16> RVLocs;
5206   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5207                     *DAG.getContext());
5208 
5209   CCRetInfo.AnalyzeCallResult(
5210       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5211                ? RetCC_PPC_Cold
5212                : RetCC_PPC);
5213 
5214   // Copy all of the result registers out of their specified physreg.
5215   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5216     CCValAssign &VA = RVLocs[i];
5217     assert(VA.isRegLoc() && "Can only return in registers!");
5218 
5219     SDValue Val;
5220 
5221     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5222       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5223                                       InFlag);
5224       Chain = Lo.getValue(1);
5225       InFlag = Lo.getValue(2);
5226       VA = RVLocs[++i]; // skip ahead to next loc
5227       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5228                                       InFlag);
5229       Chain = Hi.getValue(1);
5230       InFlag = Hi.getValue(2);
5231       if (!Subtarget.isLittleEndian())
5232         std::swap (Lo, Hi);
5233       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5234     } else {
5235       Val = DAG.getCopyFromReg(Chain, dl,
5236                                VA.getLocReg(), VA.getLocVT(), InFlag);
5237       Chain = Val.getValue(1);
5238       InFlag = Val.getValue(2);
5239     }
5240 
5241     switch (VA.getLocInfo()) {
5242     default: llvm_unreachable("Unknown loc info!");
5243     case CCValAssign::Full: break;
5244     case CCValAssign::AExt:
5245       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5246       break;
5247     case CCValAssign::ZExt:
5248       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5249                         DAG.getValueType(VA.getValVT()));
5250       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5251       break;
5252     case CCValAssign::SExt:
5253       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5254                         DAG.getValueType(VA.getValVT()));
5255       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5256       break;
5257     }
5258 
5259     InVals.push_back(Val);
5260   }
5261 
5262   return Chain;
5263 }
5264 
5265 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5266                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5267   // PatchPoint calls are not indirect.
5268   if (isPatchPoint)
5269     return false;
5270 
5271   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5272     return false;
5273 
5274   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5275   // becuase the immediate function pointer points to a descriptor instead of
5276   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5277   // pointer immediate points to the global entry point, while the BLA would
5278   // need to jump to the local entry point (see rL211174).
5279   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5280       isBLACompatibleAddress(Callee, DAG))
5281     return false;
5282 
5283   return true;
5284 }
5285 
5286 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5287 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5288   return Subtarget.isAIXABI() ||
5289          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5290 }
5291 
5292 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5293                               const Function &Caller,
5294                               const SDValue &Callee,
5295                               const PPCSubtarget &Subtarget,
5296                               const TargetMachine &TM) {
5297   if (CFlags.IsTailCall)
5298     return PPCISD::TC_RETURN;
5299 
5300   // This is a call through a function pointer.
5301   if (CFlags.IsIndirect) {
5302     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5303     // indirect calls. The save of the caller's TOC pointer to the stack will be
5304     // inserted into the DAG as part of call lowering. The restore of the TOC
5305     // pointer is modeled by using a pseudo instruction for the call opcode that
5306     // represents the 2 instruction sequence of an indirect branch and link,
5307     // immediately followed by a load of the TOC pointer from the the stack save
5308     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5309     // as it is not saved or used.
5310     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5311                                                : PPCISD::BCTRL;
5312   }
5313 
5314   if (Subtarget.isUsingPCRelativeCalls()) {
5315     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5316     return PPCISD::CALL_NOTOC;
5317   }
5318 
5319   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5320   // immediately following the call instruction if the caller and callee may
5321   // have different TOC bases. At link time if the linker determines the calls
5322   // may not share a TOC base, the call is redirected to a trampoline inserted
5323   // by the linker. The trampoline will (among other things) save the callers
5324   // TOC pointer at an ABI designated offset in the linkage area and the linker
5325   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5326   // into gpr2.
5327   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5328     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5329                                                   : PPCISD::CALL_NOP;
5330 
5331   return PPCISD::CALL;
5332 }
5333 
5334 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5335                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5336   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5337     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5338       return SDValue(Dest, 0);
5339 
5340   // Returns true if the callee is local, and false otherwise.
5341   auto isLocalCallee = [&]() {
5342     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5343     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5344     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5345 
5346     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5347            !dyn_cast_or_null<GlobalIFunc>(GV);
5348   };
5349 
5350   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5351   // a static relocation model causes some versions of GNU LD (2.17.50, at
5352   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5353   // built with secure-PLT.
5354   bool UsePlt =
5355       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5356       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5357 
5358   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5359     const TargetMachine &TM = Subtarget.getTargetMachine();
5360     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5361     MCSymbolXCOFF *S =
5362         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5363 
5364     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5365     return DAG.getMCSymbol(S, PtrVT);
5366   };
5367 
5368   if (isFunctionGlobalAddress(Callee)) {
5369     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5370 
5371     if (Subtarget.isAIXABI()) {
5372       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5373       return getAIXFuncEntryPointSymbolSDNode(GV);
5374     }
5375     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5376                                       UsePlt ? PPCII::MO_PLT : 0);
5377   }
5378 
5379   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5380     const char *SymName = S->getSymbol();
5381     if (Subtarget.isAIXABI()) {
5382       // If there exists a user-declared function whose name is the same as the
5383       // ExternalSymbol's, then we pick up the user-declared version.
5384       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5385       if (const Function *F =
5386               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5387         return getAIXFuncEntryPointSymbolSDNode(F);
5388 
5389       // On AIX, direct function calls reference the symbol for the function's
5390       // entry point, which is named by prepending a "." before the function's
5391       // C-linkage name. A Qualname is returned here because an external
5392       // function entry point is a csect with XTY_ER property.
5393       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5394         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5395         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5396             (Twine(".") + Twine(SymName)).str(), XCOFF::XMC_PR, XCOFF::XTY_ER,
5397             SectionKind::getMetadata());
5398         return Sec->getQualNameSymbol();
5399       };
5400 
5401       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5402     }
5403     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5404                                        UsePlt ? PPCII::MO_PLT : 0);
5405   }
5406 
5407   // No transformation needed.
5408   assert(Callee.getNode() && "What no callee?");
5409   return Callee;
5410 }
5411 
5412 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5413   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5414          "Expected a CALLSEQ_STARTSDNode.");
5415 
5416   // The last operand is the chain, except when the node has glue. If the node
5417   // has glue, then the last operand is the glue, and the chain is the second
5418   // last operand.
5419   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5420   if (LastValue.getValueType() != MVT::Glue)
5421     return LastValue;
5422 
5423   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5424 }
5425 
5426 // Creates the node that moves a functions address into the count register
5427 // to prepare for an indirect call instruction.
5428 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5429                                 SDValue &Glue, SDValue &Chain,
5430                                 const SDLoc &dl) {
5431   SDValue MTCTROps[] = {Chain, Callee, Glue};
5432   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5433   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5434                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5435   // The glue is the second value produced.
5436   Glue = Chain.getValue(1);
5437 }
5438 
5439 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5440                                           SDValue &Glue, SDValue &Chain,
5441                                           SDValue CallSeqStart,
5442                                           const CallBase *CB, const SDLoc &dl,
5443                                           bool hasNest,
5444                                           const PPCSubtarget &Subtarget) {
5445   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5446   // entry point, but to the function descriptor (the function entry point
5447   // address is part of the function descriptor though).
5448   // The function descriptor is a three doubleword structure with the
5449   // following fields: function entry point, TOC base address and
5450   // environment pointer.
5451   // Thus for a call through a function pointer, the following actions need
5452   // to be performed:
5453   //   1. Save the TOC of the caller in the TOC save area of its stack
5454   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5455   //   2. Load the address of the function entry point from the function
5456   //      descriptor.
5457   //   3. Load the TOC of the callee from the function descriptor into r2.
5458   //   4. Load the environment pointer from the function descriptor into
5459   //      r11.
5460   //   5. Branch to the function entry point address.
5461   //   6. On return of the callee, the TOC of the caller needs to be
5462   //      restored (this is done in FinishCall()).
5463   //
5464   // The loads are scheduled at the beginning of the call sequence, and the
5465   // register copies are flagged together to ensure that no other
5466   // operations can be scheduled in between. E.g. without flagging the
5467   // copies together, a TOC access in the caller could be scheduled between
5468   // the assignment of the callee TOC and the branch to the callee, which leads
5469   // to incorrect code.
5470 
5471   // Start by loading the function address from the descriptor.
5472   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5473   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5474                       ? (MachineMemOperand::MODereferenceable |
5475                          MachineMemOperand::MOInvariant)
5476                       : MachineMemOperand::MONone;
5477 
5478   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5479 
5480   // Registers used in building the DAG.
5481   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5482   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5483 
5484   // Offsets of descriptor members.
5485   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5486   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5487 
5488   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5489   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5490 
5491   // One load for the functions entry point address.
5492   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5493                                     Alignment, MMOFlags);
5494 
5495   // One for loading the TOC anchor for the module that contains the called
5496   // function.
5497   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5498   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5499   SDValue TOCPtr =
5500       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5501                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5502 
5503   // One for loading the environment pointer.
5504   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5505   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5506   SDValue LoadEnvPtr =
5507       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5508                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5509 
5510 
5511   // Then copy the newly loaded TOC anchor to the TOC pointer.
5512   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5513   Chain = TOCVal.getValue(0);
5514   Glue = TOCVal.getValue(1);
5515 
5516   // If the function call has an explicit 'nest' parameter, it takes the
5517   // place of the environment pointer.
5518   assert((!hasNest || !Subtarget.isAIXABI()) &&
5519          "Nest parameter is not supported on AIX.");
5520   if (!hasNest) {
5521     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5522     Chain = EnvVal.getValue(0);
5523     Glue = EnvVal.getValue(1);
5524   }
5525 
5526   // The rest of the indirect call sequence is the same as the non-descriptor
5527   // DAG.
5528   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5529 }
5530 
5531 static void
5532 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5533                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5534                   SelectionDAG &DAG,
5535                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5536                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5537                   const PPCSubtarget &Subtarget) {
5538   const bool IsPPC64 = Subtarget.isPPC64();
5539   // MVT for a general purpose register.
5540   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5541 
5542   // First operand is always the chain.
5543   Ops.push_back(Chain);
5544 
5545   // If it's a direct call pass the callee as the second operand.
5546   if (!CFlags.IsIndirect)
5547     Ops.push_back(Callee);
5548   else {
5549     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5550 
5551     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5552     // on the stack (this would have been done in `LowerCall_64SVR4` or
5553     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5554     // represents both the indirect branch and a load that restores the TOC
5555     // pointer from the linkage area. The operand for the TOC restore is an add
5556     // of the TOC save offset to the stack pointer. This must be the second
5557     // operand: after the chain input but before any other variadic arguments.
5558     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5559     // saved or used.
5560     if (isTOCSaveRestoreRequired(Subtarget)) {
5561       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5562 
5563       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5564       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5565       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5566       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5567       Ops.push_back(AddTOC);
5568     }
5569 
5570     // Add the register used for the environment pointer.
5571     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5572       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5573                                     RegVT));
5574 
5575 
5576     // Add CTR register as callee so a bctr can be emitted later.
5577     if (CFlags.IsTailCall)
5578       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5579   }
5580 
5581   // If this is a tail call add stack pointer delta.
5582   if (CFlags.IsTailCall)
5583     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5584 
5585   // Add argument registers to the end of the list so that they are known live
5586   // into the call.
5587   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5588     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5589                                   RegsToPass[i].second.getValueType()));
5590 
5591   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5592   // no way to mark dependencies as implicit here.
5593   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5594   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5595        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5596     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5597 
5598   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5599   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5600     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5601 
5602   // Add a register mask operand representing the call-preserved registers.
5603   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5604   const uint32_t *Mask =
5605       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5606   assert(Mask && "Missing call preserved mask for calling convention");
5607   Ops.push_back(DAG.getRegisterMask(Mask));
5608 
5609   // If the glue is valid, it is the last operand.
5610   if (Glue.getNode())
5611     Ops.push_back(Glue);
5612 }
5613 
5614 SDValue PPCTargetLowering::FinishCall(
5615     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5616     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5617     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5618     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5619     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5620 
5621   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5622       Subtarget.isAIXABI())
5623     setUsesTOCBasePtr(DAG);
5624 
5625   unsigned CallOpc =
5626       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5627                     Subtarget, DAG.getTarget());
5628 
5629   if (!CFlags.IsIndirect)
5630     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5631   else if (Subtarget.usesFunctionDescriptors())
5632     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5633                                   dl, CFlags.HasNest, Subtarget);
5634   else
5635     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5636 
5637   // Build the operand list for the call instruction.
5638   SmallVector<SDValue, 8> Ops;
5639   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5640                     SPDiff, Subtarget);
5641 
5642   // Emit tail call.
5643   if (CFlags.IsTailCall) {
5644     // Indirect tail call when using PC Relative calls do not have the same
5645     // constraints.
5646     assert(((Callee.getOpcode() == ISD::Register &&
5647              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5648             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5649             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5650             isa<ConstantSDNode>(Callee) ||
5651             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5652            "Expecting a global address, external symbol, absolute value, "
5653            "register or an indirect tail call when PC Relative calls are "
5654            "used.");
5655     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5656     assert(CallOpc == PPCISD::TC_RETURN &&
5657            "Unexpected call opcode for a tail call.");
5658     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5659     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5660   }
5661 
5662   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5663   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5664   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5665   Glue = Chain.getValue(1);
5666 
5667   // When performing tail call optimization the callee pops its arguments off
5668   // the stack. Account for this here so these bytes can be pushed back on in
5669   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5670   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5671                          getTargetMachine().Options.GuaranteedTailCallOpt)
5672                             ? NumBytes
5673                             : 0;
5674 
5675   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5676                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5677                              Glue, dl);
5678   Glue = Chain.getValue(1);
5679 
5680   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5681                          DAG, InVals);
5682 }
5683 
5684 SDValue
5685 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5686                              SmallVectorImpl<SDValue> &InVals) const {
5687   SelectionDAG &DAG                     = CLI.DAG;
5688   SDLoc &dl                             = CLI.DL;
5689   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5690   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5691   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5692   SDValue Chain                         = CLI.Chain;
5693   SDValue Callee                        = CLI.Callee;
5694   bool &isTailCall                      = CLI.IsTailCall;
5695   CallingConv::ID CallConv              = CLI.CallConv;
5696   bool isVarArg                         = CLI.IsVarArg;
5697   bool isPatchPoint                     = CLI.IsPatchPoint;
5698   const CallBase *CB                    = CLI.CB;
5699 
5700   if (isTailCall) {
5701     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5702       isTailCall = false;
5703     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5704       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5705           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5706     else
5707       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5708                                                      Ins, DAG);
5709     if (isTailCall) {
5710       ++NumTailCalls;
5711       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5712         ++NumSiblingCalls;
5713 
5714       // PC Relative calls no longer guarantee that the callee is a Global
5715       // Address Node. The callee could be an indirect tail call in which
5716       // case the SDValue for the callee could be a load (to load the address
5717       // of a function pointer) or it may be a register copy (to move the
5718       // address of the callee from a function parameter into a virtual
5719       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5720       assert((Subtarget.isUsingPCRelativeCalls() ||
5721               isa<GlobalAddressSDNode>(Callee)) &&
5722              "Callee should be an llvm::Function object.");
5723 
5724       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5725                         << "\nTCO callee: ");
5726       LLVM_DEBUG(Callee.dump());
5727     }
5728   }
5729 
5730   if (!isTailCall && CB && CB->isMustTailCall())
5731     report_fatal_error("failed to perform tail call elimination on a call "
5732                        "site marked musttail");
5733 
5734   // When long calls (i.e. indirect calls) are always used, calls are always
5735   // made via function pointer. If we have a function name, first translate it
5736   // into a pointer.
5737   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5738       !isTailCall)
5739     Callee = LowerGlobalAddress(Callee, DAG);
5740 
5741   CallFlags CFlags(
5742       CallConv, isTailCall, isVarArg, isPatchPoint,
5743       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5744       // hasNest
5745       Subtarget.is64BitELFABI() &&
5746           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5747       CLI.NoMerge);
5748 
5749   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5750     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5751                             InVals, CB);
5752 
5753   if (Subtarget.isSVR4ABI())
5754     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5755                             InVals, CB);
5756 
5757   if (Subtarget.isAIXABI())
5758     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5759                          InVals, CB);
5760 
5761   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5762                           InVals, CB);
5763 }
5764 
5765 SDValue PPCTargetLowering::LowerCall_32SVR4(
5766     SDValue Chain, SDValue Callee, CallFlags CFlags,
5767     const SmallVectorImpl<ISD::OutputArg> &Outs,
5768     const SmallVectorImpl<SDValue> &OutVals,
5769     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5770     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5771     const CallBase *CB) const {
5772   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5773   // of the 32-bit SVR4 ABI stack frame layout.
5774 
5775   const CallingConv::ID CallConv = CFlags.CallConv;
5776   const bool IsVarArg = CFlags.IsVarArg;
5777   const bool IsTailCall = CFlags.IsTailCall;
5778 
5779   assert((CallConv == CallingConv::C ||
5780           CallConv == CallingConv::Cold ||
5781           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5782 
5783   const Align PtrAlign(4);
5784 
5785   MachineFunction &MF = DAG.getMachineFunction();
5786 
5787   // Mark this function as potentially containing a function that contains a
5788   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5789   // and restoring the callers stack pointer in this functions epilog. This is
5790   // done because by tail calling the called function might overwrite the value
5791   // in this function's (MF) stack pointer stack slot 0(SP).
5792   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5793       CallConv == CallingConv::Fast)
5794     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5795 
5796   // Count how many bytes are to be pushed on the stack, including the linkage
5797   // area, parameter list area and the part of the local variable space which
5798   // contains copies of aggregates which are passed by value.
5799 
5800   // Assign locations to all of the outgoing arguments.
5801   SmallVector<CCValAssign, 16> ArgLocs;
5802   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5803 
5804   // Reserve space for the linkage area on the stack.
5805   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5806                        PtrAlign);
5807   if (useSoftFloat())
5808     CCInfo.PreAnalyzeCallOperands(Outs);
5809 
5810   if (IsVarArg) {
5811     // Handle fixed and variable vector arguments differently.
5812     // Fixed vector arguments go into registers as long as registers are
5813     // available. Variable vector arguments always go into memory.
5814     unsigned NumArgs = Outs.size();
5815 
5816     for (unsigned i = 0; i != NumArgs; ++i) {
5817       MVT ArgVT = Outs[i].VT;
5818       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5819       bool Result;
5820 
5821       if (Outs[i].IsFixed) {
5822         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5823                                CCInfo);
5824       } else {
5825         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5826                                       ArgFlags, CCInfo);
5827       }
5828 
5829       if (Result) {
5830 #ifndef NDEBUG
5831         errs() << "Call operand #" << i << " has unhandled type "
5832              << EVT(ArgVT).getEVTString() << "\n";
5833 #endif
5834         llvm_unreachable(nullptr);
5835       }
5836     }
5837   } else {
5838     // All arguments are treated the same.
5839     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5840   }
5841   CCInfo.clearWasPPCF128();
5842 
5843   // Assign locations to all of the outgoing aggregate by value arguments.
5844   SmallVector<CCValAssign, 16> ByValArgLocs;
5845   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5846 
5847   // Reserve stack space for the allocations in CCInfo.
5848   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5849 
5850   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5851 
5852   // Size of the linkage area, parameter list area and the part of the local
5853   // space variable where copies of aggregates which are passed by value are
5854   // stored.
5855   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5856 
5857   // Calculate by how many bytes the stack has to be adjusted in case of tail
5858   // call optimization.
5859   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5860 
5861   // Adjust the stack pointer for the new arguments...
5862   // These operations are automatically eliminated by the prolog/epilog pass
5863   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5864   SDValue CallSeqStart = Chain;
5865 
5866   // Load the return address and frame pointer so it can be moved somewhere else
5867   // later.
5868   SDValue LROp, FPOp;
5869   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5870 
5871   // Set up a copy of the stack pointer for use loading and storing any
5872   // arguments that may not fit in the registers available for argument
5873   // passing.
5874   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5875 
5876   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5877   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5878   SmallVector<SDValue, 8> MemOpChains;
5879 
5880   bool seenFloatArg = false;
5881   // Walk the register/memloc assignments, inserting copies/loads.
5882   // i - Tracks the index into the list of registers allocated for the call
5883   // RealArgIdx - Tracks the index into the list of actual function arguments
5884   // j - Tracks the index into the list of byval arguments
5885   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5886        i != e;
5887        ++i, ++RealArgIdx) {
5888     CCValAssign &VA = ArgLocs[i];
5889     SDValue Arg = OutVals[RealArgIdx];
5890     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5891 
5892     if (Flags.isByVal()) {
5893       // Argument is an aggregate which is passed by value, thus we need to
5894       // create a copy of it in the local variable space of the current stack
5895       // frame (which is the stack frame of the caller) and pass the address of
5896       // this copy to the callee.
5897       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5898       CCValAssign &ByValVA = ByValArgLocs[j++];
5899       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5900 
5901       // Memory reserved in the local variable space of the callers stack frame.
5902       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5903 
5904       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5905       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5906                            StackPtr, PtrOff);
5907 
5908       // Create a copy of the argument in the local area of the current
5909       // stack frame.
5910       SDValue MemcpyCall =
5911         CreateCopyOfByValArgument(Arg, PtrOff,
5912                                   CallSeqStart.getNode()->getOperand(0),
5913                                   Flags, DAG, dl);
5914 
5915       // This must go outside the CALLSEQ_START..END.
5916       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5917                                                      SDLoc(MemcpyCall));
5918       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5919                              NewCallSeqStart.getNode());
5920       Chain = CallSeqStart = NewCallSeqStart;
5921 
5922       // Pass the address of the aggregate copy on the stack either in a
5923       // physical register or in the parameter list area of the current stack
5924       // frame to the callee.
5925       Arg = PtrOff;
5926     }
5927 
5928     // When useCRBits() is true, there can be i1 arguments.
5929     // It is because getRegisterType(MVT::i1) => MVT::i1,
5930     // and for other integer types getRegisterType() => MVT::i32.
5931     // Extend i1 and ensure callee will get i32.
5932     if (Arg.getValueType() == MVT::i1)
5933       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5934                         dl, MVT::i32, Arg);
5935 
5936     if (VA.isRegLoc()) {
5937       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5938       // Put argument in a physical register.
5939       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5940         bool IsLE = Subtarget.isLittleEndian();
5941         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5942                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5943         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5944         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5945                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5946         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5947                              SVal.getValue(0)));
5948       } else
5949         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5950     } else {
5951       // Put argument in the parameter list area of the current stack frame.
5952       assert(VA.isMemLoc());
5953       unsigned LocMemOffset = VA.getLocMemOffset();
5954 
5955       if (!IsTailCall) {
5956         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5957         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5958                              StackPtr, PtrOff);
5959 
5960         MemOpChains.push_back(
5961             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5962       } else {
5963         // Calculate and remember argument location.
5964         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5965                                  TailCallArguments);
5966       }
5967     }
5968   }
5969 
5970   if (!MemOpChains.empty())
5971     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5972 
5973   // Build a sequence of copy-to-reg nodes chained together with token chain
5974   // and flag operands which copy the outgoing args into the appropriate regs.
5975   SDValue InFlag;
5976   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5977     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5978                              RegsToPass[i].second, InFlag);
5979     InFlag = Chain.getValue(1);
5980   }
5981 
5982   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5983   // registers.
5984   if (IsVarArg) {
5985     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5986     SDValue Ops[] = { Chain, InFlag };
5987 
5988     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5989                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5990 
5991     InFlag = Chain.getValue(1);
5992   }
5993 
5994   if (IsTailCall)
5995     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5996                     TailCallArguments);
5997 
5998   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5999                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6000 }
6001 
6002 // Copy an argument into memory, being careful to do this outside the
6003 // call sequence for the call to which the argument belongs.
6004 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
6005     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
6006     SelectionDAG &DAG, const SDLoc &dl) const {
6007   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
6008                         CallSeqStart.getNode()->getOperand(0),
6009                         Flags, DAG, dl);
6010   // The MEMCPY must go outside the CALLSEQ_START..END.
6011   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
6012   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
6013                                                  SDLoc(MemcpyCall));
6014   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
6015                          NewCallSeqStart.getNode());
6016   return NewCallSeqStart;
6017 }
6018 
6019 SDValue PPCTargetLowering::LowerCall_64SVR4(
6020     SDValue Chain, SDValue Callee, CallFlags CFlags,
6021     const SmallVectorImpl<ISD::OutputArg> &Outs,
6022     const SmallVectorImpl<SDValue> &OutVals,
6023     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6024     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6025     const CallBase *CB) const {
6026   bool isELFv2ABI = Subtarget.isELFv2ABI();
6027   bool isLittleEndian = Subtarget.isLittleEndian();
6028   unsigned NumOps = Outs.size();
6029   bool IsSibCall = false;
6030   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
6031 
6032   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6033   unsigned PtrByteSize = 8;
6034 
6035   MachineFunction &MF = DAG.getMachineFunction();
6036 
6037   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
6038     IsSibCall = true;
6039 
6040   // Mark this function as potentially containing a function that contains a
6041   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6042   // and restoring the callers stack pointer in this functions epilog. This is
6043   // done because by tail calling the called function might overwrite the value
6044   // in this function's (MF) stack pointer stack slot 0(SP).
6045   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6046     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6047 
6048   assert(!(IsFastCall && CFlags.IsVarArg) &&
6049          "fastcc not supported on varargs functions");
6050 
6051   // Count how many bytes are to be pushed on the stack, including the linkage
6052   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
6053   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
6054   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
6055   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6056   unsigned NumBytes = LinkageSize;
6057   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6058 
6059   static const MCPhysReg GPR[] = {
6060     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6061     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6062   };
6063   static const MCPhysReg VR[] = {
6064     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6065     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6066   };
6067 
6068   const unsigned NumGPRs = array_lengthof(GPR);
6069   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
6070   const unsigned NumVRs  = array_lengthof(VR);
6071 
6072   // On ELFv2, we can avoid allocating the parameter area if all the arguments
6073   // can be passed to the callee in registers.
6074   // For the fast calling convention, there is another check below.
6075   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6076   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6077   if (!HasParameterArea) {
6078     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6079     unsigned AvailableFPRs = NumFPRs;
6080     unsigned AvailableVRs = NumVRs;
6081     unsigned NumBytesTmp = NumBytes;
6082     for (unsigned i = 0; i != NumOps; ++i) {
6083       if (Outs[i].Flags.isNest()) continue;
6084       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6085                                  PtrByteSize, LinkageSize, ParamAreaSize,
6086                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
6087         HasParameterArea = true;
6088     }
6089   }
6090 
6091   // When using the fast calling convention, we don't provide backing for
6092   // arguments that will be in registers.
6093   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6094 
6095   // Avoid allocating parameter area for fastcc functions if all the arguments
6096   // can be passed in the registers.
6097   if (IsFastCall)
6098     HasParameterArea = false;
6099 
6100   // Add up all the space actually used.
6101   for (unsigned i = 0; i != NumOps; ++i) {
6102     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6103     EVT ArgVT = Outs[i].VT;
6104     EVT OrigVT = Outs[i].ArgVT;
6105 
6106     if (Flags.isNest())
6107       continue;
6108 
6109     if (IsFastCall) {
6110       if (Flags.isByVal()) {
6111         NumGPRsUsed += (Flags.getByValSize()+7)/8;
6112         if (NumGPRsUsed > NumGPRs)
6113           HasParameterArea = true;
6114       } else {
6115         switch (ArgVT.getSimpleVT().SimpleTy) {
6116         default: llvm_unreachable("Unexpected ValueType for argument!");
6117         case MVT::i1:
6118         case MVT::i32:
6119         case MVT::i64:
6120           if (++NumGPRsUsed <= NumGPRs)
6121             continue;
6122           break;
6123         case MVT::v4i32:
6124         case MVT::v8i16:
6125         case MVT::v16i8:
6126         case MVT::v2f64:
6127         case MVT::v2i64:
6128         case MVT::v1i128:
6129         case MVT::f128:
6130           if (++NumVRsUsed <= NumVRs)
6131             continue;
6132           break;
6133         case MVT::v4f32:
6134           if (++NumVRsUsed <= NumVRs)
6135             continue;
6136           break;
6137         case MVT::f32:
6138         case MVT::f64:
6139           if (++NumFPRsUsed <= NumFPRs)
6140             continue;
6141           break;
6142         }
6143         HasParameterArea = true;
6144       }
6145     }
6146 
6147     /* Respect alignment of argument on the stack.  */
6148     auto Alignement =
6149         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6150     NumBytes = alignTo(NumBytes, Alignement);
6151 
6152     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6153     if (Flags.isInConsecutiveRegsLast())
6154       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6155   }
6156 
6157   unsigned NumBytesActuallyUsed = NumBytes;
6158 
6159   // In the old ELFv1 ABI,
6160   // the prolog code of the callee may store up to 8 GPR argument registers to
6161   // the stack, allowing va_start to index over them in memory if its varargs.
6162   // Because we cannot tell if this is needed on the caller side, we have to
6163   // conservatively assume that it is needed.  As such, make sure we have at
6164   // least enough stack space for the caller to store the 8 GPRs.
6165   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6166   // really requires memory operands, e.g. a vararg function.
6167   if (HasParameterArea)
6168     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6169   else
6170     NumBytes = LinkageSize;
6171 
6172   // Tail call needs the stack to be aligned.
6173   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6174     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6175 
6176   int SPDiff = 0;
6177 
6178   // Calculate by how many bytes the stack has to be adjusted in case of tail
6179   // call optimization.
6180   if (!IsSibCall)
6181     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6182 
6183   // To protect arguments on the stack from being clobbered in a tail call,
6184   // force all the loads to happen before doing any other lowering.
6185   if (CFlags.IsTailCall)
6186     Chain = DAG.getStackArgumentTokenFactor(Chain);
6187 
6188   // Adjust the stack pointer for the new arguments...
6189   // These operations are automatically eliminated by the prolog/epilog pass
6190   if (!IsSibCall)
6191     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6192   SDValue CallSeqStart = Chain;
6193 
6194   // Load the return address and frame pointer so it can be move somewhere else
6195   // later.
6196   SDValue LROp, FPOp;
6197   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6198 
6199   // Set up a copy of the stack pointer for use loading and storing any
6200   // arguments that may not fit in the registers available for argument
6201   // passing.
6202   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6203 
6204   // Figure out which arguments are going to go in registers, and which in
6205   // memory.  Also, if this is a vararg function, floating point operations
6206   // must be stored to our stack, and loaded into integer regs as well, if
6207   // any integer regs are available for argument passing.
6208   unsigned ArgOffset = LinkageSize;
6209 
6210   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6211   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6212 
6213   SmallVector<SDValue, 8> MemOpChains;
6214   for (unsigned i = 0; i != NumOps; ++i) {
6215     SDValue Arg = OutVals[i];
6216     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6217     EVT ArgVT = Outs[i].VT;
6218     EVT OrigVT = Outs[i].ArgVT;
6219 
6220     // PtrOff will be used to store the current argument to the stack if a
6221     // register cannot be found for it.
6222     SDValue PtrOff;
6223 
6224     // We re-align the argument offset for each argument, except when using the
6225     // fast calling convention, when we need to make sure we do that only when
6226     // we'll actually use a stack slot.
6227     auto ComputePtrOff = [&]() {
6228       /* Respect alignment of argument on the stack.  */
6229       auto Alignment =
6230           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6231       ArgOffset = alignTo(ArgOffset, Alignment);
6232 
6233       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6234 
6235       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6236     };
6237 
6238     if (!IsFastCall) {
6239       ComputePtrOff();
6240 
6241       /* Compute GPR index associated with argument offset.  */
6242       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6243       GPR_idx = std::min(GPR_idx, NumGPRs);
6244     }
6245 
6246     // Promote integers to 64-bit values.
6247     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6248       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6249       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6250       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6251     }
6252 
6253     // FIXME memcpy is used way more than necessary.  Correctness first.
6254     // Note: "by value" is code for passing a structure by value, not
6255     // basic types.
6256     if (Flags.isByVal()) {
6257       // Note: Size includes alignment padding, so
6258       //   struct x { short a; char b; }
6259       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6260       // These are the proper values we need for right-justifying the
6261       // aggregate in a parameter register.
6262       unsigned Size = Flags.getByValSize();
6263 
6264       // An empty aggregate parameter takes up no storage and no
6265       // registers.
6266       if (Size == 0)
6267         continue;
6268 
6269       if (IsFastCall)
6270         ComputePtrOff();
6271 
6272       // All aggregates smaller than 8 bytes must be passed right-justified.
6273       if (Size==1 || Size==2 || Size==4) {
6274         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6275         if (GPR_idx != NumGPRs) {
6276           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6277                                         MachinePointerInfo(), VT);
6278           MemOpChains.push_back(Load.getValue(1));
6279           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6280 
6281           ArgOffset += PtrByteSize;
6282           continue;
6283         }
6284       }
6285 
6286       if (GPR_idx == NumGPRs && Size < 8) {
6287         SDValue AddPtr = PtrOff;
6288         if (!isLittleEndian) {
6289           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6290                                           PtrOff.getValueType());
6291           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6292         }
6293         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6294                                                           CallSeqStart,
6295                                                           Flags, DAG, dl);
6296         ArgOffset += PtrByteSize;
6297         continue;
6298       }
6299       // Copy entire object into memory.  There are cases where gcc-generated
6300       // code assumes it is there, even if it could be put entirely into
6301       // registers.  (This is not what the doc says.)
6302 
6303       // FIXME: The above statement is likely due to a misunderstanding of the
6304       // documents.  All arguments must be copied into the parameter area BY
6305       // THE CALLEE in the event that the callee takes the address of any
6306       // formal argument.  That has not yet been implemented.  However, it is
6307       // reasonable to use the stack area as a staging area for the register
6308       // load.
6309 
6310       // Skip this for small aggregates, as we will use the same slot for a
6311       // right-justified copy, below.
6312       if (Size >= 8)
6313         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6314                                                           CallSeqStart,
6315                                                           Flags, DAG, dl);
6316 
6317       // When a register is available, pass a small aggregate right-justified.
6318       if (Size < 8 && GPR_idx != NumGPRs) {
6319         // The easiest way to get this right-justified in a register
6320         // is to copy the structure into the rightmost portion of a
6321         // local variable slot, then load the whole slot into the
6322         // register.
6323         // FIXME: The memcpy seems to produce pretty awful code for
6324         // small aggregates, particularly for packed ones.
6325         // FIXME: It would be preferable to use the slot in the
6326         // parameter save area instead of a new local variable.
6327         SDValue AddPtr = PtrOff;
6328         if (!isLittleEndian) {
6329           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6330           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6331         }
6332         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6333                                                           CallSeqStart,
6334                                                           Flags, DAG, dl);
6335 
6336         // Load the slot into the register.
6337         SDValue Load =
6338             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6339         MemOpChains.push_back(Load.getValue(1));
6340         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6341 
6342         // Done with this argument.
6343         ArgOffset += PtrByteSize;
6344         continue;
6345       }
6346 
6347       // For aggregates larger than PtrByteSize, copy the pieces of the
6348       // object that fit into registers from the parameter save area.
6349       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6350         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6351         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6352         if (GPR_idx != NumGPRs) {
6353           SDValue Load =
6354               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6355           MemOpChains.push_back(Load.getValue(1));
6356           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6357           ArgOffset += PtrByteSize;
6358         } else {
6359           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6360           break;
6361         }
6362       }
6363       continue;
6364     }
6365 
6366     switch (Arg.getSimpleValueType().SimpleTy) {
6367     default: llvm_unreachable("Unexpected ValueType for argument!");
6368     case MVT::i1:
6369     case MVT::i32:
6370     case MVT::i64:
6371       if (Flags.isNest()) {
6372         // The 'nest' parameter, if any, is passed in R11.
6373         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6374         break;
6375       }
6376 
6377       // These can be scalar arguments or elements of an integer array type
6378       // passed directly.  Clang may use those instead of "byval" aggregate
6379       // types to avoid forcing arguments to memory unnecessarily.
6380       if (GPR_idx != NumGPRs) {
6381         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6382       } else {
6383         if (IsFastCall)
6384           ComputePtrOff();
6385 
6386         assert(HasParameterArea &&
6387                "Parameter area must exist to pass an argument in memory.");
6388         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6389                          true, CFlags.IsTailCall, false, MemOpChains,
6390                          TailCallArguments, dl);
6391         if (IsFastCall)
6392           ArgOffset += PtrByteSize;
6393       }
6394       if (!IsFastCall)
6395         ArgOffset += PtrByteSize;
6396       break;
6397     case MVT::f32:
6398     case MVT::f64: {
6399       // These can be scalar arguments or elements of a float array type
6400       // passed directly.  The latter are used to implement ELFv2 homogenous
6401       // float aggregates.
6402 
6403       // Named arguments go into FPRs first, and once they overflow, the
6404       // remaining arguments go into GPRs and then the parameter save area.
6405       // Unnamed arguments for vararg functions always go to GPRs and
6406       // then the parameter save area.  For now, put all arguments to vararg
6407       // routines always in both locations (FPR *and* GPR or stack slot).
6408       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6409       bool NeededLoad = false;
6410 
6411       // First load the argument into the next available FPR.
6412       if (FPR_idx != NumFPRs)
6413         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6414 
6415       // Next, load the argument into GPR or stack slot if needed.
6416       if (!NeedGPROrStack)
6417         ;
6418       else if (GPR_idx != NumGPRs && !IsFastCall) {
6419         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6420         // once we support fp <-> gpr moves.
6421 
6422         // In the non-vararg case, this can only ever happen in the
6423         // presence of f32 array types, since otherwise we never run
6424         // out of FPRs before running out of GPRs.
6425         SDValue ArgVal;
6426 
6427         // Double values are always passed in a single GPR.
6428         if (Arg.getValueType() != MVT::f32) {
6429           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6430 
6431         // Non-array float values are extended and passed in a GPR.
6432         } else if (!Flags.isInConsecutiveRegs()) {
6433           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6434           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6435 
6436         // If we have an array of floats, we collect every odd element
6437         // together with its predecessor into one GPR.
6438         } else if (ArgOffset % PtrByteSize != 0) {
6439           SDValue Lo, Hi;
6440           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6441           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6442           if (!isLittleEndian)
6443             std::swap(Lo, Hi);
6444           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6445 
6446         // The final element, if even, goes into the first half of a GPR.
6447         } else if (Flags.isInConsecutiveRegsLast()) {
6448           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6449           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6450           if (!isLittleEndian)
6451             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6452                                  DAG.getConstant(32, dl, MVT::i32));
6453 
6454         // Non-final even elements are skipped; they will be handled
6455         // together the with subsequent argument on the next go-around.
6456         } else
6457           ArgVal = SDValue();
6458 
6459         if (ArgVal.getNode())
6460           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6461       } else {
6462         if (IsFastCall)
6463           ComputePtrOff();
6464 
6465         // Single-precision floating-point values are mapped to the
6466         // second (rightmost) word of the stack doubleword.
6467         if (Arg.getValueType() == MVT::f32 &&
6468             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6469           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6470           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6471         }
6472 
6473         assert(HasParameterArea &&
6474                "Parameter area must exist to pass an argument in memory.");
6475         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6476                          true, CFlags.IsTailCall, false, MemOpChains,
6477                          TailCallArguments, dl);
6478 
6479         NeededLoad = true;
6480       }
6481       // When passing an array of floats, the array occupies consecutive
6482       // space in the argument area; only round up to the next doubleword
6483       // at the end of the array.  Otherwise, each float takes 8 bytes.
6484       if (!IsFastCall || NeededLoad) {
6485         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6486                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6487         if (Flags.isInConsecutiveRegsLast())
6488           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6489       }
6490       break;
6491     }
6492     case MVT::v4f32:
6493     case MVT::v4i32:
6494     case MVT::v8i16:
6495     case MVT::v16i8:
6496     case MVT::v2f64:
6497     case MVT::v2i64:
6498     case MVT::v1i128:
6499     case MVT::f128:
6500       // These can be scalar arguments or elements of a vector array type
6501       // passed directly.  The latter are used to implement ELFv2 homogenous
6502       // vector aggregates.
6503 
6504       // For a varargs call, named arguments go into VRs or on the stack as
6505       // usual; unnamed arguments always go to the stack or the corresponding
6506       // GPRs when within range.  For now, we always put the value in both
6507       // locations (or even all three).
6508       if (CFlags.IsVarArg) {
6509         assert(HasParameterArea &&
6510                "Parameter area must exist if we have a varargs call.");
6511         // We could elide this store in the case where the object fits
6512         // entirely in R registers.  Maybe later.
6513         SDValue Store =
6514             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6515         MemOpChains.push_back(Store);
6516         if (VR_idx != NumVRs) {
6517           SDValue Load =
6518               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6519           MemOpChains.push_back(Load.getValue(1));
6520           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6521         }
6522         ArgOffset += 16;
6523         for (unsigned i=0; i<16; i+=PtrByteSize) {
6524           if (GPR_idx == NumGPRs)
6525             break;
6526           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6527                                    DAG.getConstant(i, dl, PtrVT));
6528           SDValue Load =
6529               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6530           MemOpChains.push_back(Load.getValue(1));
6531           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6532         }
6533         break;
6534       }
6535 
6536       // Non-varargs Altivec params go into VRs or on the stack.
6537       if (VR_idx != NumVRs) {
6538         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6539       } else {
6540         if (IsFastCall)
6541           ComputePtrOff();
6542 
6543         assert(HasParameterArea &&
6544                "Parameter area must exist to pass an argument in memory.");
6545         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6546                          true, CFlags.IsTailCall, true, MemOpChains,
6547                          TailCallArguments, dl);
6548         if (IsFastCall)
6549           ArgOffset += 16;
6550       }
6551 
6552       if (!IsFastCall)
6553         ArgOffset += 16;
6554       break;
6555     }
6556   }
6557 
6558   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6559          "mismatch in size of parameter area");
6560   (void)NumBytesActuallyUsed;
6561 
6562   if (!MemOpChains.empty())
6563     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6564 
6565   // Check if this is an indirect call (MTCTR/BCTRL).
6566   // See prepareDescriptorIndirectCall and buildCallOperands for more
6567   // information about calls through function pointers in the 64-bit SVR4 ABI.
6568   if (CFlags.IsIndirect) {
6569     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6570     // caller in the TOC save area.
6571     if (isTOCSaveRestoreRequired(Subtarget)) {
6572       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6573       // Load r2 into a virtual register and store it to the TOC save area.
6574       setUsesTOCBasePtr(DAG);
6575       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6576       // TOC save area offset.
6577       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6578       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6579       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6580       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6581                            MachinePointerInfo::getStack(
6582                                DAG.getMachineFunction(), TOCSaveOffset));
6583     }
6584     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6585     // This does not mean the MTCTR instruction must use R12; it's easier
6586     // to model this as an extra parameter, so do that.
6587     if (isELFv2ABI && !CFlags.IsPatchPoint)
6588       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6589   }
6590 
6591   // Build a sequence of copy-to-reg nodes chained together with token chain
6592   // and flag operands which copy the outgoing args into the appropriate regs.
6593   SDValue InFlag;
6594   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6595     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6596                              RegsToPass[i].second, InFlag);
6597     InFlag = Chain.getValue(1);
6598   }
6599 
6600   if (CFlags.IsTailCall && !IsSibCall)
6601     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6602                     TailCallArguments);
6603 
6604   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6605                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6606 }
6607 
6608 SDValue PPCTargetLowering::LowerCall_Darwin(
6609     SDValue Chain, SDValue Callee, CallFlags CFlags,
6610     const SmallVectorImpl<ISD::OutputArg> &Outs,
6611     const SmallVectorImpl<SDValue> &OutVals,
6612     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6613     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6614     const CallBase *CB) const {
6615   unsigned NumOps = Outs.size();
6616 
6617   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6618   bool isPPC64 = PtrVT == MVT::i64;
6619   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6620 
6621   MachineFunction &MF = DAG.getMachineFunction();
6622 
6623   // Mark this function as potentially containing a function that contains a
6624   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6625   // and restoring the callers stack pointer in this functions epilog. This is
6626   // done because by tail calling the called function might overwrite the value
6627   // in this function's (MF) stack pointer stack slot 0(SP).
6628   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6629       CFlags.CallConv == CallingConv::Fast)
6630     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6631 
6632   // Count how many bytes are to be pushed on the stack, including the linkage
6633   // area, and parameter passing area.  We start with 24/48 bytes, which is
6634   // prereserved space for [SP][CR][LR][3 x unused].
6635   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6636   unsigned NumBytes = LinkageSize;
6637 
6638   // Add up all the space actually used.
6639   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6640   // they all go in registers, but we must reserve stack space for them for
6641   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6642   // assigned stack space in order, with padding so Altivec parameters are
6643   // 16-byte aligned.
6644   unsigned nAltivecParamsAtEnd = 0;
6645   for (unsigned i = 0; i != NumOps; ++i) {
6646     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6647     EVT ArgVT = Outs[i].VT;
6648     // Varargs Altivec parameters are padded to a 16 byte boundary.
6649     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6650         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6651         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6652       if (!CFlags.IsVarArg && !isPPC64) {
6653         // Non-varargs Altivec parameters go after all the non-Altivec
6654         // parameters; handle those later so we know how much padding we need.
6655         nAltivecParamsAtEnd++;
6656         continue;
6657       }
6658       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6659       NumBytes = ((NumBytes+15)/16)*16;
6660     }
6661     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6662   }
6663 
6664   // Allow for Altivec parameters at the end, if needed.
6665   if (nAltivecParamsAtEnd) {
6666     NumBytes = ((NumBytes+15)/16)*16;
6667     NumBytes += 16*nAltivecParamsAtEnd;
6668   }
6669 
6670   // The prolog code of the callee may store up to 8 GPR argument registers to
6671   // the stack, allowing va_start to index over them in memory if its varargs.
6672   // Because we cannot tell if this is needed on the caller side, we have to
6673   // conservatively assume that it is needed.  As such, make sure we have at
6674   // least enough stack space for the caller to store the 8 GPRs.
6675   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6676 
6677   // Tail call needs the stack to be aligned.
6678   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6679       CFlags.CallConv == CallingConv::Fast)
6680     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6681 
6682   // Calculate by how many bytes the stack has to be adjusted in case of tail
6683   // call optimization.
6684   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6685 
6686   // To protect arguments on the stack from being clobbered in a tail call,
6687   // force all the loads to happen before doing any other lowering.
6688   if (CFlags.IsTailCall)
6689     Chain = DAG.getStackArgumentTokenFactor(Chain);
6690 
6691   // Adjust the stack pointer for the new arguments...
6692   // These operations are automatically eliminated by the prolog/epilog pass
6693   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6694   SDValue CallSeqStart = Chain;
6695 
6696   // Load the return address and frame pointer so it can be move somewhere else
6697   // later.
6698   SDValue LROp, FPOp;
6699   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6700 
6701   // Set up a copy of the stack pointer for use loading and storing any
6702   // arguments that may not fit in the registers available for argument
6703   // passing.
6704   SDValue StackPtr;
6705   if (isPPC64)
6706     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6707   else
6708     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6709 
6710   // Figure out which arguments are going to go in registers, and which in
6711   // memory.  Also, if this is a vararg function, floating point operations
6712   // must be stored to our stack, and loaded into integer regs as well, if
6713   // any integer regs are available for argument passing.
6714   unsigned ArgOffset = LinkageSize;
6715   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6716 
6717   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6718     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6719     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6720   };
6721   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6722     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6723     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6724   };
6725   static const MCPhysReg VR[] = {
6726     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6727     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6728   };
6729   const unsigned NumGPRs = array_lengthof(GPR_32);
6730   const unsigned NumFPRs = 13;
6731   const unsigned NumVRs  = array_lengthof(VR);
6732 
6733   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6734 
6735   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6736   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6737 
6738   SmallVector<SDValue, 8> MemOpChains;
6739   for (unsigned i = 0; i != NumOps; ++i) {
6740     SDValue Arg = OutVals[i];
6741     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6742 
6743     // PtrOff will be used to store the current argument to the stack if a
6744     // register cannot be found for it.
6745     SDValue PtrOff;
6746 
6747     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6748 
6749     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6750 
6751     // On PPC64, promote integers to 64-bit values.
6752     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6753       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6754       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6755       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6756     }
6757 
6758     // FIXME memcpy is used way more than necessary.  Correctness first.
6759     // Note: "by value" is code for passing a structure by value, not
6760     // basic types.
6761     if (Flags.isByVal()) {
6762       unsigned Size = Flags.getByValSize();
6763       // Very small objects are passed right-justified.  Everything else is
6764       // passed left-justified.
6765       if (Size==1 || Size==2) {
6766         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6767         if (GPR_idx != NumGPRs) {
6768           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6769                                         MachinePointerInfo(), VT);
6770           MemOpChains.push_back(Load.getValue(1));
6771           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6772 
6773           ArgOffset += PtrByteSize;
6774         } else {
6775           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6776                                           PtrOff.getValueType());
6777           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6778           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6779                                                             CallSeqStart,
6780                                                             Flags, DAG, dl);
6781           ArgOffset += PtrByteSize;
6782         }
6783         continue;
6784       }
6785       // Copy entire object into memory.  There are cases where gcc-generated
6786       // code assumes it is there, even if it could be put entirely into
6787       // registers.  (This is not what the doc says.)
6788       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6789                                                         CallSeqStart,
6790                                                         Flags, DAG, dl);
6791 
6792       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6793       // copy the pieces of the object that fit into registers from the
6794       // parameter save area.
6795       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6796         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6797         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6798         if (GPR_idx != NumGPRs) {
6799           SDValue Load =
6800               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6801           MemOpChains.push_back(Load.getValue(1));
6802           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6803           ArgOffset += PtrByteSize;
6804         } else {
6805           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6806           break;
6807         }
6808       }
6809       continue;
6810     }
6811 
6812     switch (Arg.getSimpleValueType().SimpleTy) {
6813     default: llvm_unreachable("Unexpected ValueType for argument!");
6814     case MVT::i1:
6815     case MVT::i32:
6816     case MVT::i64:
6817       if (GPR_idx != NumGPRs) {
6818         if (Arg.getValueType() == MVT::i1)
6819           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6820 
6821         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6822       } else {
6823         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6824                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6825                          TailCallArguments, dl);
6826       }
6827       ArgOffset += PtrByteSize;
6828       break;
6829     case MVT::f32:
6830     case MVT::f64:
6831       if (FPR_idx != NumFPRs) {
6832         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6833 
6834         if (CFlags.IsVarArg) {
6835           SDValue Store =
6836               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6837           MemOpChains.push_back(Store);
6838 
6839           // Float varargs are always shadowed in available integer registers
6840           if (GPR_idx != NumGPRs) {
6841             SDValue Load =
6842                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6843             MemOpChains.push_back(Load.getValue(1));
6844             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6845           }
6846           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6847             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6848             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6849             SDValue Load =
6850                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6851             MemOpChains.push_back(Load.getValue(1));
6852             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6853           }
6854         } else {
6855           // If we have any FPRs remaining, we may also have GPRs remaining.
6856           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6857           // GPRs.
6858           if (GPR_idx != NumGPRs)
6859             ++GPR_idx;
6860           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6861               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6862             ++GPR_idx;
6863         }
6864       } else
6865         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6866                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6867                          TailCallArguments, dl);
6868       if (isPPC64)
6869         ArgOffset += 8;
6870       else
6871         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6872       break;
6873     case MVT::v4f32:
6874     case MVT::v4i32:
6875     case MVT::v8i16:
6876     case MVT::v16i8:
6877       if (CFlags.IsVarArg) {
6878         // These go aligned on the stack, or in the corresponding R registers
6879         // when within range.  The Darwin PPC ABI doc claims they also go in
6880         // V registers; in fact gcc does this only for arguments that are
6881         // prototyped, not for those that match the ...  We do it for all
6882         // arguments, seems to work.
6883         while (ArgOffset % 16 !=0) {
6884           ArgOffset += PtrByteSize;
6885           if (GPR_idx != NumGPRs)
6886             GPR_idx++;
6887         }
6888         // We could elide this store in the case where the object fits
6889         // entirely in R registers.  Maybe later.
6890         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6891                              DAG.getConstant(ArgOffset, dl, PtrVT));
6892         SDValue Store =
6893             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6894         MemOpChains.push_back(Store);
6895         if (VR_idx != NumVRs) {
6896           SDValue Load =
6897               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6898           MemOpChains.push_back(Load.getValue(1));
6899           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6900         }
6901         ArgOffset += 16;
6902         for (unsigned i=0; i<16; i+=PtrByteSize) {
6903           if (GPR_idx == NumGPRs)
6904             break;
6905           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6906                                    DAG.getConstant(i, dl, PtrVT));
6907           SDValue Load =
6908               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6909           MemOpChains.push_back(Load.getValue(1));
6910           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6911         }
6912         break;
6913       }
6914 
6915       // Non-varargs Altivec params generally go in registers, but have
6916       // stack space allocated at the end.
6917       if (VR_idx != NumVRs) {
6918         // Doesn't have GPR space allocated.
6919         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6920       } else if (nAltivecParamsAtEnd==0) {
6921         // We are emitting Altivec params in order.
6922         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6923                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6924                          TailCallArguments, dl);
6925         ArgOffset += 16;
6926       }
6927       break;
6928     }
6929   }
6930   // If all Altivec parameters fit in registers, as they usually do,
6931   // they get stack space following the non-Altivec parameters.  We
6932   // don't track this here because nobody below needs it.
6933   // If there are more Altivec parameters than fit in registers emit
6934   // the stores here.
6935   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6936     unsigned j = 0;
6937     // Offset is aligned; skip 1st 12 params which go in V registers.
6938     ArgOffset = ((ArgOffset+15)/16)*16;
6939     ArgOffset += 12*16;
6940     for (unsigned i = 0; i != NumOps; ++i) {
6941       SDValue Arg = OutVals[i];
6942       EVT ArgType = Outs[i].VT;
6943       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6944           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6945         if (++j > NumVRs) {
6946           SDValue PtrOff;
6947           // We are emitting Altivec params in order.
6948           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6949                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6950                            TailCallArguments, dl);
6951           ArgOffset += 16;
6952         }
6953       }
6954     }
6955   }
6956 
6957   if (!MemOpChains.empty())
6958     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6959 
6960   // On Darwin, R12 must contain the address of an indirect callee.  This does
6961   // not mean the MTCTR instruction must use R12; it's easier to model this as
6962   // an extra parameter, so do that.
6963   if (CFlags.IsIndirect) {
6964     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6965     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6966                                                    PPC::R12), Callee));
6967   }
6968 
6969   // Build a sequence of copy-to-reg nodes chained together with token chain
6970   // and flag operands which copy the outgoing args into the appropriate regs.
6971   SDValue InFlag;
6972   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6973     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6974                              RegsToPass[i].second, InFlag);
6975     InFlag = Chain.getValue(1);
6976   }
6977 
6978   if (CFlags.IsTailCall)
6979     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6980                     TailCallArguments);
6981 
6982   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6983                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6984 }
6985 
6986 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6987                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6988                    CCState &State) {
6989 
6990   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6991       State.getMachineFunction().getSubtarget());
6992   const bool IsPPC64 = Subtarget.isPPC64();
6993   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6994   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6995 
6996   if (ValVT.isVector() && !State.getMachineFunction()
6997                                .getTarget()
6998                                .Options.EnableAIXExtendedAltivecABI)
6999     report_fatal_error("the default Altivec AIX ABI is not yet supported");
7000 
7001   if (ValVT.isVector() && State.getMachineFunction()
7002                               .getTarget()
7003                               .Options.EnableAIXExtendedAltivecABI)
7004     report_fatal_error("the extended Altivec AIX ABI is not yet supported");
7005 
7006   assert((!ValVT.isInteger() ||
7007           (ValVT.getFixedSizeInBits() <= RegVT.getFixedSizeInBits())) &&
7008          "Integer argument exceeds register size: should have been legalized");
7009 
7010   if (ValVT == MVT::f128)
7011     report_fatal_error("f128 is unimplemented on AIX.");
7012 
7013   if (ArgFlags.isNest())
7014     report_fatal_error("Nest arguments are unimplemented.");
7015 
7016   if (ValVT.isVector() || LocVT.isVector())
7017     report_fatal_error("Vector arguments are unimplemented on AIX.");
7018 
7019   static const MCPhysReg GPR_32[] = {// 32-bit registers.
7020                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7021                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7022   static const MCPhysReg GPR_64[] = {// 64-bit registers.
7023                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7024                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7025 
7026   if (ArgFlags.isByVal()) {
7027     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
7028       report_fatal_error("Pass-by-value arguments with alignment greater than "
7029                          "register width are not supported.");
7030 
7031     const unsigned ByValSize = ArgFlags.getByValSize();
7032 
7033     // An empty aggregate parameter takes up no storage and no registers,
7034     // but needs a MemLoc for a stack slot for the formal arguments side.
7035     if (ByValSize == 0) {
7036       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
7037                                        State.getNextStackOffset(), RegVT,
7038                                        LocInfo));
7039       return false;
7040     }
7041 
7042     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
7043     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
7044     for (const unsigned E = Offset + StackSize; Offset < E;
7045          Offset += PtrAlign.value()) {
7046       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
7047         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7048       else {
7049         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
7050                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
7051                                          LocInfo));
7052         break;
7053       }
7054     }
7055     return false;
7056   }
7057 
7058   // Arguments always reserve parameter save area.
7059   switch (ValVT.SimpleTy) {
7060   default:
7061     report_fatal_error("Unhandled value type for argument.");
7062   case MVT::i64:
7063     // i64 arguments should have been split to i32 for PPC32.
7064     assert(IsPPC64 && "PPC32 should have split i64 values.");
7065     LLVM_FALLTHROUGH;
7066   case MVT::i1:
7067   case MVT::i32: {
7068     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
7069     // AIX integer arguments are always passed in register width.
7070     if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
7071       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
7072                                   : CCValAssign::LocInfo::ZExt;
7073     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
7074       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7075     else
7076       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
7077 
7078     return false;
7079   }
7080   case MVT::f32:
7081   case MVT::f64: {
7082     // Parameter save area (PSA) is reserved even if the float passes in fpr.
7083     const unsigned StoreSize = LocVT.getStoreSize();
7084     // Floats are always 4-byte aligned in the PSA on AIX.
7085     // This includes f64 in 64-bit mode for ABI compatibility.
7086     const unsigned Offset =
7087         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
7088     unsigned FReg = State.AllocateReg(FPR);
7089     if (FReg)
7090       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
7091 
7092     // Reserve and initialize GPRs or initialize the PSA as required.
7093     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
7094       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
7095         assert(FReg && "An FPR should be available when a GPR is reserved.");
7096         if (State.isVarArg()) {
7097           // Successfully reserved GPRs are only initialized for vararg calls.
7098           // Custom handling is required for:
7099           //   f64 in PPC32 needs to be split into 2 GPRs.
7100           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
7101           State.addLoc(
7102               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7103         }
7104       } else {
7105         // If there are insufficient GPRs, the PSA needs to be initialized.
7106         // Initialization occurs even if an FPR was initialized for
7107         // compatibility with the AIX XL compiler. The full memory for the
7108         // argument will be initialized even if a prior word is saved in GPR.
7109         // A custom memLoc is used when the argument also passes in FPR so
7110         // that the callee handling can skip over it easily.
7111         State.addLoc(
7112             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
7113                                              LocInfo)
7114                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7115         break;
7116       }
7117     }
7118 
7119     return false;
7120   }
7121   }
7122   return true;
7123 }
7124 
7125 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
7126                                                     bool IsPPC64) {
7127   assert((IsPPC64 || SVT != MVT::i64) &&
7128          "i64 should have been split for 32-bit codegen.");
7129 
7130   switch (SVT) {
7131   default:
7132     report_fatal_error("Unexpected value type for formal argument");
7133   case MVT::i1:
7134   case MVT::i32:
7135   case MVT::i64:
7136     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7137   case MVT::f32:
7138     return &PPC::F4RCRegClass;
7139   case MVT::f64:
7140     return &PPC::F8RCRegClass;
7141   }
7142 }
7143 
7144 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
7145                                         SelectionDAG &DAG, SDValue ArgValue,
7146                                         MVT LocVT, const SDLoc &dl) {
7147   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7148   assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
7149 
7150   if (Flags.isSExt())
7151     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7152                            DAG.getValueType(ValVT));
7153   else if (Flags.isZExt())
7154     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7155                            DAG.getValueType(ValVT));
7156 
7157   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7158 }
7159 
7160 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7161   const unsigned LASize = FL->getLinkageSize();
7162 
7163   if (PPC::GPRCRegClass.contains(Reg)) {
7164     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7165            "Reg must be a valid argument register!");
7166     return LASize + 4 * (Reg - PPC::R3);
7167   }
7168 
7169   if (PPC::G8RCRegClass.contains(Reg)) {
7170     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7171            "Reg must be a valid argument register!");
7172     return LASize + 8 * (Reg - PPC::X3);
7173   }
7174 
7175   llvm_unreachable("Only general purpose registers expected.");
7176 }
7177 
7178 //   AIX ABI Stack Frame Layout:
7179 //
7180 //   Low Memory +--------------------------------------------+
7181 //   SP   +---> | Back chain                                 | ---+
7182 //        |     +--------------------------------------------+    |
7183 //        |     | Saved Condition Register                   |    |
7184 //        |     +--------------------------------------------+    |
7185 //        |     | Saved Linkage Register                     |    |
7186 //        |     +--------------------------------------------+    | Linkage Area
7187 //        |     | Reserved for compilers                     |    |
7188 //        |     +--------------------------------------------+    |
7189 //        |     | Reserved for binders                       |    |
7190 //        |     +--------------------------------------------+    |
7191 //        |     | Saved TOC pointer                          | ---+
7192 //        |     +--------------------------------------------+
7193 //        |     | Parameter save area                        |
7194 //        |     +--------------------------------------------+
7195 //        |     | Alloca space                               |
7196 //        |     +--------------------------------------------+
7197 //        |     | Local variable space                       |
7198 //        |     +--------------------------------------------+
7199 //        |     | Float/int conversion temporary             |
7200 //        |     +--------------------------------------------+
7201 //        |     | Save area for AltiVec registers            |
7202 //        |     +--------------------------------------------+
7203 //        |     | AltiVec alignment padding                  |
7204 //        |     +--------------------------------------------+
7205 //        |     | Save area for VRSAVE register              |
7206 //        |     +--------------------------------------------+
7207 //        |     | Save area for General Purpose registers    |
7208 //        |     +--------------------------------------------+
7209 //        |     | Save area for Floating Point registers     |
7210 //        |     +--------------------------------------------+
7211 //        +---- | Back chain                                 |
7212 // High Memory  +--------------------------------------------+
7213 //
7214 //  Specifications:
7215 //  AIX 7.2 Assembler Language Reference
7216 //  Subroutine linkage convention
7217 
7218 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7219     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7220     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7221     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7222 
7223   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7224           CallConv == CallingConv::Fast) &&
7225          "Unexpected calling convention!");
7226 
7227   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7228     report_fatal_error("Tail call support is unimplemented on AIX.");
7229 
7230   if (useSoftFloat())
7231     report_fatal_error("Soft float support is unimplemented on AIX.");
7232 
7233   const PPCSubtarget &Subtarget =
7234       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7235 
7236   const bool IsPPC64 = Subtarget.isPPC64();
7237   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7238 
7239   // Assign locations to all of the incoming arguments.
7240   SmallVector<CCValAssign, 16> ArgLocs;
7241   MachineFunction &MF = DAG.getMachineFunction();
7242   MachineFrameInfo &MFI = MF.getFrameInfo();
7243   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7244 
7245   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7246   // Reserve space for the linkage area on the stack.
7247   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7248   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7249   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7250 
7251   SmallVector<SDValue, 8> MemOps;
7252 
7253   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7254     CCValAssign &VA = ArgLocs[I++];
7255     MVT LocVT = VA.getLocVT();
7256     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7257 
7258     // For compatibility with the AIX XL compiler, the float args in the
7259     // parameter save area are initialized even if the argument is available
7260     // in register.  The caller is required to initialize both the register
7261     // and memory, however, the callee can choose to expect it in either.
7262     // The memloc is dismissed here because the argument is retrieved from
7263     // the register.
7264     if (VA.isMemLoc() && VA.needsCustom())
7265       continue;
7266 
7267     if (Flags.isByVal() && VA.isMemLoc()) {
7268       const unsigned Size =
7269           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7270                   PtrByteSize);
7271       const int FI = MF.getFrameInfo().CreateFixedObject(
7272           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7273           /* IsAliased */ true);
7274       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7275       InVals.push_back(FIN);
7276 
7277       continue;
7278     }
7279 
7280     if (Flags.isByVal()) {
7281       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7282 
7283       const MCPhysReg ArgReg = VA.getLocReg();
7284       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7285 
7286       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7287         report_fatal_error("Over aligned byvals not supported yet.");
7288 
7289       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7290       const int FI = MF.getFrameInfo().CreateFixedObject(
7291           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7292           /* IsAliased */ true);
7293       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7294       InVals.push_back(FIN);
7295 
7296       // Add live ins for all the RegLocs for the same ByVal.
7297       const TargetRegisterClass *RegClass =
7298           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7299 
7300       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7301                                                unsigned Offset) {
7302         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7303         // Since the callers side has left justified the aggregate in the
7304         // register, we can simply store the entire register into the stack
7305         // slot.
7306         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7307         // The store to the fixedstack object is needed becuase accessing a
7308         // field of the ByVal will use a gep and load. Ideally we will optimize
7309         // to extracting the value from the register directly, and elide the
7310         // stores when the arguments address is not taken, but that will need to
7311         // be future work.
7312         SDValue Store = DAG.getStore(
7313             CopyFrom.getValue(1), dl, CopyFrom,
7314             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7315             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7316 
7317         MemOps.push_back(Store);
7318       };
7319 
7320       unsigned Offset = 0;
7321       HandleRegLoc(VA.getLocReg(), Offset);
7322       Offset += PtrByteSize;
7323       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7324            Offset += PtrByteSize) {
7325         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7326                "RegLocs should be for ByVal argument.");
7327 
7328         const CCValAssign RL = ArgLocs[I++];
7329         HandleRegLoc(RL.getLocReg(), Offset);
7330       }
7331 
7332       if (Offset != StackSize) {
7333         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7334                "Expected MemLoc for remaining bytes.");
7335         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7336         // Consume the MemLoc.The InVal has already been emitted, so nothing
7337         // more needs to be done.
7338         ++I;
7339       }
7340 
7341       continue;
7342     }
7343 
7344     EVT ValVT = VA.getValVT();
7345     if (VA.isRegLoc() && !VA.needsCustom()) {
7346       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7347       unsigned VReg =
7348           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7349       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7350       if (ValVT.isScalarInteger() &&
7351           (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7352         ArgValue =
7353             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7354       }
7355       InVals.push_back(ArgValue);
7356       continue;
7357     }
7358     if (VA.isMemLoc()) {
7359       const unsigned LocSize = LocVT.getStoreSize();
7360       const unsigned ValSize = ValVT.getStoreSize();
7361       assert((ValSize <= LocSize) &&
7362              "Object size is larger than size of MemLoc");
7363       int CurArgOffset = VA.getLocMemOffset();
7364       // Objects are right-justified because AIX is big-endian.
7365       if (LocSize > ValSize)
7366         CurArgOffset += LocSize - ValSize;
7367       // Potential tail calls could cause overwriting of argument stack slots.
7368       const bool IsImmutable =
7369           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7370             (CallConv == CallingConv::Fast));
7371       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7372       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7373       SDValue ArgValue =
7374           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7375       InVals.push_back(ArgValue);
7376       continue;
7377     }
7378   }
7379 
7380   // On AIX a minimum of 8 words is saved to the parameter save area.
7381   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7382   // Area that is at least reserved in the caller of this function.
7383   unsigned CallerReservedArea =
7384       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7385 
7386   // Set the size that is at least reserved in caller of this function. Tail
7387   // call optimized function's reserved stack space needs to be aligned so
7388   // that taking the difference between two stack areas will result in an
7389   // aligned stack.
7390   CallerReservedArea =
7391       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7392   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7393   FuncInfo->setMinReservedArea(CallerReservedArea);
7394 
7395   if (isVarArg) {
7396     FuncInfo->setVarArgsFrameIndex(
7397         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7398     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7399 
7400     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7401                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7402 
7403     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7404                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7405     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7406 
7407     // The fixed integer arguments of a variadic function are stored to the
7408     // VarArgsFrameIndex on the stack so that they may be loaded by
7409     // dereferencing the result of va_next.
7410     for (unsigned GPRIndex =
7411              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7412          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7413 
7414       const unsigned VReg =
7415           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7416                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7417 
7418       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7419       SDValue Store =
7420           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7421       MemOps.push_back(Store);
7422       // Increment the address for the next argument to store.
7423       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7424       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7425     }
7426   }
7427 
7428   if (!MemOps.empty())
7429     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7430 
7431   return Chain;
7432 }
7433 
7434 SDValue PPCTargetLowering::LowerCall_AIX(
7435     SDValue Chain, SDValue Callee, CallFlags CFlags,
7436     const SmallVectorImpl<ISD::OutputArg> &Outs,
7437     const SmallVectorImpl<SDValue> &OutVals,
7438     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7439     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7440     const CallBase *CB) const {
7441   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7442   // AIX ABI stack frame layout.
7443 
7444   assert((CFlags.CallConv == CallingConv::C ||
7445           CFlags.CallConv == CallingConv::Cold ||
7446           CFlags.CallConv == CallingConv::Fast) &&
7447          "Unexpected calling convention!");
7448 
7449   if (CFlags.IsPatchPoint)
7450     report_fatal_error("This call type is unimplemented on AIX.");
7451 
7452   const PPCSubtarget& Subtarget =
7453       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7454   if (Subtarget.hasAltivec())
7455     report_fatal_error("Altivec support is unimplemented on AIX.");
7456 
7457   MachineFunction &MF = DAG.getMachineFunction();
7458   SmallVector<CCValAssign, 16> ArgLocs;
7459   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7460                  *DAG.getContext());
7461 
7462   // Reserve space for the linkage save area (LSA) on the stack.
7463   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7464   //   [SP][CR][LR][2 x reserved][TOC].
7465   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7466   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7467   const bool IsPPC64 = Subtarget.isPPC64();
7468   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7469   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7470   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7471   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7472 
7473   // The prolog code of the callee may store up to 8 GPR argument registers to
7474   // the stack, allowing va_start to index over them in memory if the callee
7475   // is variadic.
7476   // Because we cannot tell if this is needed on the caller side, we have to
7477   // conservatively assume that it is needed.  As such, make sure we have at
7478   // least enough stack space for the caller to store the 8 GPRs.
7479   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7480   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7481                                      CCInfo.getNextStackOffset());
7482 
7483   // Adjust the stack pointer for the new arguments...
7484   // These operations are automatically eliminated by the prolog/epilog pass.
7485   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7486   SDValue CallSeqStart = Chain;
7487 
7488   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7489   SmallVector<SDValue, 8> MemOpChains;
7490 
7491   // Set up a copy of the stack pointer for loading and storing any
7492   // arguments that may not fit in the registers available for argument
7493   // passing.
7494   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7495                                    : DAG.getRegister(PPC::R1, MVT::i32);
7496 
7497   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7498     const unsigned ValNo = ArgLocs[I].getValNo();
7499     SDValue Arg = OutVals[ValNo];
7500     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7501 
7502     if (Flags.isByVal()) {
7503       const unsigned ByValSize = Flags.getByValSize();
7504 
7505       // Nothing to do for zero-sized ByVals on the caller side.
7506       if (!ByValSize) {
7507         ++I;
7508         continue;
7509       }
7510 
7511       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7512         return DAG.getExtLoad(
7513             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7514             (LoadOffset != 0)
7515                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7516                 : Arg,
7517             MachinePointerInfo(), VT);
7518       };
7519 
7520       unsigned LoadOffset = 0;
7521 
7522       // Initialize registers, which are fully occupied by the by-val argument.
7523       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7524         SDValue Load = GetLoad(PtrVT, LoadOffset);
7525         MemOpChains.push_back(Load.getValue(1));
7526         LoadOffset += PtrByteSize;
7527         const CCValAssign &ByValVA = ArgLocs[I++];
7528         assert(ByValVA.getValNo() == ValNo &&
7529                "Unexpected location for pass-by-value argument.");
7530         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7531       }
7532 
7533       if (LoadOffset == ByValSize)
7534         continue;
7535 
7536       // There must be one more loc to handle the remainder.
7537       assert(ArgLocs[I].getValNo() == ValNo &&
7538              "Expected additional location for by-value argument.");
7539 
7540       if (ArgLocs[I].isMemLoc()) {
7541         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7542         const CCValAssign &ByValVA = ArgLocs[I++];
7543         ISD::ArgFlagsTy MemcpyFlags = Flags;
7544         // Only memcpy the bytes that don't pass in register.
7545         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7546         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7547             (LoadOffset != 0)
7548                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7549                 : Arg,
7550             DAG.getObjectPtrOffset(dl, StackPtr,
7551                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7552             CallSeqStart, MemcpyFlags, DAG, dl);
7553         continue;
7554       }
7555 
7556       // Initialize the final register residue.
7557       // Any residue that occupies the final by-val arg register must be
7558       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7559       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7560       // 2 and 1 byte loads.
7561       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7562       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7563              "Unexpected register residue for by-value argument.");
7564       SDValue ResidueVal;
7565       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7566         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7567         const MVT VT =
7568             N == 1 ? MVT::i8
7569                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7570         SDValue Load = GetLoad(VT, LoadOffset);
7571         MemOpChains.push_back(Load.getValue(1));
7572         LoadOffset += N;
7573         Bytes += N;
7574 
7575         // By-val arguments are passed left-justfied in register.
7576         // Every load here needs to be shifted, otherwise a full register load
7577         // should have been used.
7578         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7579                "Unexpected load emitted during handling of pass-by-value "
7580                "argument.");
7581         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7582         EVT ShiftAmountTy =
7583             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7584         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7585         SDValue ShiftedLoad =
7586             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7587         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7588                                               ShiftedLoad)
7589                                 : ShiftedLoad;
7590       }
7591 
7592       const CCValAssign &ByValVA = ArgLocs[I++];
7593       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7594       continue;
7595     }
7596 
7597     CCValAssign &VA = ArgLocs[I++];
7598     const MVT LocVT = VA.getLocVT();
7599     const MVT ValVT = VA.getValVT();
7600 
7601     switch (VA.getLocInfo()) {
7602     default:
7603       report_fatal_error("Unexpected argument extension type.");
7604     case CCValAssign::Full:
7605       break;
7606     case CCValAssign::ZExt:
7607       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7608       break;
7609     case CCValAssign::SExt:
7610       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7611       break;
7612     }
7613 
7614     if (VA.isRegLoc() && !VA.needsCustom()) {
7615       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7616       continue;
7617     }
7618 
7619     if (VA.isMemLoc()) {
7620       SDValue PtrOff =
7621           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7622       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7623       MemOpChains.push_back(
7624           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7625 
7626       continue;
7627     }
7628 
7629     // Custom handling is used for GPR initializations for vararg float
7630     // arguments.
7631     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7632            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7633            "Unexpected register handling for calling convention.");
7634 
7635     SDValue ArgAsInt =
7636         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7637 
7638     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7639       // f32 in 32-bit GPR
7640       // f64 in 64-bit GPR
7641       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7642     else if (Arg.getValueType().getFixedSizeInBits() <
7643              LocVT.getFixedSizeInBits())
7644       // f32 in 64-bit GPR.
7645       RegsToPass.push_back(std::make_pair(
7646           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7647     else {
7648       // f64 in two 32-bit GPRs
7649       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7650       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7651              "Unexpected custom register for argument!");
7652       CCValAssign &GPR1 = VA;
7653       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7654                                      DAG.getConstant(32, dl, MVT::i8));
7655       RegsToPass.push_back(std::make_pair(
7656           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7657 
7658       if (I != E) {
7659         // If only 1 GPR was available, there will only be one custom GPR and
7660         // the argument will also pass in memory.
7661         CCValAssign &PeekArg = ArgLocs[I];
7662         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7663           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7664           CCValAssign &GPR2 = ArgLocs[I++];
7665           RegsToPass.push_back(std::make_pair(
7666               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7667         }
7668       }
7669     }
7670   }
7671 
7672   if (!MemOpChains.empty())
7673     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7674 
7675   // For indirect calls, we need to save the TOC base to the stack for
7676   // restoration after the call.
7677   if (CFlags.IsIndirect) {
7678     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7679     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7680     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7681     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7682     const unsigned TOCSaveOffset =
7683         Subtarget.getFrameLowering()->getTOCSaveOffset();
7684 
7685     setUsesTOCBasePtr(DAG);
7686     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7687     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7688     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7689     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7690     Chain = DAG.getStore(
7691         Val.getValue(1), dl, Val, AddPtr,
7692         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7693   }
7694 
7695   // Build a sequence of copy-to-reg nodes chained together with token chain
7696   // and flag operands which copy the outgoing args into the appropriate regs.
7697   SDValue InFlag;
7698   for (auto Reg : RegsToPass) {
7699     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7700     InFlag = Chain.getValue(1);
7701   }
7702 
7703   const int SPDiff = 0;
7704   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7705                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7706 }
7707 
7708 bool
7709 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7710                                   MachineFunction &MF, bool isVarArg,
7711                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7712                                   LLVMContext &Context) const {
7713   SmallVector<CCValAssign, 16> RVLocs;
7714   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7715   return CCInfo.CheckReturn(
7716       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7717                 ? RetCC_PPC_Cold
7718                 : RetCC_PPC);
7719 }
7720 
7721 SDValue
7722 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7723                                bool isVarArg,
7724                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7725                                const SmallVectorImpl<SDValue> &OutVals,
7726                                const SDLoc &dl, SelectionDAG &DAG) const {
7727   SmallVector<CCValAssign, 16> RVLocs;
7728   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7729                  *DAG.getContext());
7730   CCInfo.AnalyzeReturn(Outs,
7731                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7732                            ? RetCC_PPC_Cold
7733                            : RetCC_PPC);
7734 
7735   SDValue Flag;
7736   SmallVector<SDValue, 4> RetOps(1, Chain);
7737 
7738   // Copy the result values into the output registers.
7739   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7740     CCValAssign &VA = RVLocs[i];
7741     assert(VA.isRegLoc() && "Can only return in registers!");
7742 
7743     SDValue Arg = OutVals[RealResIdx];
7744 
7745     if (Subtarget.isAIXABI() &&
7746         (VA.getLocVT().isVector() || VA.getValVT().isVector()))
7747       report_fatal_error("Returning vector types not yet supported on AIX.");
7748 
7749     switch (VA.getLocInfo()) {
7750     default: llvm_unreachable("Unknown loc info!");
7751     case CCValAssign::Full: break;
7752     case CCValAssign::AExt:
7753       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7754       break;
7755     case CCValAssign::ZExt:
7756       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7757       break;
7758     case CCValAssign::SExt:
7759       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7760       break;
7761     }
7762     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7763       bool isLittleEndian = Subtarget.isLittleEndian();
7764       // Legalize ret f64 -> ret 2 x i32.
7765       SDValue SVal =
7766           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7767                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7768       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7769       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7770       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7771                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7772       Flag = Chain.getValue(1);
7773       VA = RVLocs[++i]; // skip ahead to next loc
7774       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7775     } else
7776       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7777     Flag = Chain.getValue(1);
7778     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7779   }
7780 
7781   RetOps[0] = Chain;  // Update chain.
7782 
7783   // Add the flag if we have it.
7784   if (Flag.getNode())
7785     RetOps.push_back(Flag);
7786 
7787   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7788 }
7789 
7790 SDValue
7791 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7792                                                 SelectionDAG &DAG) const {
7793   SDLoc dl(Op);
7794 
7795   // Get the correct type for integers.
7796   EVT IntVT = Op.getValueType();
7797 
7798   // Get the inputs.
7799   SDValue Chain = Op.getOperand(0);
7800   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7801   // Build a DYNAREAOFFSET node.
7802   SDValue Ops[2] = {Chain, FPSIdx};
7803   SDVTList VTs = DAG.getVTList(IntVT);
7804   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7805 }
7806 
7807 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7808                                              SelectionDAG &DAG) const {
7809   // When we pop the dynamic allocation we need to restore the SP link.
7810   SDLoc dl(Op);
7811 
7812   // Get the correct type for pointers.
7813   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7814 
7815   // Construct the stack pointer operand.
7816   bool isPPC64 = Subtarget.isPPC64();
7817   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7818   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7819 
7820   // Get the operands for the STACKRESTORE.
7821   SDValue Chain = Op.getOperand(0);
7822   SDValue SaveSP = Op.getOperand(1);
7823 
7824   // Load the old link SP.
7825   SDValue LoadLinkSP =
7826       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7827 
7828   // Restore the stack pointer.
7829   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7830 
7831   // Store the old link SP.
7832   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7833 }
7834 
7835 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7836   MachineFunction &MF = DAG.getMachineFunction();
7837   bool isPPC64 = Subtarget.isPPC64();
7838   EVT PtrVT = getPointerTy(MF.getDataLayout());
7839 
7840   // Get current frame pointer save index.  The users of this index will be
7841   // primarily DYNALLOC instructions.
7842   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7843   int RASI = FI->getReturnAddrSaveIndex();
7844 
7845   // If the frame pointer save index hasn't been defined yet.
7846   if (!RASI) {
7847     // Find out what the fix offset of the frame pointer save area.
7848     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7849     // Allocate the frame index for frame pointer save area.
7850     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7851     // Save the result.
7852     FI->setReturnAddrSaveIndex(RASI);
7853   }
7854   return DAG.getFrameIndex(RASI, PtrVT);
7855 }
7856 
7857 SDValue
7858 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7859   MachineFunction &MF = DAG.getMachineFunction();
7860   bool isPPC64 = Subtarget.isPPC64();
7861   EVT PtrVT = getPointerTy(MF.getDataLayout());
7862 
7863   // Get current frame pointer save index.  The users of this index will be
7864   // primarily DYNALLOC instructions.
7865   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7866   int FPSI = FI->getFramePointerSaveIndex();
7867 
7868   // If the frame pointer save index hasn't been defined yet.
7869   if (!FPSI) {
7870     // Find out what the fix offset of the frame pointer save area.
7871     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7872     // Allocate the frame index for frame pointer save area.
7873     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7874     // Save the result.
7875     FI->setFramePointerSaveIndex(FPSI);
7876   }
7877   return DAG.getFrameIndex(FPSI, PtrVT);
7878 }
7879 
7880 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7881                                                    SelectionDAG &DAG) const {
7882   MachineFunction &MF = DAG.getMachineFunction();
7883   // Get the inputs.
7884   SDValue Chain = Op.getOperand(0);
7885   SDValue Size  = Op.getOperand(1);
7886   SDLoc dl(Op);
7887 
7888   // Get the correct type for pointers.
7889   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7890   // Negate the size.
7891   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7892                                 DAG.getConstant(0, dl, PtrVT), Size);
7893   // Construct a node for the frame pointer save index.
7894   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7895   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7896   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7897   if (hasInlineStackProbe(MF))
7898     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7899   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7900 }
7901 
7902 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7903                                                      SelectionDAG &DAG) const {
7904   MachineFunction &MF = DAG.getMachineFunction();
7905 
7906   bool isPPC64 = Subtarget.isPPC64();
7907   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7908 
7909   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7910   return DAG.getFrameIndex(FI, PtrVT);
7911 }
7912 
7913 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7914                                                SelectionDAG &DAG) const {
7915   SDLoc DL(Op);
7916   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7917                      DAG.getVTList(MVT::i32, MVT::Other),
7918                      Op.getOperand(0), Op.getOperand(1));
7919 }
7920 
7921 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7922                                                 SelectionDAG &DAG) const {
7923   SDLoc DL(Op);
7924   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7925                      Op.getOperand(0), Op.getOperand(1));
7926 }
7927 
7928 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7929   if (Op.getValueType().isVector())
7930     return LowerVectorLoad(Op, DAG);
7931 
7932   assert(Op.getValueType() == MVT::i1 &&
7933          "Custom lowering only for i1 loads");
7934 
7935   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7936 
7937   SDLoc dl(Op);
7938   LoadSDNode *LD = cast<LoadSDNode>(Op);
7939 
7940   SDValue Chain = LD->getChain();
7941   SDValue BasePtr = LD->getBasePtr();
7942   MachineMemOperand *MMO = LD->getMemOperand();
7943 
7944   SDValue NewLD =
7945       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7946                      BasePtr, MVT::i8, MMO);
7947   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7948 
7949   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7950   return DAG.getMergeValues(Ops, dl);
7951 }
7952 
7953 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7954   if (Op.getOperand(1).getValueType().isVector())
7955     return LowerVectorStore(Op, DAG);
7956 
7957   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7958          "Custom lowering only for i1 stores");
7959 
7960   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7961 
7962   SDLoc dl(Op);
7963   StoreSDNode *ST = cast<StoreSDNode>(Op);
7964 
7965   SDValue Chain = ST->getChain();
7966   SDValue BasePtr = ST->getBasePtr();
7967   SDValue Value = ST->getValue();
7968   MachineMemOperand *MMO = ST->getMemOperand();
7969 
7970   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7971                       Value);
7972   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7973 }
7974 
7975 // FIXME: Remove this once the ANDI glue bug is fixed:
7976 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7977   assert(Op.getValueType() == MVT::i1 &&
7978          "Custom lowering only for i1 results");
7979 
7980   SDLoc DL(Op);
7981   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7982 }
7983 
7984 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7985                                                SelectionDAG &DAG) const {
7986 
7987   // Implements a vector truncate that fits in a vector register as a shuffle.
7988   // We want to legalize vector truncates down to where the source fits in
7989   // a vector register (and target is therefore smaller than vector register
7990   // size).  At that point legalization will try to custom lower the sub-legal
7991   // result and get here - where we can contain the truncate as a single target
7992   // operation.
7993 
7994   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7995   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7996   //
7997   // We will implement it for big-endian ordering as this (where x denotes
7998   // undefined):
7999   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
8000   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
8001   //
8002   // The same operation in little-endian ordering will be:
8003   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
8004   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
8005 
8006   EVT TrgVT = Op.getValueType();
8007   assert(TrgVT.isVector() && "Vector type expected.");
8008   unsigned TrgNumElts = TrgVT.getVectorNumElements();
8009   EVT EltVT = TrgVT.getVectorElementType();
8010   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
8011       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
8012       !isPowerOf2_32(EltVT.getSizeInBits()))
8013     return SDValue();
8014 
8015   SDValue N1 = Op.getOperand(0);
8016   EVT SrcVT = N1.getValueType();
8017   unsigned SrcSize = SrcVT.getSizeInBits();
8018   if (SrcSize > 256 ||
8019       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
8020       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
8021     return SDValue();
8022   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
8023     return SDValue();
8024 
8025   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8026   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8027 
8028   SDLoc DL(Op);
8029   SDValue Op1, Op2;
8030   if (SrcSize == 256) {
8031     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
8032     EVT SplitVT =
8033         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
8034     unsigned SplitNumElts = SplitVT.getVectorNumElements();
8035     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
8036                       DAG.getConstant(0, DL, VecIdxTy));
8037     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
8038                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
8039   }
8040   else {
8041     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
8042     Op2 = DAG.getUNDEF(WideVT);
8043   }
8044 
8045   // First list the elements we want to keep.
8046   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
8047   SmallVector<int, 16> ShuffV;
8048   if (Subtarget.isLittleEndian())
8049     for (unsigned i = 0; i < TrgNumElts; ++i)
8050       ShuffV.push_back(i * SizeMult);
8051   else
8052     for (unsigned i = 1; i <= TrgNumElts; ++i)
8053       ShuffV.push_back(i * SizeMult - 1);
8054 
8055   // Populate the remaining elements with undefs.
8056   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
8057     // ShuffV.push_back(i + WideNumElts);
8058     ShuffV.push_back(WideNumElts + 1);
8059 
8060   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
8061   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
8062   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
8063 }
8064 
8065 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
8066 /// possible.
8067 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
8068   // Not FP, or using SPE? Not a fsel.
8069   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
8070       !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE())
8071     return Op;
8072 
8073   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
8074 
8075   EVT ResVT = Op.getValueType();
8076   EVT CmpVT = Op.getOperand(0).getValueType();
8077   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8078   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
8079   SDLoc dl(Op);
8080   SDNodeFlags Flags = Op.getNode()->getFlags();
8081 
8082   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
8083   // presence of infinities.
8084   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
8085     switch (CC) {
8086     default:
8087       break;
8088     case ISD::SETOGT:
8089     case ISD::SETGT:
8090       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
8091     case ISD::SETOLT:
8092     case ISD::SETLT:
8093       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
8094     }
8095   }
8096 
8097   // We might be able to do better than this under some circumstances, but in
8098   // general, fsel-based lowering of select is a finite-math-only optimization.
8099   // For more information, see section F.3 of the 2.06 ISA specification.
8100   // With ISA 3.0
8101   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
8102       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
8103     return Op;
8104 
8105   // If the RHS of the comparison is a 0.0, we don't need to do the
8106   // subtraction at all.
8107   SDValue Sel1;
8108   if (isFloatingPointZero(RHS))
8109     switch (CC) {
8110     default: break;       // SETUO etc aren't handled by fsel.
8111     case ISD::SETNE:
8112       std::swap(TV, FV);
8113       LLVM_FALLTHROUGH;
8114     case ISD::SETEQ:
8115       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8116         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8117       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8118       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8119         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8120       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8121                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
8122     case ISD::SETULT:
8123     case ISD::SETLT:
8124       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8125       LLVM_FALLTHROUGH;
8126     case ISD::SETOGE:
8127     case ISD::SETGE:
8128       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8129         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8130       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8131     case ISD::SETUGT:
8132     case ISD::SETGT:
8133       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8134       LLVM_FALLTHROUGH;
8135     case ISD::SETOLE:
8136     case ISD::SETLE:
8137       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8138         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8139       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8140                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
8141     }
8142 
8143   SDValue Cmp;
8144   switch (CC) {
8145   default: break;       // SETUO etc aren't handled by fsel.
8146   case ISD::SETNE:
8147     std::swap(TV, FV);
8148     LLVM_FALLTHROUGH;
8149   case ISD::SETEQ:
8150     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8151     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8152       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8153     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8154     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8155       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8156     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8157                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8158   case ISD::SETULT:
8159   case ISD::SETLT:
8160     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8161     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8162       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8163     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8164   case ISD::SETOGE:
8165   case ISD::SETGE:
8166     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8167     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8168       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8169     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8170   case ISD::SETUGT:
8171   case ISD::SETGT:
8172     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8173     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8174       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8175     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8176   case ISD::SETOLE:
8177   case ISD::SETLE:
8178     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8179     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8180       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8181     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8182   }
8183   return Op;
8184 }
8185 
8186 static unsigned getPPCStrictOpcode(unsigned Opc) {
8187   switch (Opc) {
8188   default:
8189     llvm_unreachable("No strict version of this opcode!");
8190   case PPCISD::FCTIDZ:
8191     return PPCISD::STRICT_FCTIDZ;
8192   case PPCISD::FCTIWZ:
8193     return PPCISD::STRICT_FCTIWZ;
8194   case PPCISD::FCTIDUZ:
8195     return PPCISD::STRICT_FCTIDUZ;
8196   case PPCISD::FCTIWUZ:
8197     return PPCISD::STRICT_FCTIWUZ;
8198   case PPCISD::FCFID:
8199     return PPCISD::STRICT_FCFID;
8200   case PPCISD::FCFIDU:
8201     return PPCISD::STRICT_FCFIDU;
8202   case PPCISD::FCFIDS:
8203     return PPCISD::STRICT_FCFIDS;
8204   case PPCISD::FCFIDUS:
8205     return PPCISD::STRICT_FCFIDUS;
8206   }
8207 }
8208 
8209 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
8210                               const PPCSubtarget &Subtarget) {
8211   SDLoc dl(Op);
8212   bool IsStrict = Op->isStrictFPOpcode();
8213   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8214                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8215 
8216   // TODO: Any other flags to propagate?
8217   SDNodeFlags Flags;
8218   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8219 
8220   // For strict nodes, source is the second operand.
8221   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8222   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8223   assert(Src.getValueType().isFloatingPoint());
8224   if (Src.getValueType() == MVT::f32) {
8225     if (IsStrict) {
8226       Src =
8227           DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
8228                       DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
8229       Chain = Src.getValue(1);
8230     } else
8231       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8232   }
8233   SDValue Conv;
8234   unsigned Opc = ISD::DELETED_NODE;
8235   switch (Op.getSimpleValueType().SimpleTy) {
8236   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8237   case MVT::i32:
8238     Opc = IsSigned ? PPCISD::FCTIWZ
8239                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8240     break;
8241   case MVT::i64:
8242     assert((IsSigned || Subtarget.hasFPCVT()) &&
8243            "i64 FP_TO_UINT is supported only with FPCVT");
8244     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8245   }
8246   if (IsStrict) {
8247     Opc = getPPCStrictOpcode(Opc);
8248     Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
8249                        {Chain, Src}, Flags);
8250   } else {
8251     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8252   }
8253   return Conv;
8254 }
8255 
8256 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8257                                                SelectionDAG &DAG,
8258                                                const SDLoc &dl) const {
8259   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8260   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8261                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8262   bool IsStrict = Op->isStrictFPOpcode();
8263 
8264   // Convert the FP value to an int value through memory.
8265   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8266                   (IsSigned || Subtarget.hasFPCVT());
8267   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8268   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8269   MachinePointerInfo MPI =
8270       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8271 
8272   // Emit a store to the stack slot.
8273   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8274   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8275   if (i32Stack) {
8276     MachineFunction &MF = DAG.getMachineFunction();
8277     Alignment = Align(4);
8278     MachineMemOperand *MMO =
8279         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8280     SDValue Ops[] = { Chain, Tmp, FIPtr };
8281     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8282               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8283   } else
8284     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8285 
8286   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8287   // add in a bias on big endian.
8288   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8289     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8290                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8291     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8292   }
8293 
8294   RLI.Chain = Chain;
8295   RLI.Ptr = FIPtr;
8296   RLI.MPI = MPI;
8297   RLI.Alignment = Alignment;
8298 }
8299 
8300 /// Custom lowers floating point to integer conversions to use
8301 /// the direct move instructions available in ISA 2.07 to avoid the
8302 /// need for load/store combinations.
8303 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8304                                                     SelectionDAG &DAG,
8305                                                     const SDLoc &dl) const {
8306   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8307   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8308   if (Op->isStrictFPOpcode())
8309     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8310   else
8311     return Mov;
8312 }
8313 
8314 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8315                                           const SDLoc &dl) const {
8316   bool IsStrict = Op->isStrictFPOpcode();
8317   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8318                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8319   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8320   EVT SrcVT = Src.getValueType();
8321   EVT DstVT = Op.getValueType();
8322 
8323   // FP to INT conversions are legal for f128.
8324   if (SrcVT == MVT::f128)
8325     return Op;
8326 
8327   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8328   // PPC (the libcall is not available).
8329   if (SrcVT == MVT::ppcf128) {
8330     if (DstVT == MVT::i32) {
8331       // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8332       // set other fast-math flags to FP operations in both strict and
8333       // non-strict cases. (FP_TO_SINT, FSUB)
8334       SDNodeFlags Flags;
8335       Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8336 
8337       if (IsSigned) {
8338         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8339                                  DAG.getIntPtrConstant(0, dl));
8340         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8341                                  DAG.getIntPtrConstant(1, dl));
8342 
8343         // Add the two halves of the long double in round-to-zero mode, and use
8344         // a smaller FP_TO_SINT.
8345         if (IsStrict) {
8346           SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8347                                     DAG.getVTList(MVT::f64, MVT::Other),
8348                                     {Op.getOperand(0), Lo, Hi}, Flags);
8349           return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8350                              DAG.getVTList(MVT::i32, MVT::Other),
8351                              {Res.getValue(1), Res}, Flags);
8352         } else {
8353           SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8354           return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8355         }
8356       } else {
8357         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8358         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8359         SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8360         SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8361         if (IsStrict) {
8362           // Sel = Src < 0x80000000
8363           // FltOfs = select Sel, 0.0, 0x80000000
8364           // IntOfs = select Sel, 0, 0x80000000
8365           // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8366           SDValue Chain = Op.getOperand(0);
8367           EVT SetCCVT =
8368               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8369           EVT DstSetCCVT =
8370               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8371           SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8372                                      Chain, true);
8373           Chain = Sel.getValue(1);
8374 
8375           SDValue FltOfs = DAG.getSelect(
8376               dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8377           Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8378 
8379           SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8380                                     DAG.getVTList(SrcVT, MVT::Other),
8381                                     {Chain, Src, FltOfs}, Flags);
8382           Chain = Val.getValue(1);
8383           SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8384                                      DAG.getVTList(DstVT, MVT::Other),
8385                                      {Chain, Val}, Flags);
8386           Chain = SInt.getValue(1);
8387           SDValue IntOfs = DAG.getSelect(
8388               dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8389           SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8390           return DAG.getMergeValues({Result, Chain}, dl);
8391         } else {
8392           // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8393           // FIXME: generated code sucks.
8394           SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8395           True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8396           True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8397           SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8398           return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8399         }
8400       }
8401     }
8402 
8403     return SDValue();
8404   }
8405 
8406   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8407     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8408 
8409   ReuseLoadInfo RLI;
8410   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8411 
8412   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8413                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8414 }
8415 
8416 // We're trying to insert a regular store, S, and then a load, L. If the
8417 // incoming value, O, is a load, we might just be able to have our load use the
8418 // address used by O. However, we don't know if anything else will store to
8419 // that address before we can load from it. To prevent this situation, we need
8420 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8421 // the same chain operand as O, we create a token factor from the chain results
8422 // of O and L, and we replace all uses of O's chain result with that token
8423 // factor (see spliceIntoChain below for this last part).
8424 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8425                                             ReuseLoadInfo &RLI,
8426                                             SelectionDAG &DAG,
8427                                             ISD::LoadExtType ET) const {
8428   // Conservatively skip reusing for constrained FP nodes.
8429   if (Op->isStrictFPOpcode())
8430     return false;
8431 
8432   SDLoc dl(Op);
8433   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8434                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8435   if (ET == ISD::NON_EXTLOAD &&
8436       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8437       isOperationLegalOrCustom(Op.getOpcode(),
8438                                Op.getOperand(0).getValueType())) {
8439 
8440     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8441     return true;
8442   }
8443 
8444   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8445   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8446       LD->isNonTemporal())
8447     return false;
8448   if (LD->getMemoryVT() != MemVT)
8449     return false;
8450 
8451   // If the result of the load is an illegal type, then we can't build a
8452   // valid chain for reuse since the legalised loads and token factor node that
8453   // ties the legalised loads together uses a different output chain then the
8454   // illegal load.
8455   if (!isTypeLegal(LD->getValueType(0)))
8456     return false;
8457 
8458   RLI.Ptr = LD->getBasePtr();
8459   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8460     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8461            "Non-pre-inc AM on PPC?");
8462     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8463                           LD->getOffset());
8464   }
8465 
8466   RLI.Chain = LD->getChain();
8467   RLI.MPI = LD->getPointerInfo();
8468   RLI.IsDereferenceable = LD->isDereferenceable();
8469   RLI.IsInvariant = LD->isInvariant();
8470   RLI.Alignment = LD->getAlign();
8471   RLI.AAInfo = LD->getAAInfo();
8472   RLI.Ranges = LD->getRanges();
8473 
8474   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8475   return true;
8476 }
8477 
8478 // Given the head of the old chain, ResChain, insert a token factor containing
8479 // it and NewResChain, and make users of ResChain now be users of that token
8480 // factor.
8481 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8482 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8483                                         SDValue NewResChain,
8484                                         SelectionDAG &DAG) const {
8485   if (!ResChain)
8486     return;
8487 
8488   SDLoc dl(NewResChain);
8489 
8490   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8491                            NewResChain, DAG.getUNDEF(MVT::Other));
8492   assert(TF.getNode() != NewResChain.getNode() &&
8493          "A new TF really is required here");
8494 
8495   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8496   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8497 }
8498 
8499 /// Analyze profitability of direct move
8500 /// prefer float load to int load plus direct move
8501 /// when there is no integer use of int load
8502 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8503   SDNode *Origin = Op.getOperand(0).getNode();
8504   if (Origin->getOpcode() != ISD::LOAD)
8505     return true;
8506 
8507   // If there is no LXSIBZX/LXSIHZX, like Power8,
8508   // prefer direct move if the memory size is 1 or 2 bytes.
8509   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8510   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8511     return true;
8512 
8513   for (SDNode::use_iterator UI = Origin->use_begin(),
8514                             UE = Origin->use_end();
8515        UI != UE; ++UI) {
8516 
8517     // Only look at the users of the loaded value.
8518     if (UI.getUse().get().getResNo() != 0)
8519       continue;
8520 
8521     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8522         UI->getOpcode() != ISD::UINT_TO_FP &&
8523         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8524         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8525       return true;
8526   }
8527 
8528   return false;
8529 }
8530 
8531 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8532                               const PPCSubtarget &Subtarget,
8533                               SDValue Chain = SDValue()) {
8534   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8535                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8536   SDLoc dl(Op);
8537 
8538   // TODO: Any other flags to propagate?
8539   SDNodeFlags Flags;
8540   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8541 
8542   // If we have FCFIDS, then use it when converting to single-precision.
8543   // Otherwise, convert to double-precision and then round.
8544   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8545   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8546                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8547   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8548   if (Op->isStrictFPOpcode()) {
8549     if (!Chain)
8550       Chain = Op.getOperand(0);
8551     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8552                        DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8553   } else
8554     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8555 }
8556 
8557 /// Custom lowers integer to floating point conversions to use
8558 /// the direct move instructions available in ISA 2.07 to avoid the
8559 /// need for load/store combinations.
8560 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8561                                                     SelectionDAG &DAG,
8562                                                     const SDLoc &dl) const {
8563   assert((Op.getValueType() == MVT::f32 ||
8564           Op.getValueType() == MVT::f64) &&
8565          "Invalid floating point type as target of conversion");
8566   assert(Subtarget.hasFPCVT() &&
8567          "Int to FP conversions with direct moves require FPCVT");
8568   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8569   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8570   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8571                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8572   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8573   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8574   return convertIntToFP(Op, Mov, DAG, Subtarget);
8575 }
8576 
8577 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8578 
8579   EVT VecVT = Vec.getValueType();
8580   assert(VecVT.isVector() && "Expected a vector type.");
8581   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8582 
8583   EVT EltVT = VecVT.getVectorElementType();
8584   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8585   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8586 
8587   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8588   SmallVector<SDValue, 16> Ops(NumConcat);
8589   Ops[0] = Vec;
8590   SDValue UndefVec = DAG.getUNDEF(VecVT);
8591   for (unsigned i = 1; i < NumConcat; ++i)
8592     Ops[i] = UndefVec;
8593 
8594   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8595 }
8596 
8597 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8598                                                 const SDLoc &dl) const {
8599   bool IsStrict = Op->isStrictFPOpcode();
8600   unsigned Opc = Op.getOpcode();
8601   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8602   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8603           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8604          "Unexpected conversion type");
8605   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8606          "Supports conversions to v2f64/v4f32 only.");
8607 
8608   // TODO: Any other flags to propagate?
8609   SDNodeFlags Flags;
8610   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8611 
8612   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8613   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8614 
8615   SDValue Wide = widenVec(DAG, Src, dl);
8616   EVT WideVT = Wide.getValueType();
8617   unsigned WideNumElts = WideVT.getVectorNumElements();
8618   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8619 
8620   SmallVector<int, 16> ShuffV;
8621   for (unsigned i = 0; i < WideNumElts; ++i)
8622     ShuffV.push_back(i + WideNumElts);
8623 
8624   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8625   int SaveElts = FourEltRes ? 4 : 2;
8626   if (Subtarget.isLittleEndian())
8627     for (int i = 0; i < SaveElts; i++)
8628       ShuffV[i * Stride] = i;
8629   else
8630     for (int i = 1; i <= SaveElts; i++)
8631       ShuffV[i * Stride - 1] = i - 1;
8632 
8633   SDValue ShuffleSrc2 =
8634       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8635   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8636 
8637   SDValue Extend;
8638   if (SignedConv) {
8639     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8640     EVT ExtVT = Src.getValueType();
8641     if (Subtarget.hasP9Altivec())
8642       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8643                                IntermediateVT.getVectorNumElements());
8644 
8645     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8646                          DAG.getValueType(ExtVT));
8647   } else
8648     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8649 
8650   if (IsStrict)
8651     return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8652                        {Op.getOperand(0), Extend}, Flags);
8653 
8654   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8655 }
8656 
8657 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8658                                           SelectionDAG &DAG) const {
8659   SDLoc dl(Op);
8660   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8661                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8662   bool IsStrict = Op->isStrictFPOpcode();
8663   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8664   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8665 
8666   // TODO: Any other flags to propagate?
8667   SDNodeFlags Flags;
8668   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8669 
8670   EVT InVT = Src.getValueType();
8671   EVT OutVT = Op.getValueType();
8672   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8673       isOperationCustom(Op.getOpcode(), InVT))
8674     return LowerINT_TO_FPVector(Op, DAG, dl);
8675 
8676   // Conversions to f128 are legal.
8677   if (Op.getValueType() == MVT::f128)
8678     return Op;
8679 
8680   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8681   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8682     return SDValue();
8683 
8684   if (Src.getValueType() == MVT::i1)
8685     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8686                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8687                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8688 
8689   // If we have direct moves, we can do all the conversion, skip the store/load
8690   // however, without FPCVT we can't do most conversions.
8691   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8692       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8693     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8694 
8695   assert((IsSigned || Subtarget.hasFPCVT()) &&
8696          "UINT_TO_FP is supported only with FPCVT");
8697 
8698   if (Src.getValueType() == MVT::i64) {
8699     SDValue SINT = Src;
8700     // When converting to single-precision, we actually need to convert
8701     // to double-precision first and then round to single-precision.
8702     // To avoid double-rounding effects during that operation, we have
8703     // to prepare the input operand.  Bits that might be truncated when
8704     // converting to double-precision are replaced by a bit that won't
8705     // be lost at this stage, but is below the single-precision rounding
8706     // position.
8707     //
8708     // However, if -enable-unsafe-fp-math is in effect, accept double
8709     // rounding to avoid the extra overhead.
8710     if (Op.getValueType() == MVT::f32 &&
8711         !Subtarget.hasFPCVT() &&
8712         !DAG.getTarget().Options.UnsafeFPMath) {
8713 
8714       // Twiddle input to make sure the low 11 bits are zero.  (If this
8715       // is the case, we are guaranteed the value will fit into the 53 bit
8716       // mantissa of an IEEE double-precision value without rounding.)
8717       // If any of those low 11 bits were not zero originally, make sure
8718       // bit 12 (value 2048) is set instead, so that the final rounding
8719       // to single-precision gets the correct result.
8720       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8721                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8722       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8723                           Round, DAG.getConstant(2047, dl, MVT::i64));
8724       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8725       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8726                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8727 
8728       // However, we cannot use that value unconditionally: if the magnitude
8729       // of the input value is small, the bit-twiddling we did above might
8730       // end up visibly changing the output.  Fortunately, in that case, we
8731       // don't need to twiddle bits since the original input will convert
8732       // exactly to double-precision floating-point already.  Therefore,
8733       // construct a conditional to use the original value if the top 11
8734       // bits are all sign-bit copies, and use the rounded value computed
8735       // above otherwise.
8736       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8737                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8738       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8739                          Cond, DAG.getConstant(1, dl, MVT::i64));
8740       Cond = DAG.getSetCC(
8741           dl,
8742           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8743           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8744 
8745       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8746     }
8747 
8748     ReuseLoadInfo RLI;
8749     SDValue Bits;
8750 
8751     MachineFunction &MF = DAG.getMachineFunction();
8752     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8753       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8754                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8755       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8756     } else if (Subtarget.hasLFIWAX() &&
8757                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8758       MachineMemOperand *MMO =
8759         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8760                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8761       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8762       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8763                                      DAG.getVTList(MVT::f64, MVT::Other),
8764                                      Ops, MVT::i32, MMO);
8765       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8766     } else if (Subtarget.hasFPCVT() &&
8767                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8768       MachineMemOperand *MMO =
8769         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8770                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8771       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8772       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8773                                      DAG.getVTList(MVT::f64, MVT::Other),
8774                                      Ops, MVT::i32, MMO);
8775       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8776     } else if (((Subtarget.hasLFIWAX() &&
8777                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8778                 (Subtarget.hasFPCVT() &&
8779                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8780                SINT.getOperand(0).getValueType() == MVT::i32) {
8781       MachineFrameInfo &MFI = MF.getFrameInfo();
8782       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8783 
8784       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8785       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8786 
8787       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8788                                    MachinePointerInfo::getFixedStack(
8789                                        DAG.getMachineFunction(), FrameIdx));
8790       Chain = Store;
8791 
8792       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8793              "Expected an i32 store");
8794 
8795       RLI.Ptr = FIdx;
8796       RLI.Chain = Chain;
8797       RLI.MPI =
8798           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8799       RLI.Alignment = Align(4);
8800 
8801       MachineMemOperand *MMO =
8802         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8803                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8804       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8805       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8806                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8807                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8808                                      Ops, MVT::i32, MMO);
8809       Chain = Bits.getValue(1);
8810     } else
8811       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8812 
8813     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8814     if (IsStrict)
8815       Chain = FP.getValue(1);
8816 
8817     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8818       if (IsStrict)
8819         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8820                          DAG.getVTList(MVT::f32, MVT::Other),
8821                          {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8822       else
8823         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8824                          DAG.getIntPtrConstant(0, dl));
8825     }
8826     return FP;
8827   }
8828 
8829   assert(Src.getValueType() == MVT::i32 &&
8830          "Unhandled INT_TO_FP type in custom expander!");
8831   // Since we only generate this in 64-bit mode, we can take advantage of
8832   // 64-bit registers.  In particular, sign extend the input value into the
8833   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8834   // then lfd it and fcfid it.
8835   MachineFunction &MF = DAG.getMachineFunction();
8836   MachineFrameInfo &MFI = MF.getFrameInfo();
8837   EVT PtrVT = getPointerTy(MF.getDataLayout());
8838 
8839   SDValue Ld;
8840   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8841     ReuseLoadInfo RLI;
8842     bool ReusingLoad;
8843     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8844       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8845       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8846 
8847       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8848                                    MachinePointerInfo::getFixedStack(
8849                                        DAG.getMachineFunction(), FrameIdx));
8850       Chain = Store;
8851 
8852       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8853              "Expected an i32 store");
8854 
8855       RLI.Ptr = FIdx;
8856       RLI.Chain = Chain;
8857       RLI.MPI =
8858           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8859       RLI.Alignment = Align(4);
8860     }
8861 
8862     MachineMemOperand *MMO =
8863       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8864                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8865     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8866     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8867                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8868                                  MVT::i32, MMO);
8869     Chain = Ld.getValue(1);
8870     if (ReusingLoad)
8871       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8872   } else {
8873     assert(Subtarget.isPPC64() &&
8874            "i32->FP without LFIWAX supported only on PPC64");
8875 
8876     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8877     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8878 
8879     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8880 
8881     // STD the extended value into the stack slot.
8882     SDValue Store = DAG.getStore(
8883         Chain, dl, Ext64, FIdx,
8884         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8885     Chain = Store;
8886 
8887     // Load the value as a double.
8888     Ld = DAG.getLoad(
8889         MVT::f64, dl, Chain, FIdx,
8890         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8891     Chain = Ld.getValue(1);
8892   }
8893 
8894   // FCFID it and return it.
8895   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8896   if (IsStrict)
8897     Chain = FP.getValue(1);
8898   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8899     if (IsStrict)
8900       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8901                        DAG.getVTList(MVT::f32, MVT::Other),
8902                        {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8903     else
8904       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8905                        DAG.getIntPtrConstant(0, dl));
8906   }
8907   return FP;
8908 }
8909 
8910 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8911                                             SelectionDAG &DAG) const {
8912   SDLoc dl(Op);
8913   /*
8914    The rounding mode is in bits 30:31 of FPSR, and has the following
8915    settings:
8916      00 Round to nearest
8917      01 Round to 0
8918      10 Round to +inf
8919      11 Round to -inf
8920 
8921   FLT_ROUNDS, on the other hand, expects the following:
8922     -1 Undefined
8923      0 Round to 0
8924      1 Round to nearest
8925      2 Round to +inf
8926      3 Round to -inf
8927 
8928   To perform the conversion, we do:
8929     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8930   */
8931 
8932   MachineFunction &MF = DAG.getMachineFunction();
8933   EVT VT = Op.getValueType();
8934   EVT PtrVT = getPointerTy(MF.getDataLayout());
8935 
8936   // Save FP Control Word to register
8937   SDValue Chain = Op.getOperand(0);
8938   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8939   Chain = MFFS.getValue(1);
8940 
8941   // Save FP register to stack slot
8942   int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8943   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8944   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8945 
8946   // Load FP Control Word from low 32 bits of stack slot.
8947   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8948   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8949   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8950   Chain = CWD.getValue(1);
8951 
8952   // Transform as necessary
8953   SDValue CWD1 =
8954     DAG.getNode(ISD::AND, dl, MVT::i32,
8955                 CWD, DAG.getConstant(3, dl, MVT::i32));
8956   SDValue CWD2 =
8957     DAG.getNode(ISD::SRL, dl, MVT::i32,
8958                 DAG.getNode(ISD::AND, dl, MVT::i32,
8959                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8960                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8961                             DAG.getConstant(3, dl, MVT::i32)),
8962                 DAG.getConstant(1, dl, MVT::i32));
8963 
8964   SDValue RetVal =
8965     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8966 
8967   RetVal =
8968       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8969                   dl, VT, RetVal);
8970 
8971   return DAG.getMergeValues({RetVal, Chain}, dl);
8972 }
8973 
8974 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8975   EVT VT = Op.getValueType();
8976   unsigned BitWidth = VT.getSizeInBits();
8977   SDLoc dl(Op);
8978   assert(Op.getNumOperands() == 3 &&
8979          VT == Op.getOperand(1).getValueType() &&
8980          "Unexpected SHL!");
8981 
8982   // Expand into a bunch of logical ops.  Note that these ops
8983   // depend on the PPC behavior for oversized shift amounts.
8984   SDValue Lo = Op.getOperand(0);
8985   SDValue Hi = Op.getOperand(1);
8986   SDValue Amt = Op.getOperand(2);
8987   EVT AmtVT = Amt.getValueType();
8988 
8989   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8990                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8991   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8992   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8993   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8994   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8995                              DAG.getConstant(-BitWidth, dl, AmtVT));
8996   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8997   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8998   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8999   SDValue OutOps[] = { OutLo, OutHi };
9000   return DAG.getMergeValues(OutOps, dl);
9001 }
9002 
9003 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
9004   EVT VT = Op.getValueType();
9005   SDLoc dl(Op);
9006   unsigned BitWidth = VT.getSizeInBits();
9007   assert(Op.getNumOperands() == 3 &&
9008          VT == Op.getOperand(1).getValueType() &&
9009          "Unexpected SRL!");
9010 
9011   // Expand into a bunch of logical ops.  Note that these ops
9012   // depend on the PPC behavior for oversized shift amounts.
9013   SDValue Lo = Op.getOperand(0);
9014   SDValue Hi = Op.getOperand(1);
9015   SDValue Amt = Op.getOperand(2);
9016   EVT AmtVT = Amt.getValueType();
9017 
9018   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
9019                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
9020   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
9021   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
9022   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
9023   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
9024                              DAG.getConstant(-BitWidth, dl, AmtVT));
9025   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
9026   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
9027   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
9028   SDValue OutOps[] = { OutLo, OutHi };
9029   return DAG.getMergeValues(OutOps, dl);
9030 }
9031 
9032 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
9033   SDLoc dl(Op);
9034   EVT VT = Op.getValueType();
9035   unsigned BitWidth = VT.getSizeInBits();
9036   assert(Op.getNumOperands() == 3 &&
9037          VT == Op.getOperand(1).getValueType() &&
9038          "Unexpected SRA!");
9039 
9040   // Expand into a bunch of logical ops, followed by a select_cc.
9041   SDValue Lo = Op.getOperand(0);
9042   SDValue Hi = Op.getOperand(1);
9043   SDValue Amt = Op.getOperand(2);
9044   EVT AmtVT = Amt.getValueType();
9045 
9046   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
9047                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
9048   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
9049   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
9050   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
9051   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
9052                              DAG.getConstant(-BitWidth, dl, AmtVT));
9053   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
9054   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
9055   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
9056                                   Tmp4, Tmp6, ISD::SETLE);
9057   SDValue OutOps[] = { OutLo, OutHi };
9058   return DAG.getMergeValues(OutOps, dl);
9059 }
9060 
9061 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
9062                                             SelectionDAG &DAG) const {
9063   SDLoc dl(Op);
9064   EVT VT = Op.getValueType();
9065   unsigned BitWidth = VT.getSizeInBits();
9066 
9067   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
9068   SDValue X = Op.getOperand(0);
9069   SDValue Y = Op.getOperand(1);
9070   SDValue Z = Op.getOperand(2);
9071   EVT AmtVT = Z.getValueType();
9072 
9073   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
9074   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
9075   // This is simpler than TargetLowering::expandFunnelShift because we can rely
9076   // on PowerPC shift by BW being well defined.
9077   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
9078                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
9079   SDValue SubZ =
9080       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
9081   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
9082   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
9083   return DAG.getNode(ISD::OR, dl, VT, X, Y);
9084 }
9085 
9086 //===----------------------------------------------------------------------===//
9087 // Vector related lowering.
9088 //
9089 
9090 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
9091 /// element size of SplatSize. Cast the result to VT.
9092 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
9093                                       SelectionDAG &DAG, const SDLoc &dl) {
9094   static const MVT VTys[] = { // canonical VT to use for each size.
9095     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
9096   };
9097 
9098   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
9099 
9100   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
9101   if (Val == ((1LU << (SplatSize * 8)) - 1)) {
9102     SplatSize = 1;
9103     Val = 0xFF;
9104   }
9105 
9106   EVT CanonicalVT = VTys[SplatSize-1];
9107 
9108   // Build a canonical splat for this value.
9109   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
9110 }
9111 
9112 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
9113 /// specified intrinsic ID.
9114 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
9115                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
9116   if (DestVT == MVT::Other) DestVT = Op.getValueType();
9117   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9118                      DAG.getConstant(IID, dl, MVT::i32), Op);
9119 }
9120 
9121 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
9122 /// specified intrinsic ID.
9123 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
9124                                 SelectionDAG &DAG, const SDLoc &dl,
9125                                 EVT DestVT = MVT::Other) {
9126   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
9127   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9128                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
9129 }
9130 
9131 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
9132 /// specified intrinsic ID.
9133 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
9134                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
9135                                 EVT DestVT = MVT::Other) {
9136   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
9137   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9138                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
9139 }
9140 
9141 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
9142 /// amount.  The result has the specified value type.
9143 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
9144                            SelectionDAG &DAG, const SDLoc &dl) {
9145   // Force LHS/RHS to be the right type.
9146   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
9147   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
9148 
9149   int Ops[16];
9150   for (unsigned i = 0; i != 16; ++i)
9151     Ops[i] = i + Amt;
9152   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
9153   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9154 }
9155 
9156 /// Do we have an efficient pattern in a .td file for this node?
9157 ///
9158 /// \param V - pointer to the BuildVectorSDNode being matched
9159 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
9160 ///
9161 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
9162 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
9163 /// the opposite is true (expansion is beneficial) are:
9164 /// - The node builds a vector out of integers that are not 32 or 64-bits
9165 /// - The node builds a vector out of constants
9166 /// - The node is a "load-and-splat"
9167 /// In all other cases, we will choose to keep the BUILD_VECTOR.
9168 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
9169                                             bool HasDirectMove,
9170                                             bool HasP8Vector) {
9171   EVT VecVT = V->getValueType(0);
9172   bool RightType = VecVT == MVT::v2f64 ||
9173     (HasP8Vector && VecVT == MVT::v4f32) ||
9174     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
9175   if (!RightType)
9176     return false;
9177 
9178   bool IsSplat = true;
9179   bool IsLoad = false;
9180   SDValue Op0 = V->getOperand(0);
9181 
9182   // This function is called in a block that confirms the node is not a constant
9183   // splat. So a constant BUILD_VECTOR here means the vector is built out of
9184   // different constants.
9185   if (V->isConstant())
9186     return false;
9187   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9188     if (V->getOperand(i).isUndef())
9189       return false;
9190     // We want to expand nodes that represent load-and-splat even if the
9191     // loaded value is a floating point truncation or conversion to int.
9192     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9193         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9194          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9195         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9196          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9197         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9198          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9199       IsLoad = true;
9200     // If the operands are different or the input is not a load and has more
9201     // uses than just this BV node, then it isn't a splat.
9202     if (V->getOperand(i) != Op0 ||
9203         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9204       IsSplat = false;
9205   }
9206   return !(IsSplat && IsLoad);
9207 }
9208 
9209 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9210 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9211 
9212   SDLoc dl(Op);
9213   SDValue Op0 = Op->getOperand(0);
9214 
9215   if ((Op.getValueType() != MVT::f128) ||
9216       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9217       (Op0.getOperand(0).getValueType() != MVT::i64) ||
9218       (Op0.getOperand(1).getValueType() != MVT::i64))
9219     return SDValue();
9220 
9221   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9222                      Op0.getOperand(1));
9223 }
9224 
9225 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9226   const SDValue *InputLoad = &Op;
9227   if (InputLoad->getOpcode() == ISD::BITCAST)
9228     InputLoad = &InputLoad->getOperand(0);
9229   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9230       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9231     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9232     InputLoad = &InputLoad->getOperand(0);
9233   }
9234   if (InputLoad->getOpcode() != ISD::LOAD)
9235     return nullptr;
9236   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9237   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9238 }
9239 
9240 // Convert the argument APFloat to a single precision APFloat if there is no
9241 // loss in information during the conversion to single precision APFloat and the
9242 // resulting number is not a denormal number. Return true if successful.
9243 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9244   APFloat APFloatToConvert = ArgAPFloat;
9245   bool LosesInfo = true;
9246   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9247                            &LosesInfo);
9248   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9249   if (Success)
9250     ArgAPFloat = APFloatToConvert;
9251   return Success;
9252 }
9253 
9254 // Bitcast the argument APInt to a double and convert it to a single precision
9255 // APFloat, bitcast the APFloat to an APInt and assign it to the original
9256 // argument if there is no loss in information during the conversion from
9257 // double to single precision APFloat and the resulting number is not a denormal
9258 // number. Return true if successful.
9259 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9260   double DpValue = ArgAPInt.bitsToDouble();
9261   APFloat APFloatDp(DpValue);
9262   bool Success = convertToNonDenormSingle(APFloatDp);
9263   if (Success)
9264     ArgAPInt = APFloatDp.bitcastToAPInt();
9265   return Success;
9266 }
9267 
9268 // If this is a case we can't handle, return null and let the default
9269 // expansion code take care of it.  If we CAN select this case, and if it
9270 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9271 // this case more efficiently than a constant pool load, lower it to the
9272 // sequence of ops that should be used.
9273 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9274                                              SelectionDAG &DAG) const {
9275   SDLoc dl(Op);
9276   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9277   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9278 
9279   // Check if this is a splat of a constant value.
9280   APInt APSplatBits, APSplatUndef;
9281   unsigned SplatBitSize;
9282   bool HasAnyUndefs;
9283   bool BVNIsConstantSplat =
9284       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9285                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9286 
9287   // If it is a splat of a double, check if we can shrink it to a 32 bit
9288   // non-denormal float which when converted back to double gives us the same
9289   // double. This is to exploit the XXSPLTIDP instruction.
9290   if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() &&
9291       (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) &&
9292       convertToNonDenormSingle(APSplatBits)) {
9293     SDValue SplatNode = DAG.getNode(
9294         PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9295         DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9296     return DAG.getBitcast(Op.getValueType(), SplatNode);
9297   }
9298 
9299   if (!BVNIsConstantSplat || SplatBitSize > 32) {
9300 
9301     bool IsPermutedLoad = false;
9302     const SDValue *InputLoad =
9303         getNormalLoadInput(Op.getOperand(0), IsPermutedLoad);
9304     // Handle load-and-splat patterns as we have instructions that will do this
9305     // in one go.
9306     if (InputLoad && DAG.isSplatValue(Op, true)) {
9307       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9308 
9309       // We have handling for 4 and 8 byte elements.
9310       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9311 
9312       // Checking for a single use of this load, we have to check for vector
9313       // width (128 bits) / ElementSize uses (since each operand of the
9314       // BUILD_VECTOR is a separate use of the value.
9315       unsigned NumUsesOfInputLD = 128 / ElementSize;
9316       for (SDValue BVInOp : Op->ops())
9317         if (BVInOp.isUndef())
9318           NumUsesOfInputLD--;
9319       assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
9320       if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
9321           ((Subtarget.hasVSX() && ElementSize == 64) ||
9322            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9323         SDValue Ops[] = {
9324           LD->getChain(),    // Chain
9325           LD->getBasePtr(),  // Ptr
9326           DAG.getValueType(Op.getValueType()) // VT
9327         };
9328         SDValue LdSplt = DAG.getMemIntrinsicNode(
9329             PPCISD::LD_SPLAT, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
9330             Ops, LD->getMemoryVT(), LD->getMemOperand());
9331         // Replace all uses of the output chain of the original load with the
9332         // output chain of the new load.
9333         DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
9334                                       LdSplt.getValue(1));
9335         return LdSplt;
9336       }
9337     }
9338 
9339     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
9340     // lowered to VSX instructions under certain conditions.
9341     // Without VSX, there is no pattern more efficient than expanding the node.
9342     if (Subtarget.hasVSX() &&
9343         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9344                                         Subtarget.hasP8Vector()))
9345       return Op;
9346     return SDValue();
9347   }
9348 
9349   uint64_t SplatBits = APSplatBits.getZExtValue();
9350   uint64_t SplatUndef = APSplatUndef.getZExtValue();
9351   unsigned SplatSize = SplatBitSize / 8;
9352 
9353   // First, handle single instruction cases.
9354 
9355   // All zeros?
9356   if (SplatBits == 0) {
9357     // Canonicalize all zero vectors to be v4i32.
9358     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9359       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9360       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9361     }
9362     return Op;
9363   }
9364 
9365   // We have XXSPLTIW for constant splats four bytes wide.
9366   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9367   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9368   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9369   // turned into a 4-byte splat of 0xABABABAB.
9370   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9371     return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
9372                                   Op.getValueType(), DAG, dl);
9373 
9374   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9375     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9376                                   dl);
9377 
9378   // We have XXSPLTIB for constant splats one byte wide.
9379   if (Subtarget.hasP9Vector() && SplatSize == 1)
9380     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9381                                   dl);
9382 
9383   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9384   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9385                     (32-SplatBitSize));
9386   if (SextVal >= -16 && SextVal <= 15)
9387     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9388                                   dl);
9389 
9390   // Two instruction sequences.
9391 
9392   // If this value is in the range [-32,30] and is even, use:
9393   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9394   // If this value is in the range [17,31] and is odd, use:
9395   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9396   // If this value is in the range [-31,-17] and is odd, use:
9397   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9398   // Note the last two are three-instruction sequences.
9399   if (SextVal >= -32 && SextVal <= 31) {
9400     // To avoid having these optimizations undone by constant folding,
9401     // we convert to a pseudo that will be expanded later into one of
9402     // the above forms.
9403     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9404     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9405               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9406     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9407     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9408     if (VT == Op.getValueType())
9409       return RetVal;
9410     else
9411       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9412   }
9413 
9414   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9415   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9416   // for fneg/fabs.
9417   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9418     // Make -1 and vspltisw -1:
9419     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9420 
9421     // Make the VSLW intrinsic, computing 0x8000_0000.
9422     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9423                                    OnesV, DAG, dl);
9424 
9425     // xor by OnesV to invert it.
9426     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9427     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9428   }
9429 
9430   // Check to see if this is a wide variety of vsplti*, binop self cases.
9431   static const signed char SplatCsts[] = {
9432     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9433     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9434   };
9435 
9436   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9437     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9438     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9439     int i = SplatCsts[idx];
9440 
9441     // Figure out what shift amount will be used by altivec if shifted by i in
9442     // this splat size.
9443     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9444 
9445     // vsplti + shl self.
9446     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9447       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9448       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9449         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9450         Intrinsic::ppc_altivec_vslw
9451       };
9452       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9453       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9454     }
9455 
9456     // vsplti + srl self.
9457     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9458       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9459       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9460         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9461         Intrinsic::ppc_altivec_vsrw
9462       };
9463       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9464       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9465     }
9466 
9467     // vsplti + sra self.
9468     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9469       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9470       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9471         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9472         Intrinsic::ppc_altivec_vsraw
9473       };
9474       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9475       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9476     }
9477 
9478     // vsplti + rol self.
9479     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9480                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9481       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9482       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9483         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9484         Intrinsic::ppc_altivec_vrlw
9485       };
9486       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9487       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9488     }
9489 
9490     // t = vsplti c, result = vsldoi t, t, 1
9491     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9492       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9493       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9494       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9495     }
9496     // t = vsplti c, result = vsldoi t, t, 2
9497     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9498       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9499       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9500       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9501     }
9502     // t = vsplti c, result = vsldoi t, t, 3
9503     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9504       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9505       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9506       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9507     }
9508   }
9509 
9510   return SDValue();
9511 }
9512 
9513 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9514 /// the specified operations to build the shuffle.
9515 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9516                                       SDValue RHS, SelectionDAG &DAG,
9517                                       const SDLoc &dl) {
9518   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9519   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9520   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9521 
9522   enum {
9523     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9524     OP_VMRGHW,
9525     OP_VMRGLW,
9526     OP_VSPLTISW0,
9527     OP_VSPLTISW1,
9528     OP_VSPLTISW2,
9529     OP_VSPLTISW3,
9530     OP_VSLDOI4,
9531     OP_VSLDOI8,
9532     OP_VSLDOI12
9533   };
9534 
9535   if (OpNum == OP_COPY) {
9536     if (LHSID == (1*9+2)*9+3) return LHS;
9537     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9538     return RHS;
9539   }
9540 
9541   SDValue OpLHS, OpRHS;
9542   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9543   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9544 
9545   int ShufIdxs[16];
9546   switch (OpNum) {
9547   default: llvm_unreachable("Unknown i32 permute!");
9548   case OP_VMRGHW:
9549     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9550     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9551     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9552     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9553     break;
9554   case OP_VMRGLW:
9555     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9556     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9557     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9558     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9559     break;
9560   case OP_VSPLTISW0:
9561     for (unsigned i = 0; i != 16; ++i)
9562       ShufIdxs[i] = (i&3)+0;
9563     break;
9564   case OP_VSPLTISW1:
9565     for (unsigned i = 0; i != 16; ++i)
9566       ShufIdxs[i] = (i&3)+4;
9567     break;
9568   case OP_VSPLTISW2:
9569     for (unsigned i = 0; i != 16; ++i)
9570       ShufIdxs[i] = (i&3)+8;
9571     break;
9572   case OP_VSPLTISW3:
9573     for (unsigned i = 0; i != 16; ++i)
9574       ShufIdxs[i] = (i&3)+12;
9575     break;
9576   case OP_VSLDOI4:
9577     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9578   case OP_VSLDOI8:
9579     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9580   case OP_VSLDOI12:
9581     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9582   }
9583   EVT VT = OpLHS.getValueType();
9584   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9585   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9586   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9587   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9588 }
9589 
9590 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9591 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9592 /// SDValue.
9593 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9594                                            SelectionDAG &DAG) const {
9595   const unsigned BytesInVector = 16;
9596   bool IsLE = Subtarget.isLittleEndian();
9597   SDLoc dl(N);
9598   SDValue V1 = N->getOperand(0);
9599   SDValue V2 = N->getOperand(1);
9600   unsigned ShiftElts = 0, InsertAtByte = 0;
9601   bool Swap = false;
9602 
9603   // Shifts required to get the byte we want at element 7.
9604   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9605                                    0, 15, 14, 13, 12, 11, 10, 9};
9606   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9607                                 1, 2,  3,  4,  5,  6,  7,  8};
9608 
9609   ArrayRef<int> Mask = N->getMask();
9610   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9611 
9612   // For each mask element, find out if we're just inserting something
9613   // from V2 into V1 or vice versa.
9614   // Possible permutations inserting an element from V2 into V1:
9615   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9616   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9617   //   ...
9618   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9619   // Inserting from V1 into V2 will be similar, except mask range will be
9620   // [16,31].
9621 
9622   bool FoundCandidate = false;
9623   // If both vector operands for the shuffle are the same vector, the mask
9624   // will contain only elements from the first one and the second one will be
9625   // undef.
9626   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9627   // Go through the mask of half-words to find an element that's being moved
9628   // from one vector to the other.
9629   for (unsigned i = 0; i < BytesInVector; ++i) {
9630     unsigned CurrentElement = Mask[i];
9631     // If 2nd operand is undefined, we should only look for element 7 in the
9632     // Mask.
9633     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9634       continue;
9635 
9636     bool OtherElementsInOrder = true;
9637     // Examine the other elements in the Mask to see if they're in original
9638     // order.
9639     for (unsigned j = 0; j < BytesInVector; ++j) {
9640       if (j == i)
9641         continue;
9642       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9643       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9644       // in which we always assume we're always picking from the 1st operand.
9645       int MaskOffset =
9646           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9647       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9648         OtherElementsInOrder = false;
9649         break;
9650       }
9651     }
9652     // If other elements are in original order, we record the number of shifts
9653     // we need to get the element we want into element 7. Also record which byte
9654     // in the vector we should insert into.
9655     if (OtherElementsInOrder) {
9656       // If 2nd operand is undefined, we assume no shifts and no swapping.
9657       if (V2.isUndef()) {
9658         ShiftElts = 0;
9659         Swap = false;
9660       } else {
9661         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9662         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9663                          : BigEndianShifts[CurrentElement & 0xF];
9664         Swap = CurrentElement < BytesInVector;
9665       }
9666       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9667       FoundCandidate = true;
9668       break;
9669     }
9670   }
9671 
9672   if (!FoundCandidate)
9673     return SDValue();
9674 
9675   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9676   // optionally with VECSHL if shift is required.
9677   if (Swap)
9678     std::swap(V1, V2);
9679   if (V2.isUndef())
9680     V2 = V1;
9681   if (ShiftElts) {
9682     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9683                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9684     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9685                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9686   }
9687   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9688                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9689 }
9690 
9691 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9692 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9693 /// SDValue.
9694 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9695                                            SelectionDAG &DAG) const {
9696   const unsigned NumHalfWords = 8;
9697   const unsigned BytesInVector = NumHalfWords * 2;
9698   // Check that the shuffle is on half-words.
9699   if (!isNByteElemShuffleMask(N, 2, 1))
9700     return SDValue();
9701 
9702   bool IsLE = Subtarget.isLittleEndian();
9703   SDLoc dl(N);
9704   SDValue V1 = N->getOperand(0);
9705   SDValue V2 = N->getOperand(1);
9706   unsigned ShiftElts = 0, InsertAtByte = 0;
9707   bool Swap = false;
9708 
9709   // Shifts required to get the half-word we want at element 3.
9710   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9711   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9712 
9713   uint32_t Mask = 0;
9714   uint32_t OriginalOrderLow = 0x1234567;
9715   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9716   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9717   // 32-bit space, only need 4-bit nibbles per element.
9718   for (unsigned i = 0; i < NumHalfWords; ++i) {
9719     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9720     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9721   }
9722 
9723   // For each mask element, find out if we're just inserting something
9724   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9725   // from V2 into V1:
9726   //   X, 1, 2, 3, 4, 5, 6, 7
9727   //   0, X, 2, 3, 4, 5, 6, 7
9728   //   0, 1, X, 3, 4, 5, 6, 7
9729   //   0, 1, 2, X, 4, 5, 6, 7
9730   //   0, 1, 2, 3, X, 5, 6, 7
9731   //   0, 1, 2, 3, 4, X, 6, 7
9732   //   0, 1, 2, 3, 4, 5, X, 7
9733   //   0, 1, 2, 3, 4, 5, 6, X
9734   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9735 
9736   bool FoundCandidate = false;
9737   // Go through the mask of half-words to find an element that's being moved
9738   // from one vector to the other.
9739   for (unsigned i = 0; i < NumHalfWords; ++i) {
9740     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9741     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9742     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9743     uint32_t TargetOrder = 0x0;
9744 
9745     // If both vector operands for the shuffle are the same vector, the mask
9746     // will contain only elements from the first one and the second one will be
9747     // undef.
9748     if (V2.isUndef()) {
9749       ShiftElts = 0;
9750       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9751       TargetOrder = OriginalOrderLow;
9752       Swap = false;
9753       // Skip if not the correct element or mask of other elements don't equal
9754       // to our expected order.
9755       if (MaskOneElt == VINSERTHSrcElem &&
9756           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9757         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9758         FoundCandidate = true;
9759         break;
9760       }
9761     } else { // If both operands are defined.
9762       // Target order is [8,15] if the current mask is between [0,7].
9763       TargetOrder =
9764           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9765       // Skip if mask of other elements don't equal our expected order.
9766       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9767         // We only need the last 3 bits for the number of shifts.
9768         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9769                          : BigEndianShifts[MaskOneElt & 0x7];
9770         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9771         Swap = MaskOneElt < NumHalfWords;
9772         FoundCandidate = true;
9773         break;
9774       }
9775     }
9776   }
9777 
9778   if (!FoundCandidate)
9779     return SDValue();
9780 
9781   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9782   // optionally with VECSHL if shift is required.
9783   if (Swap)
9784     std::swap(V1, V2);
9785   if (V2.isUndef())
9786     V2 = V1;
9787   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9788   if (ShiftElts) {
9789     // Double ShiftElts because we're left shifting on v16i8 type.
9790     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9791                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9792     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9793     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9794                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9795     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9796   }
9797   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9798   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9799                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9800   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9801 }
9802 
9803 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9804 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9805 /// return the default SDValue.
9806 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9807                                               SelectionDAG &DAG) const {
9808   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9809   // to v16i8. Peek through the bitcasts to get the actual operands.
9810   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9811   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9812 
9813   auto ShuffleMask = SVN->getMask();
9814   SDValue VecShuffle(SVN, 0);
9815   SDLoc DL(SVN);
9816 
9817   // Check that we have a four byte shuffle.
9818   if (!isNByteElemShuffleMask(SVN, 4, 1))
9819     return SDValue();
9820 
9821   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9822   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9823     std::swap(LHS, RHS);
9824     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9825     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9826   }
9827 
9828   // Ensure that the RHS is a vector of constants.
9829   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9830   if (!BVN)
9831     return SDValue();
9832 
9833   // Check if RHS is a splat of 4-bytes (or smaller).
9834   APInt APSplatValue, APSplatUndef;
9835   unsigned SplatBitSize;
9836   bool HasAnyUndefs;
9837   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9838                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9839       SplatBitSize > 32)
9840     return SDValue();
9841 
9842   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9843   // The instruction splats a constant C into two words of the source vector
9844   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9845   // Thus we check that the shuffle mask is the equivalent  of
9846   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9847   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9848   // within each word are consecutive, so we only need to check the first byte.
9849   SDValue Index;
9850   bool IsLE = Subtarget.isLittleEndian();
9851   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9852       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9853        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9854     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9855   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9856            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9857             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9858     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9859   else
9860     return SDValue();
9861 
9862   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9863   // for XXSPLTI32DX.
9864   unsigned SplatVal = APSplatValue.getZExtValue();
9865   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9866     SplatVal |= (SplatVal << SplatBitSize);
9867 
9868   SDValue SplatNode = DAG.getNode(
9869       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9870       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9871   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9872 }
9873 
9874 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9875 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9876 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9877 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9878 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9879   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9880   assert(Op.getValueType() == MVT::v1i128 &&
9881          "Only set v1i128 as custom, other type shouldn't reach here!");
9882   SDLoc dl(Op);
9883   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9884   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9885   unsigned SHLAmt = N1.getConstantOperandVal(0);
9886   if (SHLAmt % 8 == 0) {
9887     SmallVector<int, 16> Mask(16, 0);
9888     std::iota(Mask.begin(), Mask.end(), 0);
9889     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9890     if (SDValue Shuffle =
9891             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9892                                  DAG.getUNDEF(MVT::v16i8), Mask))
9893       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9894   }
9895   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9896   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9897                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9898   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9899                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9900   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9901   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9902 }
9903 
9904 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9905 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9906 /// return the code it can be lowered into.  Worst case, it can always be
9907 /// lowered into a vperm.
9908 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9909                                                SelectionDAG &DAG) const {
9910   SDLoc dl(Op);
9911   SDValue V1 = Op.getOperand(0);
9912   SDValue V2 = Op.getOperand(1);
9913   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9914 
9915   // Any nodes that were combined in the target-independent combiner prior
9916   // to vector legalization will not be sent to the target combine. Try to
9917   // combine it here.
9918   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9919     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9920       return NewShuffle;
9921     Op = NewShuffle;
9922     SVOp = cast<ShuffleVectorSDNode>(Op);
9923     V1 = Op.getOperand(0);
9924     V2 = Op.getOperand(1);
9925   }
9926   EVT VT = Op.getValueType();
9927   bool isLittleEndian = Subtarget.isLittleEndian();
9928 
9929   unsigned ShiftElts, InsertAtByte;
9930   bool Swap = false;
9931 
9932   // If this is a load-and-splat, we can do that with a single instruction
9933   // in some cases. However if the load has multiple uses, we don't want to
9934   // combine it because that will just produce multiple loads.
9935   bool IsPermutedLoad = false;
9936   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9937   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9938       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9939       InputLoad->hasOneUse()) {
9940     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9941     int SplatIdx =
9942       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9943 
9944     // The splat index for permuted loads will be in the left half of the vector
9945     // which is strictly wider than the loaded value by 8 bytes. So we need to
9946     // adjust the splat index to point to the correct address in memory.
9947     if (IsPermutedLoad) {
9948       assert(isLittleEndian && "Unexpected permuted load on big endian target");
9949       SplatIdx += IsFourByte ? 2 : 1;
9950       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9951              "Splat of a value outside of the loaded memory");
9952     }
9953 
9954     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9955     // For 4-byte load-and-splat, we need Power9.
9956     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9957       uint64_t Offset = 0;
9958       if (IsFourByte)
9959         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9960       else
9961         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9962 
9963       SDValue BasePtr = LD->getBasePtr();
9964       if (Offset != 0)
9965         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9966                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9967       SDValue Ops[] = {
9968         LD->getChain(),    // Chain
9969         BasePtr,           // BasePtr
9970         DAG.getValueType(Op.getValueType()) // VT
9971       };
9972       SDVTList VTL =
9973         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9974       SDValue LdSplt =
9975         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9976                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9977       DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
9978       if (LdSplt.getValueType() != SVOp->getValueType(0))
9979         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9980       return LdSplt;
9981     }
9982   }
9983   if (Subtarget.hasP9Vector() &&
9984       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9985                            isLittleEndian)) {
9986     if (Swap)
9987       std::swap(V1, V2);
9988     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9989     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9990     if (ShiftElts) {
9991       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9992                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9993       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9994                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9995       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9996     }
9997     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9998                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9999     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
10000   }
10001 
10002   if (Subtarget.hasPrefixInstrs()) {
10003     SDValue SplatInsertNode;
10004     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
10005       return SplatInsertNode;
10006   }
10007 
10008   if (Subtarget.hasP9Altivec()) {
10009     SDValue NewISDNode;
10010     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
10011       return NewISDNode;
10012 
10013     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
10014       return NewISDNode;
10015   }
10016 
10017   if (Subtarget.hasVSX() &&
10018       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
10019     if (Swap)
10020       std::swap(V1, V2);
10021     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10022     SDValue Conv2 =
10023         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
10024 
10025     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
10026                               DAG.getConstant(ShiftElts, dl, MVT::i32));
10027     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
10028   }
10029 
10030   if (Subtarget.hasVSX() &&
10031     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
10032     if (Swap)
10033       std::swap(V1, V2);
10034     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10035     SDValue Conv2 =
10036         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
10037 
10038     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
10039                               DAG.getConstant(ShiftElts, dl, MVT::i32));
10040     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
10041   }
10042 
10043   if (Subtarget.hasP9Vector()) {
10044      if (PPC::isXXBRHShuffleMask(SVOp)) {
10045       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10046       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
10047       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
10048     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
10049       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10050       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
10051       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
10052     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
10053       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10054       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
10055       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
10056     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
10057       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
10058       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
10059       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
10060     }
10061   }
10062 
10063   if (Subtarget.hasVSX()) {
10064     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
10065       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
10066 
10067       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10068       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
10069                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
10070       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
10071     }
10072 
10073     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
10074     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
10075       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
10076       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
10077       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
10078     }
10079   }
10080 
10081   // Cases that are handled by instructions that take permute immediates
10082   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
10083   // selected by the instruction selector.
10084   if (V2.isUndef()) {
10085     if (PPC::isSplatShuffleMask(SVOp, 1) ||
10086         PPC::isSplatShuffleMask(SVOp, 2) ||
10087         PPC::isSplatShuffleMask(SVOp, 4) ||
10088         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
10089         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
10090         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
10091         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
10092         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
10093         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
10094         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
10095         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
10096         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
10097         (Subtarget.hasP8Altivec() && (
10098          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
10099          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
10100          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
10101       return Op;
10102     }
10103   }
10104 
10105   // Altivec has a variety of "shuffle immediates" that take two vector inputs
10106   // and produce a fixed permutation.  If any of these match, do not lower to
10107   // VPERM.
10108   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
10109   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10110       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10111       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
10112       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10113       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10114       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10115       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10116       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10117       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10118       (Subtarget.hasP8Altivec() && (
10119        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10120        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
10121        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
10122     return Op;
10123 
10124   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
10125   // perfect shuffle table to emit an optimal matching sequence.
10126   ArrayRef<int> PermMask = SVOp->getMask();
10127 
10128   unsigned PFIndexes[4];
10129   bool isFourElementShuffle = true;
10130   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
10131     unsigned EltNo = 8;   // Start out undef.
10132     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
10133       if (PermMask[i*4+j] < 0)
10134         continue;   // Undef, ignore it.
10135 
10136       unsigned ByteSource = PermMask[i*4+j];
10137       if ((ByteSource & 3) != j) {
10138         isFourElementShuffle = false;
10139         break;
10140       }
10141 
10142       if (EltNo == 8) {
10143         EltNo = ByteSource/4;
10144       } else if (EltNo != ByteSource/4) {
10145         isFourElementShuffle = false;
10146         break;
10147       }
10148     }
10149     PFIndexes[i] = EltNo;
10150   }
10151 
10152   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
10153   // perfect shuffle vector to determine if it is cost effective to do this as
10154   // discrete instructions, or whether we should use a vperm.
10155   // For now, we skip this for little endian until such time as we have a
10156   // little-endian perfect shuffle table.
10157   if (isFourElementShuffle && !isLittleEndian) {
10158     // Compute the index in the perfect shuffle table.
10159     unsigned PFTableIndex =
10160       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
10161 
10162     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10163     unsigned Cost  = (PFEntry >> 30);
10164 
10165     // Determining when to avoid vperm is tricky.  Many things affect the cost
10166     // of vperm, particularly how many times the perm mask needs to be computed.
10167     // For example, if the perm mask can be hoisted out of a loop or is already
10168     // used (perhaps because there are multiple permutes with the same shuffle
10169     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
10170     // the loop requires an extra register.
10171     //
10172     // As a compromise, we only emit discrete instructions if the shuffle can be
10173     // generated in 3 or fewer operations.  When we have loop information
10174     // available, if this block is within a loop, we should avoid using vperm
10175     // for 3-operation perms and use a constant pool load instead.
10176     if (Cost < 3)
10177       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10178   }
10179 
10180   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10181   // vector that will get spilled to the constant pool.
10182   if (V2.isUndef()) V2 = V1;
10183 
10184   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10185   // that it is in input element units, not in bytes.  Convert now.
10186 
10187   // For little endian, the order of the input vectors is reversed, and
10188   // the permutation mask is complemented with respect to 31.  This is
10189   // necessary to produce proper semantics with the big-endian-biased vperm
10190   // instruction.
10191   EVT EltVT = V1.getValueType().getVectorElementType();
10192   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
10193 
10194   SmallVector<SDValue, 16> ResultMask;
10195   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10196     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10197 
10198     for (unsigned j = 0; j != BytesPerElement; ++j)
10199       if (isLittleEndian)
10200         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
10201                                              dl, MVT::i32));
10202       else
10203         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
10204                                              MVT::i32));
10205   }
10206 
10207   ShufflesHandledWithVPERM++;
10208   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10209   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
10210   LLVM_DEBUG(SVOp->dump());
10211   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
10212   LLVM_DEBUG(VPermMask.dump());
10213 
10214   if (isLittleEndian)
10215     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10216                        V2, V1, VPermMask);
10217   else
10218     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10219                        V1, V2, VPermMask);
10220 }
10221 
10222 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10223 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10224 /// information about the intrinsic.
10225 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10226                                  bool &isDot, const PPCSubtarget &Subtarget) {
10227   unsigned IntrinsicID =
10228       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10229   CompareOpc = -1;
10230   isDot = false;
10231   switch (IntrinsicID) {
10232   default:
10233     return false;
10234   // Comparison predicates.
10235   case Intrinsic::ppc_altivec_vcmpbfp_p:
10236     CompareOpc = 966;
10237     isDot = true;
10238     break;
10239   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10240     CompareOpc = 198;
10241     isDot = true;
10242     break;
10243   case Intrinsic::ppc_altivec_vcmpequb_p:
10244     CompareOpc = 6;
10245     isDot = true;
10246     break;
10247   case Intrinsic::ppc_altivec_vcmpequh_p:
10248     CompareOpc = 70;
10249     isDot = true;
10250     break;
10251   case Intrinsic::ppc_altivec_vcmpequw_p:
10252     CompareOpc = 134;
10253     isDot = true;
10254     break;
10255   case Intrinsic::ppc_altivec_vcmpequd_p:
10256     if (Subtarget.hasP8Altivec()) {
10257       CompareOpc = 199;
10258       isDot = true;
10259     } else
10260       return false;
10261     break;
10262   case Intrinsic::ppc_altivec_vcmpneb_p:
10263   case Intrinsic::ppc_altivec_vcmpneh_p:
10264   case Intrinsic::ppc_altivec_vcmpnew_p:
10265   case Intrinsic::ppc_altivec_vcmpnezb_p:
10266   case Intrinsic::ppc_altivec_vcmpnezh_p:
10267   case Intrinsic::ppc_altivec_vcmpnezw_p:
10268     if (Subtarget.hasP9Altivec()) {
10269       switch (IntrinsicID) {
10270       default:
10271         llvm_unreachable("Unknown comparison intrinsic.");
10272       case Intrinsic::ppc_altivec_vcmpneb_p:
10273         CompareOpc = 7;
10274         break;
10275       case Intrinsic::ppc_altivec_vcmpneh_p:
10276         CompareOpc = 71;
10277         break;
10278       case Intrinsic::ppc_altivec_vcmpnew_p:
10279         CompareOpc = 135;
10280         break;
10281       case Intrinsic::ppc_altivec_vcmpnezb_p:
10282         CompareOpc = 263;
10283         break;
10284       case Intrinsic::ppc_altivec_vcmpnezh_p:
10285         CompareOpc = 327;
10286         break;
10287       case Intrinsic::ppc_altivec_vcmpnezw_p:
10288         CompareOpc = 391;
10289         break;
10290       }
10291       isDot = true;
10292     } else
10293       return false;
10294     break;
10295   case Intrinsic::ppc_altivec_vcmpgefp_p:
10296     CompareOpc = 454;
10297     isDot = true;
10298     break;
10299   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10300     CompareOpc = 710;
10301     isDot = true;
10302     break;
10303   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10304     CompareOpc = 774;
10305     isDot = true;
10306     break;
10307   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10308     CompareOpc = 838;
10309     isDot = true;
10310     break;
10311   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10312     CompareOpc = 902;
10313     isDot = true;
10314     break;
10315   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10316     if (Subtarget.hasP8Altivec()) {
10317       CompareOpc = 967;
10318       isDot = true;
10319     } else
10320       return false;
10321     break;
10322   case Intrinsic::ppc_altivec_vcmpgtub_p:
10323     CompareOpc = 518;
10324     isDot = true;
10325     break;
10326   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10327     CompareOpc = 582;
10328     isDot = true;
10329     break;
10330   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10331     CompareOpc = 646;
10332     isDot = true;
10333     break;
10334   case Intrinsic::ppc_altivec_vcmpgtud_p:
10335     if (Subtarget.hasP8Altivec()) {
10336       CompareOpc = 711;
10337       isDot = true;
10338     } else
10339       return false;
10340     break;
10341 
10342   case Intrinsic::ppc_altivec_vcmpequq:
10343   case Intrinsic::ppc_altivec_vcmpgtsq:
10344   case Intrinsic::ppc_altivec_vcmpgtuq:
10345     if (!Subtarget.isISA3_1())
10346       return false;
10347     switch (IntrinsicID) {
10348     default:
10349       llvm_unreachable("Unknown comparison intrinsic.");
10350     case Intrinsic::ppc_altivec_vcmpequq:
10351       CompareOpc = 455;
10352       break;
10353     case Intrinsic::ppc_altivec_vcmpgtsq:
10354       CompareOpc = 903;
10355       break;
10356     case Intrinsic::ppc_altivec_vcmpgtuq:
10357       CompareOpc = 647;
10358       break;
10359     }
10360     break;
10361 
10362   // VSX predicate comparisons use the same infrastructure
10363   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10364   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10365   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10366   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10367   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10368   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10369     if (Subtarget.hasVSX()) {
10370       switch (IntrinsicID) {
10371       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10372         CompareOpc = 99;
10373         break;
10374       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10375         CompareOpc = 115;
10376         break;
10377       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10378         CompareOpc = 107;
10379         break;
10380       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10381         CompareOpc = 67;
10382         break;
10383       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10384         CompareOpc = 83;
10385         break;
10386       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10387         CompareOpc = 75;
10388         break;
10389       }
10390       isDot = true;
10391     } else
10392       return false;
10393     break;
10394 
10395   // Normal Comparisons.
10396   case Intrinsic::ppc_altivec_vcmpbfp:
10397     CompareOpc = 966;
10398     break;
10399   case Intrinsic::ppc_altivec_vcmpeqfp:
10400     CompareOpc = 198;
10401     break;
10402   case Intrinsic::ppc_altivec_vcmpequb:
10403     CompareOpc = 6;
10404     break;
10405   case Intrinsic::ppc_altivec_vcmpequh:
10406     CompareOpc = 70;
10407     break;
10408   case Intrinsic::ppc_altivec_vcmpequw:
10409     CompareOpc = 134;
10410     break;
10411   case Intrinsic::ppc_altivec_vcmpequd:
10412     if (Subtarget.hasP8Altivec())
10413       CompareOpc = 199;
10414     else
10415       return false;
10416     break;
10417   case Intrinsic::ppc_altivec_vcmpneb:
10418   case Intrinsic::ppc_altivec_vcmpneh:
10419   case Intrinsic::ppc_altivec_vcmpnew:
10420   case Intrinsic::ppc_altivec_vcmpnezb:
10421   case Intrinsic::ppc_altivec_vcmpnezh:
10422   case Intrinsic::ppc_altivec_vcmpnezw:
10423     if (Subtarget.hasP9Altivec())
10424       switch (IntrinsicID) {
10425       default:
10426         llvm_unreachable("Unknown comparison intrinsic.");
10427       case Intrinsic::ppc_altivec_vcmpneb:
10428         CompareOpc = 7;
10429         break;
10430       case Intrinsic::ppc_altivec_vcmpneh:
10431         CompareOpc = 71;
10432         break;
10433       case Intrinsic::ppc_altivec_vcmpnew:
10434         CompareOpc = 135;
10435         break;
10436       case Intrinsic::ppc_altivec_vcmpnezb:
10437         CompareOpc = 263;
10438         break;
10439       case Intrinsic::ppc_altivec_vcmpnezh:
10440         CompareOpc = 327;
10441         break;
10442       case Intrinsic::ppc_altivec_vcmpnezw:
10443         CompareOpc = 391;
10444         break;
10445       }
10446     else
10447       return false;
10448     break;
10449   case Intrinsic::ppc_altivec_vcmpgefp:
10450     CompareOpc = 454;
10451     break;
10452   case Intrinsic::ppc_altivec_vcmpgtfp:
10453     CompareOpc = 710;
10454     break;
10455   case Intrinsic::ppc_altivec_vcmpgtsb:
10456     CompareOpc = 774;
10457     break;
10458   case Intrinsic::ppc_altivec_vcmpgtsh:
10459     CompareOpc = 838;
10460     break;
10461   case Intrinsic::ppc_altivec_vcmpgtsw:
10462     CompareOpc = 902;
10463     break;
10464   case Intrinsic::ppc_altivec_vcmpgtsd:
10465     if (Subtarget.hasP8Altivec())
10466       CompareOpc = 967;
10467     else
10468       return false;
10469     break;
10470   case Intrinsic::ppc_altivec_vcmpgtub:
10471     CompareOpc = 518;
10472     break;
10473   case Intrinsic::ppc_altivec_vcmpgtuh:
10474     CompareOpc = 582;
10475     break;
10476   case Intrinsic::ppc_altivec_vcmpgtuw:
10477     CompareOpc = 646;
10478     break;
10479   case Intrinsic::ppc_altivec_vcmpgtud:
10480     if (Subtarget.hasP8Altivec())
10481       CompareOpc = 711;
10482     else
10483       return false;
10484     break;
10485   case Intrinsic::ppc_altivec_vcmpequq_p:
10486   case Intrinsic::ppc_altivec_vcmpgtsq_p:
10487   case Intrinsic::ppc_altivec_vcmpgtuq_p:
10488     if (!Subtarget.isISA3_1())
10489       return false;
10490     switch (IntrinsicID) {
10491     default:
10492       llvm_unreachable("Unknown comparison intrinsic.");
10493     case Intrinsic::ppc_altivec_vcmpequq_p:
10494       CompareOpc = 455;
10495       break;
10496     case Intrinsic::ppc_altivec_vcmpgtsq_p:
10497       CompareOpc = 903;
10498       break;
10499     case Intrinsic::ppc_altivec_vcmpgtuq_p:
10500       CompareOpc = 647;
10501       break;
10502     }
10503     isDot = true;
10504     break;
10505   }
10506   return true;
10507 }
10508 
10509 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10510 /// lower, do it, otherwise return null.
10511 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10512                                                    SelectionDAG &DAG) const {
10513   unsigned IntrinsicID =
10514     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10515 
10516   SDLoc dl(Op);
10517 
10518   switch (IntrinsicID) {
10519   case Intrinsic::thread_pointer:
10520     // Reads the thread pointer register, used for __builtin_thread_pointer.
10521     if (Subtarget.isPPC64())
10522       return DAG.getRegister(PPC::X13, MVT::i64);
10523     return DAG.getRegister(PPC::R2, MVT::i32);
10524 
10525   case Intrinsic::ppc_mma_disassemble_acc:
10526   case Intrinsic::ppc_mma_disassemble_pair: {
10527     int NumVecs = 2;
10528     SDValue WideVec = Op.getOperand(1);
10529     if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
10530       NumVecs = 4;
10531       WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
10532     }
10533     SmallVector<SDValue, 4> RetOps;
10534     for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
10535       SDValue Extract = DAG.getNode(
10536           PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
10537           DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
10538                                                      : VecNo,
10539                           dl, MVT::i64));
10540       RetOps.push_back(Extract);
10541     }
10542     return DAG.getMergeValues(RetOps, dl);
10543   }
10544   }
10545 
10546   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10547   // opcode number of the comparison.
10548   int CompareOpc;
10549   bool isDot;
10550   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10551     return SDValue();    // Don't custom lower most intrinsics.
10552 
10553   // If this is a non-dot comparison, make the VCMP node and we are done.
10554   if (!isDot) {
10555     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10556                               Op.getOperand(1), Op.getOperand(2),
10557                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10558     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10559   }
10560 
10561   // Create the PPCISD altivec 'dot' comparison node.
10562   SDValue Ops[] = {
10563     Op.getOperand(2),  // LHS
10564     Op.getOperand(3),  // RHS
10565     DAG.getConstant(CompareOpc, dl, MVT::i32)
10566   };
10567   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10568   SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
10569 
10570   // Now that we have the comparison, emit a copy from the CR to a GPR.
10571   // This is flagged to the above dot comparison.
10572   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10573                                 DAG.getRegister(PPC::CR6, MVT::i32),
10574                                 CompNode.getValue(1));
10575 
10576   // Unpack the result based on how the target uses it.
10577   unsigned BitNo;   // Bit # of CR6.
10578   bool InvertBit;   // Invert result?
10579   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10580   default:  // Can't happen, don't crash on invalid number though.
10581   case 0:   // Return the value of the EQ bit of CR6.
10582     BitNo = 0; InvertBit = false;
10583     break;
10584   case 1:   // Return the inverted value of the EQ bit of CR6.
10585     BitNo = 0; InvertBit = true;
10586     break;
10587   case 2:   // Return the value of the LT bit of CR6.
10588     BitNo = 2; InvertBit = false;
10589     break;
10590   case 3:   // Return the inverted value of the LT bit of CR6.
10591     BitNo = 2; InvertBit = true;
10592     break;
10593   }
10594 
10595   // Shift the bit into the low position.
10596   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10597                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10598   // Isolate the bit.
10599   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10600                       DAG.getConstant(1, dl, MVT::i32));
10601 
10602   // If we are supposed to, toggle the bit.
10603   if (InvertBit)
10604     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10605                         DAG.getConstant(1, dl, MVT::i32));
10606   return Flags;
10607 }
10608 
10609 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10610                                                SelectionDAG &DAG) const {
10611   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10612   // the beginning of the argument list.
10613   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10614   SDLoc DL(Op);
10615   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10616   case Intrinsic::ppc_cfence: {
10617     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10618     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10619     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10620                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10621                                                   Op.getOperand(ArgStart + 1)),
10622                                       Op.getOperand(0)),
10623                    0);
10624   }
10625   default:
10626     break;
10627   }
10628   return SDValue();
10629 }
10630 
10631 // Lower scalar BSWAP64 to xxbrd.
10632 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10633   SDLoc dl(Op);
10634   // MTVSRDD
10635   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10636                    Op.getOperand(0));
10637   // XXBRD
10638   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10639   // MFVSRD
10640   int VectorIndex = 0;
10641   if (Subtarget.isLittleEndian())
10642     VectorIndex = 1;
10643   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10644                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10645   return Op;
10646 }
10647 
10648 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10649 // compared to a value that is atomically loaded (atomic loads zero-extend).
10650 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10651                                                 SelectionDAG &DAG) const {
10652   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10653          "Expecting an atomic compare-and-swap here.");
10654   SDLoc dl(Op);
10655   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10656   EVT MemVT = AtomicNode->getMemoryVT();
10657   if (MemVT.getSizeInBits() >= 32)
10658     return Op;
10659 
10660   SDValue CmpOp = Op.getOperand(2);
10661   // If this is already correctly zero-extended, leave it alone.
10662   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10663   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10664     return Op;
10665 
10666   // Clear the high bits of the compare operand.
10667   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10668   SDValue NewCmpOp =
10669     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10670                 DAG.getConstant(MaskVal, dl, MVT::i32));
10671 
10672   // Replace the existing compare operand with the properly zero-extended one.
10673   SmallVector<SDValue, 4> Ops;
10674   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10675     Ops.push_back(AtomicNode->getOperand(i));
10676   Ops[2] = NewCmpOp;
10677   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10678   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10679   auto NodeTy =
10680     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10681   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10682 }
10683 
10684 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10685                                                  SelectionDAG &DAG) const {
10686   SDLoc dl(Op);
10687   // Create a stack slot that is 16-byte aligned.
10688   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10689   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10690   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10691   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10692 
10693   // Store the input value into Value#0 of the stack slot.
10694   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10695                                MachinePointerInfo());
10696   // Load it out.
10697   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10698 }
10699 
10700 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10701                                                   SelectionDAG &DAG) const {
10702   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10703          "Should only be called for ISD::INSERT_VECTOR_ELT");
10704 
10705   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10706   // We have legal lowering for constant indices but not for variable ones.
10707   if (!C)
10708     return SDValue();
10709 
10710   EVT VT = Op.getValueType();
10711   SDLoc dl(Op);
10712   SDValue V1 = Op.getOperand(0);
10713   SDValue V2 = Op.getOperand(1);
10714   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10715   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10716     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10717     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10718     unsigned InsertAtElement = C->getZExtValue();
10719     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10720     if (Subtarget.isLittleEndian()) {
10721       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10722     }
10723     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10724                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10725   }
10726   return Op;
10727 }
10728 
10729 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10730                                            SelectionDAG &DAG) const {
10731   SDLoc dl(Op);
10732   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10733   SDValue LoadChain = LN->getChain();
10734   SDValue BasePtr = LN->getBasePtr();
10735   EVT VT = Op.getValueType();
10736 
10737   if (VT != MVT::v256i1 && VT != MVT::v512i1)
10738     return Op;
10739 
10740   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10741   // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
10742   // 2 or 4 vsx registers.
10743   assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
10744          "Type unsupported without MMA");
10745   assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10746          "Type unsupported without paired vector support");
10747   Align Alignment = LN->getAlign();
10748   SmallVector<SDValue, 4> Loads;
10749   SmallVector<SDValue, 4> LoadChains;
10750   unsigned NumVecs = VT.getSizeInBits() / 128;
10751   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10752     SDValue Load =
10753         DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
10754                     LN->getPointerInfo().getWithOffset(Idx * 16),
10755                     commonAlignment(Alignment, Idx * 16),
10756                     LN->getMemOperand()->getFlags(), LN->getAAInfo());
10757     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10758                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10759     Loads.push_back(Load);
10760     LoadChains.push_back(Load.getValue(1));
10761   }
10762   if (Subtarget.isLittleEndian()) {
10763     std::reverse(Loads.begin(), Loads.end());
10764     std::reverse(LoadChains.begin(), LoadChains.end());
10765   }
10766   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10767   SDValue Value =
10768       DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
10769                   dl, VT, Loads);
10770   SDValue RetOps[] = {Value, TF};
10771   return DAG.getMergeValues(RetOps, dl);
10772 }
10773 
10774 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10775                                             SelectionDAG &DAG) const {
10776   SDLoc dl(Op);
10777   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10778   SDValue StoreChain = SN->getChain();
10779   SDValue BasePtr = SN->getBasePtr();
10780   SDValue Value = SN->getValue();
10781   EVT StoreVT = Value.getValueType();
10782 
10783   if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
10784     return Op;
10785 
10786   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10787   // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
10788   // underlying registers individually.
10789   assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
10790          "Type unsupported without MMA");
10791   assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10792          "Type unsupported without paired vector support");
10793   Align Alignment = SN->getAlign();
10794   SmallVector<SDValue, 4> Stores;
10795   unsigned NumVecs = 2;
10796   if (StoreVT == MVT::v512i1) {
10797     Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
10798     NumVecs = 4;
10799   }
10800   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10801     unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
10802     SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
10803                               DAG.getConstant(VecNum, dl, MVT::i64));
10804     SDValue Store =
10805         DAG.getStore(StoreChain, dl, Elt, BasePtr,
10806                      SN->getPointerInfo().getWithOffset(Idx * 16),
10807                      commonAlignment(Alignment, Idx * 16),
10808                      SN->getMemOperand()->getFlags(), SN->getAAInfo());
10809     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10810                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10811     Stores.push_back(Store);
10812   }
10813   SDValue TF = DAG.getTokenFactor(dl, Stores);
10814   return TF;
10815 }
10816 
10817 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10818   SDLoc dl(Op);
10819   if (Op.getValueType() == MVT::v4i32) {
10820     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10821 
10822     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10823     // +16 as shift amt.
10824     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10825     SDValue RHSSwap =   // = vrlw RHS, 16
10826       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10827 
10828     // Shrinkify inputs to v8i16.
10829     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10830     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10831     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10832 
10833     // Low parts multiplied together, generating 32-bit results (we ignore the
10834     // top parts).
10835     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10836                                         LHS, RHS, DAG, dl, MVT::v4i32);
10837 
10838     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10839                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10840     // Shift the high parts up 16 bits.
10841     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10842                               Neg16, DAG, dl);
10843     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10844   } else if (Op.getValueType() == MVT::v16i8) {
10845     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10846     bool isLittleEndian = Subtarget.isLittleEndian();
10847 
10848     // Multiply the even 8-bit parts, producing 16-bit sums.
10849     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10850                                            LHS, RHS, DAG, dl, MVT::v8i16);
10851     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10852 
10853     // Multiply the odd 8-bit parts, producing 16-bit sums.
10854     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10855                                           LHS, RHS, DAG, dl, MVT::v8i16);
10856     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10857 
10858     // Merge the results together.  Because vmuleub and vmuloub are
10859     // instructions with a big-endian bias, we must reverse the
10860     // element numbering and reverse the meaning of "odd" and "even"
10861     // when generating little endian code.
10862     int Ops[16];
10863     for (unsigned i = 0; i != 8; ++i) {
10864       if (isLittleEndian) {
10865         Ops[i*2  ] = 2*i;
10866         Ops[i*2+1] = 2*i+16;
10867       } else {
10868         Ops[i*2  ] = 2*i+1;
10869         Ops[i*2+1] = 2*i+1+16;
10870       }
10871     }
10872     if (isLittleEndian)
10873       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10874     else
10875       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10876   } else {
10877     llvm_unreachable("Unknown mul to lower!");
10878   }
10879 }
10880 
10881 // Custom lowering for fpext vf32 to v2f64
10882 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10883 
10884   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10885          "Should only be called for ISD::FP_EXTEND");
10886 
10887   // FIXME: handle extends from half precision float vectors on P9.
10888   // We only want to custom lower an extend from v2f32 to v2f64.
10889   if (Op.getValueType() != MVT::v2f64 ||
10890       Op.getOperand(0).getValueType() != MVT::v2f32)
10891     return SDValue();
10892 
10893   SDLoc dl(Op);
10894   SDValue Op0 = Op.getOperand(0);
10895 
10896   switch (Op0.getOpcode()) {
10897   default:
10898     return SDValue();
10899   case ISD::EXTRACT_SUBVECTOR: {
10900     assert(Op0.getNumOperands() == 2 &&
10901            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10902            "Node should have 2 operands with second one being a constant!");
10903 
10904     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10905       return SDValue();
10906 
10907     // Custom lower is only done for high or low doubleword.
10908     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10909     if (Idx % 2 != 0)
10910       return SDValue();
10911 
10912     // Since input is v4f32, at this point Idx is either 0 or 2.
10913     // Shift to get the doubleword position we want.
10914     int DWord = Idx >> 1;
10915 
10916     // High and low word positions are different on little endian.
10917     if (Subtarget.isLittleEndian())
10918       DWord ^= 0x1;
10919 
10920     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10921                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10922   }
10923   case ISD::FADD:
10924   case ISD::FMUL:
10925   case ISD::FSUB: {
10926     SDValue NewLoad[2];
10927     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10928       // Ensure both input are loads.
10929       SDValue LdOp = Op0.getOperand(i);
10930       if (LdOp.getOpcode() != ISD::LOAD)
10931         return SDValue();
10932       // Generate new load node.
10933       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10934       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10935       NewLoad[i] = DAG.getMemIntrinsicNode(
10936           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10937           LD->getMemoryVT(), LD->getMemOperand());
10938     }
10939     SDValue NewOp =
10940         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10941                     NewLoad[1], Op0.getNode()->getFlags());
10942     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10943                        DAG.getConstant(0, dl, MVT::i32));
10944   }
10945   case ISD::LOAD: {
10946     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10947     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10948     SDValue NewLd = DAG.getMemIntrinsicNode(
10949         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10950         LD->getMemoryVT(), LD->getMemOperand());
10951     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10952                        DAG.getConstant(0, dl, MVT::i32));
10953   }
10954   }
10955   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10956 }
10957 
10958 /// LowerOperation - Provide custom lowering hooks for some operations.
10959 ///
10960 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10961   switch (Op.getOpcode()) {
10962   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10963   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10964   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10965   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10966   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10967   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10968   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10969   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10970   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10971 
10972   // Variable argument lowering.
10973   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10974   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10975   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10976 
10977   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10978   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10979   case ISD::GET_DYNAMIC_AREA_OFFSET:
10980     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10981 
10982   // Exception handling lowering.
10983   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10984   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10985   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10986 
10987   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10988   case ISD::STORE:              return LowerSTORE(Op, DAG);
10989   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10990   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10991   case ISD::STRICT_FP_TO_UINT:
10992   case ISD::STRICT_FP_TO_SINT:
10993   case ISD::FP_TO_UINT:
10994   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10995   case ISD::STRICT_UINT_TO_FP:
10996   case ISD::STRICT_SINT_TO_FP:
10997   case ISD::UINT_TO_FP:
10998   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10999   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11000 
11001   // Lower 64-bit shifts.
11002   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
11003   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
11004   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
11005 
11006   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
11007   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
11008 
11009   // Vector-related lowering.
11010   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11011   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11012   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11013   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11014   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11015   case ISD::MUL:                return LowerMUL(Op, DAG);
11016   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
11017   case ISD::ROTL:               return LowerROTL(Op, DAG);
11018 
11019   // For counter-based loop handling.
11020   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
11021 
11022   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11023 
11024   // Frame & Return address.
11025   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11026   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11027 
11028   case ISD::INTRINSIC_VOID:
11029     return LowerINTRINSIC_VOID(Op, DAG);
11030   case ISD::BSWAP:
11031     return LowerBSWAP(Op, DAG);
11032   case ISD::ATOMIC_CMP_SWAP:
11033     return LowerATOMIC_CMP_SWAP(Op, DAG);
11034   }
11035 }
11036 
11037 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
11038                                            SmallVectorImpl<SDValue>&Results,
11039                                            SelectionDAG &DAG) const {
11040   SDLoc dl(N);
11041   switch (N->getOpcode()) {
11042   default:
11043     llvm_unreachable("Do not know how to custom type legalize this operation!");
11044   case ISD::READCYCLECOUNTER: {
11045     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11046     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
11047 
11048     Results.push_back(
11049         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
11050     Results.push_back(RTB.getValue(2));
11051     break;
11052   }
11053   case ISD::INTRINSIC_W_CHAIN: {
11054     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
11055         Intrinsic::loop_decrement)
11056       break;
11057 
11058     assert(N->getValueType(0) == MVT::i1 &&
11059            "Unexpected result type for CTR decrement intrinsic");
11060     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11061                                  N->getValueType(0));
11062     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
11063     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
11064                                  N->getOperand(1));
11065 
11066     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
11067     Results.push_back(NewInt.getValue(1));
11068     break;
11069   }
11070   case ISD::VAARG: {
11071     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
11072       return;
11073 
11074     EVT VT = N->getValueType(0);
11075 
11076     if (VT == MVT::i64) {
11077       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
11078 
11079       Results.push_back(NewNode);
11080       Results.push_back(NewNode.getValue(1));
11081     }
11082     return;
11083   }
11084   case ISD::STRICT_FP_TO_SINT:
11085   case ISD::STRICT_FP_TO_UINT:
11086   case ISD::FP_TO_SINT:
11087   case ISD::FP_TO_UINT:
11088     // LowerFP_TO_INT() can only handle f32 and f64.
11089     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
11090         MVT::ppcf128)
11091       return;
11092     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
11093     return;
11094   case ISD::TRUNCATE: {
11095     if (!N->getValueType(0).isVector())
11096       return;
11097     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
11098     if (Lowered)
11099       Results.push_back(Lowered);
11100     return;
11101   }
11102   case ISD::FSHL:
11103   case ISD::FSHR:
11104     // Don't handle funnel shifts here.
11105     return;
11106   case ISD::BITCAST:
11107     // Don't handle bitcast here.
11108     return;
11109   case ISD::FP_EXTEND:
11110     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
11111     if (Lowered)
11112       Results.push_back(Lowered);
11113     return;
11114   }
11115 }
11116 
11117 //===----------------------------------------------------------------------===//
11118 //  Other Lowering Code
11119 //===----------------------------------------------------------------------===//
11120 
11121 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
11122   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11123   Function *Func = Intrinsic::getDeclaration(M, Id);
11124   return Builder.CreateCall(Func, {});
11125 }
11126 
11127 // The mappings for emitLeading/TrailingFence is taken from
11128 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11129 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11130                                                  Instruction *Inst,
11131                                                  AtomicOrdering Ord) const {
11132   if (Ord == AtomicOrdering::SequentiallyConsistent)
11133     return callIntrinsic(Builder, Intrinsic::ppc_sync);
11134   if (isReleaseOrStronger(Ord))
11135     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11136   return nullptr;
11137 }
11138 
11139 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11140                                                   Instruction *Inst,
11141                                                   AtomicOrdering Ord) const {
11142   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11143     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11144     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11145     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11146     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11147       return Builder.CreateCall(
11148           Intrinsic::getDeclaration(
11149               Builder.GetInsertBlock()->getParent()->getParent(),
11150               Intrinsic::ppc_cfence, {Inst->getType()}),
11151           {Inst});
11152     // FIXME: Can use isync for rmw operation.
11153     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11154   }
11155   return nullptr;
11156 }
11157 
11158 MachineBasicBlock *
11159 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11160                                     unsigned AtomicSize,
11161                                     unsigned BinOpcode,
11162                                     unsigned CmpOpcode,
11163                                     unsigned CmpPred) const {
11164   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11165   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11166 
11167   auto LoadMnemonic = PPC::LDARX;
11168   auto StoreMnemonic = PPC::STDCX;
11169   switch (AtomicSize) {
11170   default:
11171     llvm_unreachable("Unexpected size of atomic entity");
11172   case 1:
11173     LoadMnemonic = PPC::LBARX;
11174     StoreMnemonic = PPC::STBCX;
11175     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11176     break;
11177   case 2:
11178     LoadMnemonic = PPC::LHARX;
11179     StoreMnemonic = PPC::STHCX;
11180     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11181     break;
11182   case 4:
11183     LoadMnemonic = PPC::LWARX;
11184     StoreMnemonic = PPC::STWCX;
11185     break;
11186   case 8:
11187     LoadMnemonic = PPC::LDARX;
11188     StoreMnemonic = PPC::STDCX;
11189     break;
11190   }
11191 
11192   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11193   MachineFunction *F = BB->getParent();
11194   MachineFunction::iterator It = ++BB->getIterator();
11195 
11196   Register dest = MI.getOperand(0).getReg();
11197   Register ptrA = MI.getOperand(1).getReg();
11198   Register ptrB = MI.getOperand(2).getReg();
11199   Register incr = MI.getOperand(3).getReg();
11200   DebugLoc dl = MI.getDebugLoc();
11201 
11202   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11203   MachineBasicBlock *loop2MBB =
11204     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11205   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11206   F->insert(It, loopMBB);
11207   if (CmpOpcode)
11208     F->insert(It, loop2MBB);
11209   F->insert(It, exitMBB);
11210   exitMBB->splice(exitMBB->begin(), BB,
11211                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11212   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11213 
11214   MachineRegisterInfo &RegInfo = F->getRegInfo();
11215   Register TmpReg = (!BinOpcode) ? incr :
11216     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11217                                            : &PPC::GPRCRegClass);
11218 
11219   //  thisMBB:
11220   //   ...
11221   //   fallthrough --> loopMBB
11222   BB->addSuccessor(loopMBB);
11223 
11224   //  loopMBB:
11225   //   l[wd]arx dest, ptr
11226   //   add r0, dest, incr
11227   //   st[wd]cx. r0, ptr
11228   //   bne- loopMBB
11229   //   fallthrough --> exitMBB
11230 
11231   // For max/min...
11232   //  loopMBB:
11233   //   l[wd]arx dest, ptr
11234   //   cmpl?[wd] incr, dest
11235   //   bgt exitMBB
11236   //  loop2MBB:
11237   //   st[wd]cx. dest, ptr
11238   //   bne- loopMBB
11239   //   fallthrough --> exitMBB
11240 
11241   BB = loopMBB;
11242   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11243     .addReg(ptrA).addReg(ptrB);
11244   if (BinOpcode)
11245     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11246   if (CmpOpcode) {
11247     // Signed comparisons of byte or halfword values must be sign-extended.
11248     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11249       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11250       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11251               ExtReg).addReg(dest);
11252       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11253         .addReg(incr).addReg(ExtReg);
11254     } else
11255       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11256         .addReg(incr).addReg(dest);
11257 
11258     BuildMI(BB, dl, TII->get(PPC::BCC))
11259       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11260     BB->addSuccessor(loop2MBB);
11261     BB->addSuccessor(exitMBB);
11262     BB = loop2MBB;
11263   }
11264   BuildMI(BB, dl, TII->get(StoreMnemonic))
11265     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11266   BuildMI(BB, dl, TII->get(PPC::BCC))
11267     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11268   BB->addSuccessor(loopMBB);
11269   BB->addSuccessor(exitMBB);
11270 
11271   //  exitMBB:
11272   //   ...
11273   BB = exitMBB;
11274   return BB;
11275 }
11276 
11277 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11278     MachineInstr &MI, MachineBasicBlock *BB,
11279     bool is8bit, // operation
11280     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11281   // If we support part-word atomic mnemonics, just use them
11282   if (Subtarget.hasPartwordAtomics())
11283     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11284                             CmpPred);
11285 
11286   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11287   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11288   // In 64 bit mode we have to use 64 bits for addresses, even though the
11289   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11290   // registers without caring whether they're 32 or 64, but here we're
11291   // doing actual arithmetic on the addresses.
11292   bool is64bit = Subtarget.isPPC64();
11293   bool isLittleEndian = Subtarget.isLittleEndian();
11294   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11295 
11296   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11297   MachineFunction *F = BB->getParent();
11298   MachineFunction::iterator It = ++BB->getIterator();
11299 
11300   Register dest = MI.getOperand(0).getReg();
11301   Register ptrA = MI.getOperand(1).getReg();
11302   Register ptrB = MI.getOperand(2).getReg();
11303   Register incr = MI.getOperand(3).getReg();
11304   DebugLoc dl = MI.getDebugLoc();
11305 
11306   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11307   MachineBasicBlock *loop2MBB =
11308       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11309   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11310   F->insert(It, loopMBB);
11311   if (CmpOpcode)
11312     F->insert(It, loop2MBB);
11313   F->insert(It, exitMBB);
11314   exitMBB->splice(exitMBB->begin(), BB,
11315                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11316   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11317 
11318   MachineRegisterInfo &RegInfo = F->getRegInfo();
11319   const TargetRegisterClass *RC =
11320       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11321   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11322 
11323   Register PtrReg = RegInfo.createVirtualRegister(RC);
11324   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11325   Register ShiftReg =
11326       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11327   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11328   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11329   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11330   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11331   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11332   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11333   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11334   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11335   Register Ptr1Reg;
11336   Register TmpReg =
11337       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11338 
11339   //  thisMBB:
11340   //   ...
11341   //   fallthrough --> loopMBB
11342   BB->addSuccessor(loopMBB);
11343 
11344   // The 4-byte load must be aligned, while a char or short may be
11345   // anywhere in the word.  Hence all this nasty bookkeeping code.
11346   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11347   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11348   //   xori shift, shift1, 24 [16]
11349   //   rlwinm ptr, ptr1, 0, 0, 29
11350   //   slw incr2, incr, shift
11351   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11352   //   slw mask, mask2, shift
11353   //  loopMBB:
11354   //   lwarx tmpDest, ptr
11355   //   add tmp, tmpDest, incr2
11356   //   andc tmp2, tmpDest, mask
11357   //   and tmp3, tmp, mask
11358   //   or tmp4, tmp3, tmp2
11359   //   stwcx. tmp4, ptr
11360   //   bne- loopMBB
11361   //   fallthrough --> exitMBB
11362   //   srw dest, tmpDest, shift
11363   if (ptrA != ZeroReg) {
11364     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11365     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11366         .addReg(ptrA)
11367         .addReg(ptrB);
11368   } else {
11369     Ptr1Reg = ptrB;
11370   }
11371   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11372   // mode.
11373   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11374       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11375       .addImm(3)
11376       .addImm(27)
11377       .addImm(is8bit ? 28 : 27);
11378   if (!isLittleEndian)
11379     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11380         .addReg(Shift1Reg)
11381         .addImm(is8bit ? 24 : 16);
11382   if (is64bit)
11383     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11384         .addReg(Ptr1Reg)
11385         .addImm(0)
11386         .addImm(61);
11387   else
11388     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11389         .addReg(Ptr1Reg)
11390         .addImm(0)
11391         .addImm(0)
11392         .addImm(29);
11393   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11394   if (is8bit)
11395     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11396   else {
11397     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11398     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11399         .addReg(Mask3Reg)
11400         .addImm(65535);
11401   }
11402   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11403       .addReg(Mask2Reg)
11404       .addReg(ShiftReg);
11405 
11406   BB = loopMBB;
11407   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11408       .addReg(ZeroReg)
11409       .addReg(PtrReg);
11410   if (BinOpcode)
11411     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11412         .addReg(Incr2Reg)
11413         .addReg(TmpDestReg);
11414   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11415       .addReg(TmpDestReg)
11416       .addReg(MaskReg);
11417   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11418   if (CmpOpcode) {
11419     // For unsigned comparisons, we can directly compare the shifted values.
11420     // For signed comparisons we shift and sign extend.
11421     Register SReg = RegInfo.createVirtualRegister(GPRC);
11422     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11423         .addReg(TmpDestReg)
11424         .addReg(MaskReg);
11425     unsigned ValueReg = SReg;
11426     unsigned CmpReg = Incr2Reg;
11427     if (CmpOpcode == PPC::CMPW) {
11428       ValueReg = RegInfo.createVirtualRegister(GPRC);
11429       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11430           .addReg(SReg)
11431           .addReg(ShiftReg);
11432       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11433       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11434           .addReg(ValueReg);
11435       ValueReg = ValueSReg;
11436       CmpReg = incr;
11437     }
11438     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11439         .addReg(CmpReg)
11440         .addReg(ValueReg);
11441     BuildMI(BB, dl, TII->get(PPC::BCC))
11442         .addImm(CmpPred)
11443         .addReg(PPC::CR0)
11444         .addMBB(exitMBB);
11445     BB->addSuccessor(loop2MBB);
11446     BB->addSuccessor(exitMBB);
11447     BB = loop2MBB;
11448   }
11449   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11450   BuildMI(BB, dl, TII->get(PPC::STWCX))
11451       .addReg(Tmp4Reg)
11452       .addReg(ZeroReg)
11453       .addReg(PtrReg);
11454   BuildMI(BB, dl, TII->get(PPC::BCC))
11455       .addImm(PPC::PRED_NE)
11456       .addReg(PPC::CR0)
11457       .addMBB(loopMBB);
11458   BB->addSuccessor(loopMBB);
11459   BB->addSuccessor(exitMBB);
11460 
11461   //  exitMBB:
11462   //   ...
11463   BB = exitMBB;
11464   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11465       .addReg(TmpDestReg)
11466       .addReg(ShiftReg);
11467   return BB;
11468 }
11469 
11470 llvm::MachineBasicBlock *
11471 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11472                                     MachineBasicBlock *MBB) const {
11473   DebugLoc DL = MI.getDebugLoc();
11474   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11475   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11476 
11477   MachineFunction *MF = MBB->getParent();
11478   MachineRegisterInfo &MRI = MF->getRegInfo();
11479 
11480   const BasicBlock *BB = MBB->getBasicBlock();
11481   MachineFunction::iterator I = ++MBB->getIterator();
11482 
11483   Register DstReg = MI.getOperand(0).getReg();
11484   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11485   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11486   Register mainDstReg = MRI.createVirtualRegister(RC);
11487   Register restoreDstReg = MRI.createVirtualRegister(RC);
11488 
11489   MVT PVT = getPointerTy(MF->getDataLayout());
11490   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11491          "Invalid Pointer Size!");
11492   // For v = setjmp(buf), we generate
11493   //
11494   // thisMBB:
11495   //  SjLjSetup mainMBB
11496   //  bl mainMBB
11497   //  v_restore = 1
11498   //  b sinkMBB
11499   //
11500   // mainMBB:
11501   //  buf[LabelOffset] = LR
11502   //  v_main = 0
11503   //
11504   // sinkMBB:
11505   //  v = phi(main, restore)
11506   //
11507 
11508   MachineBasicBlock *thisMBB = MBB;
11509   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11510   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11511   MF->insert(I, mainMBB);
11512   MF->insert(I, sinkMBB);
11513 
11514   MachineInstrBuilder MIB;
11515 
11516   // Transfer the remainder of BB and its successor edges to sinkMBB.
11517   sinkMBB->splice(sinkMBB->begin(), MBB,
11518                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11519   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11520 
11521   // Note that the structure of the jmp_buf used here is not compatible
11522   // with that used by libc, and is not designed to be. Specifically, it
11523   // stores only those 'reserved' registers that LLVM does not otherwise
11524   // understand how to spill. Also, by convention, by the time this
11525   // intrinsic is called, Clang has already stored the frame address in the
11526   // first slot of the buffer and stack address in the third. Following the
11527   // X86 target code, we'll store the jump address in the second slot. We also
11528   // need to save the TOC pointer (R2) to handle jumps between shared
11529   // libraries, and that will be stored in the fourth slot. The thread
11530   // identifier (R13) is not affected.
11531 
11532   // thisMBB:
11533   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11534   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11535   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11536 
11537   // Prepare IP either in reg.
11538   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11539   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11540   Register BufReg = MI.getOperand(1).getReg();
11541 
11542   if (Subtarget.is64BitELFABI()) {
11543     setUsesTOCBasePtr(*MBB->getParent());
11544     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11545               .addReg(PPC::X2)
11546               .addImm(TOCOffset)
11547               .addReg(BufReg)
11548               .cloneMemRefs(MI);
11549   }
11550 
11551   // Naked functions never have a base pointer, and so we use r1. For all
11552   // other functions, this decision must be delayed until during PEI.
11553   unsigned BaseReg;
11554   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11555     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11556   else
11557     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11558 
11559   MIB = BuildMI(*thisMBB, MI, DL,
11560                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11561             .addReg(BaseReg)
11562             .addImm(BPOffset)
11563             .addReg(BufReg)
11564             .cloneMemRefs(MI);
11565 
11566   // Setup
11567   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11568   MIB.addRegMask(TRI->getNoPreservedMask());
11569 
11570   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11571 
11572   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11573           .addMBB(mainMBB);
11574   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11575 
11576   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11577   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11578 
11579   // mainMBB:
11580   //  mainDstReg = 0
11581   MIB =
11582       BuildMI(mainMBB, DL,
11583               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11584 
11585   // Store IP
11586   if (Subtarget.isPPC64()) {
11587     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11588             .addReg(LabelReg)
11589             .addImm(LabelOffset)
11590             .addReg(BufReg);
11591   } else {
11592     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11593             .addReg(LabelReg)
11594             .addImm(LabelOffset)
11595             .addReg(BufReg);
11596   }
11597   MIB.cloneMemRefs(MI);
11598 
11599   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11600   mainMBB->addSuccessor(sinkMBB);
11601 
11602   // sinkMBB:
11603   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11604           TII->get(PPC::PHI), DstReg)
11605     .addReg(mainDstReg).addMBB(mainMBB)
11606     .addReg(restoreDstReg).addMBB(thisMBB);
11607 
11608   MI.eraseFromParent();
11609   return sinkMBB;
11610 }
11611 
11612 MachineBasicBlock *
11613 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11614                                      MachineBasicBlock *MBB) const {
11615   DebugLoc DL = MI.getDebugLoc();
11616   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11617 
11618   MachineFunction *MF = MBB->getParent();
11619   MachineRegisterInfo &MRI = MF->getRegInfo();
11620 
11621   MVT PVT = getPointerTy(MF->getDataLayout());
11622   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11623          "Invalid Pointer Size!");
11624 
11625   const TargetRegisterClass *RC =
11626     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11627   Register Tmp = MRI.createVirtualRegister(RC);
11628   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11629   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11630   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11631   unsigned BP =
11632       (PVT == MVT::i64)
11633           ? PPC::X30
11634           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11635                                                               : PPC::R30);
11636 
11637   MachineInstrBuilder MIB;
11638 
11639   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11640   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11641   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11642   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11643 
11644   Register BufReg = MI.getOperand(0).getReg();
11645 
11646   // Reload FP (the jumped-to function may not have had a
11647   // frame pointer, and if so, then its r31 will be restored
11648   // as necessary).
11649   if (PVT == MVT::i64) {
11650     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11651             .addImm(0)
11652             .addReg(BufReg);
11653   } else {
11654     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11655             .addImm(0)
11656             .addReg(BufReg);
11657   }
11658   MIB.cloneMemRefs(MI);
11659 
11660   // Reload IP
11661   if (PVT == MVT::i64) {
11662     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11663             .addImm(LabelOffset)
11664             .addReg(BufReg);
11665   } else {
11666     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11667             .addImm(LabelOffset)
11668             .addReg(BufReg);
11669   }
11670   MIB.cloneMemRefs(MI);
11671 
11672   // Reload SP
11673   if (PVT == MVT::i64) {
11674     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11675             .addImm(SPOffset)
11676             .addReg(BufReg);
11677   } else {
11678     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11679             .addImm(SPOffset)
11680             .addReg(BufReg);
11681   }
11682   MIB.cloneMemRefs(MI);
11683 
11684   // Reload BP
11685   if (PVT == MVT::i64) {
11686     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11687             .addImm(BPOffset)
11688             .addReg(BufReg);
11689   } else {
11690     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11691             .addImm(BPOffset)
11692             .addReg(BufReg);
11693   }
11694   MIB.cloneMemRefs(MI);
11695 
11696   // Reload TOC
11697   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11698     setUsesTOCBasePtr(*MBB->getParent());
11699     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11700               .addImm(TOCOffset)
11701               .addReg(BufReg)
11702               .cloneMemRefs(MI);
11703   }
11704 
11705   // Jump
11706   BuildMI(*MBB, MI, DL,
11707           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11708   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11709 
11710   MI.eraseFromParent();
11711   return MBB;
11712 }
11713 
11714 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11715   // If the function specifically requests inline stack probes, emit them.
11716   if (MF.getFunction().hasFnAttribute("probe-stack"))
11717     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11718            "inline-asm";
11719   return false;
11720 }
11721 
11722 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11723   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11724   unsigned StackAlign = TFI->getStackAlignment();
11725   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11726          "Unexpected stack alignment");
11727   // The default stack probe size is 4096 if the function has no
11728   // stack-probe-size attribute.
11729   unsigned StackProbeSize = 4096;
11730   const Function &Fn = MF.getFunction();
11731   if (Fn.hasFnAttribute("stack-probe-size"))
11732     Fn.getFnAttribute("stack-probe-size")
11733         .getValueAsString()
11734         .getAsInteger(0, StackProbeSize);
11735   // Round down to the stack alignment.
11736   StackProbeSize &= ~(StackAlign - 1);
11737   return StackProbeSize ? StackProbeSize : StackAlign;
11738 }
11739 
11740 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11741 // into three phases. In the first phase, it uses pseudo instruction
11742 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11743 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11744 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11745 // MaxCallFrameSize so that it can calculate correct data area pointer.
11746 MachineBasicBlock *
11747 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11748                                     MachineBasicBlock *MBB) const {
11749   const bool isPPC64 = Subtarget.isPPC64();
11750   MachineFunction *MF = MBB->getParent();
11751   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11752   DebugLoc DL = MI.getDebugLoc();
11753   const unsigned ProbeSize = getStackProbeSize(*MF);
11754   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11755   MachineRegisterInfo &MRI = MF->getRegInfo();
11756   // The CFG of probing stack looks as
11757   //         +-----+
11758   //         | MBB |
11759   //         +--+--+
11760   //            |
11761   //       +----v----+
11762   //  +--->+ TestMBB +---+
11763   //  |    +----+----+   |
11764   //  |         |        |
11765   //  |   +-----v----+   |
11766   //  +---+ BlockMBB |   |
11767   //      +----------+   |
11768   //                     |
11769   //       +---------+   |
11770   //       | TailMBB +<--+
11771   //       +---------+
11772   // In MBB, calculate previous frame pointer and final stack pointer.
11773   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11774   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11775   // TailMBB is spliced via \p MI.
11776   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11777   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11778   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11779 
11780   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11781   MF->insert(MBBIter, TestMBB);
11782   MF->insert(MBBIter, BlockMBB);
11783   MF->insert(MBBIter, TailMBB);
11784 
11785   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11786   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11787 
11788   Register DstReg = MI.getOperand(0).getReg();
11789   Register NegSizeReg = MI.getOperand(1).getReg();
11790   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11791   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11792   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11793   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11794 
11795   // Since value of NegSizeReg might be realigned in prologepilog, insert a
11796   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
11797   // NegSize.
11798   unsigned ProbeOpc;
11799   if (!MRI.hasOneNonDBGUse(NegSizeReg))
11800     ProbeOpc =
11801         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
11802   else
11803     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
11804     // and NegSizeReg will be allocated in the same phyreg to avoid
11805     // redundant copy when NegSizeReg has only one use which is current MI and
11806     // will be replaced by PREPARE_PROBED_ALLOCA then.
11807     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
11808                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
11809   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
11810       .addDef(ActualNegSizeReg)
11811       .addReg(NegSizeReg)
11812       .add(MI.getOperand(2))
11813       .add(MI.getOperand(3));
11814 
11815   // Calculate final stack pointer, which equals to SP + ActualNegSize.
11816   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
11817           FinalStackPtr)
11818       .addReg(SPReg)
11819       .addReg(ActualNegSizeReg);
11820 
11821   // Materialize a scratch register for update.
11822   int64_t NegProbeSize = -(int64_t)ProbeSize;
11823   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
11824   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11825   if (!isInt<16>(NegProbeSize)) {
11826     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11827     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
11828         .addImm(NegProbeSize >> 16);
11829     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
11830             ScratchReg)
11831         .addReg(TempReg)
11832         .addImm(NegProbeSize & 0xFFFF);
11833   } else
11834     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
11835         .addImm(NegProbeSize);
11836 
11837   {
11838     // Probing leading residual part.
11839     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11840     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
11841         .addReg(ActualNegSizeReg)
11842         .addReg(ScratchReg);
11843     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11844     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
11845         .addReg(Div)
11846         .addReg(ScratchReg);
11847     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11848     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
11849         .addReg(Mul)
11850         .addReg(ActualNegSizeReg);
11851     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11852         .addReg(FramePointer)
11853         .addReg(SPReg)
11854         .addReg(NegMod);
11855   }
11856 
11857   {
11858     // Remaining part should be multiple of ProbeSize.
11859     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
11860     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
11861         .addReg(SPReg)
11862         .addReg(FinalStackPtr);
11863     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
11864         .addImm(PPC::PRED_EQ)
11865         .addReg(CmpResult)
11866         .addMBB(TailMBB);
11867     TestMBB->addSuccessor(BlockMBB);
11868     TestMBB->addSuccessor(TailMBB);
11869   }
11870 
11871   {
11872     // Touch the block.
11873     // |P...|P...|P...
11874     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11875         .addReg(FramePointer)
11876         .addReg(SPReg)
11877         .addReg(ScratchReg);
11878     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
11879     BlockMBB->addSuccessor(TestMBB);
11880   }
11881 
11882   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
11883   // DYNAREAOFFSET pseudo instruction to get the future result.
11884   Register MaxCallFrameSizeReg =
11885       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11886   BuildMI(TailMBB, DL,
11887           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
11888           MaxCallFrameSizeReg)
11889       .add(MI.getOperand(2))
11890       .add(MI.getOperand(3));
11891   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
11892       .addReg(SPReg)
11893       .addReg(MaxCallFrameSizeReg);
11894 
11895   // Splice instructions after MI to TailMBB.
11896   TailMBB->splice(TailMBB->end(), MBB,
11897                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11898   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
11899   MBB->addSuccessor(TestMBB);
11900 
11901   // Delete the pseudo instruction.
11902   MI.eraseFromParent();
11903 
11904   ++NumDynamicAllocaProbed;
11905   return TailMBB;
11906 }
11907 
11908 MachineBasicBlock *
11909 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11910                                                MachineBasicBlock *BB) const {
11911   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11912       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11913     if (Subtarget.is64BitELFABI() &&
11914         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11915         !Subtarget.isUsingPCRelativeCalls()) {
11916       // Call lowering should have added an r2 operand to indicate a dependence
11917       // on the TOC base pointer value. It can't however, because there is no
11918       // way to mark the dependence as implicit there, and so the stackmap code
11919       // will confuse it with a regular operand. Instead, add the dependence
11920       // here.
11921       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11922     }
11923 
11924     return emitPatchPoint(MI, BB);
11925   }
11926 
11927   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11928       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11929     return emitEHSjLjSetJmp(MI, BB);
11930   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11931              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11932     return emitEHSjLjLongJmp(MI, BB);
11933   }
11934 
11935   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11936 
11937   // To "insert" these instructions we actually have to insert their
11938   // control-flow patterns.
11939   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11940   MachineFunction::iterator It = ++BB->getIterator();
11941 
11942   MachineFunction *F = BB->getParent();
11943 
11944   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11945       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11946       MI.getOpcode() == PPC::SELECT_I8) {
11947     SmallVector<MachineOperand, 2> Cond;
11948     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11949         MI.getOpcode() == PPC::SELECT_CC_I8)
11950       Cond.push_back(MI.getOperand(4));
11951     else
11952       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11953     Cond.push_back(MI.getOperand(1));
11954 
11955     DebugLoc dl = MI.getDebugLoc();
11956     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11957                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11958   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11959              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11960              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11961              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11962              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11963              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11964              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11965              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11966              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11967              MI.getOpcode() == PPC::SELECT_F4 ||
11968              MI.getOpcode() == PPC::SELECT_F8 ||
11969              MI.getOpcode() == PPC::SELECT_F16 ||
11970              MI.getOpcode() == PPC::SELECT_SPE ||
11971              MI.getOpcode() == PPC::SELECT_SPE4 ||
11972              MI.getOpcode() == PPC::SELECT_VRRC ||
11973              MI.getOpcode() == PPC::SELECT_VSFRC ||
11974              MI.getOpcode() == PPC::SELECT_VSSRC ||
11975              MI.getOpcode() == PPC::SELECT_VSRC) {
11976     // The incoming instruction knows the destination vreg to set, the
11977     // condition code register to branch on, the true/false values to
11978     // select between, and a branch opcode to use.
11979 
11980     //  thisMBB:
11981     //  ...
11982     //   TrueVal = ...
11983     //   cmpTY ccX, r1, r2
11984     //   bCC copy1MBB
11985     //   fallthrough --> copy0MBB
11986     MachineBasicBlock *thisMBB = BB;
11987     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11988     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11989     DebugLoc dl = MI.getDebugLoc();
11990     F->insert(It, copy0MBB);
11991     F->insert(It, sinkMBB);
11992 
11993     // Transfer the remainder of BB and its successor edges to sinkMBB.
11994     sinkMBB->splice(sinkMBB->begin(), BB,
11995                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11996     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11997 
11998     // Next, add the true and fallthrough blocks as its successors.
11999     BB->addSuccessor(copy0MBB);
12000     BB->addSuccessor(sinkMBB);
12001 
12002     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
12003         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
12004         MI.getOpcode() == PPC::SELECT_F16 ||
12005         MI.getOpcode() == PPC::SELECT_SPE4 ||
12006         MI.getOpcode() == PPC::SELECT_SPE ||
12007         MI.getOpcode() == PPC::SELECT_VRRC ||
12008         MI.getOpcode() == PPC::SELECT_VSFRC ||
12009         MI.getOpcode() == PPC::SELECT_VSSRC ||
12010         MI.getOpcode() == PPC::SELECT_VSRC) {
12011       BuildMI(BB, dl, TII->get(PPC::BC))
12012           .addReg(MI.getOperand(1).getReg())
12013           .addMBB(sinkMBB);
12014     } else {
12015       unsigned SelectPred = MI.getOperand(4).getImm();
12016       BuildMI(BB, dl, TII->get(PPC::BCC))
12017           .addImm(SelectPred)
12018           .addReg(MI.getOperand(1).getReg())
12019           .addMBB(sinkMBB);
12020     }
12021 
12022     //  copy0MBB:
12023     //   %FalseValue = ...
12024     //   # fallthrough to sinkMBB
12025     BB = copy0MBB;
12026 
12027     // Update machine-CFG edges
12028     BB->addSuccessor(sinkMBB);
12029 
12030     //  sinkMBB:
12031     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12032     //  ...
12033     BB = sinkMBB;
12034     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
12035         .addReg(MI.getOperand(3).getReg())
12036         .addMBB(copy0MBB)
12037         .addReg(MI.getOperand(2).getReg())
12038         .addMBB(thisMBB);
12039   } else if (MI.getOpcode() == PPC::ReadTB) {
12040     // To read the 64-bit time-base register on a 32-bit target, we read the
12041     // two halves. Should the counter have wrapped while it was being read, we
12042     // need to try again.
12043     // ...
12044     // readLoop:
12045     // mfspr Rx,TBU # load from TBU
12046     // mfspr Ry,TB  # load from TB
12047     // mfspr Rz,TBU # load from TBU
12048     // cmpw crX,Rx,Rz # check if 'old'='new'
12049     // bne readLoop   # branch if they're not equal
12050     // ...
12051 
12052     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
12053     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12054     DebugLoc dl = MI.getDebugLoc();
12055     F->insert(It, readMBB);
12056     F->insert(It, sinkMBB);
12057 
12058     // Transfer the remainder of BB and its successor edges to sinkMBB.
12059     sinkMBB->splice(sinkMBB->begin(), BB,
12060                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12061     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12062 
12063     BB->addSuccessor(readMBB);
12064     BB = readMBB;
12065 
12066     MachineRegisterInfo &RegInfo = F->getRegInfo();
12067     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
12068     Register LoReg = MI.getOperand(0).getReg();
12069     Register HiReg = MI.getOperand(1).getReg();
12070 
12071     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
12072     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
12073     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
12074 
12075     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12076 
12077     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
12078         .addReg(HiReg)
12079         .addReg(ReadAgainReg);
12080     BuildMI(BB, dl, TII->get(PPC::BCC))
12081         .addImm(PPC::PRED_NE)
12082         .addReg(CmpReg)
12083         .addMBB(readMBB);
12084 
12085     BB->addSuccessor(readMBB);
12086     BB->addSuccessor(sinkMBB);
12087   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
12088     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
12089   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
12090     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
12091   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
12092     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
12093   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
12094     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
12095 
12096   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
12097     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
12098   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
12099     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
12100   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
12101     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
12102   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
12103     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
12104 
12105   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
12106     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
12107   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
12108     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
12109   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
12110     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
12111   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
12112     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
12113 
12114   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
12115     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
12116   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
12117     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
12118   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
12119     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
12120   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
12121     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
12122 
12123   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
12124     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
12125   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
12126     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
12127   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
12128     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
12129   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
12130     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
12131 
12132   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
12133     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
12134   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
12135     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
12136   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
12137     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
12138   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
12139     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
12140 
12141   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
12142     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
12143   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
12144     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
12145   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
12146     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
12147   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
12148     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
12149 
12150   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
12151     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
12152   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
12153     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
12154   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
12155     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
12156   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
12157     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
12158 
12159   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
12160     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
12161   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
12162     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
12163   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
12164     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
12165   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
12166     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
12167 
12168   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
12169     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
12170   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
12171     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
12172   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
12173     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
12174   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
12175     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
12176 
12177   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
12178     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
12179   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
12180     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
12181   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
12182     BB = EmitAtomicBinary(MI, BB, 4, 0);
12183   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
12184     BB = EmitAtomicBinary(MI, BB, 8, 0);
12185   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
12186            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
12187            (Subtarget.hasPartwordAtomics() &&
12188             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
12189            (Subtarget.hasPartwordAtomics() &&
12190             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
12191     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
12192 
12193     auto LoadMnemonic = PPC::LDARX;
12194     auto StoreMnemonic = PPC::STDCX;
12195     switch (MI.getOpcode()) {
12196     default:
12197       llvm_unreachable("Compare and swap of unknown size");
12198     case PPC::ATOMIC_CMP_SWAP_I8:
12199       LoadMnemonic = PPC::LBARX;
12200       StoreMnemonic = PPC::STBCX;
12201       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12202       break;
12203     case PPC::ATOMIC_CMP_SWAP_I16:
12204       LoadMnemonic = PPC::LHARX;
12205       StoreMnemonic = PPC::STHCX;
12206       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12207       break;
12208     case PPC::ATOMIC_CMP_SWAP_I32:
12209       LoadMnemonic = PPC::LWARX;
12210       StoreMnemonic = PPC::STWCX;
12211       break;
12212     case PPC::ATOMIC_CMP_SWAP_I64:
12213       LoadMnemonic = PPC::LDARX;
12214       StoreMnemonic = PPC::STDCX;
12215       break;
12216     }
12217     Register dest = MI.getOperand(0).getReg();
12218     Register ptrA = MI.getOperand(1).getReg();
12219     Register ptrB = MI.getOperand(2).getReg();
12220     Register oldval = MI.getOperand(3).getReg();
12221     Register newval = MI.getOperand(4).getReg();
12222     DebugLoc dl = MI.getDebugLoc();
12223 
12224     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12225     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12226     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12227     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12228     F->insert(It, loop1MBB);
12229     F->insert(It, loop2MBB);
12230     F->insert(It, midMBB);
12231     F->insert(It, exitMBB);
12232     exitMBB->splice(exitMBB->begin(), BB,
12233                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12234     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12235 
12236     //  thisMBB:
12237     //   ...
12238     //   fallthrough --> loopMBB
12239     BB->addSuccessor(loop1MBB);
12240 
12241     // loop1MBB:
12242     //   l[bhwd]arx dest, ptr
12243     //   cmp[wd] dest, oldval
12244     //   bne- midMBB
12245     // loop2MBB:
12246     //   st[bhwd]cx. newval, ptr
12247     //   bne- loopMBB
12248     //   b exitBB
12249     // midMBB:
12250     //   st[bhwd]cx. dest, ptr
12251     // exitBB:
12252     BB = loop1MBB;
12253     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12254     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12255         .addReg(oldval)
12256         .addReg(dest);
12257     BuildMI(BB, dl, TII->get(PPC::BCC))
12258         .addImm(PPC::PRED_NE)
12259         .addReg(PPC::CR0)
12260         .addMBB(midMBB);
12261     BB->addSuccessor(loop2MBB);
12262     BB->addSuccessor(midMBB);
12263 
12264     BB = loop2MBB;
12265     BuildMI(BB, dl, TII->get(StoreMnemonic))
12266         .addReg(newval)
12267         .addReg(ptrA)
12268         .addReg(ptrB);
12269     BuildMI(BB, dl, TII->get(PPC::BCC))
12270         .addImm(PPC::PRED_NE)
12271         .addReg(PPC::CR0)
12272         .addMBB(loop1MBB);
12273     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12274     BB->addSuccessor(loop1MBB);
12275     BB->addSuccessor(exitMBB);
12276 
12277     BB = midMBB;
12278     BuildMI(BB, dl, TII->get(StoreMnemonic))
12279         .addReg(dest)
12280         .addReg(ptrA)
12281         .addReg(ptrB);
12282     BB->addSuccessor(exitMBB);
12283 
12284     //  exitMBB:
12285     //   ...
12286     BB = exitMBB;
12287   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12288              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12289     // We must use 64-bit registers for addresses when targeting 64-bit,
12290     // since we're actually doing arithmetic on them.  Other registers
12291     // can be 32-bit.
12292     bool is64bit = Subtarget.isPPC64();
12293     bool isLittleEndian = Subtarget.isLittleEndian();
12294     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12295 
12296     Register dest = MI.getOperand(0).getReg();
12297     Register ptrA = MI.getOperand(1).getReg();
12298     Register ptrB = MI.getOperand(2).getReg();
12299     Register oldval = MI.getOperand(3).getReg();
12300     Register newval = MI.getOperand(4).getReg();
12301     DebugLoc dl = MI.getDebugLoc();
12302 
12303     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12304     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12305     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12306     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12307     F->insert(It, loop1MBB);
12308     F->insert(It, loop2MBB);
12309     F->insert(It, midMBB);
12310     F->insert(It, exitMBB);
12311     exitMBB->splice(exitMBB->begin(), BB,
12312                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12313     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12314 
12315     MachineRegisterInfo &RegInfo = F->getRegInfo();
12316     const TargetRegisterClass *RC =
12317         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12318     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12319 
12320     Register PtrReg = RegInfo.createVirtualRegister(RC);
12321     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12322     Register ShiftReg =
12323         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12324     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12325     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12326     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12327     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12328     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12329     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12330     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12331     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12332     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12333     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12334     Register Ptr1Reg;
12335     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12336     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12337     //  thisMBB:
12338     //   ...
12339     //   fallthrough --> loopMBB
12340     BB->addSuccessor(loop1MBB);
12341 
12342     // The 4-byte load must be aligned, while a char or short may be
12343     // anywhere in the word.  Hence all this nasty bookkeeping code.
12344     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12345     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12346     //   xori shift, shift1, 24 [16]
12347     //   rlwinm ptr, ptr1, 0, 0, 29
12348     //   slw newval2, newval, shift
12349     //   slw oldval2, oldval,shift
12350     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12351     //   slw mask, mask2, shift
12352     //   and newval3, newval2, mask
12353     //   and oldval3, oldval2, mask
12354     // loop1MBB:
12355     //   lwarx tmpDest, ptr
12356     //   and tmp, tmpDest, mask
12357     //   cmpw tmp, oldval3
12358     //   bne- midMBB
12359     // loop2MBB:
12360     //   andc tmp2, tmpDest, mask
12361     //   or tmp4, tmp2, newval3
12362     //   stwcx. tmp4, ptr
12363     //   bne- loop1MBB
12364     //   b exitBB
12365     // midMBB:
12366     //   stwcx. tmpDest, ptr
12367     // exitBB:
12368     //   srw dest, tmpDest, shift
12369     if (ptrA != ZeroReg) {
12370       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12371       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12372           .addReg(ptrA)
12373           .addReg(ptrB);
12374     } else {
12375       Ptr1Reg = ptrB;
12376     }
12377 
12378     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12379     // mode.
12380     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12381         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12382         .addImm(3)
12383         .addImm(27)
12384         .addImm(is8bit ? 28 : 27);
12385     if (!isLittleEndian)
12386       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12387           .addReg(Shift1Reg)
12388           .addImm(is8bit ? 24 : 16);
12389     if (is64bit)
12390       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12391           .addReg(Ptr1Reg)
12392           .addImm(0)
12393           .addImm(61);
12394     else
12395       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12396           .addReg(Ptr1Reg)
12397           .addImm(0)
12398           .addImm(0)
12399           .addImm(29);
12400     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12401         .addReg(newval)
12402         .addReg(ShiftReg);
12403     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12404         .addReg(oldval)
12405         .addReg(ShiftReg);
12406     if (is8bit)
12407       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12408     else {
12409       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12410       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12411           .addReg(Mask3Reg)
12412           .addImm(65535);
12413     }
12414     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12415         .addReg(Mask2Reg)
12416         .addReg(ShiftReg);
12417     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12418         .addReg(NewVal2Reg)
12419         .addReg(MaskReg);
12420     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12421         .addReg(OldVal2Reg)
12422         .addReg(MaskReg);
12423 
12424     BB = loop1MBB;
12425     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12426         .addReg(ZeroReg)
12427         .addReg(PtrReg);
12428     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12429         .addReg(TmpDestReg)
12430         .addReg(MaskReg);
12431     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12432         .addReg(TmpReg)
12433         .addReg(OldVal3Reg);
12434     BuildMI(BB, dl, TII->get(PPC::BCC))
12435         .addImm(PPC::PRED_NE)
12436         .addReg(PPC::CR0)
12437         .addMBB(midMBB);
12438     BB->addSuccessor(loop2MBB);
12439     BB->addSuccessor(midMBB);
12440 
12441     BB = loop2MBB;
12442     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12443         .addReg(TmpDestReg)
12444         .addReg(MaskReg);
12445     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12446         .addReg(Tmp2Reg)
12447         .addReg(NewVal3Reg);
12448     BuildMI(BB, dl, TII->get(PPC::STWCX))
12449         .addReg(Tmp4Reg)
12450         .addReg(ZeroReg)
12451         .addReg(PtrReg);
12452     BuildMI(BB, dl, TII->get(PPC::BCC))
12453         .addImm(PPC::PRED_NE)
12454         .addReg(PPC::CR0)
12455         .addMBB(loop1MBB);
12456     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12457     BB->addSuccessor(loop1MBB);
12458     BB->addSuccessor(exitMBB);
12459 
12460     BB = midMBB;
12461     BuildMI(BB, dl, TII->get(PPC::STWCX))
12462         .addReg(TmpDestReg)
12463         .addReg(ZeroReg)
12464         .addReg(PtrReg);
12465     BB->addSuccessor(exitMBB);
12466 
12467     //  exitMBB:
12468     //   ...
12469     BB = exitMBB;
12470     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12471         .addReg(TmpReg)
12472         .addReg(ShiftReg);
12473   } else if (MI.getOpcode() == PPC::FADDrtz) {
12474     // This pseudo performs an FADD with rounding mode temporarily forced
12475     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12476     // is not modeled at the SelectionDAG level.
12477     Register Dest = MI.getOperand(0).getReg();
12478     Register Src1 = MI.getOperand(1).getReg();
12479     Register Src2 = MI.getOperand(2).getReg();
12480     DebugLoc dl = MI.getDebugLoc();
12481 
12482     MachineRegisterInfo &RegInfo = F->getRegInfo();
12483     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12484 
12485     // Save FPSCR value.
12486     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12487 
12488     // Set rounding mode to round-to-zero.
12489     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12490         .addImm(31)
12491         .addReg(PPC::RM, RegState::ImplicitDefine);
12492 
12493     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12494         .addImm(30)
12495         .addReg(PPC::RM, RegState::ImplicitDefine);
12496 
12497     // Perform addition.
12498     auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
12499                    .addReg(Src1)
12500                    .addReg(Src2);
12501     if (MI.getFlag(MachineInstr::NoFPExcept))
12502       MIB.setMIFlag(MachineInstr::NoFPExcept);
12503 
12504     // Restore FPSCR value.
12505     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12506   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12507              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12508              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12509              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12510     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12511                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12512                           ? PPC::ANDI8_rec
12513                           : PPC::ANDI_rec;
12514     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12515                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12516 
12517     MachineRegisterInfo &RegInfo = F->getRegInfo();
12518     Register Dest = RegInfo.createVirtualRegister(
12519         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12520 
12521     DebugLoc Dl = MI.getDebugLoc();
12522     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12523         .addReg(MI.getOperand(1).getReg())
12524         .addImm(1);
12525     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12526             MI.getOperand(0).getReg())
12527         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12528   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12529     DebugLoc Dl = MI.getDebugLoc();
12530     MachineRegisterInfo &RegInfo = F->getRegInfo();
12531     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12532     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12533     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12534             MI.getOperand(0).getReg())
12535         .addReg(CRReg);
12536   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12537     DebugLoc Dl = MI.getDebugLoc();
12538     unsigned Imm = MI.getOperand(1).getImm();
12539     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12540     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12541             MI.getOperand(0).getReg())
12542         .addReg(PPC::CR0EQ);
12543   } else if (MI.getOpcode() == PPC::SETRNDi) {
12544     DebugLoc dl = MI.getDebugLoc();
12545     Register OldFPSCRReg = MI.getOperand(0).getReg();
12546 
12547     // Save FPSCR value.
12548     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12549 
12550     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12551     // the following settings:
12552     //   00 Round to nearest
12553     //   01 Round to 0
12554     //   10 Round to +inf
12555     //   11 Round to -inf
12556 
12557     // When the operand is immediate, using the two least significant bits of
12558     // the immediate to set the bits 62:63 of FPSCR.
12559     unsigned Mode = MI.getOperand(1).getImm();
12560     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12561         .addImm(31)
12562         .addReg(PPC::RM, RegState::ImplicitDefine);
12563 
12564     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12565         .addImm(30)
12566         .addReg(PPC::RM, RegState::ImplicitDefine);
12567   } else if (MI.getOpcode() == PPC::SETRND) {
12568     DebugLoc dl = MI.getDebugLoc();
12569 
12570     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12571     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12572     // If the target doesn't have DirectMove, we should use stack to do the
12573     // conversion, because the target doesn't have the instructions like mtvsrd
12574     // or mfvsrd to do this conversion directly.
12575     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12576       if (Subtarget.hasDirectMove()) {
12577         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12578           .addReg(SrcReg);
12579       } else {
12580         // Use stack to do the register copy.
12581         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12582         MachineRegisterInfo &RegInfo = F->getRegInfo();
12583         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12584         if (RC == &PPC::F8RCRegClass) {
12585           // Copy register from F8RCRegClass to G8RCRegclass.
12586           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12587                  "Unsupported RegClass.");
12588 
12589           StoreOp = PPC::STFD;
12590           LoadOp = PPC::LD;
12591         } else {
12592           // Copy register from G8RCRegClass to F8RCRegclass.
12593           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12594                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12595                  "Unsupported RegClass.");
12596         }
12597 
12598         MachineFrameInfo &MFI = F->getFrameInfo();
12599         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12600 
12601         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12602             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12603             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12604             MFI.getObjectAlign(FrameIdx));
12605 
12606         // Store the SrcReg into the stack.
12607         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12608           .addReg(SrcReg)
12609           .addImm(0)
12610           .addFrameIndex(FrameIdx)
12611           .addMemOperand(MMOStore);
12612 
12613         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12614             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12615             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12616             MFI.getObjectAlign(FrameIdx));
12617 
12618         // Load from the stack where SrcReg is stored, and save to DestReg,
12619         // so we have done the RegClass conversion from RegClass::SrcReg to
12620         // RegClass::DestReg.
12621         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12622           .addImm(0)
12623           .addFrameIndex(FrameIdx)
12624           .addMemOperand(MMOLoad);
12625       }
12626     };
12627 
12628     Register OldFPSCRReg = MI.getOperand(0).getReg();
12629 
12630     // Save FPSCR value.
12631     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12632 
12633     // When the operand is gprc register, use two least significant bits of the
12634     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12635     //
12636     // copy OldFPSCRTmpReg, OldFPSCRReg
12637     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12638     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12639     // copy NewFPSCRReg, NewFPSCRTmpReg
12640     // mtfsf 255, NewFPSCRReg
12641     MachineOperand SrcOp = MI.getOperand(1);
12642     MachineRegisterInfo &RegInfo = F->getRegInfo();
12643     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12644 
12645     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12646 
12647     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12648     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12649 
12650     // The first operand of INSERT_SUBREG should be a register which has
12651     // subregisters, we only care about its RegClass, so we should use an
12652     // IMPLICIT_DEF register.
12653     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12654     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12655       .addReg(ImDefReg)
12656       .add(SrcOp)
12657       .addImm(1);
12658 
12659     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12660     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12661       .addReg(OldFPSCRTmpReg)
12662       .addReg(ExtSrcReg)
12663       .addImm(0)
12664       .addImm(62);
12665 
12666     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12667     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12668 
12669     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12670     // bits of FPSCR.
12671     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12672       .addImm(255)
12673       .addReg(NewFPSCRReg)
12674       .addImm(0)
12675       .addImm(0);
12676   } else if (MI.getOpcode() == PPC::SETFLM) {
12677     DebugLoc Dl = MI.getDebugLoc();
12678 
12679     // Result of setflm is previous FPSCR content, so we need to save it first.
12680     Register OldFPSCRReg = MI.getOperand(0).getReg();
12681     BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12682 
12683     // Put bits in 32:63 to FPSCR.
12684     Register NewFPSCRReg = MI.getOperand(1).getReg();
12685     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12686         .addImm(255)
12687         .addReg(NewFPSCRReg)
12688         .addImm(0)
12689         .addImm(0);
12690   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12691              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12692     return emitProbedAlloca(MI, BB);
12693   } else {
12694     llvm_unreachable("Unexpected instr type to insert");
12695   }
12696 
12697   MI.eraseFromParent(); // The pseudo instruction is gone now.
12698   return BB;
12699 }
12700 
12701 //===----------------------------------------------------------------------===//
12702 // Target Optimization Hooks
12703 //===----------------------------------------------------------------------===//
12704 
12705 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12706   // For the estimates, convergence is quadratic, so we essentially double the
12707   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12708   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12709   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12710   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12711   if (VT.getScalarType() == MVT::f64)
12712     RefinementSteps++;
12713   return RefinementSteps;
12714 }
12715 
12716 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
12717                                             const DenormalMode &Mode) const {
12718   // TODO - add support for v2f64/v4f32
12719   EVT VT = Op.getValueType();
12720   if (VT != MVT::f64)
12721     return SDValue();
12722 
12723   SDLoc DL(Op);
12724   // The output register of FTSQRT is CR field.
12725   SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
12726   // ftsqrt BF,FRB
12727   // Let e_b be the unbiased exponent of the double-precision
12728   // floating-point operand in register FRB.
12729   // fe_flag is set to 1 if either of the following conditions occurs.
12730   //   - The double-precision floating-point operand in register FRB is a zero,
12731   //     a NaN, or an infinity, or a negative value.
12732   //   - e_b is less than or equal to -970.
12733   // Otherwise fe_flag is set to 0.
12734   // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
12735   // not eligible for iteration. (zero/negative/infinity/nan or unbiased
12736   // exponent is less than -970)
12737   SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
12738   return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
12739                                     FTSQRT, SRIdxVal),
12740                  0);
12741 }
12742 
12743 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12744                                            int Enabled, int &RefinementSteps,
12745                                            bool &UseOneConstNR,
12746                                            bool Reciprocal) const {
12747   EVT VT = Operand.getValueType();
12748   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12749       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12750       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12751       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12752     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12753       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12754 
12755     // The Newton-Raphson computation with a single constant does not provide
12756     // enough accuracy on some CPUs.
12757     UseOneConstNR = !Subtarget.needsTwoConstNR();
12758     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12759   }
12760   return SDValue();
12761 }
12762 
12763 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12764                                             int Enabled,
12765                                             int &RefinementSteps) const {
12766   EVT VT = Operand.getValueType();
12767   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12768       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12769       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12770       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12771     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12772       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12773     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12774   }
12775   return SDValue();
12776 }
12777 
12778 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12779   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12780   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12781   // enabled for division), this functionality is redundant with the default
12782   // combiner logic (once the division -> reciprocal/multiply transformation
12783   // has taken place). As a result, this matters more for older cores than for
12784   // newer ones.
12785 
12786   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12787   // reciprocal if there are two or more FDIVs (for embedded cores with only
12788   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12789   switch (Subtarget.getCPUDirective()) {
12790   default:
12791     return 3;
12792   case PPC::DIR_440:
12793   case PPC::DIR_A2:
12794   case PPC::DIR_E500:
12795   case PPC::DIR_E500mc:
12796   case PPC::DIR_E5500:
12797     return 2;
12798   }
12799 }
12800 
12801 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12802 // collapsed, and so we need to look through chains of them.
12803 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12804                                      int64_t& Offset, SelectionDAG &DAG) {
12805   if (DAG.isBaseWithConstantOffset(Loc)) {
12806     Base = Loc.getOperand(0);
12807     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12808 
12809     // The base might itself be a base plus an offset, and if so, accumulate
12810     // that as well.
12811     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12812   }
12813 }
12814 
12815 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12816                             unsigned Bytes, int Dist,
12817                             SelectionDAG &DAG) {
12818   if (VT.getSizeInBits() / 8 != Bytes)
12819     return false;
12820 
12821   SDValue BaseLoc = Base->getBasePtr();
12822   if (Loc.getOpcode() == ISD::FrameIndex) {
12823     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12824       return false;
12825     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12826     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12827     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12828     int FS  = MFI.getObjectSize(FI);
12829     int BFS = MFI.getObjectSize(BFI);
12830     if (FS != BFS || FS != (int)Bytes) return false;
12831     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12832   }
12833 
12834   SDValue Base1 = Loc, Base2 = BaseLoc;
12835   int64_t Offset1 = 0, Offset2 = 0;
12836   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12837   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12838   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12839     return true;
12840 
12841   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12842   const GlobalValue *GV1 = nullptr;
12843   const GlobalValue *GV2 = nullptr;
12844   Offset1 = 0;
12845   Offset2 = 0;
12846   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12847   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12848   if (isGA1 && isGA2 && GV1 == GV2)
12849     return Offset1 == (Offset2 + Dist*Bytes);
12850   return false;
12851 }
12852 
12853 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12854 // not enforce equality of the chain operands.
12855 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12856                             unsigned Bytes, int Dist,
12857                             SelectionDAG &DAG) {
12858   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12859     EVT VT = LS->getMemoryVT();
12860     SDValue Loc = LS->getBasePtr();
12861     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12862   }
12863 
12864   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12865     EVT VT;
12866     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12867     default: return false;
12868     case Intrinsic::ppc_altivec_lvx:
12869     case Intrinsic::ppc_altivec_lvxl:
12870     case Intrinsic::ppc_vsx_lxvw4x:
12871     case Intrinsic::ppc_vsx_lxvw4x_be:
12872       VT = MVT::v4i32;
12873       break;
12874     case Intrinsic::ppc_vsx_lxvd2x:
12875     case Intrinsic::ppc_vsx_lxvd2x_be:
12876       VT = MVT::v2f64;
12877       break;
12878     case Intrinsic::ppc_altivec_lvebx:
12879       VT = MVT::i8;
12880       break;
12881     case Intrinsic::ppc_altivec_lvehx:
12882       VT = MVT::i16;
12883       break;
12884     case Intrinsic::ppc_altivec_lvewx:
12885       VT = MVT::i32;
12886       break;
12887     }
12888 
12889     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12890   }
12891 
12892   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12893     EVT VT;
12894     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12895     default: return false;
12896     case Intrinsic::ppc_altivec_stvx:
12897     case Intrinsic::ppc_altivec_stvxl:
12898     case Intrinsic::ppc_vsx_stxvw4x:
12899       VT = MVT::v4i32;
12900       break;
12901     case Intrinsic::ppc_vsx_stxvd2x:
12902       VT = MVT::v2f64;
12903       break;
12904     case Intrinsic::ppc_vsx_stxvw4x_be:
12905       VT = MVT::v4i32;
12906       break;
12907     case Intrinsic::ppc_vsx_stxvd2x_be:
12908       VT = MVT::v2f64;
12909       break;
12910     case Intrinsic::ppc_altivec_stvebx:
12911       VT = MVT::i8;
12912       break;
12913     case Intrinsic::ppc_altivec_stvehx:
12914       VT = MVT::i16;
12915       break;
12916     case Intrinsic::ppc_altivec_stvewx:
12917       VT = MVT::i32;
12918       break;
12919     }
12920 
12921     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12922   }
12923 
12924   return false;
12925 }
12926 
12927 // Return true is there is a nearyby consecutive load to the one provided
12928 // (regardless of alignment). We search up and down the chain, looking though
12929 // token factors and other loads (but nothing else). As a result, a true result
12930 // indicates that it is safe to create a new consecutive load adjacent to the
12931 // load provided.
12932 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12933   SDValue Chain = LD->getChain();
12934   EVT VT = LD->getMemoryVT();
12935 
12936   SmallSet<SDNode *, 16> LoadRoots;
12937   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12938   SmallSet<SDNode *, 16> Visited;
12939 
12940   // First, search up the chain, branching to follow all token-factor operands.
12941   // If we find a consecutive load, then we're done, otherwise, record all
12942   // nodes just above the top-level loads and token factors.
12943   while (!Queue.empty()) {
12944     SDNode *ChainNext = Queue.pop_back_val();
12945     if (!Visited.insert(ChainNext).second)
12946       continue;
12947 
12948     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12949       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12950         return true;
12951 
12952       if (!Visited.count(ChainLD->getChain().getNode()))
12953         Queue.push_back(ChainLD->getChain().getNode());
12954     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12955       for (const SDUse &O : ChainNext->ops())
12956         if (!Visited.count(O.getNode()))
12957           Queue.push_back(O.getNode());
12958     } else
12959       LoadRoots.insert(ChainNext);
12960   }
12961 
12962   // Second, search down the chain, starting from the top-level nodes recorded
12963   // in the first phase. These top-level nodes are the nodes just above all
12964   // loads and token factors. Starting with their uses, recursively look though
12965   // all loads (just the chain uses) and token factors to find a consecutive
12966   // load.
12967   Visited.clear();
12968   Queue.clear();
12969 
12970   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12971        IE = LoadRoots.end(); I != IE; ++I) {
12972     Queue.push_back(*I);
12973 
12974     while (!Queue.empty()) {
12975       SDNode *LoadRoot = Queue.pop_back_val();
12976       if (!Visited.insert(LoadRoot).second)
12977         continue;
12978 
12979       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12980         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12981           return true;
12982 
12983       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12984            UE = LoadRoot->use_end(); UI != UE; ++UI)
12985         if (((isa<MemSDNode>(*UI) &&
12986             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12987             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12988           Queue.push_back(*UI);
12989     }
12990   }
12991 
12992   return false;
12993 }
12994 
12995 /// This function is called when we have proved that a SETCC node can be replaced
12996 /// by subtraction (and other supporting instructions) so that the result of
12997 /// comparison is kept in a GPR instead of CR. This function is purely for
12998 /// codegen purposes and has some flags to guide the codegen process.
12999 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
13000                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
13001   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13002 
13003   // Zero extend the operands to the largest legal integer. Originally, they
13004   // must be of a strictly smaller size.
13005   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
13006                          DAG.getConstant(Size, DL, MVT::i32));
13007   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
13008                          DAG.getConstant(Size, DL, MVT::i32));
13009 
13010   // Swap if needed. Depends on the condition code.
13011   if (Swap)
13012     std::swap(Op0, Op1);
13013 
13014   // Subtract extended integers.
13015   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
13016 
13017   // Move the sign bit to the least significant position and zero out the rest.
13018   // Now the least significant bit carries the result of original comparison.
13019   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
13020                              DAG.getConstant(Size - 1, DL, MVT::i32));
13021   auto Final = Shifted;
13022 
13023   // Complement the result if needed. Based on the condition code.
13024   if (Complement)
13025     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
13026                         DAG.getConstant(1, DL, MVT::i64));
13027 
13028   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
13029 }
13030 
13031 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
13032                                                   DAGCombinerInfo &DCI) const {
13033   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13034 
13035   SelectionDAG &DAG = DCI.DAG;
13036   SDLoc DL(N);
13037 
13038   // Size of integers being compared has a critical role in the following
13039   // analysis, so we prefer to do this when all types are legal.
13040   if (!DCI.isAfterLegalizeDAG())
13041     return SDValue();
13042 
13043   // If all users of SETCC extend its value to a legal integer type
13044   // then we replace SETCC with a subtraction
13045   for (SDNode::use_iterator UI = N->use_begin(),
13046        UE = N->use_end(); UI != UE; ++UI) {
13047     if (UI->getOpcode() != ISD::ZERO_EXTEND)
13048       return SDValue();
13049   }
13050 
13051   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13052   auto OpSize = N->getOperand(0).getValueSizeInBits();
13053 
13054   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
13055 
13056   if (OpSize < Size) {
13057     switch (CC) {
13058     default: break;
13059     case ISD::SETULT:
13060       return generateEquivalentSub(N, Size, false, false, DL, DAG);
13061     case ISD::SETULE:
13062       return generateEquivalentSub(N, Size, true, true, DL, DAG);
13063     case ISD::SETUGT:
13064       return generateEquivalentSub(N, Size, false, true, DL, DAG);
13065     case ISD::SETUGE:
13066       return generateEquivalentSub(N, Size, true, false, DL, DAG);
13067     }
13068   }
13069 
13070   return SDValue();
13071 }
13072 
13073 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
13074                                                   DAGCombinerInfo &DCI) const {
13075   SelectionDAG &DAG = DCI.DAG;
13076   SDLoc dl(N);
13077 
13078   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
13079   // If we're tracking CR bits, we need to be careful that we don't have:
13080   //   trunc(binary-ops(zext(x), zext(y)))
13081   // or
13082   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
13083   // such that we're unnecessarily moving things into GPRs when it would be
13084   // better to keep them in CR bits.
13085 
13086   // Note that trunc here can be an actual i1 trunc, or can be the effective
13087   // truncation that comes from a setcc or select_cc.
13088   if (N->getOpcode() == ISD::TRUNCATE &&
13089       N->getValueType(0) != MVT::i1)
13090     return SDValue();
13091 
13092   if (N->getOperand(0).getValueType() != MVT::i32 &&
13093       N->getOperand(0).getValueType() != MVT::i64)
13094     return SDValue();
13095 
13096   if (N->getOpcode() == ISD::SETCC ||
13097       N->getOpcode() == ISD::SELECT_CC) {
13098     // If we're looking at a comparison, then we need to make sure that the
13099     // high bits (all except for the first) don't matter the result.
13100     ISD::CondCode CC =
13101       cast<CondCodeSDNode>(N->getOperand(
13102         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
13103     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
13104 
13105     if (ISD::isSignedIntSetCC(CC)) {
13106       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
13107           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
13108         return SDValue();
13109     } else if (ISD::isUnsignedIntSetCC(CC)) {
13110       if (!DAG.MaskedValueIsZero(N->getOperand(0),
13111                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
13112           !DAG.MaskedValueIsZero(N->getOperand(1),
13113                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
13114         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
13115                                              : SDValue());
13116     } else {
13117       // This is neither a signed nor an unsigned comparison, just make sure
13118       // that the high bits are equal.
13119       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
13120       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
13121 
13122       // We don't really care about what is known about the first bit (if
13123       // anything), so clear it in all masks prior to comparing them.
13124       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
13125       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
13126 
13127       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
13128         return SDValue();
13129     }
13130   }
13131 
13132   // We now know that the higher-order bits are irrelevant, we just need to
13133   // make sure that all of the intermediate operations are bit operations, and
13134   // all inputs are extensions.
13135   if (N->getOperand(0).getOpcode() != ISD::AND &&
13136       N->getOperand(0).getOpcode() != ISD::OR  &&
13137       N->getOperand(0).getOpcode() != ISD::XOR &&
13138       N->getOperand(0).getOpcode() != ISD::SELECT &&
13139       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
13140       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
13141       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
13142       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
13143       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
13144     return SDValue();
13145 
13146   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
13147       N->getOperand(1).getOpcode() != ISD::AND &&
13148       N->getOperand(1).getOpcode() != ISD::OR  &&
13149       N->getOperand(1).getOpcode() != ISD::XOR &&
13150       N->getOperand(1).getOpcode() != ISD::SELECT &&
13151       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
13152       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
13153       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
13154       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
13155       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
13156     return SDValue();
13157 
13158   SmallVector<SDValue, 4> Inputs;
13159   SmallVector<SDValue, 8> BinOps, PromOps;
13160   SmallPtrSet<SDNode *, 16> Visited;
13161 
13162   for (unsigned i = 0; i < 2; ++i) {
13163     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13164           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13165           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13166           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13167         isa<ConstantSDNode>(N->getOperand(i)))
13168       Inputs.push_back(N->getOperand(i));
13169     else
13170       BinOps.push_back(N->getOperand(i));
13171 
13172     if (N->getOpcode() == ISD::TRUNCATE)
13173       break;
13174   }
13175 
13176   // Visit all inputs, collect all binary operations (and, or, xor and
13177   // select) that are all fed by extensions.
13178   while (!BinOps.empty()) {
13179     SDValue BinOp = BinOps.back();
13180     BinOps.pop_back();
13181 
13182     if (!Visited.insert(BinOp.getNode()).second)
13183       continue;
13184 
13185     PromOps.push_back(BinOp);
13186 
13187     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13188       // The condition of the select is not promoted.
13189       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13190         continue;
13191       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13192         continue;
13193 
13194       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13195             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13196             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13197            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13198           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13199         Inputs.push_back(BinOp.getOperand(i));
13200       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13201                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13202                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13203                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13204                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
13205                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13206                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13207                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13208                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
13209         BinOps.push_back(BinOp.getOperand(i));
13210       } else {
13211         // We have an input that is not an extension or another binary
13212         // operation; we'll abort this transformation.
13213         return SDValue();
13214       }
13215     }
13216   }
13217 
13218   // Make sure that this is a self-contained cluster of operations (which
13219   // is not quite the same thing as saying that everything has only one
13220   // use).
13221   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13222     if (isa<ConstantSDNode>(Inputs[i]))
13223       continue;
13224 
13225     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13226                               UE = Inputs[i].getNode()->use_end();
13227          UI != UE; ++UI) {
13228       SDNode *User = *UI;
13229       if (User != N && !Visited.count(User))
13230         return SDValue();
13231 
13232       // Make sure that we're not going to promote the non-output-value
13233       // operand(s) or SELECT or SELECT_CC.
13234       // FIXME: Although we could sometimes handle this, and it does occur in
13235       // practice that one of the condition inputs to the select is also one of
13236       // the outputs, we currently can't deal with this.
13237       if (User->getOpcode() == ISD::SELECT) {
13238         if (User->getOperand(0) == Inputs[i])
13239           return SDValue();
13240       } else if (User->getOpcode() == ISD::SELECT_CC) {
13241         if (User->getOperand(0) == Inputs[i] ||
13242             User->getOperand(1) == Inputs[i])
13243           return SDValue();
13244       }
13245     }
13246   }
13247 
13248   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13249     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13250                               UE = PromOps[i].getNode()->use_end();
13251          UI != UE; ++UI) {
13252       SDNode *User = *UI;
13253       if (User != N && !Visited.count(User))
13254         return SDValue();
13255 
13256       // Make sure that we're not going to promote the non-output-value
13257       // operand(s) or SELECT or SELECT_CC.
13258       // FIXME: Although we could sometimes handle this, and it does occur in
13259       // practice that one of the condition inputs to the select is also one of
13260       // the outputs, we currently can't deal with this.
13261       if (User->getOpcode() == ISD::SELECT) {
13262         if (User->getOperand(0) == PromOps[i])
13263           return SDValue();
13264       } else if (User->getOpcode() == ISD::SELECT_CC) {
13265         if (User->getOperand(0) == PromOps[i] ||
13266             User->getOperand(1) == PromOps[i])
13267           return SDValue();
13268       }
13269     }
13270   }
13271 
13272   // Replace all inputs with the extension operand.
13273   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13274     // Constants may have users outside the cluster of to-be-promoted nodes,
13275     // and so we need to replace those as we do the promotions.
13276     if (isa<ConstantSDNode>(Inputs[i]))
13277       continue;
13278     else
13279       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13280   }
13281 
13282   std::list<HandleSDNode> PromOpHandles;
13283   for (auto &PromOp : PromOps)
13284     PromOpHandles.emplace_back(PromOp);
13285 
13286   // Replace all operations (these are all the same, but have a different
13287   // (i1) return type). DAG.getNode will validate that the types of
13288   // a binary operator match, so go through the list in reverse so that
13289   // we've likely promoted both operands first. Any intermediate truncations or
13290   // extensions disappear.
13291   while (!PromOpHandles.empty()) {
13292     SDValue PromOp = PromOpHandles.back().getValue();
13293     PromOpHandles.pop_back();
13294 
13295     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13296         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13297         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13298         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13299       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13300           PromOp.getOperand(0).getValueType() != MVT::i1) {
13301         // The operand is not yet ready (see comment below).
13302         PromOpHandles.emplace_front(PromOp);
13303         continue;
13304       }
13305 
13306       SDValue RepValue = PromOp.getOperand(0);
13307       if (isa<ConstantSDNode>(RepValue))
13308         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13309 
13310       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13311       continue;
13312     }
13313 
13314     unsigned C;
13315     switch (PromOp.getOpcode()) {
13316     default:             C = 0; break;
13317     case ISD::SELECT:    C = 1; break;
13318     case ISD::SELECT_CC: C = 2; break;
13319     }
13320 
13321     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13322          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13323         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13324          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13325       // The to-be-promoted operands of this node have not yet been
13326       // promoted (this should be rare because we're going through the
13327       // list backward, but if one of the operands has several users in
13328       // this cluster of to-be-promoted nodes, it is possible).
13329       PromOpHandles.emplace_front(PromOp);
13330       continue;
13331     }
13332 
13333     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13334                                 PromOp.getNode()->op_end());
13335 
13336     // If there are any constant inputs, make sure they're replaced now.
13337     for (unsigned i = 0; i < 2; ++i)
13338       if (isa<ConstantSDNode>(Ops[C+i]))
13339         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13340 
13341     DAG.ReplaceAllUsesOfValueWith(PromOp,
13342       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13343   }
13344 
13345   // Now we're left with the initial truncation itself.
13346   if (N->getOpcode() == ISD::TRUNCATE)
13347     return N->getOperand(0);
13348 
13349   // Otherwise, this is a comparison. The operands to be compared have just
13350   // changed type (to i1), but everything else is the same.
13351   return SDValue(N, 0);
13352 }
13353 
13354 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13355                                                   DAGCombinerInfo &DCI) const {
13356   SelectionDAG &DAG = DCI.DAG;
13357   SDLoc dl(N);
13358 
13359   // If we're tracking CR bits, we need to be careful that we don't have:
13360   //   zext(binary-ops(trunc(x), trunc(y)))
13361   // or
13362   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13363   // such that we're unnecessarily moving things into CR bits that can more
13364   // efficiently stay in GPRs. Note that if we're not certain that the high
13365   // bits are set as required by the final extension, we still may need to do
13366   // some masking to get the proper behavior.
13367 
13368   // This same functionality is important on PPC64 when dealing with
13369   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13370   // the return values of functions. Because it is so similar, it is handled
13371   // here as well.
13372 
13373   if (N->getValueType(0) != MVT::i32 &&
13374       N->getValueType(0) != MVT::i64)
13375     return SDValue();
13376 
13377   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13378         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13379     return SDValue();
13380 
13381   if (N->getOperand(0).getOpcode() != ISD::AND &&
13382       N->getOperand(0).getOpcode() != ISD::OR  &&
13383       N->getOperand(0).getOpcode() != ISD::XOR &&
13384       N->getOperand(0).getOpcode() != ISD::SELECT &&
13385       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13386     return SDValue();
13387 
13388   SmallVector<SDValue, 4> Inputs;
13389   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13390   SmallPtrSet<SDNode *, 16> Visited;
13391 
13392   // Visit all inputs, collect all binary operations (and, or, xor and
13393   // select) that are all fed by truncations.
13394   while (!BinOps.empty()) {
13395     SDValue BinOp = BinOps.back();
13396     BinOps.pop_back();
13397 
13398     if (!Visited.insert(BinOp.getNode()).second)
13399       continue;
13400 
13401     PromOps.push_back(BinOp);
13402 
13403     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13404       // The condition of the select is not promoted.
13405       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13406         continue;
13407       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13408         continue;
13409 
13410       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13411           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13412         Inputs.push_back(BinOp.getOperand(i));
13413       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13414                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13415                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13416                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13417                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13418         BinOps.push_back(BinOp.getOperand(i));
13419       } else {
13420         // We have an input that is not a truncation or another binary
13421         // operation; we'll abort this transformation.
13422         return SDValue();
13423       }
13424     }
13425   }
13426 
13427   // The operands of a select that must be truncated when the select is
13428   // promoted because the operand is actually part of the to-be-promoted set.
13429   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13430 
13431   // Make sure that this is a self-contained cluster of operations (which
13432   // is not quite the same thing as saying that everything has only one
13433   // use).
13434   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13435     if (isa<ConstantSDNode>(Inputs[i]))
13436       continue;
13437 
13438     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13439                               UE = Inputs[i].getNode()->use_end();
13440          UI != UE; ++UI) {
13441       SDNode *User = *UI;
13442       if (User != N && !Visited.count(User))
13443         return SDValue();
13444 
13445       // If we're going to promote the non-output-value operand(s) or SELECT or
13446       // SELECT_CC, record them for truncation.
13447       if (User->getOpcode() == ISD::SELECT) {
13448         if (User->getOperand(0) == Inputs[i])
13449           SelectTruncOp[0].insert(std::make_pair(User,
13450                                     User->getOperand(0).getValueType()));
13451       } else if (User->getOpcode() == ISD::SELECT_CC) {
13452         if (User->getOperand(0) == Inputs[i])
13453           SelectTruncOp[0].insert(std::make_pair(User,
13454                                     User->getOperand(0).getValueType()));
13455         if (User->getOperand(1) == Inputs[i])
13456           SelectTruncOp[1].insert(std::make_pair(User,
13457                                     User->getOperand(1).getValueType()));
13458       }
13459     }
13460   }
13461 
13462   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13463     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13464                               UE = PromOps[i].getNode()->use_end();
13465          UI != UE; ++UI) {
13466       SDNode *User = *UI;
13467       if (User != N && !Visited.count(User))
13468         return SDValue();
13469 
13470       // If we're going to promote the non-output-value operand(s) or SELECT or
13471       // SELECT_CC, record them for truncation.
13472       if (User->getOpcode() == ISD::SELECT) {
13473         if (User->getOperand(0) == PromOps[i])
13474           SelectTruncOp[0].insert(std::make_pair(User,
13475                                     User->getOperand(0).getValueType()));
13476       } else if (User->getOpcode() == ISD::SELECT_CC) {
13477         if (User->getOperand(0) == PromOps[i])
13478           SelectTruncOp[0].insert(std::make_pair(User,
13479                                     User->getOperand(0).getValueType()));
13480         if (User->getOperand(1) == PromOps[i])
13481           SelectTruncOp[1].insert(std::make_pair(User,
13482                                     User->getOperand(1).getValueType()));
13483       }
13484     }
13485   }
13486 
13487   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13488   bool ReallyNeedsExt = false;
13489   if (N->getOpcode() != ISD::ANY_EXTEND) {
13490     // If all of the inputs are not already sign/zero extended, then
13491     // we'll still need to do that at the end.
13492     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13493       if (isa<ConstantSDNode>(Inputs[i]))
13494         continue;
13495 
13496       unsigned OpBits =
13497         Inputs[i].getOperand(0).getValueSizeInBits();
13498       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13499 
13500       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13501            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13502                                   APInt::getHighBitsSet(OpBits,
13503                                                         OpBits-PromBits))) ||
13504           (N->getOpcode() == ISD::SIGN_EXTEND &&
13505            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13506              (OpBits-(PromBits-1)))) {
13507         ReallyNeedsExt = true;
13508         break;
13509       }
13510     }
13511   }
13512 
13513   // Replace all inputs, either with the truncation operand, or a
13514   // truncation or extension to the final output type.
13515   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13516     // Constant inputs need to be replaced with the to-be-promoted nodes that
13517     // use them because they might have users outside of the cluster of
13518     // promoted nodes.
13519     if (isa<ConstantSDNode>(Inputs[i]))
13520       continue;
13521 
13522     SDValue InSrc = Inputs[i].getOperand(0);
13523     if (Inputs[i].getValueType() == N->getValueType(0))
13524       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13525     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13526       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13527         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13528     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13529       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13530         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13531     else
13532       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13533         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13534   }
13535 
13536   std::list<HandleSDNode> PromOpHandles;
13537   for (auto &PromOp : PromOps)
13538     PromOpHandles.emplace_back(PromOp);
13539 
13540   // Replace all operations (these are all the same, but have a different
13541   // (promoted) return type). DAG.getNode will validate that the types of
13542   // a binary operator match, so go through the list in reverse so that
13543   // we've likely promoted both operands first.
13544   while (!PromOpHandles.empty()) {
13545     SDValue PromOp = PromOpHandles.back().getValue();
13546     PromOpHandles.pop_back();
13547 
13548     unsigned C;
13549     switch (PromOp.getOpcode()) {
13550     default:             C = 0; break;
13551     case ISD::SELECT:    C = 1; break;
13552     case ISD::SELECT_CC: C = 2; break;
13553     }
13554 
13555     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13556          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13557         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13558          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13559       // The to-be-promoted operands of this node have not yet been
13560       // promoted (this should be rare because we're going through the
13561       // list backward, but if one of the operands has several users in
13562       // this cluster of to-be-promoted nodes, it is possible).
13563       PromOpHandles.emplace_front(PromOp);
13564       continue;
13565     }
13566 
13567     // For SELECT and SELECT_CC nodes, we do a similar check for any
13568     // to-be-promoted comparison inputs.
13569     if (PromOp.getOpcode() == ISD::SELECT ||
13570         PromOp.getOpcode() == ISD::SELECT_CC) {
13571       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13572            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13573           (SelectTruncOp[1].count(PromOp.getNode()) &&
13574            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13575         PromOpHandles.emplace_front(PromOp);
13576         continue;
13577       }
13578     }
13579 
13580     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13581                                 PromOp.getNode()->op_end());
13582 
13583     // If this node has constant inputs, then they'll need to be promoted here.
13584     for (unsigned i = 0; i < 2; ++i) {
13585       if (!isa<ConstantSDNode>(Ops[C+i]))
13586         continue;
13587       if (Ops[C+i].getValueType() == N->getValueType(0))
13588         continue;
13589 
13590       if (N->getOpcode() == ISD::SIGN_EXTEND)
13591         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13592       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13593         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13594       else
13595         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13596     }
13597 
13598     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13599     // truncate them again to the original value type.
13600     if (PromOp.getOpcode() == ISD::SELECT ||
13601         PromOp.getOpcode() == ISD::SELECT_CC) {
13602       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13603       if (SI0 != SelectTruncOp[0].end())
13604         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13605       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13606       if (SI1 != SelectTruncOp[1].end())
13607         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13608     }
13609 
13610     DAG.ReplaceAllUsesOfValueWith(PromOp,
13611       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13612   }
13613 
13614   // Now we're left with the initial extension itself.
13615   if (!ReallyNeedsExt)
13616     return N->getOperand(0);
13617 
13618   // To zero extend, just mask off everything except for the first bit (in the
13619   // i1 case).
13620   if (N->getOpcode() == ISD::ZERO_EXTEND)
13621     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13622                        DAG.getConstant(APInt::getLowBitsSet(
13623                                          N->getValueSizeInBits(0), PromBits),
13624                                        dl, N->getValueType(0)));
13625 
13626   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13627          "Invalid extension type");
13628   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13629   SDValue ShiftCst =
13630       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13631   return DAG.getNode(
13632       ISD::SRA, dl, N->getValueType(0),
13633       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13634       ShiftCst);
13635 }
13636 
13637 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13638                                         DAGCombinerInfo &DCI) const {
13639   assert(N->getOpcode() == ISD::SETCC &&
13640          "Should be called with a SETCC node");
13641 
13642   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13643   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13644     SDValue LHS = N->getOperand(0);
13645     SDValue RHS = N->getOperand(1);
13646 
13647     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13648     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13649         LHS.hasOneUse())
13650       std::swap(LHS, RHS);
13651 
13652     // x == 0-y --> x+y == 0
13653     // x != 0-y --> x+y != 0
13654     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13655         RHS.hasOneUse()) {
13656       SDLoc DL(N);
13657       SelectionDAG &DAG = DCI.DAG;
13658       EVT VT = N->getValueType(0);
13659       EVT OpVT = LHS.getValueType();
13660       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13661       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13662     }
13663   }
13664 
13665   return DAGCombineTruncBoolExt(N, DCI);
13666 }
13667 
13668 // Is this an extending load from an f32 to an f64?
13669 static bool isFPExtLoad(SDValue Op) {
13670   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13671     return LD->getExtensionType() == ISD::EXTLOAD &&
13672       Op.getValueType() == MVT::f64;
13673   return false;
13674 }
13675 
13676 /// Reduces the number of fp-to-int conversion when building a vector.
13677 ///
13678 /// If this vector is built out of floating to integer conversions,
13679 /// transform it to a vector built out of floating point values followed by a
13680 /// single floating to integer conversion of the vector.
13681 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13682 /// becomes (fptosi (build_vector ($A, $B, ...)))
13683 SDValue PPCTargetLowering::
13684 combineElementTruncationToVectorTruncation(SDNode *N,
13685                                            DAGCombinerInfo &DCI) const {
13686   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13687          "Should be called with a BUILD_VECTOR node");
13688 
13689   SelectionDAG &DAG = DCI.DAG;
13690   SDLoc dl(N);
13691 
13692   SDValue FirstInput = N->getOperand(0);
13693   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13694          "The input operand must be an fp-to-int conversion.");
13695 
13696   // This combine happens after legalization so the fp_to_[su]i nodes are
13697   // already converted to PPCSISD nodes.
13698   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13699   if (FirstConversion == PPCISD::FCTIDZ ||
13700       FirstConversion == PPCISD::FCTIDUZ ||
13701       FirstConversion == PPCISD::FCTIWZ ||
13702       FirstConversion == PPCISD::FCTIWUZ) {
13703     bool IsSplat = true;
13704     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13705       FirstConversion == PPCISD::FCTIWUZ;
13706     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13707     SmallVector<SDValue, 4> Ops;
13708     EVT TargetVT = N->getValueType(0);
13709     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13710       SDValue NextOp = N->getOperand(i);
13711       if (NextOp.getOpcode() != PPCISD::MFVSR)
13712         return SDValue();
13713       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13714       if (NextConversion != FirstConversion)
13715         return SDValue();
13716       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13717       // This is not valid if the input was originally double precision. It is
13718       // also not profitable to do unless this is an extending load in which
13719       // case doing this combine will allow us to combine consecutive loads.
13720       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13721         return SDValue();
13722       if (N->getOperand(i) != FirstInput)
13723         IsSplat = false;
13724     }
13725 
13726     // If this is a splat, we leave it as-is since there will be only a single
13727     // fp-to-int conversion followed by a splat of the integer. This is better
13728     // for 32-bit and smaller ints and neutral for 64-bit ints.
13729     if (IsSplat)
13730       return SDValue();
13731 
13732     // Now that we know we have the right type of node, get its operands
13733     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13734       SDValue In = N->getOperand(i).getOperand(0);
13735       if (Is32Bit) {
13736         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13737         // here, we know that all inputs are extending loads so this is safe).
13738         if (In.isUndef())
13739           Ops.push_back(DAG.getUNDEF(SrcVT));
13740         else {
13741           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13742                                       MVT::f32, In.getOperand(0),
13743                                       DAG.getIntPtrConstant(1, dl));
13744           Ops.push_back(Trunc);
13745         }
13746       } else
13747         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13748     }
13749 
13750     unsigned Opcode;
13751     if (FirstConversion == PPCISD::FCTIDZ ||
13752         FirstConversion == PPCISD::FCTIWZ)
13753       Opcode = ISD::FP_TO_SINT;
13754     else
13755       Opcode = ISD::FP_TO_UINT;
13756 
13757     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13758     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13759     return DAG.getNode(Opcode, dl, TargetVT, BV);
13760   }
13761   return SDValue();
13762 }
13763 
13764 /// Reduce the number of loads when building a vector.
13765 ///
13766 /// Building a vector out of multiple loads can be converted to a load
13767 /// of the vector type if the loads are consecutive. If the loads are
13768 /// consecutive but in descending order, a shuffle is added at the end
13769 /// to reorder the vector.
13770 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13771   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13772          "Should be called with a BUILD_VECTOR node");
13773 
13774   SDLoc dl(N);
13775 
13776   // Return early for non byte-sized type, as they can't be consecutive.
13777   if (!N->getValueType(0).getVectorElementType().isByteSized())
13778     return SDValue();
13779 
13780   bool InputsAreConsecutiveLoads = true;
13781   bool InputsAreReverseConsecutive = true;
13782   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13783   SDValue FirstInput = N->getOperand(0);
13784   bool IsRoundOfExtLoad = false;
13785 
13786   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13787       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13788     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13789     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13790   }
13791   // Not a build vector of (possibly fp_rounded) loads.
13792   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13793       N->getNumOperands() == 1)
13794     return SDValue();
13795 
13796   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13797     // If any inputs are fp_round(extload), they all must be.
13798     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13799       return SDValue();
13800 
13801     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13802       N->getOperand(i);
13803     if (NextInput.getOpcode() != ISD::LOAD)
13804       return SDValue();
13805 
13806     SDValue PreviousInput =
13807       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13808     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13809     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13810 
13811     // If any inputs are fp_round(extload), they all must be.
13812     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13813       return SDValue();
13814 
13815     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13816       InputsAreConsecutiveLoads = false;
13817     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13818       InputsAreReverseConsecutive = false;
13819 
13820     // Exit early if the loads are neither consecutive nor reverse consecutive.
13821     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13822       return SDValue();
13823   }
13824 
13825   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13826          "The loads cannot be both consecutive and reverse consecutive.");
13827 
13828   SDValue FirstLoadOp =
13829     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13830   SDValue LastLoadOp =
13831     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13832                        N->getOperand(N->getNumOperands()-1);
13833 
13834   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13835   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13836   if (InputsAreConsecutiveLoads) {
13837     assert(LD1 && "Input needs to be a LoadSDNode.");
13838     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13839                        LD1->getBasePtr(), LD1->getPointerInfo(),
13840                        LD1->getAlignment());
13841   }
13842   if (InputsAreReverseConsecutive) {
13843     assert(LDL && "Input needs to be a LoadSDNode.");
13844     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13845                                LDL->getBasePtr(), LDL->getPointerInfo(),
13846                                LDL->getAlignment());
13847     SmallVector<int, 16> Ops;
13848     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13849       Ops.push_back(i);
13850 
13851     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13852                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13853   }
13854   return SDValue();
13855 }
13856 
13857 // This function adds the required vector_shuffle needed to get
13858 // the elements of the vector extract in the correct position
13859 // as specified by the CorrectElems encoding.
13860 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13861                                       SDValue Input, uint64_t Elems,
13862                                       uint64_t CorrectElems) {
13863   SDLoc dl(N);
13864 
13865   unsigned NumElems = Input.getValueType().getVectorNumElements();
13866   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13867 
13868   // Knowing the element indices being extracted from the original
13869   // vector and the order in which they're being inserted, just put
13870   // them at element indices required for the instruction.
13871   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13872     if (DAG.getDataLayout().isLittleEndian())
13873       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13874     else
13875       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13876     CorrectElems = CorrectElems >> 8;
13877     Elems = Elems >> 8;
13878   }
13879 
13880   SDValue Shuffle =
13881       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13882                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13883 
13884   EVT VT = N->getValueType(0);
13885   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13886 
13887   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13888                                Input.getValueType().getVectorElementType(),
13889                                VT.getVectorNumElements());
13890   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13891                      DAG.getValueType(ExtVT));
13892 }
13893 
13894 // Look for build vector patterns where input operands come from sign
13895 // extended vector_extract elements of specific indices. If the correct indices
13896 // aren't used, add a vector shuffle to fix up the indices and create
13897 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13898 // during instruction selection.
13899 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13900   // This array encodes the indices that the vector sign extend instructions
13901   // extract from when extending from one type to another for both BE and LE.
13902   // The right nibble of each byte corresponds to the LE incides.
13903   // and the left nibble of each byte corresponds to the BE incides.
13904   // For example: 0x3074B8FC  byte->word
13905   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13906   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13907   // For example: 0x000070F8  byte->double word
13908   // For LE: the allowed indices are: 0x0,0x8
13909   // For BE: the allowed indices are: 0x7,0xF
13910   uint64_t TargetElems[] = {
13911       0x3074B8FC, // b->w
13912       0x000070F8, // b->d
13913       0x10325476, // h->w
13914       0x00003074, // h->d
13915       0x00001032, // w->d
13916   };
13917 
13918   uint64_t Elems = 0;
13919   int Index;
13920   SDValue Input;
13921 
13922   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13923     if (!Op)
13924       return false;
13925     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13926         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13927       return false;
13928 
13929     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13930     // of the right width.
13931     SDValue Extract = Op.getOperand(0);
13932     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13933       Extract = Extract.getOperand(0);
13934     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13935       return false;
13936 
13937     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13938     if (!ExtOp)
13939       return false;
13940 
13941     Index = ExtOp->getZExtValue();
13942     if (Input && Input != Extract.getOperand(0))
13943       return false;
13944 
13945     if (!Input)
13946       Input = Extract.getOperand(0);
13947 
13948     Elems = Elems << 8;
13949     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13950     Elems |= Index;
13951 
13952     return true;
13953   };
13954 
13955   // If the build vector operands aren't sign extended vector extracts,
13956   // of the same input vector, then return.
13957   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13958     if (!isSExtOfVecExtract(N->getOperand(i))) {
13959       return SDValue();
13960     }
13961   }
13962 
13963   // If the vector extract indicies are not correct, add the appropriate
13964   // vector_shuffle.
13965   int TgtElemArrayIdx;
13966   int InputSize = Input.getValueType().getScalarSizeInBits();
13967   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13968   if (InputSize + OutputSize == 40)
13969     TgtElemArrayIdx = 0;
13970   else if (InputSize + OutputSize == 72)
13971     TgtElemArrayIdx = 1;
13972   else if (InputSize + OutputSize == 48)
13973     TgtElemArrayIdx = 2;
13974   else if (InputSize + OutputSize == 80)
13975     TgtElemArrayIdx = 3;
13976   else if (InputSize + OutputSize == 96)
13977     TgtElemArrayIdx = 4;
13978   else
13979     return SDValue();
13980 
13981   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13982   CorrectElems = DAG.getDataLayout().isLittleEndian()
13983                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13984                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13985   if (Elems != CorrectElems) {
13986     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13987   }
13988 
13989   // Regular lowering will catch cases where a shuffle is not needed.
13990   return SDValue();
13991 }
13992 
13993 // Look for the pattern of a load from a narrow width to i128, feeding
13994 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
13995 // (LXVRZX). This node represents a zero extending load that will be matched
13996 // to the Load VSX Vector Rightmost instructions.
13997 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
13998   SDLoc DL(N);
13999 
14000   // This combine is only eligible for a BUILD_VECTOR of v1i128.
14001   if (N->getValueType(0) != MVT::v1i128)
14002     return SDValue();
14003 
14004   SDValue Operand = N->getOperand(0);
14005   // Proceed with the transformation if the operand to the BUILD_VECTOR
14006   // is a load instruction.
14007   if (Operand.getOpcode() != ISD::LOAD)
14008     return SDValue();
14009 
14010   LoadSDNode *LD = dyn_cast<LoadSDNode>(Operand);
14011   EVT MemoryType = LD->getMemoryVT();
14012 
14013   // This transformation is only valid if the we are loading either a byte,
14014   // halfword, word, or doubleword.
14015   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
14016                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
14017 
14018   // Ensure that the load from the narrow width is being zero extended to i128.
14019   if (!ValidLDType ||
14020       (LD->getExtensionType() != ISD::ZEXTLOAD &&
14021        LD->getExtensionType() != ISD::EXTLOAD))
14022     return SDValue();
14023 
14024   SDValue LoadOps[] = {
14025       LD->getChain(), LD->getBasePtr(),
14026       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
14027 
14028   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
14029                                  DAG.getVTList(MVT::v1i128, MVT::Other),
14030                                  LoadOps, MemoryType, LD->getMemOperand());
14031 }
14032 
14033 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
14034                                                  DAGCombinerInfo &DCI) const {
14035   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14036          "Should be called with a BUILD_VECTOR node");
14037 
14038   SelectionDAG &DAG = DCI.DAG;
14039   SDLoc dl(N);
14040 
14041   if (!Subtarget.hasVSX())
14042     return SDValue();
14043 
14044   // The target independent DAG combiner will leave a build_vector of
14045   // float-to-int conversions intact. We can generate MUCH better code for
14046   // a float-to-int conversion of a vector of floats.
14047   SDValue FirstInput = N->getOperand(0);
14048   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
14049     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
14050     if (Reduced)
14051       return Reduced;
14052   }
14053 
14054   // If we're building a vector out of consecutive loads, just load that
14055   // vector type.
14056   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
14057   if (Reduced)
14058     return Reduced;
14059 
14060   // If we're building a vector out of extended elements from another vector
14061   // we have P9 vector integer extend instructions. The code assumes legal
14062   // input types (i.e. it can't handle things like v4i16) so do not run before
14063   // legalization.
14064   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
14065     Reduced = combineBVOfVecSExt(N, DAG);
14066     if (Reduced)
14067       return Reduced;
14068   }
14069 
14070   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
14071   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
14072   // is a load from <valid narrow width> to i128.
14073   if (Subtarget.isISA3_1()) {
14074     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
14075     if (BVOfZLoad)
14076       return BVOfZLoad;
14077   }
14078 
14079   if (N->getValueType(0) != MVT::v2f64)
14080     return SDValue();
14081 
14082   // Looking for:
14083   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
14084   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
14085       FirstInput.getOpcode() != ISD::UINT_TO_FP)
14086     return SDValue();
14087   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
14088       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
14089     return SDValue();
14090   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
14091     return SDValue();
14092 
14093   SDValue Ext1 = FirstInput.getOperand(0);
14094   SDValue Ext2 = N->getOperand(1).getOperand(0);
14095   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14096      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14097     return SDValue();
14098 
14099   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
14100   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
14101   if (!Ext1Op || !Ext2Op)
14102     return SDValue();
14103   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
14104       Ext1.getOperand(0) != Ext2.getOperand(0))
14105     return SDValue();
14106 
14107   int FirstElem = Ext1Op->getZExtValue();
14108   int SecondElem = Ext2Op->getZExtValue();
14109   int SubvecIdx;
14110   if (FirstElem == 0 && SecondElem == 1)
14111     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
14112   else if (FirstElem == 2 && SecondElem == 3)
14113     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
14114   else
14115     return SDValue();
14116 
14117   SDValue SrcVec = Ext1.getOperand(0);
14118   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
14119     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
14120   return DAG.getNode(NodeType, dl, MVT::v2f64,
14121                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
14122 }
14123 
14124 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
14125                                               DAGCombinerInfo &DCI) const {
14126   assert((N->getOpcode() == ISD::SINT_TO_FP ||
14127           N->getOpcode() == ISD::UINT_TO_FP) &&
14128          "Need an int -> FP conversion node here");
14129 
14130   if (useSoftFloat() || !Subtarget.has64BitSupport())
14131     return SDValue();
14132 
14133   SelectionDAG &DAG = DCI.DAG;
14134   SDLoc dl(N);
14135   SDValue Op(N, 0);
14136 
14137   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
14138   // from the hardware.
14139   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
14140     return SDValue();
14141   if (!Op.getOperand(0).getValueType().isSimple())
14142     return SDValue();
14143   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
14144       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
14145     return SDValue();
14146 
14147   SDValue FirstOperand(Op.getOperand(0));
14148   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
14149     (FirstOperand.getValueType() == MVT::i8 ||
14150      FirstOperand.getValueType() == MVT::i16);
14151   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
14152     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
14153     bool DstDouble = Op.getValueType() == MVT::f64;
14154     unsigned ConvOp = Signed ?
14155       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
14156       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
14157     SDValue WidthConst =
14158       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
14159                             dl, false);
14160     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
14161     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
14162     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
14163                                          DAG.getVTList(MVT::f64, MVT::Other),
14164                                          Ops, MVT::i8, LDN->getMemOperand());
14165 
14166     // For signed conversion, we need to sign-extend the value in the VSR
14167     if (Signed) {
14168       SDValue ExtOps[] = { Ld, WidthConst };
14169       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
14170       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
14171     } else
14172       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
14173   }
14174 
14175 
14176   // For i32 intermediate values, unfortunately, the conversion functions
14177   // leave the upper 32 bits of the value are undefined. Within the set of
14178   // scalar instructions, we have no method for zero- or sign-extending the
14179   // value. Thus, we cannot handle i32 intermediate values here.
14180   if (Op.getOperand(0).getValueType() == MVT::i32)
14181     return SDValue();
14182 
14183   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
14184          "UINT_TO_FP is supported only with FPCVT");
14185 
14186   // If we have FCFIDS, then use it when converting to single-precision.
14187   // Otherwise, convert to double-precision and then round.
14188   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14189                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
14190                                                             : PPCISD::FCFIDS)
14191                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
14192                                                             : PPCISD::FCFID);
14193   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14194                   ? MVT::f32
14195                   : MVT::f64;
14196 
14197   // If we're converting from a float, to an int, and back to a float again,
14198   // then we don't need the store/load pair at all.
14199   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
14200        Subtarget.hasFPCVT()) ||
14201       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
14202     SDValue Src = Op.getOperand(0).getOperand(0);
14203     if (Src.getValueType() == MVT::f32) {
14204       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
14205       DCI.AddToWorklist(Src.getNode());
14206     } else if (Src.getValueType() != MVT::f64) {
14207       // Make sure that we don't pick up a ppc_fp128 source value.
14208       return SDValue();
14209     }
14210 
14211     unsigned FCTOp =
14212       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
14213                                                         PPCISD::FCTIDUZ;
14214 
14215     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
14216     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
14217 
14218     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
14219       FP = DAG.getNode(ISD::FP_ROUND, dl,
14220                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
14221       DCI.AddToWorklist(FP.getNode());
14222     }
14223 
14224     return FP;
14225   }
14226 
14227   return SDValue();
14228 }
14229 
14230 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
14231 // builtins) into loads with swaps.
14232 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
14233                                               DAGCombinerInfo &DCI) const {
14234   SelectionDAG &DAG = DCI.DAG;
14235   SDLoc dl(N);
14236   SDValue Chain;
14237   SDValue Base;
14238   MachineMemOperand *MMO;
14239 
14240   switch (N->getOpcode()) {
14241   default:
14242     llvm_unreachable("Unexpected opcode for little endian VSX load");
14243   case ISD::LOAD: {
14244     LoadSDNode *LD = cast<LoadSDNode>(N);
14245     Chain = LD->getChain();
14246     Base = LD->getBasePtr();
14247     MMO = LD->getMemOperand();
14248     // If the MMO suggests this isn't a load of a full vector, leave
14249     // things alone.  For a built-in, we have to make the change for
14250     // correctness, so if there is a size problem that will be a bug.
14251     if (MMO->getSize() < 16)
14252       return SDValue();
14253     break;
14254   }
14255   case ISD::INTRINSIC_W_CHAIN: {
14256     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14257     Chain = Intrin->getChain();
14258     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
14259     // us what we want. Get operand 2 instead.
14260     Base = Intrin->getOperand(2);
14261     MMO = Intrin->getMemOperand();
14262     break;
14263   }
14264   }
14265 
14266   MVT VecTy = N->getValueType(0).getSimpleVT();
14267 
14268   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
14269   // aligned and the type is a vector with elements up to 4 bytes
14270   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14271       VecTy.getScalarSizeInBits() <= 32) {
14272     return SDValue();
14273   }
14274 
14275   SDValue LoadOps[] = { Chain, Base };
14276   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14277                                          DAG.getVTList(MVT::v2f64, MVT::Other),
14278                                          LoadOps, MVT::v2f64, MMO);
14279 
14280   DCI.AddToWorklist(Load.getNode());
14281   Chain = Load.getValue(1);
14282   SDValue Swap = DAG.getNode(
14283       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14284   DCI.AddToWorklist(Swap.getNode());
14285 
14286   // Add a bitcast if the resulting load type doesn't match v2f64.
14287   if (VecTy != MVT::v2f64) {
14288     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14289     DCI.AddToWorklist(N.getNode());
14290     // Package {bitcast value, swap's chain} to match Load's shape.
14291     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14292                        N, Swap.getValue(1));
14293   }
14294 
14295   return Swap;
14296 }
14297 
14298 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14299 // builtins) into stores with swaps.
14300 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14301                                                DAGCombinerInfo &DCI) const {
14302   SelectionDAG &DAG = DCI.DAG;
14303   SDLoc dl(N);
14304   SDValue Chain;
14305   SDValue Base;
14306   unsigned SrcOpnd;
14307   MachineMemOperand *MMO;
14308 
14309   switch (N->getOpcode()) {
14310   default:
14311     llvm_unreachable("Unexpected opcode for little endian VSX store");
14312   case ISD::STORE: {
14313     StoreSDNode *ST = cast<StoreSDNode>(N);
14314     Chain = ST->getChain();
14315     Base = ST->getBasePtr();
14316     MMO = ST->getMemOperand();
14317     SrcOpnd = 1;
14318     // If the MMO suggests this isn't a store of a full vector, leave
14319     // things alone.  For a built-in, we have to make the change for
14320     // correctness, so if there is a size problem that will be a bug.
14321     if (MMO->getSize() < 16)
14322       return SDValue();
14323     break;
14324   }
14325   case ISD::INTRINSIC_VOID: {
14326     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14327     Chain = Intrin->getChain();
14328     // Intrin->getBasePtr() oddly does not get what we want.
14329     Base = Intrin->getOperand(3);
14330     MMO = Intrin->getMemOperand();
14331     SrcOpnd = 2;
14332     break;
14333   }
14334   }
14335 
14336   SDValue Src = N->getOperand(SrcOpnd);
14337   MVT VecTy = Src.getValueType().getSimpleVT();
14338 
14339   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14340   // aligned and the type is a vector with elements up to 4 bytes
14341   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14342       VecTy.getScalarSizeInBits() <= 32) {
14343     return SDValue();
14344   }
14345 
14346   // All stores are done as v2f64 and possible bit cast.
14347   if (VecTy != MVT::v2f64) {
14348     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14349     DCI.AddToWorklist(Src.getNode());
14350   }
14351 
14352   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14353                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14354   DCI.AddToWorklist(Swap.getNode());
14355   Chain = Swap.getValue(1);
14356   SDValue StoreOps[] = { Chain, Swap, Base };
14357   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14358                                           DAG.getVTList(MVT::Other),
14359                                           StoreOps, VecTy, MMO);
14360   DCI.AddToWorklist(Store.getNode());
14361   return Store;
14362 }
14363 
14364 // Handle DAG combine for STORE (FP_TO_INT F).
14365 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14366                                                DAGCombinerInfo &DCI) const {
14367 
14368   SelectionDAG &DAG = DCI.DAG;
14369   SDLoc dl(N);
14370   unsigned Opcode = N->getOperand(1).getOpcode();
14371 
14372   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14373          && "Not a FP_TO_INT Instruction!");
14374 
14375   SDValue Val = N->getOperand(1).getOperand(0);
14376   EVT Op1VT = N->getOperand(1).getValueType();
14377   EVT ResVT = Val.getValueType();
14378 
14379   if (!isTypeLegal(ResVT))
14380     return SDValue();
14381 
14382   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14383   bool ValidTypeForStoreFltAsInt =
14384         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14385          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14386 
14387   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14388       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14389     return SDValue();
14390 
14391   // Extend f32 values to f64
14392   if (ResVT.getScalarSizeInBits() == 32) {
14393     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14394     DCI.AddToWorklist(Val.getNode());
14395   }
14396 
14397   // Set signed or unsigned conversion opcode.
14398   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14399                           PPCISD::FP_TO_SINT_IN_VSR :
14400                           PPCISD::FP_TO_UINT_IN_VSR;
14401 
14402   Val = DAG.getNode(ConvOpcode,
14403                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14404   DCI.AddToWorklist(Val.getNode());
14405 
14406   // Set number of bytes being converted.
14407   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14408   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14409                     DAG.getIntPtrConstant(ByteSize, dl, false),
14410                     DAG.getValueType(Op1VT) };
14411 
14412   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14413           DAG.getVTList(MVT::Other), Ops,
14414           cast<StoreSDNode>(N)->getMemoryVT(),
14415           cast<StoreSDNode>(N)->getMemOperand());
14416 
14417   DCI.AddToWorklist(Val.getNode());
14418   return Val;
14419 }
14420 
14421 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14422   // Check that the source of the element keeps flipping
14423   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14424   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14425   for (int i = 1, e = Mask.size(); i < e; i++) {
14426     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14427       return false;
14428     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14429       return false;
14430     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14431   }
14432   return true;
14433 }
14434 
14435 static bool isSplatBV(SDValue Op) {
14436   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14437     return false;
14438   SDValue FirstOp;
14439 
14440   // Find first non-undef input.
14441   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14442     FirstOp = Op.getOperand(i);
14443     if (!FirstOp.isUndef())
14444       break;
14445   }
14446 
14447   // All inputs are undef or the same as the first non-undef input.
14448   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14449     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14450       return false;
14451   return true;
14452 }
14453 
14454 static SDValue isScalarToVec(SDValue Op) {
14455   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14456     return Op;
14457   if (Op.getOpcode() != ISD::BITCAST)
14458     return SDValue();
14459   Op = Op.getOperand(0);
14460   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14461     return Op;
14462   return SDValue();
14463 }
14464 
14465 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14466                                             int LHSMaxIdx, int RHSMinIdx,
14467                                             int RHSMaxIdx, int HalfVec) {
14468   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14469     int Idx = ShuffV[i];
14470     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14471       ShuffV[i] += HalfVec;
14472   }
14473   return;
14474 }
14475 
14476 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14477 // the original is:
14478 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14479 // In such a case, just change the shuffle mask to extract the element
14480 // from the permuted index.
14481 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) {
14482   SDLoc dl(OrigSToV);
14483   EVT VT = OrigSToV.getValueType();
14484   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14485          "Expecting a SCALAR_TO_VECTOR here");
14486   SDValue Input = OrigSToV.getOperand(0);
14487 
14488   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14489     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14490     SDValue OrigVector = Input.getOperand(0);
14491 
14492     // Can't handle non-const element indices or different vector types
14493     // for the input to the extract and the output of the scalar_to_vector.
14494     if (Idx && VT == OrigVector.getValueType()) {
14495       SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1);
14496       NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue();
14497       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14498     }
14499   }
14500   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14501                      OrigSToV.getOperand(0));
14502 }
14503 
14504 // On little endian subtargets, combine shuffles such as:
14505 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14506 // into:
14507 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14508 // because the latter can be matched to a single instruction merge.
14509 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14510 // to put the value into element zero. Adjust the shuffle mask so that the
14511 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14512 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14513                                                 SelectionDAG &DAG) const {
14514   SDValue LHS = SVN->getOperand(0);
14515   SDValue RHS = SVN->getOperand(1);
14516   auto Mask = SVN->getMask();
14517   int NumElts = LHS.getValueType().getVectorNumElements();
14518   SDValue Res(SVN, 0);
14519   SDLoc dl(SVN);
14520 
14521   // None of these combines are useful on big endian systems since the ISA
14522   // already has a big endian bias.
14523   if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14524     return Res;
14525 
14526   // If this is not a shuffle of a shuffle and the first element comes from
14527   // the second vector, canonicalize to the commuted form. This will make it
14528   // more likely to match one of the single instruction patterns.
14529   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14530       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14531     std::swap(LHS, RHS);
14532     Res = DAG.getCommutedVectorShuffle(*SVN);
14533     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14534   }
14535 
14536   // Adjust the shuffle mask if either input vector comes from a
14537   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14538   // form (to prevent the need for a swap).
14539   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14540   SDValue SToVLHS = isScalarToVec(LHS);
14541   SDValue SToVRHS = isScalarToVec(RHS);
14542   if (SToVLHS || SToVRHS) {
14543     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14544                             : SToVRHS.getValueType().getVectorNumElements();
14545     int NumEltsOut = ShuffV.size();
14546 
14547     // Initially assume that neither input is permuted. These will be adjusted
14548     // accordingly if either input is.
14549     int LHSMaxIdx = -1;
14550     int RHSMinIdx = -1;
14551     int RHSMaxIdx = -1;
14552     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14553 
14554     // Get the permuted scalar to vector nodes for the source(s) that come from
14555     // ISD::SCALAR_TO_VECTOR.
14556     if (SToVLHS) {
14557       // Set up the values for the shuffle vector fixup.
14558       LHSMaxIdx = NumEltsOut / NumEltsIn;
14559       SToVLHS = getSToVPermuted(SToVLHS, DAG);
14560       if (SToVLHS.getValueType() != LHS.getValueType())
14561         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14562       LHS = SToVLHS;
14563     }
14564     if (SToVRHS) {
14565       RHSMinIdx = NumEltsOut;
14566       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14567       SToVRHS = getSToVPermuted(SToVRHS, DAG);
14568       if (SToVRHS.getValueType() != RHS.getValueType())
14569         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14570       RHS = SToVRHS;
14571     }
14572 
14573     // Fix up the shuffle mask to reflect where the desired element actually is.
14574     // The minimum and maximum indices that correspond to element zero for both
14575     // the LHS and RHS are computed and will control which shuffle mask entries
14576     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14577     // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by
14578     // HalfVec to refer to the corresponding element in the permuted vector.
14579     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14580                                     HalfVec);
14581     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14582 
14583     // We may have simplified away the shuffle. We won't be able to do anything
14584     // further with it here.
14585     if (!isa<ShuffleVectorSDNode>(Res))
14586       return Res;
14587     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14588   }
14589 
14590   // The common case after we commuted the shuffle is that the RHS is a splat
14591   // and we have elements coming in from the splat at indices that are not
14592   // conducive to using a merge.
14593   // Example:
14594   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14595   if (!isSplatBV(RHS))
14596     return Res;
14597 
14598   // We are looking for a mask such that all even elements are from
14599   // one vector and all odd elements from the other.
14600   if (!isAlternatingShuffMask(Mask, NumElts))
14601     return Res;
14602 
14603   // Adjust the mask so we are pulling in the same index from the splat
14604   // as the index from the interesting vector in consecutive elements.
14605   // Example (even elements from first vector):
14606   // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14607   if (Mask[0] < NumElts)
14608     for (int i = 1, e = Mask.size(); i < e; i += 2)
14609       ShuffV[i] = (ShuffV[i - 1] + NumElts);
14610   // Example (odd elements from first vector):
14611   // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14612   else
14613     for (int i = 0, e = Mask.size(); i < e; i += 2)
14614       ShuffV[i] = (ShuffV[i + 1] + NumElts);
14615 
14616   // If the RHS has undefs, we need to remove them since we may have created
14617   // a shuffle that adds those instead of the splat value.
14618   SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue();
14619   RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal);
14620 
14621   Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14622   return Res;
14623 }
14624 
14625 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14626                                                 LSBaseSDNode *LSBase,
14627                                                 DAGCombinerInfo &DCI) const {
14628   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14629         "Not a reverse memop pattern!");
14630 
14631   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14632     auto Mask = SVN->getMask();
14633     int i = 0;
14634     auto I = Mask.rbegin();
14635     auto E = Mask.rend();
14636 
14637     for (; I != E; ++I) {
14638       if (*I != i)
14639         return false;
14640       i++;
14641     }
14642     return true;
14643   };
14644 
14645   SelectionDAG &DAG = DCI.DAG;
14646   EVT VT = SVN->getValueType(0);
14647 
14648   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14649     return SDValue();
14650 
14651   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14652   // See comment in PPCVSXSwapRemoval.cpp.
14653   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14654   if (!Subtarget.hasP9Vector())
14655     return SDValue();
14656 
14657   if(!IsElementReverse(SVN))
14658     return SDValue();
14659 
14660   if (LSBase->getOpcode() == ISD::LOAD) {
14661     SDLoc dl(SVN);
14662     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14663     return DAG.getMemIntrinsicNode(
14664         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14665         LSBase->getMemoryVT(), LSBase->getMemOperand());
14666   }
14667 
14668   if (LSBase->getOpcode() == ISD::STORE) {
14669     SDLoc dl(LSBase);
14670     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14671                           LSBase->getBasePtr()};
14672     return DAG.getMemIntrinsicNode(
14673         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14674         LSBase->getMemoryVT(), LSBase->getMemOperand());
14675   }
14676 
14677   llvm_unreachable("Expected a load or store node here");
14678 }
14679 
14680 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14681                                              DAGCombinerInfo &DCI) const {
14682   SelectionDAG &DAG = DCI.DAG;
14683   SDLoc dl(N);
14684   switch (N->getOpcode()) {
14685   default: break;
14686   case ISD::ADD:
14687     return combineADD(N, DCI);
14688   case ISD::SHL:
14689     return combineSHL(N, DCI);
14690   case ISD::SRA:
14691     return combineSRA(N, DCI);
14692   case ISD::SRL:
14693     return combineSRL(N, DCI);
14694   case ISD::MUL:
14695     return combineMUL(N, DCI);
14696   case ISD::FMA:
14697   case PPCISD::FNMSUB:
14698     return combineFMALike(N, DCI);
14699   case PPCISD::SHL:
14700     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14701         return N->getOperand(0);
14702     break;
14703   case PPCISD::SRL:
14704     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14705         return N->getOperand(0);
14706     break;
14707   case PPCISD::SRA:
14708     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14709       if (C->isNullValue() ||   //  0 >>s V -> 0.
14710           C->isAllOnesValue())    // -1 >>s V -> -1.
14711         return N->getOperand(0);
14712     }
14713     break;
14714   case ISD::SIGN_EXTEND:
14715   case ISD::ZERO_EXTEND:
14716   case ISD::ANY_EXTEND:
14717     return DAGCombineExtBoolTrunc(N, DCI);
14718   case ISD::TRUNCATE:
14719     return combineTRUNCATE(N, DCI);
14720   case ISD::SETCC:
14721     if (SDValue CSCC = combineSetCC(N, DCI))
14722       return CSCC;
14723     LLVM_FALLTHROUGH;
14724   case ISD::SELECT_CC:
14725     return DAGCombineTruncBoolExt(N, DCI);
14726   case ISD::SINT_TO_FP:
14727   case ISD::UINT_TO_FP:
14728     return combineFPToIntToFP(N, DCI);
14729   case ISD::VECTOR_SHUFFLE:
14730     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14731       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14732       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14733     }
14734     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14735   case ISD::STORE: {
14736 
14737     EVT Op1VT = N->getOperand(1).getValueType();
14738     unsigned Opcode = N->getOperand(1).getOpcode();
14739 
14740     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14741       SDValue Val= combineStoreFPToInt(N, DCI);
14742       if (Val)
14743         return Val;
14744     }
14745 
14746     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14747       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14748       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14749       if (Val)
14750         return Val;
14751     }
14752 
14753     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14754     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14755         N->getOperand(1).getNode()->hasOneUse() &&
14756         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14757          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14758 
14759       // STBRX can only handle simple types and it makes no sense to store less
14760       // two bytes in byte-reversed order.
14761       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14762       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14763         break;
14764 
14765       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14766       // Do an any-extend to 32-bits if this is a half-word input.
14767       if (BSwapOp.getValueType() == MVT::i16)
14768         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14769 
14770       // If the type of BSWAP operand is wider than stored memory width
14771       // it need to be shifted to the right side before STBRX.
14772       if (Op1VT.bitsGT(mVT)) {
14773         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14774         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14775                               DAG.getConstant(Shift, dl, MVT::i32));
14776         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14777         if (Op1VT == MVT::i64)
14778           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14779       }
14780 
14781       SDValue Ops[] = {
14782         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14783       };
14784       return
14785         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14786                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14787                                 cast<StoreSDNode>(N)->getMemOperand());
14788     }
14789 
14790     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14791     // So it can increase the chance of CSE constant construction.
14792     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14793         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14794       // Need to sign-extended to 64-bits to handle negative values.
14795       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14796       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14797                                     MemVT.getSizeInBits());
14798       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14799 
14800       // DAG.getTruncStore() can't be used here because it doesn't accept
14801       // the general (base + offset) addressing mode.
14802       // So we use UpdateNodeOperands and setTruncatingStore instead.
14803       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14804                              N->getOperand(3));
14805       cast<StoreSDNode>(N)->setTruncatingStore(true);
14806       return SDValue(N, 0);
14807     }
14808 
14809     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14810     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14811     if (Op1VT.isSimple()) {
14812       MVT StoreVT = Op1VT.getSimpleVT();
14813       if (Subtarget.needsSwapsForVSXMemOps() &&
14814           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14815            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14816         return expandVSXStoreForLE(N, DCI);
14817     }
14818     break;
14819   }
14820   case ISD::LOAD: {
14821     LoadSDNode *LD = cast<LoadSDNode>(N);
14822     EVT VT = LD->getValueType(0);
14823 
14824     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14825     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14826     if (VT.isSimple()) {
14827       MVT LoadVT = VT.getSimpleVT();
14828       if (Subtarget.needsSwapsForVSXMemOps() &&
14829           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14830            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14831         return expandVSXLoadForLE(N, DCI);
14832     }
14833 
14834     // We sometimes end up with a 64-bit integer load, from which we extract
14835     // two single-precision floating-point numbers. This happens with
14836     // std::complex<float>, and other similar structures, because of the way we
14837     // canonicalize structure copies. However, if we lack direct moves,
14838     // then the final bitcasts from the extracted integer values to the
14839     // floating-point numbers turn into store/load pairs. Even with direct moves,
14840     // just loading the two floating-point numbers is likely better.
14841     auto ReplaceTwoFloatLoad = [&]() {
14842       if (VT != MVT::i64)
14843         return false;
14844 
14845       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14846           LD->isVolatile())
14847         return false;
14848 
14849       //  We're looking for a sequence like this:
14850       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14851       //      t16: i64 = srl t13, Constant:i32<32>
14852       //    t17: i32 = truncate t16
14853       //  t18: f32 = bitcast t17
14854       //    t19: i32 = truncate t13
14855       //  t20: f32 = bitcast t19
14856 
14857       if (!LD->hasNUsesOfValue(2, 0))
14858         return false;
14859 
14860       auto UI = LD->use_begin();
14861       while (UI.getUse().getResNo() != 0) ++UI;
14862       SDNode *Trunc = *UI++;
14863       while (UI.getUse().getResNo() != 0) ++UI;
14864       SDNode *RightShift = *UI;
14865       if (Trunc->getOpcode() != ISD::TRUNCATE)
14866         std::swap(Trunc, RightShift);
14867 
14868       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14869           Trunc->getValueType(0) != MVT::i32 ||
14870           !Trunc->hasOneUse())
14871         return false;
14872       if (RightShift->getOpcode() != ISD::SRL ||
14873           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14874           RightShift->getConstantOperandVal(1) != 32 ||
14875           !RightShift->hasOneUse())
14876         return false;
14877 
14878       SDNode *Trunc2 = *RightShift->use_begin();
14879       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14880           Trunc2->getValueType(0) != MVT::i32 ||
14881           !Trunc2->hasOneUse())
14882         return false;
14883 
14884       SDNode *Bitcast = *Trunc->use_begin();
14885       SDNode *Bitcast2 = *Trunc2->use_begin();
14886 
14887       if (Bitcast->getOpcode() != ISD::BITCAST ||
14888           Bitcast->getValueType(0) != MVT::f32)
14889         return false;
14890       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14891           Bitcast2->getValueType(0) != MVT::f32)
14892         return false;
14893 
14894       if (Subtarget.isLittleEndian())
14895         std::swap(Bitcast, Bitcast2);
14896 
14897       // Bitcast has the second float (in memory-layout order) and Bitcast2
14898       // has the first one.
14899 
14900       SDValue BasePtr = LD->getBasePtr();
14901       if (LD->isIndexed()) {
14902         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14903                "Non-pre-inc AM on PPC?");
14904         BasePtr =
14905           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14906                       LD->getOffset());
14907       }
14908 
14909       auto MMOFlags =
14910           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14911       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14912                                       LD->getPointerInfo(), LD->getAlignment(),
14913                                       MMOFlags, LD->getAAInfo());
14914       SDValue AddPtr =
14915         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14916                     BasePtr, DAG.getIntPtrConstant(4, dl));
14917       SDValue FloatLoad2 = DAG.getLoad(
14918           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14919           LD->getPointerInfo().getWithOffset(4),
14920           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14921 
14922       if (LD->isIndexed()) {
14923         // Note that DAGCombine should re-form any pre-increment load(s) from
14924         // what is produced here if that makes sense.
14925         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14926       }
14927 
14928       DCI.CombineTo(Bitcast2, FloatLoad);
14929       DCI.CombineTo(Bitcast, FloatLoad2);
14930 
14931       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14932                                     SDValue(FloatLoad2.getNode(), 1));
14933       return true;
14934     };
14935 
14936     if (ReplaceTwoFloatLoad())
14937       return SDValue(N, 0);
14938 
14939     EVT MemVT = LD->getMemoryVT();
14940     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14941     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
14942     if (LD->isUnindexed() && VT.isVector() &&
14943         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14944           // P8 and later hardware should just use LOAD.
14945           !Subtarget.hasP8Vector() &&
14946           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
14947            VT == MVT::v4f32))) &&
14948         LD->getAlign() < ABIAlignment) {
14949       // This is a type-legal unaligned Altivec load.
14950       SDValue Chain = LD->getChain();
14951       SDValue Ptr = LD->getBasePtr();
14952       bool isLittleEndian = Subtarget.isLittleEndian();
14953 
14954       // This implements the loading of unaligned vectors as described in
14955       // the venerable Apple Velocity Engine overview. Specifically:
14956       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14957       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14958       //
14959       // The general idea is to expand a sequence of one or more unaligned
14960       // loads into an alignment-based permutation-control instruction (lvsl
14961       // or lvsr), a series of regular vector loads (which always truncate
14962       // their input address to an aligned address), and a series of
14963       // permutations.  The results of these permutations are the requested
14964       // loaded values.  The trick is that the last "extra" load is not taken
14965       // from the address you might suspect (sizeof(vector) bytes after the
14966       // last requested load), but rather sizeof(vector) - 1 bytes after the
14967       // last requested vector. The point of this is to avoid a page fault if
14968       // the base address happened to be aligned. This works because if the
14969       // base address is aligned, then adding less than a full vector length
14970       // will cause the last vector in the sequence to be (re)loaded.
14971       // Otherwise, the next vector will be fetched as you might suspect was
14972       // necessary.
14973 
14974       // We might be able to reuse the permutation generation from
14975       // a different base address offset from this one by an aligned amount.
14976       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14977       // optimization later.
14978       Intrinsic::ID Intr, IntrLD, IntrPerm;
14979       MVT PermCntlTy, PermTy, LDTy;
14980       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14981                             : Intrinsic::ppc_altivec_lvsl;
14982       IntrLD = Intrinsic::ppc_altivec_lvx;
14983       IntrPerm = Intrinsic::ppc_altivec_vperm;
14984       PermCntlTy = MVT::v16i8;
14985       PermTy = MVT::v4i32;
14986       LDTy = MVT::v4i32;
14987 
14988       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14989 
14990       // Create the new MMO for the new base load. It is like the original MMO,
14991       // but represents an area in memory almost twice the vector size centered
14992       // on the original address. If the address is unaligned, we might start
14993       // reading up to (sizeof(vector)-1) bytes below the address of the
14994       // original unaligned load.
14995       MachineFunction &MF = DAG.getMachineFunction();
14996       MachineMemOperand *BaseMMO =
14997         MF.getMachineMemOperand(LD->getMemOperand(),
14998                                 -(long)MemVT.getStoreSize()+1,
14999                                 2*MemVT.getStoreSize()-1);
15000 
15001       // Create the new base load.
15002       SDValue LDXIntID =
15003           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
15004       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
15005       SDValue BaseLoad =
15006         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15007                                 DAG.getVTList(PermTy, MVT::Other),
15008                                 BaseLoadOps, LDTy, BaseMMO);
15009 
15010       // Note that the value of IncOffset (which is provided to the next
15011       // load's pointer info offset value, and thus used to calculate the
15012       // alignment), and the value of IncValue (which is actually used to
15013       // increment the pointer value) are different! This is because we
15014       // require the next load to appear to be aligned, even though it
15015       // is actually offset from the base pointer by a lesser amount.
15016       int IncOffset = VT.getSizeInBits() / 8;
15017       int IncValue = IncOffset;
15018 
15019       // Walk (both up and down) the chain looking for another load at the real
15020       // (aligned) offset (the alignment of the other load does not matter in
15021       // this case). If found, then do not use the offset reduction trick, as
15022       // that will prevent the loads from being later combined (as they would
15023       // otherwise be duplicates).
15024       if (!findConsecutiveLoad(LD, DAG))
15025         --IncValue;
15026 
15027       SDValue Increment =
15028           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
15029       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15030 
15031       MachineMemOperand *ExtraMMO =
15032         MF.getMachineMemOperand(LD->getMemOperand(),
15033                                 1, 2*MemVT.getStoreSize()-1);
15034       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
15035       SDValue ExtraLoad =
15036         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15037                                 DAG.getVTList(PermTy, MVT::Other),
15038                                 ExtraLoadOps, LDTy, ExtraMMO);
15039 
15040       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15041         BaseLoad.getValue(1), ExtraLoad.getValue(1));
15042 
15043       // Because vperm has a big-endian bias, we must reverse the order
15044       // of the input vectors and complement the permute control vector
15045       // when generating little endian code.  We have already handled the
15046       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
15047       // and ExtraLoad here.
15048       SDValue Perm;
15049       if (isLittleEndian)
15050         Perm = BuildIntrinsicOp(IntrPerm,
15051                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
15052       else
15053         Perm = BuildIntrinsicOp(IntrPerm,
15054                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
15055 
15056       if (VT != PermTy)
15057         Perm = Subtarget.hasAltivec()
15058                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
15059                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
15060                                  DAG.getTargetConstant(1, dl, MVT::i64));
15061                                // second argument is 1 because this rounding
15062                                // is always exact.
15063 
15064       // The output of the permutation is our loaded result, the TokenFactor is
15065       // our new chain.
15066       DCI.CombineTo(N, Perm, TF);
15067       return SDValue(N, 0);
15068     }
15069     }
15070     break;
15071     case ISD::INTRINSIC_WO_CHAIN: {
15072       bool isLittleEndian = Subtarget.isLittleEndian();
15073       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15074       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15075                                            : Intrinsic::ppc_altivec_lvsl);
15076       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
15077         SDValue Add = N->getOperand(1);
15078 
15079         int Bits = 4 /* 16 byte alignment */;
15080 
15081         if (DAG.MaskedValueIsZero(Add->getOperand(1),
15082                                   APInt::getAllOnesValue(Bits /* alignment */)
15083                                       .zext(Add.getScalarValueSizeInBits()))) {
15084           SDNode *BasePtr = Add->getOperand(0).getNode();
15085           for (SDNode::use_iterator UI = BasePtr->use_begin(),
15086                                     UE = BasePtr->use_end();
15087                UI != UE; ++UI) {
15088             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15089                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
15090                     IID) {
15091               // We've found another LVSL/LVSR, and this address is an aligned
15092               // multiple of that one. The results will be the same, so use the
15093               // one we've just found instead.
15094 
15095               return SDValue(*UI, 0);
15096             }
15097           }
15098         }
15099 
15100         if (isa<ConstantSDNode>(Add->getOperand(1))) {
15101           SDNode *BasePtr = Add->getOperand(0).getNode();
15102           for (SDNode::use_iterator UI = BasePtr->use_begin(),
15103                UE = BasePtr->use_end(); UI != UE; ++UI) {
15104             if (UI->getOpcode() == ISD::ADD &&
15105                 isa<ConstantSDNode>(UI->getOperand(1)) &&
15106                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
15107                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
15108                 (1ULL << Bits) == 0) {
15109               SDNode *OtherAdd = *UI;
15110               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
15111                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
15112                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15113                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
15114                   return SDValue(*VI, 0);
15115                 }
15116               }
15117             }
15118           }
15119         }
15120       }
15121 
15122       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
15123       // Expose the vabsduw/h/b opportunity for down stream
15124       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
15125           (IID == Intrinsic::ppc_altivec_vmaxsw ||
15126            IID == Intrinsic::ppc_altivec_vmaxsh ||
15127            IID == Intrinsic::ppc_altivec_vmaxsb)) {
15128         SDValue V1 = N->getOperand(1);
15129         SDValue V2 = N->getOperand(2);
15130         if ((V1.getSimpleValueType() == MVT::v4i32 ||
15131              V1.getSimpleValueType() == MVT::v8i16 ||
15132              V1.getSimpleValueType() == MVT::v16i8) &&
15133             V1.getSimpleValueType() == V2.getSimpleValueType()) {
15134           // (0-a, a)
15135           if (V1.getOpcode() == ISD::SUB &&
15136               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
15137               V1.getOperand(1) == V2) {
15138             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
15139           }
15140           // (a, 0-a)
15141           if (V2.getOpcode() == ISD::SUB &&
15142               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
15143               V2.getOperand(1) == V1) {
15144             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15145           }
15146           // (x-y, y-x)
15147           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
15148               V1.getOperand(0) == V2.getOperand(1) &&
15149               V1.getOperand(1) == V2.getOperand(0)) {
15150             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15151           }
15152         }
15153       }
15154     }
15155 
15156     break;
15157   case ISD::INTRINSIC_W_CHAIN:
15158     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15159     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15160     if (Subtarget.needsSwapsForVSXMemOps()) {
15161       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15162       default:
15163         break;
15164       case Intrinsic::ppc_vsx_lxvw4x:
15165       case Intrinsic::ppc_vsx_lxvd2x:
15166         return expandVSXLoadForLE(N, DCI);
15167       }
15168     }
15169     break;
15170   case ISD::INTRINSIC_VOID:
15171     // For little endian, VSX stores require generating xxswapd/stxvd2x.
15172     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15173     if (Subtarget.needsSwapsForVSXMemOps()) {
15174       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15175       default:
15176         break;
15177       case Intrinsic::ppc_vsx_stxvw4x:
15178       case Intrinsic::ppc_vsx_stxvd2x:
15179         return expandVSXStoreForLE(N, DCI);
15180       }
15181     }
15182     break;
15183   case ISD::BSWAP:
15184     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
15185     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
15186         N->getOperand(0).hasOneUse() &&
15187         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
15188          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
15189           N->getValueType(0) == MVT::i64))) {
15190       SDValue Load = N->getOperand(0);
15191       LoadSDNode *LD = cast<LoadSDNode>(Load);
15192       // Create the byte-swapping load.
15193       SDValue Ops[] = {
15194         LD->getChain(),    // Chain
15195         LD->getBasePtr(),  // Ptr
15196         DAG.getValueType(N->getValueType(0)) // VT
15197       };
15198       SDValue BSLoad =
15199         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
15200                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
15201                                               MVT::i64 : MVT::i32, MVT::Other),
15202                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
15203 
15204       // If this is an i16 load, insert the truncate.
15205       SDValue ResVal = BSLoad;
15206       if (N->getValueType(0) == MVT::i16)
15207         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
15208 
15209       // First, combine the bswap away.  This makes the value produced by the
15210       // load dead.
15211       DCI.CombineTo(N, ResVal);
15212 
15213       // Next, combine the load away, we give it a bogus result value but a real
15214       // chain result.  The result value is dead because the bswap is dead.
15215       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
15216 
15217       // Return N so it doesn't get rechecked!
15218       return SDValue(N, 0);
15219     }
15220     break;
15221   case PPCISD::VCMP:
15222     // If a VCMP_rec node already exists with exactly the same operands as this
15223     // node, use its result instead of this node (VCMP_rec computes both a CR6
15224     // and a normal output).
15225     //
15226     if (!N->getOperand(0).hasOneUse() &&
15227         !N->getOperand(1).hasOneUse() &&
15228         !N->getOperand(2).hasOneUse()) {
15229 
15230       // Scan all of the users of the LHS, looking for VCMP_rec's that match.
15231       SDNode *VCMPrecNode = nullptr;
15232 
15233       SDNode *LHSN = N->getOperand(0).getNode();
15234       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
15235            UI != E; ++UI)
15236         if (UI->getOpcode() == PPCISD::VCMP_rec &&
15237             UI->getOperand(1) == N->getOperand(1) &&
15238             UI->getOperand(2) == N->getOperand(2) &&
15239             UI->getOperand(0) == N->getOperand(0)) {
15240           VCMPrecNode = *UI;
15241           break;
15242         }
15243 
15244       // If there is no VCMP_rec node, or if the flag value has a single use,
15245       // don't transform this.
15246       if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
15247         break;
15248 
15249       // Look at the (necessarily single) use of the flag value.  If it has a
15250       // chain, this transformation is more complex.  Note that multiple things
15251       // could use the value result, which we should ignore.
15252       SDNode *FlagUser = nullptr;
15253       for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
15254            FlagUser == nullptr; ++UI) {
15255         assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
15256         SDNode *User = *UI;
15257         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
15258           if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
15259             FlagUser = User;
15260             break;
15261           }
15262         }
15263       }
15264 
15265       // If the user is a MFOCRF instruction, we know this is safe.
15266       // Otherwise we give up for right now.
15267       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
15268         return SDValue(VCMPrecNode, 0);
15269     }
15270     break;
15271   case ISD::BRCOND: {
15272     SDValue Cond = N->getOperand(1);
15273     SDValue Target = N->getOperand(2);
15274 
15275     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15276         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15277           Intrinsic::loop_decrement) {
15278 
15279       // We now need to make the intrinsic dead (it cannot be instruction
15280       // selected).
15281       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15282       assert(Cond.getNode()->hasOneUse() &&
15283              "Counter decrement has more than one use");
15284 
15285       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15286                          N->getOperand(0), Target);
15287     }
15288   }
15289   break;
15290   case ISD::BR_CC: {
15291     // If this is a branch on an altivec predicate comparison, lower this so
15292     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15293     // lowering is done pre-legalize, because the legalizer lowers the predicate
15294     // compare down to code that is difficult to reassemble.
15295     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15296     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15297 
15298     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15299     // value. If so, pass-through the AND to get to the intrinsic.
15300     if (LHS.getOpcode() == ISD::AND &&
15301         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15302         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15303           Intrinsic::loop_decrement &&
15304         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15305         !isNullConstant(LHS.getOperand(1)))
15306       LHS = LHS.getOperand(0);
15307 
15308     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15309         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15310           Intrinsic::loop_decrement &&
15311         isa<ConstantSDNode>(RHS)) {
15312       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15313              "Counter decrement comparison is not EQ or NE");
15314 
15315       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15316       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15317                     (CC == ISD::SETNE && !Val);
15318 
15319       // We now need to make the intrinsic dead (it cannot be instruction
15320       // selected).
15321       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15322       assert(LHS.getNode()->hasOneUse() &&
15323              "Counter decrement has more than one use");
15324 
15325       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15326                          N->getOperand(0), N->getOperand(4));
15327     }
15328 
15329     int CompareOpc;
15330     bool isDot;
15331 
15332     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15333         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15334         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15335       assert(isDot && "Can't compare against a vector result!");
15336 
15337       // If this is a comparison against something other than 0/1, then we know
15338       // that the condition is never/always true.
15339       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15340       if (Val != 0 && Val != 1) {
15341         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15342           return N->getOperand(0);
15343         // Always !=, turn it into an unconditional branch.
15344         return DAG.getNode(ISD::BR, dl, MVT::Other,
15345                            N->getOperand(0), N->getOperand(4));
15346       }
15347 
15348       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15349 
15350       // Create the PPCISD altivec 'dot' comparison node.
15351       SDValue Ops[] = {
15352         LHS.getOperand(2),  // LHS of compare
15353         LHS.getOperand(3),  // RHS of compare
15354         DAG.getConstant(CompareOpc, dl, MVT::i32)
15355       };
15356       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15357       SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
15358 
15359       // Unpack the result based on how the target uses it.
15360       PPC::Predicate CompOpc;
15361       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15362       default:  // Can't happen, don't crash on invalid number though.
15363       case 0:   // Branch on the value of the EQ bit of CR6.
15364         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15365         break;
15366       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15367         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15368         break;
15369       case 2:   // Branch on the value of the LT bit of CR6.
15370         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15371         break;
15372       case 3:   // Branch on the inverted value of the LT bit of CR6.
15373         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15374         break;
15375       }
15376 
15377       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15378                          DAG.getConstant(CompOpc, dl, MVT::i32),
15379                          DAG.getRegister(PPC::CR6, MVT::i32),
15380                          N->getOperand(4), CompNode.getValue(1));
15381     }
15382     break;
15383   }
15384   case ISD::BUILD_VECTOR:
15385     return DAGCombineBuildVector(N, DCI);
15386   case ISD::ABS:
15387     return combineABS(N, DCI);
15388   case ISD::VSELECT:
15389     return combineVSelect(N, DCI);
15390   }
15391 
15392   return SDValue();
15393 }
15394 
15395 SDValue
15396 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15397                                  SelectionDAG &DAG,
15398                                  SmallVectorImpl<SDNode *> &Created) const {
15399   // fold (sdiv X, pow2)
15400   EVT VT = N->getValueType(0);
15401   if (VT == MVT::i64 && !Subtarget.isPPC64())
15402     return SDValue();
15403   if ((VT != MVT::i32 && VT != MVT::i64) ||
15404       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
15405     return SDValue();
15406 
15407   SDLoc DL(N);
15408   SDValue N0 = N->getOperand(0);
15409 
15410   bool IsNegPow2 = (-Divisor).isPowerOf2();
15411   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15412   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15413 
15414   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15415   Created.push_back(Op.getNode());
15416 
15417   if (IsNegPow2) {
15418     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15419     Created.push_back(Op.getNode());
15420   }
15421 
15422   return Op;
15423 }
15424 
15425 //===----------------------------------------------------------------------===//
15426 // Inline Assembly Support
15427 //===----------------------------------------------------------------------===//
15428 
15429 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15430                                                       KnownBits &Known,
15431                                                       const APInt &DemandedElts,
15432                                                       const SelectionDAG &DAG,
15433                                                       unsigned Depth) const {
15434   Known.resetAll();
15435   switch (Op.getOpcode()) {
15436   default: break;
15437   case PPCISD::LBRX: {
15438     // lhbrx is known to have the top bits cleared out.
15439     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15440       Known.Zero = 0xFFFF0000;
15441     break;
15442   }
15443   case ISD::INTRINSIC_WO_CHAIN: {
15444     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15445     default: break;
15446     case Intrinsic::ppc_altivec_vcmpbfp_p:
15447     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15448     case Intrinsic::ppc_altivec_vcmpequb_p:
15449     case Intrinsic::ppc_altivec_vcmpequh_p:
15450     case Intrinsic::ppc_altivec_vcmpequw_p:
15451     case Intrinsic::ppc_altivec_vcmpequd_p:
15452     case Intrinsic::ppc_altivec_vcmpequq_p:
15453     case Intrinsic::ppc_altivec_vcmpgefp_p:
15454     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15455     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15456     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15457     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15458     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15459     case Intrinsic::ppc_altivec_vcmpgtsq_p:
15460     case Intrinsic::ppc_altivec_vcmpgtub_p:
15461     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15462     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15463     case Intrinsic::ppc_altivec_vcmpgtud_p:
15464     case Intrinsic::ppc_altivec_vcmpgtuq_p:
15465       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15466       break;
15467     }
15468   }
15469   }
15470 }
15471 
15472 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15473   switch (Subtarget.getCPUDirective()) {
15474   default: break;
15475   case PPC::DIR_970:
15476   case PPC::DIR_PWR4:
15477   case PPC::DIR_PWR5:
15478   case PPC::DIR_PWR5X:
15479   case PPC::DIR_PWR6:
15480   case PPC::DIR_PWR6X:
15481   case PPC::DIR_PWR7:
15482   case PPC::DIR_PWR8:
15483   case PPC::DIR_PWR9:
15484   case PPC::DIR_PWR10:
15485   case PPC::DIR_PWR_FUTURE: {
15486     if (!ML)
15487       break;
15488 
15489     if (!DisableInnermostLoopAlign32) {
15490       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15491       // so that we can decrease cache misses and branch-prediction misses.
15492       // Actual alignment of the loop will depend on the hotness check and other
15493       // logic in alignBlocks.
15494       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15495         return Align(32);
15496     }
15497 
15498     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15499 
15500     // For small loops (between 5 and 8 instructions), align to a 32-byte
15501     // boundary so that the entire loop fits in one instruction-cache line.
15502     uint64_t LoopSize = 0;
15503     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15504       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15505         LoopSize += TII->getInstSizeInBytes(*J);
15506         if (LoopSize > 32)
15507           break;
15508       }
15509 
15510     if (LoopSize > 16 && LoopSize <= 32)
15511       return Align(32);
15512 
15513     break;
15514   }
15515   }
15516 
15517   return TargetLowering::getPrefLoopAlignment(ML);
15518 }
15519 
15520 /// getConstraintType - Given a constraint, return the type of
15521 /// constraint it is for this target.
15522 PPCTargetLowering::ConstraintType
15523 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15524   if (Constraint.size() == 1) {
15525     switch (Constraint[0]) {
15526     default: break;
15527     case 'b':
15528     case 'r':
15529     case 'f':
15530     case 'd':
15531     case 'v':
15532     case 'y':
15533       return C_RegisterClass;
15534     case 'Z':
15535       // FIXME: While Z does indicate a memory constraint, it specifically
15536       // indicates an r+r address (used in conjunction with the 'y' modifier
15537       // in the replacement string). Currently, we're forcing the base
15538       // register to be r0 in the asm printer (which is interpreted as zero)
15539       // and forming the complete address in the second register. This is
15540       // suboptimal.
15541       return C_Memory;
15542     }
15543   } else if (Constraint == "wc") { // individual CR bits.
15544     return C_RegisterClass;
15545   } else if (Constraint == "wa" || Constraint == "wd" ||
15546              Constraint == "wf" || Constraint == "ws" ||
15547              Constraint == "wi" || Constraint == "ww") {
15548     return C_RegisterClass; // VSX registers.
15549   }
15550   return TargetLowering::getConstraintType(Constraint);
15551 }
15552 
15553 /// Examine constraint type and operand type and determine a weight value.
15554 /// This object must already have been set up with the operand type
15555 /// and the current alternative constraint selected.
15556 TargetLowering::ConstraintWeight
15557 PPCTargetLowering::getSingleConstraintMatchWeight(
15558     AsmOperandInfo &info, const char *constraint) const {
15559   ConstraintWeight weight = CW_Invalid;
15560   Value *CallOperandVal = info.CallOperandVal;
15561     // If we don't have a value, we can't do a match,
15562     // but allow it at the lowest weight.
15563   if (!CallOperandVal)
15564     return CW_Default;
15565   Type *type = CallOperandVal->getType();
15566 
15567   // Look at the constraint type.
15568   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15569     return CW_Register; // an individual CR bit.
15570   else if ((StringRef(constraint) == "wa" ||
15571             StringRef(constraint) == "wd" ||
15572             StringRef(constraint) == "wf") &&
15573            type->isVectorTy())
15574     return CW_Register;
15575   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15576     return CW_Register; // just hold 64-bit integers data.
15577   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15578     return CW_Register;
15579   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15580     return CW_Register;
15581 
15582   switch (*constraint) {
15583   default:
15584     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15585     break;
15586   case 'b':
15587     if (type->isIntegerTy())
15588       weight = CW_Register;
15589     break;
15590   case 'f':
15591     if (type->isFloatTy())
15592       weight = CW_Register;
15593     break;
15594   case 'd':
15595     if (type->isDoubleTy())
15596       weight = CW_Register;
15597     break;
15598   case 'v':
15599     if (type->isVectorTy())
15600       weight = CW_Register;
15601     break;
15602   case 'y':
15603     weight = CW_Register;
15604     break;
15605   case 'Z':
15606     weight = CW_Memory;
15607     break;
15608   }
15609   return weight;
15610 }
15611 
15612 std::pair<unsigned, const TargetRegisterClass *>
15613 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15614                                                 StringRef Constraint,
15615                                                 MVT VT) const {
15616   if (Constraint.size() == 1) {
15617     // GCC RS6000 Constraint Letters
15618     switch (Constraint[0]) {
15619     case 'b':   // R1-R31
15620       if (VT == MVT::i64 && Subtarget.isPPC64())
15621         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15622       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15623     case 'r':   // R0-R31
15624       if (VT == MVT::i64 && Subtarget.isPPC64())
15625         return std::make_pair(0U, &PPC::G8RCRegClass);
15626       return std::make_pair(0U, &PPC::GPRCRegClass);
15627     // 'd' and 'f' constraints are both defined to be "the floating point
15628     // registers", where one is for 32-bit and the other for 64-bit. We don't
15629     // really care overly much here so just give them all the same reg classes.
15630     case 'd':
15631     case 'f':
15632       if (Subtarget.hasSPE()) {
15633         if (VT == MVT::f32 || VT == MVT::i32)
15634           return std::make_pair(0U, &PPC::GPRCRegClass);
15635         if (VT == MVT::f64 || VT == MVT::i64)
15636           return std::make_pair(0U, &PPC::SPERCRegClass);
15637       } else {
15638         if (VT == MVT::f32 || VT == MVT::i32)
15639           return std::make_pair(0U, &PPC::F4RCRegClass);
15640         if (VT == MVT::f64 || VT == MVT::i64)
15641           return std::make_pair(0U, &PPC::F8RCRegClass);
15642       }
15643       break;
15644     case 'v':
15645       if (Subtarget.hasAltivec())
15646         return std::make_pair(0U, &PPC::VRRCRegClass);
15647       break;
15648     case 'y':   // crrc
15649       return std::make_pair(0U, &PPC::CRRCRegClass);
15650     }
15651   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15652     // An individual CR bit.
15653     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15654   } else if ((Constraint == "wa" || Constraint == "wd" ||
15655              Constraint == "wf" || Constraint == "wi") &&
15656              Subtarget.hasVSX()) {
15657     return std::make_pair(0U, &PPC::VSRCRegClass);
15658   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15659     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15660       return std::make_pair(0U, &PPC::VSSRCRegClass);
15661     else
15662       return std::make_pair(0U, &PPC::VSFRCRegClass);
15663   }
15664 
15665   // If we name a VSX register, we can't defer to the base class because it
15666   // will not recognize the correct register (their names will be VSL{0-31}
15667   // and V{0-31} so they won't match). So we match them here.
15668   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15669     int VSNum = atoi(Constraint.data() + 3);
15670     assert(VSNum >= 0 && VSNum <= 63 &&
15671            "Attempted to access a vsr out of range");
15672     if (VSNum < 32)
15673       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15674     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15675   }
15676   std::pair<unsigned, const TargetRegisterClass *> R =
15677       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15678 
15679   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15680   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15681   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15682   // register.
15683   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15684   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15685   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15686       PPC::GPRCRegClass.contains(R.first))
15687     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15688                             PPC::sub_32, &PPC::G8RCRegClass),
15689                           &PPC::G8RCRegClass);
15690 
15691   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15692   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15693     R.first = PPC::CR0;
15694     R.second = &PPC::CRRCRegClass;
15695   }
15696 
15697   return R;
15698 }
15699 
15700 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15701 /// vector.  If it is invalid, don't add anything to Ops.
15702 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15703                                                      std::string &Constraint,
15704                                                      std::vector<SDValue>&Ops,
15705                                                      SelectionDAG &DAG) const {
15706   SDValue Result;
15707 
15708   // Only support length 1 constraints.
15709   if (Constraint.length() > 1) return;
15710 
15711   char Letter = Constraint[0];
15712   switch (Letter) {
15713   default: break;
15714   case 'I':
15715   case 'J':
15716   case 'K':
15717   case 'L':
15718   case 'M':
15719   case 'N':
15720   case 'O':
15721   case 'P': {
15722     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15723     if (!CST) return; // Must be an immediate to match.
15724     SDLoc dl(Op);
15725     int64_t Value = CST->getSExtValue();
15726     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15727                          // numbers are printed as such.
15728     switch (Letter) {
15729     default: llvm_unreachable("Unknown constraint letter!");
15730     case 'I':  // "I" is a signed 16-bit constant.
15731       if (isInt<16>(Value))
15732         Result = DAG.getTargetConstant(Value, dl, TCVT);
15733       break;
15734     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15735       if (isShiftedUInt<16, 16>(Value))
15736         Result = DAG.getTargetConstant(Value, dl, TCVT);
15737       break;
15738     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15739       if (isShiftedInt<16, 16>(Value))
15740         Result = DAG.getTargetConstant(Value, dl, TCVT);
15741       break;
15742     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15743       if (isUInt<16>(Value))
15744         Result = DAG.getTargetConstant(Value, dl, TCVT);
15745       break;
15746     case 'M':  // "M" is a constant that is greater than 31.
15747       if (Value > 31)
15748         Result = DAG.getTargetConstant(Value, dl, TCVT);
15749       break;
15750     case 'N':  // "N" is a positive constant that is an exact power of two.
15751       if (Value > 0 && isPowerOf2_64(Value))
15752         Result = DAG.getTargetConstant(Value, dl, TCVT);
15753       break;
15754     case 'O':  // "O" is the constant zero.
15755       if (Value == 0)
15756         Result = DAG.getTargetConstant(Value, dl, TCVT);
15757       break;
15758     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15759       if (isInt<16>(-Value))
15760         Result = DAG.getTargetConstant(Value, dl, TCVT);
15761       break;
15762     }
15763     break;
15764   }
15765   }
15766 
15767   if (Result.getNode()) {
15768     Ops.push_back(Result);
15769     return;
15770   }
15771 
15772   // Handle standard constraint letters.
15773   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15774 }
15775 
15776 // isLegalAddressingMode - Return true if the addressing mode represented
15777 // by AM is legal for this target, for a load/store of the specified type.
15778 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15779                                               const AddrMode &AM, Type *Ty,
15780                                               unsigned AS,
15781                                               Instruction *I) const {
15782   // Vector type r+i form is supported since power9 as DQ form. We don't check
15783   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
15784   // imm form is preferred and the offset can be adjusted to use imm form later
15785   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
15786   // max offset to check legal addressing mode, we should be a little aggressive
15787   // to contain other offsets for that LSRUse.
15788   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
15789     return false;
15790 
15791   // PPC allows a sign-extended 16-bit immediate field.
15792   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15793     return false;
15794 
15795   // No global is ever allowed as a base.
15796   if (AM.BaseGV)
15797     return false;
15798 
15799   // PPC only support r+r,
15800   switch (AM.Scale) {
15801   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15802     break;
15803   case 1:
15804     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15805       return false;
15806     // Otherwise we have r+r or r+i.
15807     break;
15808   case 2:
15809     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15810       return false;
15811     // Allow 2*r as r+r.
15812     break;
15813   default:
15814     // No other scales are supported.
15815     return false;
15816   }
15817 
15818   return true;
15819 }
15820 
15821 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15822                                            SelectionDAG &DAG) const {
15823   MachineFunction &MF = DAG.getMachineFunction();
15824   MachineFrameInfo &MFI = MF.getFrameInfo();
15825   MFI.setReturnAddressIsTaken(true);
15826 
15827   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15828     return SDValue();
15829 
15830   SDLoc dl(Op);
15831   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15832 
15833   // Make sure the function does not optimize away the store of the RA to
15834   // the stack.
15835   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15836   FuncInfo->setLRStoreRequired();
15837   bool isPPC64 = Subtarget.isPPC64();
15838   auto PtrVT = getPointerTy(MF.getDataLayout());
15839 
15840   if (Depth > 0) {
15841     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15842     SDValue Offset =
15843         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15844                         isPPC64 ? MVT::i64 : MVT::i32);
15845     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15846                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15847                        MachinePointerInfo());
15848   }
15849 
15850   // Just load the return address off the stack.
15851   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15852   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15853                      MachinePointerInfo());
15854 }
15855 
15856 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15857                                           SelectionDAG &DAG) const {
15858   SDLoc dl(Op);
15859   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15860 
15861   MachineFunction &MF = DAG.getMachineFunction();
15862   MachineFrameInfo &MFI = MF.getFrameInfo();
15863   MFI.setFrameAddressIsTaken(true);
15864 
15865   EVT PtrVT = getPointerTy(MF.getDataLayout());
15866   bool isPPC64 = PtrVT == MVT::i64;
15867 
15868   // Naked functions never have a frame pointer, and so we use r1. For all
15869   // other functions, this decision must be delayed until during PEI.
15870   unsigned FrameReg;
15871   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15872     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15873   else
15874     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15875 
15876   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15877                                          PtrVT);
15878   while (Depth--)
15879     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15880                             FrameAddr, MachinePointerInfo());
15881   return FrameAddr;
15882 }
15883 
15884 // FIXME? Maybe this could be a TableGen attribute on some registers and
15885 // this table could be generated automatically from RegInfo.
15886 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15887                                               const MachineFunction &MF) const {
15888   bool isPPC64 = Subtarget.isPPC64();
15889 
15890   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15891   if (!is64Bit && VT != LLT::scalar(32))
15892     report_fatal_error("Invalid register global variable type");
15893 
15894   Register Reg = StringSwitch<Register>(RegName)
15895                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15896                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15897                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15898                      .Default(Register());
15899 
15900   if (Reg)
15901     return Reg;
15902   report_fatal_error("Invalid register name global variable");
15903 }
15904 
15905 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15906   // 32-bit SVR4 ABI access everything as got-indirect.
15907   if (Subtarget.is32BitELFABI())
15908     return true;
15909 
15910   // AIX accesses everything indirectly through the TOC, which is similar to
15911   // the GOT.
15912   if (Subtarget.isAIXABI())
15913     return true;
15914 
15915   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15916   // If it is small or large code model, module locals are accessed
15917   // indirectly by loading their address from .toc/.got.
15918   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15919     return true;
15920 
15921   // JumpTable and BlockAddress are accessed as got-indirect.
15922   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15923     return true;
15924 
15925   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15926     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15927 
15928   return false;
15929 }
15930 
15931 bool
15932 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15933   // The PowerPC target isn't yet aware of offsets.
15934   return false;
15935 }
15936 
15937 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15938                                            const CallInst &I,
15939                                            MachineFunction &MF,
15940                                            unsigned Intrinsic) const {
15941   switch (Intrinsic) {
15942   case Intrinsic::ppc_altivec_lvx:
15943   case Intrinsic::ppc_altivec_lvxl:
15944   case Intrinsic::ppc_altivec_lvebx:
15945   case Intrinsic::ppc_altivec_lvehx:
15946   case Intrinsic::ppc_altivec_lvewx:
15947   case Intrinsic::ppc_vsx_lxvd2x:
15948   case Intrinsic::ppc_vsx_lxvw4x:
15949   case Intrinsic::ppc_vsx_lxvd2x_be:
15950   case Intrinsic::ppc_vsx_lxvw4x_be:
15951   case Intrinsic::ppc_vsx_lxvl:
15952   case Intrinsic::ppc_vsx_lxvll: {
15953     EVT VT;
15954     switch (Intrinsic) {
15955     case Intrinsic::ppc_altivec_lvebx:
15956       VT = MVT::i8;
15957       break;
15958     case Intrinsic::ppc_altivec_lvehx:
15959       VT = MVT::i16;
15960       break;
15961     case Intrinsic::ppc_altivec_lvewx:
15962       VT = MVT::i32;
15963       break;
15964     case Intrinsic::ppc_vsx_lxvd2x:
15965     case Intrinsic::ppc_vsx_lxvd2x_be:
15966       VT = MVT::v2f64;
15967       break;
15968     default:
15969       VT = MVT::v4i32;
15970       break;
15971     }
15972 
15973     Info.opc = ISD::INTRINSIC_W_CHAIN;
15974     Info.memVT = VT;
15975     Info.ptrVal = I.getArgOperand(0);
15976     Info.offset = -VT.getStoreSize()+1;
15977     Info.size = 2*VT.getStoreSize()-1;
15978     Info.align = Align(1);
15979     Info.flags = MachineMemOperand::MOLoad;
15980     return true;
15981   }
15982   case Intrinsic::ppc_altivec_stvx:
15983   case Intrinsic::ppc_altivec_stvxl:
15984   case Intrinsic::ppc_altivec_stvebx:
15985   case Intrinsic::ppc_altivec_stvehx:
15986   case Intrinsic::ppc_altivec_stvewx:
15987   case Intrinsic::ppc_vsx_stxvd2x:
15988   case Intrinsic::ppc_vsx_stxvw4x:
15989   case Intrinsic::ppc_vsx_stxvd2x_be:
15990   case Intrinsic::ppc_vsx_stxvw4x_be:
15991   case Intrinsic::ppc_vsx_stxvl:
15992   case Intrinsic::ppc_vsx_stxvll: {
15993     EVT VT;
15994     switch (Intrinsic) {
15995     case Intrinsic::ppc_altivec_stvebx:
15996       VT = MVT::i8;
15997       break;
15998     case Intrinsic::ppc_altivec_stvehx:
15999       VT = MVT::i16;
16000       break;
16001     case Intrinsic::ppc_altivec_stvewx:
16002       VT = MVT::i32;
16003       break;
16004     case Intrinsic::ppc_vsx_stxvd2x:
16005     case Intrinsic::ppc_vsx_stxvd2x_be:
16006       VT = MVT::v2f64;
16007       break;
16008     default:
16009       VT = MVT::v4i32;
16010       break;
16011     }
16012 
16013     Info.opc = ISD::INTRINSIC_VOID;
16014     Info.memVT = VT;
16015     Info.ptrVal = I.getArgOperand(1);
16016     Info.offset = -VT.getStoreSize()+1;
16017     Info.size = 2*VT.getStoreSize()-1;
16018     Info.align = Align(1);
16019     Info.flags = MachineMemOperand::MOStore;
16020     return true;
16021   }
16022   default:
16023     break;
16024   }
16025 
16026   return false;
16027 }
16028 
16029 /// It returns EVT::Other if the type should be determined using generic
16030 /// target-independent logic.
16031 EVT PPCTargetLowering::getOptimalMemOpType(
16032     const MemOp &Op, const AttributeList &FuncAttributes) const {
16033   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
16034     // We should use Altivec/VSX loads and stores when available. For unaligned
16035     // addresses, unaligned VSX loads are only fast starting with the P8.
16036     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
16037         (Op.isAligned(Align(16)) ||
16038          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
16039       return MVT::v4i32;
16040   }
16041 
16042   if (Subtarget.isPPC64()) {
16043     return MVT::i64;
16044   }
16045 
16046   return MVT::i32;
16047 }
16048 
16049 /// Returns true if it is beneficial to convert a load of a constant
16050 /// to just the constant itself.
16051 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16052                                                           Type *Ty) const {
16053   assert(Ty->isIntegerTy());
16054 
16055   unsigned BitSize = Ty->getPrimitiveSizeInBits();
16056   return !(BitSize == 0 || BitSize > 64);
16057 }
16058 
16059 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16060   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16061     return false;
16062   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16063   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16064   return NumBits1 == 64 && NumBits2 == 32;
16065 }
16066 
16067 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16068   if (!VT1.isInteger() || !VT2.isInteger())
16069     return false;
16070   unsigned NumBits1 = VT1.getSizeInBits();
16071   unsigned NumBits2 = VT2.getSizeInBits();
16072   return NumBits1 == 64 && NumBits2 == 32;
16073 }
16074 
16075 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16076   // Generally speaking, zexts are not free, but they are free when they can be
16077   // folded with other operations.
16078   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
16079     EVT MemVT = LD->getMemoryVT();
16080     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
16081          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
16082         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
16083          LD->getExtensionType() == ISD::ZEXTLOAD))
16084       return true;
16085   }
16086 
16087   // FIXME: Add other cases...
16088   //  - 32-bit shifts with a zext to i64
16089   //  - zext after ctlz, bswap, etc.
16090   //  - zext after and by a constant mask
16091 
16092   return TargetLowering::isZExtFree(Val, VT2);
16093 }
16094 
16095 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
16096   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
16097          "invalid fpext types");
16098   // Extending to float128 is not free.
16099   if (DestVT == MVT::f128)
16100     return false;
16101   return true;
16102 }
16103 
16104 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16105   return isInt<16>(Imm) || isUInt<16>(Imm);
16106 }
16107 
16108 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16109   return isInt<16>(Imm) || isUInt<16>(Imm);
16110 }
16111 
16112 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
16113                                                        unsigned,
16114                                                        unsigned,
16115                                                        MachineMemOperand::Flags,
16116                                                        bool *Fast) const {
16117   if (DisablePPCUnaligned)
16118     return false;
16119 
16120   // PowerPC supports unaligned memory access for simple non-vector types.
16121   // Although accessing unaligned addresses is not as efficient as accessing
16122   // aligned addresses, it is generally more efficient than manual expansion,
16123   // and generally only traps for software emulation when crossing page
16124   // boundaries.
16125 
16126   if (!VT.isSimple())
16127     return false;
16128 
16129   if (VT.isFloatingPoint() && !VT.isVector() &&
16130       !Subtarget.allowsUnalignedFPAccess())
16131     return false;
16132 
16133   if (VT.getSimpleVT().isVector()) {
16134     if (Subtarget.hasVSX()) {
16135       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
16136           VT != MVT::v4f32 && VT != MVT::v4i32)
16137         return false;
16138     } else {
16139       return false;
16140     }
16141   }
16142 
16143   if (VT == MVT::ppcf128)
16144     return false;
16145 
16146   if (Fast)
16147     *Fast = true;
16148 
16149   return true;
16150 }
16151 
16152 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
16153                                                SDValue C) const {
16154   // Check integral scalar types.
16155   if (!VT.isScalarInteger())
16156     return false;
16157   if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
16158     if (!ConstNode->getAPIntValue().isSignedIntN(64))
16159       return false;
16160     // This transformation will generate >= 2 operations. But the following
16161     // cases will generate <= 2 instructions during ISEL. So exclude them.
16162     // 1. If the constant multiplier fits 16 bits, it can be handled by one
16163     // HW instruction, ie. MULLI
16164     // 2. If the multiplier after shifted fits 16 bits, an extra shift
16165     // instruction is needed than case 1, ie. MULLI and RLDICR
16166     int64_t Imm = ConstNode->getSExtValue();
16167     unsigned Shift = countTrailingZeros<uint64_t>(Imm);
16168     Imm >>= Shift;
16169     if (isInt<16>(Imm))
16170       return false;
16171     uint64_t UImm = static_cast<uint64_t>(Imm);
16172     if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
16173         isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
16174       return true;
16175   }
16176   return false;
16177 }
16178 
16179 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16180                                                    EVT VT) const {
16181   return isFMAFasterThanFMulAndFAdd(
16182       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
16183 }
16184 
16185 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
16186                                                    Type *Ty) const {
16187   switch (Ty->getScalarType()->getTypeID()) {
16188   case Type::FloatTyID:
16189   case Type::DoubleTyID:
16190     return true;
16191   case Type::FP128TyID:
16192     return Subtarget.hasP9Vector();
16193   default:
16194     return false;
16195   }
16196 }
16197 
16198 // FIXME: add more patterns which are not profitable to hoist.
16199 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
16200   if (!I->hasOneUse())
16201     return true;
16202 
16203   Instruction *User = I->user_back();
16204   assert(User && "A single use instruction with no uses.");
16205 
16206   switch (I->getOpcode()) {
16207   case Instruction::FMul: {
16208     // Don't break FMA, PowerPC prefers FMA.
16209     if (User->getOpcode() != Instruction::FSub &&
16210         User->getOpcode() != Instruction::FAdd)
16211       return true;
16212 
16213     const TargetOptions &Options = getTargetMachine().Options;
16214     const Function *F = I->getFunction();
16215     const DataLayout &DL = F->getParent()->getDataLayout();
16216     Type *Ty = User->getOperand(0)->getType();
16217 
16218     return !(
16219         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
16220         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
16221         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
16222   }
16223   case Instruction::Load: {
16224     // Don't break "store (load float*)" pattern, this pattern will be combined
16225     // to "store (load int32)" in later InstCombine pass. See function
16226     // combineLoadToOperationType. On PowerPC, loading a float point takes more
16227     // cycles than loading a 32 bit integer.
16228     LoadInst *LI = cast<LoadInst>(I);
16229     // For the loads that combineLoadToOperationType does nothing, like
16230     // ordered load, it should be profitable to hoist them.
16231     // For swifterror load, it can only be used for pointer to pointer type, so
16232     // later type check should get rid of this case.
16233     if (!LI->isUnordered())
16234       return true;
16235 
16236     if (User->getOpcode() != Instruction::Store)
16237       return true;
16238 
16239     if (I->getType()->getTypeID() != Type::FloatTyID)
16240       return true;
16241 
16242     return false;
16243   }
16244   default:
16245     return true;
16246   }
16247   return true;
16248 }
16249 
16250 const MCPhysReg *
16251 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
16252   // LR is a callee-save register, but we must treat it as clobbered by any call
16253   // site. Hence we include LR in the scratch registers, which are in turn added
16254   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
16255   // to CTR, which is used by any indirect call.
16256   static const MCPhysReg ScratchRegs[] = {
16257     PPC::X12, PPC::LR8, PPC::CTR8, 0
16258   };
16259 
16260   return ScratchRegs;
16261 }
16262 
16263 Register PPCTargetLowering::getExceptionPointerRegister(
16264     const Constant *PersonalityFn) const {
16265   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
16266 }
16267 
16268 Register PPCTargetLowering::getExceptionSelectorRegister(
16269     const Constant *PersonalityFn) const {
16270   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
16271 }
16272 
16273 bool
16274 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
16275                      EVT VT , unsigned DefinedValues) const {
16276   if (VT == MVT::v2i64)
16277     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
16278 
16279   if (Subtarget.hasVSX())
16280     return true;
16281 
16282   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
16283 }
16284 
16285 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16286   if (DisableILPPref || Subtarget.enableMachineScheduler())
16287     return TargetLowering::getSchedulingPreference(N);
16288 
16289   return Sched::ILP;
16290 }
16291 
16292 // Create a fast isel object.
16293 FastISel *
16294 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16295                                   const TargetLibraryInfo *LibInfo) const {
16296   return PPC::createFastISel(FuncInfo, LibInfo);
16297 }
16298 
16299 // 'Inverted' means the FMA opcode after negating one multiplicand.
16300 // For example, (fma -a b c) = (fnmsub a b c)
16301 static unsigned invertFMAOpcode(unsigned Opc) {
16302   switch (Opc) {
16303   default:
16304     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16305   case ISD::FMA:
16306     return PPCISD::FNMSUB;
16307   case PPCISD::FNMSUB:
16308     return ISD::FMA;
16309   }
16310 }
16311 
16312 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16313                                                 bool LegalOps, bool OptForSize,
16314                                                 NegatibleCost &Cost,
16315                                                 unsigned Depth) const {
16316   if (Depth > SelectionDAG::MaxRecursionDepth)
16317     return SDValue();
16318 
16319   unsigned Opc = Op.getOpcode();
16320   EVT VT = Op.getValueType();
16321   SDNodeFlags Flags = Op.getNode()->getFlags();
16322 
16323   switch (Opc) {
16324   case PPCISD::FNMSUB:
16325     if (!Op.hasOneUse() || !isTypeLegal(VT))
16326       break;
16327 
16328     const TargetOptions &Options = getTargetMachine().Options;
16329     SDValue N0 = Op.getOperand(0);
16330     SDValue N1 = Op.getOperand(1);
16331     SDValue N2 = Op.getOperand(2);
16332     SDLoc Loc(Op);
16333 
16334     NegatibleCost N2Cost = NegatibleCost::Expensive;
16335     SDValue NegN2 =
16336         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16337 
16338     if (!NegN2)
16339       return SDValue();
16340 
16341     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16342     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16343     // These transformations may change sign of zeroes. For example,
16344     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16345     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16346       // Try and choose the cheaper one to negate.
16347       NegatibleCost N0Cost = NegatibleCost::Expensive;
16348       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16349                                            N0Cost, Depth + 1);
16350 
16351       NegatibleCost N1Cost = NegatibleCost::Expensive;
16352       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16353                                            N1Cost, Depth + 1);
16354 
16355       if (NegN0 && N0Cost <= N1Cost) {
16356         Cost = std::min(N0Cost, N2Cost);
16357         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16358       } else if (NegN1) {
16359         Cost = std::min(N1Cost, N2Cost);
16360         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16361       }
16362     }
16363 
16364     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16365     if (isOperationLegal(ISD::FMA, VT)) {
16366       Cost = N2Cost;
16367       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16368     }
16369 
16370     break;
16371   }
16372 
16373   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16374                                               Cost, Depth);
16375 }
16376 
16377 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16378 bool PPCTargetLowering::useLoadStackGuardNode() const {
16379   if (!Subtarget.isTargetLinux())
16380     return TargetLowering::useLoadStackGuardNode();
16381   return true;
16382 }
16383 
16384 // Override to disable global variable loading on Linux.
16385 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16386   if (!Subtarget.isTargetLinux())
16387     return TargetLowering::insertSSPDeclarations(M);
16388 }
16389 
16390 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16391                                      bool ForCodeSize) const {
16392   if (!VT.isSimple() || !Subtarget.hasVSX())
16393     return false;
16394 
16395   switch(VT.getSimpleVT().SimpleTy) {
16396   default:
16397     // For FP types that are currently not supported by PPC backend, return
16398     // false. Examples: f16, f80.
16399     return false;
16400   case MVT::f32:
16401   case MVT::f64:
16402     if (Subtarget.hasPrefixInstrs()) {
16403       // With prefixed instructions, we can materialize anything that can be
16404       // represented with a 32-bit immediate, not just positive zero.
16405       APFloat APFloatOfImm = Imm;
16406       return convertToNonDenormSingle(APFloatOfImm);
16407     }
16408     LLVM_FALLTHROUGH;
16409   case MVT::ppcf128:
16410     return Imm.isPosZero();
16411   }
16412 }
16413 
16414 // For vector shift operation op, fold
16415 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16416 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16417                                   SelectionDAG &DAG) {
16418   SDValue N0 = N->getOperand(0);
16419   SDValue N1 = N->getOperand(1);
16420   EVT VT = N0.getValueType();
16421   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16422   unsigned Opcode = N->getOpcode();
16423   unsigned TargetOpcode;
16424 
16425   switch (Opcode) {
16426   default:
16427     llvm_unreachable("Unexpected shift operation");
16428   case ISD::SHL:
16429     TargetOpcode = PPCISD::SHL;
16430     break;
16431   case ISD::SRL:
16432     TargetOpcode = PPCISD::SRL;
16433     break;
16434   case ISD::SRA:
16435     TargetOpcode = PPCISD::SRA;
16436     break;
16437   }
16438 
16439   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16440       N1->getOpcode() == ISD::AND)
16441     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16442       if (Mask->getZExtValue() == OpSizeInBits - 1)
16443         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16444 
16445   return SDValue();
16446 }
16447 
16448 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16449   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16450     return Value;
16451 
16452   SDValue N0 = N->getOperand(0);
16453   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16454   if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
16455       N0.getOpcode() != ISD::SIGN_EXTEND ||
16456       N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
16457       N->getValueType(0) != MVT::i64)
16458     return SDValue();
16459 
16460   // We can't save an operation here if the value is already extended, and
16461   // the existing shift is easier to combine.
16462   SDValue ExtsSrc = N0.getOperand(0);
16463   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16464       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16465     return SDValue();
16466 
16467   SDLoc DL(N0);
16468   SDValue ShiftBy = SDValue(CN1, 0);
16469   // We want the shift amount to be i32 on the extswli, but the shift could
16470   // have an i64.
16471   if (ShiftBy.getValueType() == MVT::i64)
16472     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16473 
16474   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16475                          ShiftBy);
16476 }
16477 
16478 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16479   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16480     return Value;
16481 
16482   return SDValue();
16483 }
16484 
16485 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16486   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16487     return Value;
16488 
16489   return SDValue();
16490 }
16491 
16492 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16493 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16494 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16495 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16496 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16497                                  const PPCSubtarget &Subtarget) {
16498   if (!Subtarget.isPPC64())
16499     return SDValue();
16500 
16501   SDValue LHS = N->getOperand(0);
16502   SDValue RHS = N->getOperand(1);
16503 
16504   auto isZextOfCompareWithConstant = [](SDValue Op) {
16505     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16506         Op.getValueType() != MVT::i64)
16507       return false;
16508 
16509     SDValue Cmp = Op.getOperand(0);
16510     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16511         Cmp.getOperand(0).getValueType() != MVT::i64)
16512       return false;
16513 
16514     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
16515       int64_t NegConstant = 0 - Constant->getSExtValue();
16516       // Due to the limitations of the addi instruction,
16517       // -C is required to be [-32768, 32767].
16518       return isInt<16>(NegConstant);
16519     }
16520 
16521     return false;
16522   };
16523 
16524   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
16525   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16526 
16527   // If there is a pattern, canonicalize a zext operand to the RHS.
16528   if (LHSHasPattern && !RHSHasPattern)
16529     std::swap(LHS, RHS);
16530   else if (!LHSHasPattern && !RHSHasPattern)
16531     return SDValue();
16532 
16533   SDLoc DL(N);
16534   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16535   SDValue Cmp = RHS.getOperand(0);
16536   SDValue Z = Cmp.getOperand(0);
16537   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
16538 
16539   assert(Constant && "Constant Should not be a null pointer.");
16540   int64_t NegConstant = 0 - Constant->getSExtValue();
16541 
16542   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16543   default: break;
16544   case ISD::SETNE: {
16545     //                                 when C == 0
16546     //                             --> addze X, (addic Z, -1).carry
16547     //                            /
16548     // add X, (zext(setne Z, C))--
16549     //                            \    when -32768 <= -C <= 32767 && C != 0
16550     //                             --> addze X, (addic (addi Z, -C), -1).carry
16551     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16552                               DAG.getConstant(NegConstant, DL, MVT::i64));
16553     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16554     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16555                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16556     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16557                        SDValue(Addc.getNode(), 1));
16558     }
16559   case ISD::SETEQ: {
16560     //                                 when C == 0
16561     //                             --> addze X, (subfic Z, 0).carry
16562     //                            /
16563     // add X, (zext(sete  Z, C))--
16564     //                            \    when -32768 <= -C <= 32767 && C != 0
16565     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16566     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16567                               DAG.getConstant(NegConstant, DL, MVT::i64));
16568     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16569     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16570                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16571     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16572                        SDValue(Subc.getNode(), 1));
16573     }
16574   }
16575 
16576   return SDValue();
16577 }
16578 
16579 // Transform
16580 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16581 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16582 // In this case both C1 and C2 must be known constants.
16583 // C1+C2 must fit into a 34 bit signed integer.
16584 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16585                                           const PPCSubtarget &Subtarget) {
16586   if (!Subtarget.isUsingPCRelativeCalls())
16587     return SDValue();
16588 
16589   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16590   // If we find that node try to cast the Global Address and the Constant.
16591   SDValue LHS = N->getOperand(0);
16592   SDValue RHS = N->getOperand(1);
16593 
16594   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16595     std::swap(LHS, RHS);
16596 
16597   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16598     return SDValue();
16599 
16600   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16601   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16602   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16603 
16604   // Check that both casts succeeded.
16605   if (!GSDN || !ConstNode)
16606     return SDValue();
16607 
16608   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16609   SDLoc DL(GSDN);
16610 
16611   // The signed int offset needs to fit in 34 bits.
16612   if (!isInt<34>(NewOffset))
16613     return SDValue();
16614 
16615   // The new global address is a copy of the old global address except
16616   // that it has the updated Offset.
16617   SDValue GA =
16618       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16619                                  NewOffset, GSDN->getTargetFlags());
16620   SDValue MatPCRel =
16621       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16622   return MatPCRel;
16623 }
16624 
16625 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16626   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16627     return Value;
16628 
16629   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16630     return Value;
16631 
16632   return SDValue();
16633 }
16634 
16635 // Detect TRUNCATE operations on bitcasts of float128 values.
16636 // What we are looking for here is the situtation where we extract a subset
16637 // of bits from a 128 bit float.
16638 // This can be of two forms:
16639 // 1) BITCAST of f128 feeding TRUNCATE
16640 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16641 // The reason this is required is because we do not have a legal i128 type
16642 // and so we want to prevent having to store the f128 and then reload part
16643 // of it.
16644 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16645                                            DAGCombinerInfo &DCI) const {
16646   // If we are using CRBits then try that first.
16647   if (Subtarget.useCRBits()) {
16648     // Check if CRBits did anything and return that if it did.
16649     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16650       return CRTruncValue;
16651   }
16652 
16653   SDLoc dl(N);
16654   SDValue Op0 = N->getOperand(0);
16655 
16656   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
16657   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
16658     EVT VT = N->getValueType(0);
16659     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16660       return SDValue();
16661     SDValue Sub = Op0.getOperand(0);
16662     if (Sub.getOpcode() == ISD::SUB) {
16663       SDValue SubOp0 = Sub.getOperand(0);
16664       SDValue SubOp1 = Sub.getOperand(1);
16665       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16666           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16667         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16668                                SubOp1.getOperand(0),
16669                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16670       }
16671     }
16672   }
16673 
16674   // Looking for a truncate of i128 to i64.
16675   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16676     return SDValue();
16677 
16678   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16679 
16680   // SRL feeding TRUNCATE.
16681   if (Op0.getOpcode() == ISD::SRL) {
16682     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16683     // The right shift has to be by 64 bits.
16684     if (!ConstNode || ConstNode->getZExtValue() != 64)
16685       return SDValue();
16686 
16687     // Switch the element number to extract.
16688     EltToExtract = EltToExtract ? 0 : 1;
16689     // Update Op0 past the SRL.
16690     Op0 = Op0.getOperand(0);
16691   }
16692 
16693   // BITCAST feeding a TRUNCATE possibly via SRL.
16694   if (Op0.getOpcode() == ISD::BITCAST &&
16695       Op0.getValueType() == MVT::i128 &&
16696       Op0.getOperand(0).getValueType() == MVT::f128) {
16697     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16698     return DCI.DAG.getNode(
16699         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16700         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16701   }
16702   return SDValue();
16703 }
16704 
16705 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16706   SelectionDAG &DAG = DCI.DAG;
16707 
16708   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16709   if (!ConstOpOrElement)
16710     return SDValue();
16711 
16712   // An imul is usually smaller than the alternative sequence for legal type.
16713   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16714       isOperationLegal(ISD::MUL, N->getValueType(0)))
16715     return SDValue();
16716 
16717   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16718     switch (this->Subtarget.getCPUDirective()) {
16719     default:
16720       // TODO: enhance the condition for subtarget before pwr8
16721       return false;
16722     case PPC::DIR_PWR8:
16723       //  type        mul     add    shl
16724       // scalar        4       1      1
16725       // vector        7       2      2
16726       return true;
16727     case PPC::DIR_PWR9:
16728     case PPC::DIR_PWR10:
16729     case PPC::DIR_PWR_FUTURE:
16730       //  type        mul     add    shl
16731       // scalar        5       2      2
16732       // vector        7       2      2
16733 
16734       // The cycle RATIO of related operations are showed as a table above.
16735       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16736       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16737       // are 4, it is always profitable; but for 3 instrs patterns
16738       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16739       // So we should only do it for vector type.
16740       return IsAddOne && IsNeg ? VT.isVector() : true;
16741     }
16742   };
16743 
16744   EVT VT = N->getValueType(0);
16745   SDLoc DL(N);
16746 
16747   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16748   bool IsNeg = MulAmt.isNegative();
16749   APInt MulAmtAbs = MulAmt.abs();
16750 
16751   if ((MulAmtAbs - 1).isPowerOf2()) {
16752     // (mul x, 2^N + 1) => (add (shl x, N), x)
16753     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16754 
16755     if (!IsProfitable(IsNeg, true, VT))
16756       return SDValue();
16757 
16758     SDValue Op0 = N->getOperand(0);
16759     SDValue Op1 =
16760         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16761                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16762     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16763 
16764     if (!IsNeg)
16765       return Res;
16766 
16767     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16768   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16769     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16770     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16771 
16772     if (!IsProfitable(IsNeg, false, VT))
16773       return SDValue();
16774 
16775     SDValue Op0 = N->getOperand(0);
16776     SDValue Op1 =
16777         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16778                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16779 
16780     if (!IsNeg)
16781       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16782     else
16783       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16784 
16785   } else {
16786     return SDValue();
16787   }
16788 }
16789 
16790 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16791 // in combiner since we need to check SD flags and other subtarget features.
16792 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16793                                           DAGCombinerInfo &DCI) const {
16794   SDValue N0 = N->getOperand(0);
16795   SDValue N1 = N->getOperand(1);
16796   SDValue N2 = N->getOperand(2);
16797   SDNodeFlags Flags = N->getFlags();
16798   EVT VT = N->getValueType(0);
16799   SelectionDAG &DAG = DCI.DAG;
16800   const TargetOptions &Options = getTargetMachine().Options;
16801   unsigned Opc = N->getOpcode();
16802   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16803   bool LegalOps = !DCI.isBeforeLegalizeOps();
16804   SDLoc Loc(N);
16805 
16806   if (!isOperationLegal(ISD::FMA, VT))
16807     return SDValue();
16808 
16809   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16810   // since (fnmsub a b c)=-0 while c-ab=+0.
16811   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16812     return SDValue();
16813 
16814   // (fma (fneg a) b c) => (fnmsub a b c)
16815   // (fnmsub (fneg a) b c) => (fma a b c)
16816   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16817     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16818 
16819   // (fma a (fneg b) c) => (fnmsub a b c)
16820   // (fnmsub a (fneg b) c) => (fma a b c)
16821   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16822     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16823 
16824   return SDValue();
16825 }
16826 
16827 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16828   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16829   if (!Subtarget.is64BitELFABI())
16830     return false;
16831 
16832   // If not a tail call then no need to proceed.
16833   if (!CI->isTailCall())
16834     return false;
16835 
16836   // If sibling calls have been disabled and tail-calls aren't guaranteed
16837   // there is no reason to duplicate.
16838   auto &TM = getTargetMachine();
16839   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16840     return false;
16841 
16842   // Can't tail call a function called indirectly, or if it has variadic args.
16843   const Function *Callee = CI->getCalledFunction();
16844   if (!Callee || Callee->isVarArg())
16845     return false;
16846 
16847   // Make sure the callee and caller calling conventions are eligible for tco.
16848   const Function *Caller = CI->getParent()->getParent();
16849   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16850                                            CI->getCallingConv()))
16851       return false;
16852 
16853   // If the function is local then we have a good chance at tail-calling it
16854   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16855 }
16856 
16857 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16858   if (!Subtarget.hasVSX())
16859     return false;
16860   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16861     return true;
16862   return VT == MVT::f32 || VT == MVT::f64 ||
16863     VT == MVT::v4f32 || VT == MVT::v2f64;
16864 }
16865 
16866 bool PPCTargetLowering::
16867 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16868   const Value *Mask = AndI.getOperand(1);
16869   // If the mask is suitable for andi. or andis. we should sink the and.
16870   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16871     // Can't handle constants wider than 64-bits.
16872     if (CI->getBitWidth() > 64)
16873       return false;
16874     int64_t ConstVal = CI->getZExtValue();
16875     return isUInt<16>(ConstVal) ||
16876       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16877   }
16878 
16879   // For non-constant masks, we can always use the record-form and.
16880   return true;
16881 }
16882 
16883 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16884 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16885 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16886 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16887 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16888 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16889   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16890   assert(Subtarget.hasP9Altivec() &&
16891          "Only combine this when P9 altivec supported!");
16892   EVT VT = N->getValueType(0);
16893   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16894     return SDValue();
16895 
16896   SelectionDAG &DAG = DCI.DAG;
16897   SDLoc dl(N);
16898   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16899     // Even for signed integers, if it's known to be positive (as signed
16900     // integer) due to zero-extended inputs.
16901     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16902     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16903     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16904          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16905         (SubOpcd1 == ISD::ZERO_EXTEND ||
16906          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16907       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16908                          N->getOperand(0)->getOperand(0),
16909                          N->getOperand(0)->getOperand(1),
16910                          DAG.getTargetConstant(0, dl, MVT::i32));
16911     }
16912 
16913     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16914     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16915         N->getOperand(0).hasOneUse()) {
16916       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16917                          N->getOperand(0)->getOperand(0),
16918                          N->getOperand(0)->getOperand(1),
16919                          DAG.getTargetConstant(1, dl, MVT::i32));
16920     }
16921   }
16922 
16923   return SDValue();
16924 }
16925 
16926 // For type v4i32/v8ii16/v16i8, transform
16927 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16928 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16929 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16930 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16931 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16932                                           DAGCombinerInfo &DCI) const {
16933   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16934   assert(Subtarget.hasP9Altivec() &&
16935          "Only combine this when P9 altivec supported!");
16936 
16937   SelectionDAG &DAG = DCI.DAG;
16938   SDLoc dl(N);
16939   SDValue Cond = N->getOperand(0);
16940   SDValue TrueOpnd = N->getOperand(1);
16941   SDValue FalseOpnd = N->getOperand(2);
16942   EVT VT = N->getOperand(1).getValueType();
16943 
16944   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16945       FalseOpnd.getOpcode() != ISD::SUB)
16946     return SDValue();
16947 
16948   // ABSD only available for type v4i32/v8i16/v16i8
16949   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16950     return SDValue();
16951 
16952   // At least to save one more dependent computation
16953   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16954     return SDValue();
16955 
16956   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16957 
16958   // Can only handle unsigned comparison here
16959   switch (CC) {
16960   default:
16961     return SDValue();
16962   case ISD::SETUGT:
16963   case ISD::SETUGE:
16964     break;
16965   case ISD::SETULT:
16966   case ISD::SETULE:
16967     std::swap(TrueOpnd, FalseOpnd);
16968     break;
16969   }
16970 
16971   SDValue CmpOpnd1 = Cond.getOperand(0);
16972   SDValue CmpOpnd2 = Cond.getOperand(1);
16973 
16974   // SETCC CmpOpnd1 CmpOpnd2 cond
16975   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16976   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16977   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16978       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16979       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16980       FalseOpnd.getOperand(1) == CmpOpnd1) {
16981     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16982                        CmpOpnd1, CmpOpnd2,
16983                        DAG.getTargetConstant(0, dl, MVT::i32));
16984   }
16985 
16986   return SDValue();
16987 }
16988