1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the PPCISelLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PPCISelLowering.h"
14 #include "MCTargetDesc/PPCPredicates.h"
15 #include "PPC.h"
16 #include "PPCCCState.h"
17 #include "PPCCallingConv.h"
18 #include "PPCFrameLowering.h"
19 #include "PPCInstrInfo.h"
20 #include "PPCMachineFunctionInfo.h"
21 #include "PPCPerfectShuffle.h"
22 #include "PPCRegisterInfo.h"
23 #include "PPCSubtarget.h"
24 #include "PPCTargetMachine.h"
25 #include "llvm/ADT/APFloat.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/None.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/CodeGen/CallingConvLower.h"
38 #include "llvm/CodeGen/ISDOpcodes.h"
39 #include "llvm/CodeGen/MachineBasicBlock.h"
40 #include "llvm/CodeGen/MachineFrameInfo.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineInstr.h"
43 #include "llvm/CodeGen/MachineInstrBuilder.h"
44 #include "llvm/CodeGen/MachineJumpTableInfo.h"
45 #include "llvm/CodeGen/MachineLoopInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/RuntimeLibcalls.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetLowering.h"
55 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/CallingConv.h"
59 #include "llvm/IR/Constant.h"
60 #include "llvm/IR/Constants.h"
61 #include "llvm/IR/DataLayout.h"
62 #include "llvm/IR/DebugLoc.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/GlobalValue.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/Intrinsics.h"
69 #include "llvm/IR/IntrinsicsPowerPC.h"
70 #include "llvm/IR/Module.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/Use.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/MC/MCContext.h"
75 #include "llvm/MC/MCExpr.h"
76 #include "llvm/MC/MCRegisterInfo.h"
77 #include "llvm/MC/MCSectionXCOFF.h"
78 #include "llvm/MC/MCSymbolXCOFF.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/BranchProbability.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/CodeGen.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/Compiler.h"
85 #include "llvm/Support/Debug.h"
86 #include "llvm/Support/ErrorHandling.h"
87 #include "llvm/Support/Format.h"
88 #include "llvm/Support/KnownBits.h"
89 #include "llvm/Support/MachineValueType.h"
90 #include "llvm/Support/MathExtras.h"
91 #include "llvm/Support/raw_ostream.h"
92 #include "llvm/Target/TargetMachine.h"
93 #include "llvm/Target/TargetOptions.h"
94 #include <algorithm>
95 #include <cassert>
96 #include <cstdint>
97 #include <iterator>
98 #include <list>
99 #include <utility>
100 #include <vector>
101 
102 using namespace llvm;
103 
104 #define DEBUG_TYPE "ppc-lowering"
105 
106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
108 
109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
111 
112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
114 
115 static cl::opt<bool> DisableSCO("disable-ppc-sco",
116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
117 
118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
120 
121 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
122 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
123 
124 // TODO - Remove this option if soft fp128 has been fully supported .
125 static cl::opt<bool>
126     EnableSoftFP128("enable-soft-fp128",
127                     cl::desc("temp option to enable soft fp128"), cl::Hidden);
128 
129 STATISTIC(NumTailCalls, "Number of tail calls");
130 STATISTIC(NumSiblingCalls, "Number of sibling calls");
131 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM");
132 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
133 
134 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
135 
136 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
137 
138 // FIXME: Remove this once the bug has been fixed!
139 extern cl::opt<bool> ANDIGlueBug;
140 
141 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
142                                      const PPCSubtarget &STI)
143     : TargetLowering(TM), Subtarget(STI) {
144   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
145   // arguments are at least 4/8 bytes aligned.
146   bool isPPC64 = Subtarget.isPPC64();
147   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
148 
149   // Set up the register classes.
150   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
151   if (!useSoftFloat()) {
152     if (hasSPE()) {
153       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
154       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
155     } else {
156       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
157       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
158     }
159   }
160 
161   // Match BITREVERSE to customized fast code sequence in the td file.
162   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
163   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
164 
165   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
166   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
167 
168   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
169   for (MVT VT : MVT::integer_valuetypes()) {
170     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
171     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
172   }
173 
174   if (Subtarget.isISA3_0()) {
175     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
176     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
177     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
178     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
179   } else {
180     // No extending loads from f16 or HW conversions back and forth.
181     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
182     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
183     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
184     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
185     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
186     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
187     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
188     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
189   }
190 
191   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
192 
193   // PowerPC has pre-inc load and store's.
194   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
195   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
196   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
197   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
198   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
199   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
200   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
201   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
202   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
203   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
204   if (!Subtarget.hasSPE()) {
205     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
206     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
207     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
208     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
209   }
210 
211   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
212   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
213   for (MVT VT : ScalarIntVTs) {
214     setOperationAction(ISD::ADDC, VT, Legal);
215     setOperationAction(ISD::ADDE, VT, Legal);
216     setOperationAction(ISD::SUBC, VT, Legal);
217     setOperationAction(ISD::SUBE, VT, Legal);
218   }
219 
220   if (Subtarget.useCRBits()) {
221     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
222 
223     if (isPPC64 || Subtarget.hasFPCVT()) {
224       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote);
225       AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1,
226                         isPPC64 ? MVT::i64 : MVT::i32);
227       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote);
228       AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1,
229                         isPPC64 ? MVT::i64 : MVT::i32);
230 
231       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
232       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
233                          isPPC64 ? MVT::i64 : MVT::i32);
234       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
235       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
236                         isPPC64 ? MVT::i64 : MVT::i32);
237 
238       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote);
239       AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1,
240                         isPPC64 ? MVT::i64 : MVT::i32);
241       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote);
242       AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1,
243                         isPPC64 ? MVT::i64 : MVT::i32);
244 
245       setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
246       AddPromotedToType(ISD::FP_TO_SINT, MVT::i1,
247                         isPPC64 ? MVT::i64 : MVT::i32);
248       setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
249       AddPromotedToType(ISD::FP_TO_UINT, MVT::i1,
250                         isPPC64 ? MVT::i64 : MVT::i32);
251     } else {
252       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom);
253       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom);
254       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
255       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
256     }
257 
258     // PowerPC does not support direct load/store of condition registers.
259     setOperationAction(ISD::LOAD, MVT::i1, Custom);
260     setOperationAction(ISD::STORE, MVT::i1, Custom);
261 
262     // FIXME: Remove this once the ANDI glue bug is fixed:
263     if (ANDIGlueBug)
264       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
265 
266     for (MVT VT : MVT::integer_valuetypes()) {
267       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
268       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
269       setTruncStoreAction(VT, MVT::i1, Expand);
270     }
271 
272     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
273   }
274 
275   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
276   // PPC (the libcall is not available).
277   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
278   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
279   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom);
280   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom);
281 
282   // We do not currently implement these libm ops for PowerPC.
283   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
284   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
285   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
286   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
287   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
288   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
289 
290   // PowerPC has no SREM/UREM instructions unless we are on P9
291   // On P9 we may use a hardware instruction to compute the remainder.
292   // When the result of both the remainder and the division is required it is
293   // more efficient to compute the remainder from the result of the division
294   // rather than use the remainder instruction. The instructions are legalized
295   // directly because the DivRemPairsPass performs the transformation at the IR
296   // level.
297   if (Subtarget.isISA3_0()) {
298     setOperationAction(ISD::SREM, MVT::i32, Legal);
299     setOperationAction(ISD::UREM, MVT::i32, Legal);
300     setOperationAction(ISD::SREM, MVT::i64, Legal);
301     setOperationAction(ISD::UREM, MVT::i64, Legal);
302   } else {
303     setOperationAction(ISD::SREM, MVT::i32, Expand);
304     setOperationAction(ISD::UREM, MVT::i32, Expand);
305     setOperationAction(ISD::SREM, MVT::i64, Expand);
306     setOperationAction(ISD::UREM, MVT::i64, Expand);
307   }
308 
309   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
310   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
311   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
312   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
313   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
314   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
315   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
316   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
317   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
318 
319   // Handle constrained floating-point operations of scalar.
320   // TODO: Handle SPE specific operation.
321   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
322   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
323   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
324   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
325   setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
326   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
327 
328   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
329   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
330   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
331   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
332   setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
333   if (Subtarget.hasVSX()) {
334     setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal);
335     setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal);
336   }
337 
338   if (Subtarget.hasFSQRT()) {
339     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
340     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
341   }
342 
343   if (Subtarget.hasFPRND()) {
344     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
345     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
346     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
347     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
348 
349     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
350     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
351     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
352     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
353   }
354 
355   // We don't support sin/cos/sqrt/fmod/pow
356   setOperationAction(ISD::FSIN , MVT::f64, Expand);
357   setOperationAction(ISD::FCOS , MVT::f64, Expand);
358   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
359   setOperationAction(ISD::FREM , MVT::f64, Expand);
360   setOperationAction(ISD::FPOW , MVT::f64, Expand);
361   setOperationAction(ISD::FSIN , MVT::f32, Expand);
362   setOperationAction(ISD::FCOS , MVT::f32, Expand);
363   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
364   setOperationAction(ISD::FREM , MVT::f32, Expand);
365   setOperationAction(ISD::FPOW , MVT::f32, Expand);
366   if (Subtarget.hasSPE()) {
367     setOperationAction(ISD::FMA  , MVT::f64, Expand);
368     setOperationAction(ISD::FMA  , MVT::f32, Expand);
369   } else {
370     setOperationAction(ISD::FMA  , MVT::f64, Legal);
371     setOperationAction(ISD::FMA  , MVT::f32, Legal);
372   }
373 
374   if (Subtarget.hasSPE())
375     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
376 
377   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
378 
379   // If we're enabling GP optimizations, use hardware square root
380   if (!Subtarget.hasFSQRT() &&
381       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
382         Subtarget.hasFRE()))
383     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
384 
385   if (!Subtarget.hasFSQRT() &&
386       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
387         Subtarget.hasFRES()))
388     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
389 
390   if (Subtarget.hasFCPSGN()) {
391     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
392     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
393   } else {
394     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
395     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
396   }
397 
398   if (Subtarget.hasFPRND()) {
399     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
400     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
401     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
402     setOperationAction(ISD::FROUND, MVT::f64, Legal);
403 
404     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
405     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
406     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
407     setOperationAction(ISD::FROUND, MVT::f32, Legal);
408   }
409 
410   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
411   // to speed up scalar BSWAP64.
412   // CTPOP or CTTZ were introduced in P8/P9 respectively
413   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
414   if (Subtarget.hasP9Vector())
415     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
416   else
417     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
418   if (Subtarget.isISA3_0()) {
419     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
420     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
421   } else {
422     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
423     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
424   }
425 
426   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
427     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
428     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
429   } else {
430     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
431     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
432   }
433 
434   // PowerPC does not have ROTR
435   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
436   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
437 
438   if (!Subtarget.useCRBits()) {
439     // PowerPC does not have Select
440     setOperationAction(ISD::SELECT, MVT::i32, Expand);
441     setOperationAction(ISD::SELECT, MVT::i64, Expand);
442     setOperationAction(ISD::SELECT, MVT::f32, Expand);
443     setOperationAction(ISD::SELECT, MVT::f64, Expand);
444   }
445 
446   // PowerPC wants to turn select_cc of FP into fsel when possible.
447   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
448   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
449 
450   // PowerPC wants to optimize integer setcc a bit
451   if (!Subtarget.useCRBits())
452     setOperationAction(ISD::SETCC, MVT::i32, Custom);
453 
454   if (Subtarget.hasFPU()) {
455     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
456     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
457     setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
458 
459     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
460     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
461     setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
462   }
463 
464   // PowerPC does not have BRCOND which requires SetCC
465   if (!Subtarget.useCRBits())
466     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
467 
468   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
469 
470   if (Subtarget.hasSPE()) {
471     // SPE has built-in conversions
472     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
473     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
474     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
475     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
476     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
477     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
478   } else {
479     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
480     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
481     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
482 
483     // PowerPC does not have [U|S]INT_TO_FP
484     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand);
485     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand);
486     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
487     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
488   }
489 
490   if (Subtarget.hasDirectMove() && isPPC64) {
491     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
492     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
493     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
494     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
495     if (TM.Options.UnsafeFPMath) {
496       setOperationAction(ISD::LRINT, MVT::f64, Legal);
497       setOperationAction(ISD::LRINT, MVT::f32, Legal);
498       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
499       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
500       setOperationAction(ISD::LROUND, MVT::f64, Legal);
501       setOperationAction(ISD::LROUND, MVT::f32, Legal);
502       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
503       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
504     }
505   } else {
506     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
507     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
508     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
509     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
510   }
511 
512   // We cannot sextinreg(i1).  Expand to shifts.
513   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
514 
515   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
516   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
517   // support continuation, user-level threading, and etc.. As a result, no
518   // other SjLj exception interfaces are implemented and please don't build
519   // your own exception handling based on them.
520   // LLVM/Clang supports zero-cost DWARF exception handling.
521   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
522   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
523 
524   // We want to legalize GlobalAddress and ConstantPool nodes into the
525   // appropriate instructions to materialize the address.
526   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
527   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
528   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
529   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
530   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
531   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
532   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
533   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
534   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
535   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
536 
537   // TRAP is legal.
538   setOperationAction(ISD::TRAP, MVT::Other, Legal);
539 
540   // TRAMPOLINE is custom lowered.
541   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
542   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
543 
544   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
545   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
546 
547   if (Subtarget.is64BitELFABI()) {
548     // VAARG always uses double-word chunks, so promote anything smaller.
549     setOperationAction(ISD::VAARG, MVT::i1, Promote);
550     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
551     setOperationAction(ISD::VAARG, MVT::i8, Promote);
552     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
553     setOperationAction(ISD::VAARG, MVT::i16, Promote);
554     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
555     setOperationAction(ISD::VAARG, MVT::i32, Promote);
556     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
557     setOperationAction(ISD::VAARG, MVT::Other, Expand);
558   } else if (Subtarget.is32BitELFABI()) {
559     // VAARG is custom lowered with the 32-bit SVR4 ABI.
560     setOperationAction(ISD::VAARG, MVT::Other, Custom);
561     setOperationAction(ISD::VAARG, MVT::i64, Custom);
562   } else
563     setOperationAction(ISD::VAARG, MVT::Other, Expand);
564 
565   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
566   if (Subtarget.is32BitELFABI())
567     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
568   else
569     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
570 
571   // Use the default implementation.
572   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
573   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
574   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
575   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
576   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
577   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
578   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
579   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
580   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
581 
582   // We want to custom lower some of our intrinsics.
583   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
584 
585   // To handle counter-based loop conditions.
586   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
587 
588   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
589   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
590   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
591   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
592 
593   // Comparisons that require checking two conditions.
594   if (Subtarget.hasSPE()) {
595     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
596     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
597     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
598     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
599   }
600   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
601   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
602   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
603   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
604   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
605   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
606   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
607   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
608   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
609   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
610   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
611   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
612 
613   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
614   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
615 
616   if (Subtarget.has64BitSupport()) {
617     // They also have instructions for converting between i64 and fp.
618     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
619     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
620     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
621     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
622     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
623     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
624     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
625     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
626     // This is just the low 32 bits of a (signed) fp->i64 conversion.
627     // We cannot do this with Promote because i64 is not a legal type.
628     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
629     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
630 
631     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
632       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
633       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
634     }
635   } else {
636     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
637     if (Subtarget.hasSPE()) {
638       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
639       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
640     } else {
641       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
642       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
643     }
644   }
645 
646   // With the instructions enabled under FPCVT, we can do everything.
647   if (Subtarget.hasFPCVT()) {
648     if (Subtarget.has64BitSupport()) {
649       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
650       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
651       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
652       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
653       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
654       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
655       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
656       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
657     }
658 
659     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
660     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
661     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
662     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
663     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
664     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
665     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
666     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
667   }
668 
669   if (Subtarget.use64BitRegs()) {
670     // 64-bit PowerPC implementations can support i64 types directly
671     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
672     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
673     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
674     // 64-bit PowerPC wants to expand i128 shifts itself.
675     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
676     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
677     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
678   } else {
679     // 32-bit PowerPC wants to expand i64 shifts itself.
680     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
681     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
682     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
683   }
684 
685   // PowerPC has better expansions for funnel shifts than the generic
686   // TargetLowering::expandFunnelShift.
687   if (Subtarget.has64BitSupport()) {
688     setOperationAction(ISD::FSHL, MVT::i64, Custom);
689     setOperationAction(ISD::FSHR, MVT::i64, Custom);
690   }
691   setOperationAction(ISD::FSHL, MVT::i32, Custom);
692   setOperationAction(ISD::FSHR, MVT::i32, Custom);
693 
694   if (Subtarget.hasVSX()) {
695     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
696     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
697     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
698     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
699   }
700 
701   if (Subtarget.hasAltivec()) {
702     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
703       setOperationAction(ISD::SADDSAT, VT, Legal);
704       setOperationAction(ISD::SSUBSAT, VT, Legal);
705       setOperationAction(ISD::UADDSAT, VT, Legal);
706       setOperationAction(ISD::USUBSAT, VT, Legal);
707     }
708     // First set operation action for all vector types to expand. Then we
709     // will selectively turn on ones that can be effectively codegen'd.
710     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
711       // add/sub are legal for all supported vector VT's.
712       setOperationAction(ISD::ADD, VT, Legal);
713       setOperationAction(ISD::SUB, VT, Legal);
714 
715       // For v2i64, these are only valid with P8Vector. This is corrected after
716       // the loop.
717       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
718         setOperationAction(ISD::SMAX, VT, Legal);
719         setOperationAction(ISD::SMIN, VT, Legal);
720         setOperationAction(ISD::UMAX, VT, Legal);
721         setOperationAction(ISD::UMIN, VT, Legal);
722       }
723       else {
724         setOperationAction(ISD::SMAX, VT, Expand);
725         setOperationAction(ISD::SMIN, VT, Expand);
726         setOperationAction(ISD::UMAX, VT, Expand);
727         setOperationAction(ISD::UMIN, VT, Expand);
728       }
729 
730       if (Subtarget.hasVSX()) {
731         setOperationAction(ISD::FMAXNUM, VT, Legal);
732         setOperationAction(ISD::FMINNUM, VT, Legal);
733       }
734 
735       // Vector instructions introduced in P8
736       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
737         setOperationAction(ISD::CTPOP, VT, Legal);
738         setOperationAction(ISD::CTLZ, VT, Legal);
739       }
740       else {
741         setOperationAction(ISD::CTPOP, VT, Expand);
742         setOperationAction(ISD::CTLZ, VT, Expand);
743       }
744 
745       // Vector instructions introduced in P9
746       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
747         setOperationAction(ISD::CTTZ, VT, Legal);
748       else
749         setOperationAction(ISD::CTTZ, VT, Expand);
750 
751       // We promote all shuffles to v16i8.
752       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
753       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
754 
755       // We promote all non-typed operations to v4i32.
756       setOperationAction(ISD::AND   , VT, Promote);
757       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
758       setOperationAction(ISD::OR    , VT, Promote);
759       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
760       setOperationAction(ISD::XOR   , VT, Promote);
761       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
762       setOperationAction(ISD::LOAD  , VT, Promote);
763       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
764       setOperationAction(ISD::SELECT, VT, Promote);
765       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
766       setOperationAction(ISD::VSELECT, VT, Legal);
767       setOperationAction(ISD::SELECT_CC, VT, Promote);
768       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
769       setOperationAction(ISD::STORE, VT, Promote);
770       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
771 
772       // No other operations are legal.
773       setOperationAction(ISD::MUL , VT, Expand);
774       setOperationAction(ISD::SDIV, VT, Expand);
775       setOperationAction(ISD::SREM, VT, Expand);
776       setOperationAction(ISD::UDIV, VT, Expand);
777       setOperationAction(ISD::UREM, VT, Expand);
778       setOperationAction(ISD::FDIV, VT, Expand);
779       setOperationAction(ISD::FREM, VT, Expand);
780       setOperationAction(ISD::FNEG, VT, Expand);
781       setOperationAction(ISD::FSQRT, VT, Expand);
782       setOperationAction(ISD::FLOG, VT, Expand);
783       setOperationAction(ISD::FLOG10, VT, Expand);
784       setOperationAction(ISD::FLOG2, VT, Expand);
785       setOperationAction(ISD::FEXP, VT, Expand);
786       setOperationAction(ISD::FEXP2, VT, Expand);
787       setOperationAction(ISD::FSIN, VT, Expand);
788       setOperationAction(ISD::FCOS, VT, Expand);
789       setOperationAction(ISD::FABS, VT, Expand);
790       setOperationAction(ISD::FFLOOR, VT, Expand);
791       setOperationAction(ISD::FCEIL,  VT, Expand);
792       setOperationAction(ISD::FTRUNC, VT, Expand);
793       setOperationAction(ISD::FRINT,  VT, Expand);
794       setOperationAction(ISD::FNEARBYINT, VT, Expand);
795       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
796       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
797       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
798       setOperationAction(ISD::MULHU, VT, Expand);
799       setOperationAction(ISD::MULHS, VT, Expand);
800       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
801       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
802       setOperationAction(ISD::UDIVREM, VT, Expand);
803       setOperationAction(ISD::SDIVREM, VT, Expand);
804       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
805       setOperationAction(ISD::FPOW, VT, Expand);
806       setOperationAction(ISD::BSWAP, VT, Expand);
807       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
808       setOperationAction(ISD::ROTL, VT, Expand);
809       setOperationAction(ISD::ROTR, VT, Expand);
810 
811       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
812         setTruncStoreAction(VT, InnerVT, Expand);
813         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
814         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
815         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
816       }
817     }
818     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
819     if (!Subtarget.hasP8Vector()) {
820       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
821       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
822       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
823       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
824     }
825 
826     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
827     // with merges, splats, etc.
828     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
829 
830     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
831     // are cheap, so handle them before they get expanded to scalar.
832     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
833     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
834     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
835     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
836     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
837 
838     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
839     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
840     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
841     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
842     setOperationAction(ISD::SELECT, MVT::v4i32,
843                        Subtarget.useCRBits() ? Legal : Expand);
844     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
845     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
846     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
847     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
848     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
849     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
850     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
851     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
852     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
853     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
854     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
855     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
856     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
857 
858     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
859     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
860     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
861     if (Subtarget.hasAltivec())
862       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
863         setOperationAction(ISD::ROTL, VT, Legal);
864     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
865     if (Subtarget.hasP8Altivec())
866       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
867 
868     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
869     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
870     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
871     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
872 
873     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
874     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
875 
876     if (Subtarget.hasVSX()) {
877       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
878       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
879     }
880 
881     if (Subtarget.hasP8Altivec())
882       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
883     else
884       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
885 
886     if (Subtarget.isISA3_1()) {
887       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
888       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
889       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
890       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
891       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
892       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
893       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
894       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
895       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
896       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
897       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
898       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
899       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
900       setOperationAction(ISD::UREM, MVT::v1i128, Legal);
901       setOperationAction(ISD::SREM, MVT::v1i128, Legal);
902       setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
903       setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
904       setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
905     }
906 
907     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
908     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
909 
910     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
911     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
912 
913     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
914     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
915     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
916     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
917 
918     // Altivec does not contain unordered floating-point compare instructions
919     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
920     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
921     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
922     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
923 
924     if (Subtarget.hasVSX()) {
925       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
926       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
927       if (Subtarget.hasP8Vector()) {
928         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
929         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
930       }
931       if (Subtarget.hasDirectMove() && isPPC64) {
932         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
933         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
934         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
935         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
936         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
937         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
938         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
939         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
940       }
941       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
942 
943       // The nearbyint variants are not allowed to raise the inexact exception
944       // so we can only code-gen them with unsafe math.
945       if (TM.Options.UnsafeFPMath) {
946         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
947         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
948       }
949 
950       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
951       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
952       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
953       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
954       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
955       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
956       setOperationAction(ISD::FROUND, MVT::f64, Legal);
957       setOperationAction(ISD::FRINT, MVT::f64, Legal);
958 
959       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
960       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
961       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
962       setOperationAction(ISD::FROUND, MVT::f32, Legal);
963       setOperationAction(ISD::FRINT, MVT::f32, Legal);
964 
965       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
966       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
967 
968       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
969       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
970 
971       // Share the Altivec comparison restrictions.
972       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
973       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
974       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
975       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
976 
977       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
978       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
979 
980       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
981 
982       if (Subtarget.hasP8Vector())
983         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
984 
985       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
986 
987       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
988       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
989       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
990 
991       if (Subtarget.hasP8Altivec()) {
992         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
993         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
994         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
995 
996         // 128 bit shifts can be accomplished via 3 instructions for SHL and
997         // SRL, but not for SRA because of the instructions available:
998         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
999         // doing
1000         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
1001         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
1002         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1003 
1004         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
1005       }
1006       else {
1007         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
1008         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1009         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1010 
1011         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1012 
1013         // VSX v2i64 only supports non-arithmetic operations.
1014         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1015         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1016       }
1017 
1018       if (Subtarget.isISA3_1())
1019         setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1020       else
1021         setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1022 
1023       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1024       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1025       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1026       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1027 
1028       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
1029 
1030       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1031       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1032       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1033       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1034       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1035       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1036       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1037       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1038 
1039       // Custom handling for partial vectors of integers converted to
1040       // floating point. We already have optimal handling for v2i32 through
1041       // the DAG combine, so those aren't necessary.
1042       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1043       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1044       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1045       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1046       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1047       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1048       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1049       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1050       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1051       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1052       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1053       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1054       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1055       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1056       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1057       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1058 
1059       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1060       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1061       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1062       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1063       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1064       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1065 
1066       if (Subtarget.hasDirectMove())
1067         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1068       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1069 
1070       // Handle constrained floating-point operations of vector.
1071       // The predictor is `hasVSX` because altivec instruction has
1072       // no exception but VSX vector instruction has.
1073       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1074       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1075       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1076       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1077       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1078       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1079       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1080       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1081       setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
1082       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1083       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1084       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1085       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1086 
1087       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1088       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1089       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1090       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1091       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1092       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1093       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1094       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1095       setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
1096       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1097       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1098       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1099       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1100 
1101       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1102     }
1103 
1104     if (Subtarget.hasP8Altivec()) {
1105       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1106       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1107     }
1108 
1109     if (Subtarget.hasP9Vector()) {
1110       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1111       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1112 
1113       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1114       // SRL, but not for SRA because of the instructions available:
1115       // VS{RL} and VS{RL}O.
1116       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1117       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1118       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1119 
1120       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1121       setOperationAction(ISD::FADD, MVT::f128, Legal);
1122       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1123       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1124       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1125       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1126       // No extending loads to f128 on PPC.
1127       for (MVT FPT : MVT::fp_valuetypes())
1128         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1129       setOperationAction(ISD::FMA, MVT::f128, Legal);
1130       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1131       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1132       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1133       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1134       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1135       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1136 
1137       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1138       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1139       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1140       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1141       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1142       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1143 
1144       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1145       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1146       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1147       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1148       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1149       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1150       // No implementation for these ops for PowerPC.
1151       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1152       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1153       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1154       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1155       setOperationAction(ISD::FREM, MVT::f128, Expand);
1156 
1157       // Handle constrained floating-point operations of fp128
1158       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1159       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1160       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1161       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1162       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1163       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1164       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1165       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1166       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1167       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1168       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1169       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1170       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1171       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1172       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1173       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1174       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1175       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1176       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1177       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1178     } else if (Subtarget.hasAltivec() && EnableSoftFP128) {
1179       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1180 
1181       for (MVT FPT : MVT::fp_valuetypes())
1182         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1183 
1184       setOperationAction(ISD::LOAD, MVT::f128, Promote);
1185       setOperationAction(ISD::STORE, MVT::f128, Promote);
1186 
1187       AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
1188       AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
1189 
1190       // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1191       // fp_to_uint and int_to_fp.
1192       setOperationAction(ISD::FADD, MVT::f128, LibCall);
1193       setOperationAction(ISD::FSUB, MVT::f128, LibCall);
1194 
1195       setOperationAction(ISD::FMUL, MVT::f128, Expand);
1196       setOperationAction(ISD::FDIV, MVT::f128, Expand);
1197       setOperationAction(ISD::FNEG, MVT::f128, Expand);
1198       setOperationAction(ISD::FABS, MVT::f128, Expand);
1199       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1200       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1201       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1202       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1203       setOperationAction(ISD::FREM, MVT::f128, Expand);
1204       setOperationAction(ISD::FSQRT, MVT::f128, Expand);
1205       setOperationAction(ISD::FMA, MVT::f128, Expand);
1206       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
1207 
1208       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1209       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1210 
1211       // Expand the fp_extend if the target type is fp128.
1212       setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand);
1213       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand);
1214 
1215       // Expand the fp_round if the source type is fp128.
1216       for (MVT VT : {MVT::f32, MVT::f64}) {
1217         setOperationAction(ISD::FP_ROUND, VT, Custom);
1218         setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom);
1219       }
1220     }
1221 
1222     if (Subtarget.hasP9Altivec()) {
1223       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1224       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1225 
1226       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1227       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1228       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1229       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1230       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1231       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1232       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1233     }
1234   }
1235 
1236   if (Subtarget.pairedVectorMemops()) {
1237     addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1238     setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1239     setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1240   }
1241   if (Subtarget.hasMMA()) {
1242     addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1243     setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1244     setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1245     setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom);
1246   }
1247 
1248   if (Subtarget.has64BitSupport())
1249     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1250 
1251   if (Subtarget.isISA3_1())
1252     setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1253 
1254   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1255 
1256   if (!isPPC64) {
1257     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1258     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1259   }
1260 
1261   setBooleanContents(ZeroOrOneBooleanContent);
1262 
1263   if (Subtarget.hasAltivec()) {
1264     // Altivec instructions set fields to all zeros or all ones.
1265     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1266   }
1267 
1268   if (!isPPC64) {
1269     // These libcalls are not available in 32-bit.
1270     setLibcallName(RTLIB::SHL_I128, nullptr);
1271     setLibcallName(RTLIB::SRL_I128, nullptr);
1272     setLibcallName(RTLIB::SRA_I128, nullptr);
1273   }
1274 
1275   if (!isPPC64)
1276     setMaxAtomicSizeInBitsSupported(32);
1277 
1278   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1279 
1280   // We have target-specific dag combine patterns for the following nodes:
1281   setTargetDAGCombine(ISD::ADD);
1282   setTargetDAGCombine(ISD::SHL);
1283   setTargetDAGCombine(ISD::SRA);
1284   setTargetDAGCombine(ISD::SRL);
1285   setTargetDAGCombine(ISD::MUL);
1286   setTargetDAGCombine(ISD::FMA);
1287   setTargetDAGCombine(ISD::SINT_TO_FP);
1288   setTargetDAGCombine(ISD::BUILD_VECTOR);
1289   if (Subtarget.hasFPCVT())
1290     setTargetDAGCombine(ISD::UINT_TO_FP);
1291   setTargetDAGCombine(ISD::LOAD);
1292   setTargetDAGCombine(ISD::STORE);
1293   setTargetDAGCombine(ISD::BR_CC);
1294   if (Subtarget.useCRBits())
1295     setTargetDAGCombine(ISD::BRCOND);
1296   setTargetDAGCombine(ISD::BSWAP);
1297   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1298   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1299   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1300 
1301   setTargetDAGCombine(ISD::SIGN_EXTEND);
1302   setTargetDAGCombine(ISD::ZERO_EXTEND);
1303   setTargetDAGCombine(ISD::ANY_EXTEND);
1304 
1305   setTargetDAGCombine(ISD::TRUNCATE);
1306   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1307 
1308 
1309   if (Subtarget.useCRBits()) {
1310     setTargetDAGCombine(ISD::TRUNCATE);
1311     setTargetDAGCombine(ISD::SETCC);
1312     setTargetDAGCombine(ISD::SELECT_CC);
1313   }
1314 
1315   if (Subtarget.hasP9Altivec()) {
1316     setTargetDAGCombine(ISD::ABS);
1317     setTargetDAGCombine(ISD::VSELECT);
1318   }
1319 
1320   setLibcallName(RTLIB::LOG_F128, "logf128");
1321   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1322   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1323   setLibcallName(RTLIB::EXP_F128, "expf128");
1324   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1325   setLibcallName(RTLIB::SIN_F128, "sinf128");
1326   setLibcallName(RTLIB::COS_F128, "cosf128");
1327   setLibcallName(RTLIB::POW_F128, "powf128");
1328   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1329   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1330   setLibcallName(RTLIB::REM_F128, "fmodf128");
1331   setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1332   setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1333   setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1334   setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1335   setLibcallName(RTLIB::ROUND_F128, "roundf128");
1336   setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1337   setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1338   setLibcallName(RTLIB::RINT_F128, "rintf128");
1339   setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1340   setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1341   setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1342   setLibcallName(RTLIB::FMA_F128, "fmaf128");
1343 
1344   // With 32 condition bits, we don't need to sink (and duplicate) compares
1345   // aggressively in CodeGenPrep.
1346   if (Subtarget.useCRBits()) {
1347     setHasMultipleConditionRegisters();
1348     setJumpIsExpensive();
1349   }
1350 
1351   setMinFunctionAlignment(Align(4));
1352 
1353   switch (Subtarget.getCPUDirective()) {
1354   default: break;
1355   case PPC::DIR_970:
1356   case PPC::DIR_A2:
1357   case PPC::DIR_E500:
1358   case PPC::DIR_E500mc:
1359   case PPC::DIR_E5500:
1360   case PPC::DIR_PWR4:
1361   case PPC::DIR_PWR5:
1362   case PPC::DIR_PWR5X:
1363   case PPC::DIR_PWR6:
1364   case PPC::DIR_PWR6X:
1365   case PPC::DIR_PWR7:
1366   case PPC::DIR_PWR8:
1367   case PPC::DIR_PWR9:
1368   case PPC::DIR_PWR10:
1369   case PPC::DIR_PWR_FUTURE:
1370     setPrefLoopAlignment(Align(16));
1371     setPrefFunctionAlignment(Align(16));
1372     break;
1373   }
1374 
1375   if (Subtarget.enableMachineScheduler())
1376     setSchedulingPreference(Sched::Source);
1377   else
1378     setSchedulingPreference(Sched::Hybrid);
1379 
1380   computeRegisterProperties(STI.getRegisterInfo());
1381 
1382   // The Freescale cores do better with aggressive inlining of memcpy and
1383   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1384   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1385       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1386     MaxStoresPerMemset = 32;
1387     MaxStoresPerMemsetOptSize = 16;
1388     MaxStoresPerMemcpy = 32;
1389     MaxStoresPerMemcpyOptSize = 8;
1390     MaxStoresPerMemmove = 32;
1391     MaxStoresPerMemmoveOptSize = 8;
1392   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1393     // The A2 also benefits from (very) aggressive inlining of memcpy and
1394     // friends. The overhead of a the function call, even when warm, can be
1395     // over one hundred cycles.
1396     MaxStoresPerMemset = 128;
1397     MaxStoresPerMemcpy = 128;
1398     MaxStoresPerMemmove = 128;
1399     MaxLoadsPerMemcmp = 128;
1400   } else {
1401     MaxLoadsPerMemcmp = 8;
1402     MaxLoadsPerMemcmpOptSize = 4;
1403   }
1404 
1405   IsStrictFPEnabled = true;
1406 
1407   // Let the subtarget (CPU) decide if a predictable select is more expensive
1408   // than the corresponding branch. This information is used in CGP to decide
1409   // when to convert selects into branches.
1410   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1411 }
1412 
1413 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1414 /// the desired ByVal argument alignment.
1415 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1416   if (MaxAlign == MaxMaxAlign)
1417     return;
1418   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1419     if (MaxMaxAlign >= 32 &&
1420         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1421       MaxAlign = Align(32);
1422     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1423              MaxAlign < 16)
1424       MaxAlign = Align(16);
1425   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1426     Align EltAlign;
1427     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1428     if (EltAlign > MaxAlign)
1429       MaxAlign = EltAlign;
1430   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1431     for (auto *EltTy : STy->elements()) {
1432       Align EltAlign;
1433       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1434       if (EltAlign > MaxAlign)
1435         MaxAlign = EltAlign;
1436       if (MaxAlign == MaxMaxAlign)
1437         break;
1438     }
1439   }
1440 }
1441 
1442 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1443 /// function arguments in the caller parameter area.
1444 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1445                                                   const DataLayout &DL) const {
1446   // 16byte and wider vectors are passed on 16byte boundary.
1447   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1448   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1449   if (Subtarget.hasAltivec())
1450     getMaxByValAlign(Ty, Alignment, Align(16));
1451   return Alignment.value();
1452 }
1453 
1454 bool PPCTargetLowering::useSoftFloat() const {
1455   return Subtarget.useSoftFloat();
1456 }
1457 
1458 bool PPCTargetLowering::hasSPE() const {
1459   return Subtarget.hasSPE();
1460 }
1461 
1462 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1463   return VT.isScalarInteger();
1464 }
1465 
1466 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1467   switch ((PPCISD::NodeType)Opcode) {
1468   case PPCISD::FIRST_NUMBER:    break;
1469   case PPCISD::FSEL:            return "PPCISD::FSEL";
1470   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1471   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1472   case PPCISD::FCFID:           return "PPCISD::FCFID";
1473   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1474   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1475   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1476   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1477   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1478   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1479   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1480   case PPCISD::FP_TO_UINT_IN_VSR:
1481                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1482   case PPCISD::FP_TO_SINT_IN_VSR:
1483                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1484   case PPCISD::FRE:             return "PPCISD::FRE";
1485   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1486   case PPCISD::FTSQRT:
1487     return "PPCISD::FTSQRT";
1488   case PPCISD::FSQRT:
1489     return "PPCISD::FSQRT";
1490   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1491   case PPCISD::VPERM:           return "PPCISD::VPERM";
1492   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1493   case PPCISD::XXSPLTI_SP_TO_DP:
1494     return "PPCISD::XXSPLTI_SP_TO_DP";
1495   case PPCISD::XXSPLTI32DX:
1496     return "PPCISD::XXSPLTI32DX";
1497   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1498   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1499   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1500   case PPCISD::CMPB:            return "PPCISD::CMPB";
1501   case PPCISD::Hi:              return "PPCISD::Hi";
1502   case PPCISD::Lo:              return "PPCISD::Lo";
1503   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1504   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1505   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1506   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1507   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1508   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1509   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1510   case PPCISD::SRL:             return "PPCISD::SRL";
1511   case PPCISD::SRA:             return "PPCISD::SRA";
1512   case PPCISD::SHL:             return "PPCISD::SHL";
1513   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1514   case PPCISD::CALL:            return "PPCISD::CALL";
1515   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1516   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1517   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1518   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1519   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1520   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1521   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1522   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1523   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1524   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1525   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1526   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1527   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1528   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1529   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1530   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1531     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1532   case PPCISD::ANDI_rec_1_EQ_BIT:
1533     return "PPCISD::ANDI_rec_1_EQ_BIT";
1534   case PPCISD::ANDI_rec_1_GT_BIT:
1535     return "PPCISD::ANDI_rec_1_GT_BIT";
1536   case PPCISD::VCMP:            return "PPCISD::VCMP";
1537   case PPCISD::VCMP_rec:        return "PPCISD::VCMP_rec";
1538   case PPCISD::LBRX:            return "PPCISD::LBRX";
1539   case PPCISD::STBRX:           return "PPCISD::STBRX";
1540   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1541   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1542   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1543   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1544   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1545   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1546   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1547   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1548   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1549   case PPCISD::ST_VSR_SCAL_INT:
1550                                 return "PPCISD::ST_VSR_SCAL_INT";
1551   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1552   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1553   case PPCISD::BDZ:             return "PPCISD::BDZ";
1554   case PPCISD::MFFS:            return "PPCISD::MFFS";
1555   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1556   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1557   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1558   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1559   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1560   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1561   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1562   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1563   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1564   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1565   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1566   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1567   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1568   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1569   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1570   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1571   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1572   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1573   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1574   case PPCISD::PADDI_DTPREL:
1575     return "PPCISD::PADDI_DTPREL";
1576   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1577   case PPCISD::SC:              return "PPCISD::SC";
1578   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1579   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1580   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1581   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1582   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1583   case PPCISD::VABSD:           return "PPCISD::VABSD";
1584   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1585   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1586   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1587   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1588   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1589   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1590   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1591   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1592     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1593   case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1594     return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1595   case PPCISD::ACC_BUILD:       return "PPCISD::ACC_BUILD";
1596   case PPCISD::PAIR_BUILD:      return "PPCISD::PAIR_BUILD";
1597   case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1598   case PPCISD::XXMFACC:         return "PPCISD::XXMFACC";
1599   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1600   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1601   case PPCISD::STRICT_FADDRTZ:
1602     return "PPCISD::STRICT_FADDRTZ";
1603   case PPCISD::STRICT_FCTIDZ:
1604     return "PPCISD::STRICT_FCTIDZ";
1605   case PPCISD::STRICT_FCTIWZ:
1606     return "PPCISD::STRICT_FCTIWZ";
1607   case PPCISD::STRICT_FCTIDUZ:
1608     return "PPCISD::STRICT_FCTIDUZ";
1609   case PPCISD::STRICT_FCTIWUZ:
1610     return "PPCISD::STRICT_FCTIWUZ";
1611   case PPCISD::STRICT_FCFID:
1612     return "PPCISD::STRICT_FCFID";
1613   case PPCISD::STRICT_FCFIDU:
1614     return "PPCISD::STRICT_FCFIDU";
1615   case PPCISD::STRICT_FCFIDS:
1616     return "PPCISD::STRICT_FCFIDS";
1617   case PPCISD::STRICT_FCFIDUS:
1618     return "PPCISD::STRICT_FCFIDUS";
1619   case PPCISD::LXVRZX:          return "PPCISD::LXVRZX";
1620   }
1621   return nullptr;
1622 }
1623 
1624 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1625                                           EVT VT) const {
1626   if (!VT.isVector())
1627     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1628 
1629   return VT.changeVectorElementTypeToInteger();
1630 }
1631 
1632 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1633   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1634   return true;
1635 }
1636 
1637 //===----------------------------------------------------------------------===//
1638 // Node matching predicates, for use by the tblgen matching code.
1639 //===----------------------------------------------------------------------===//
1640 
1641 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1642 static bool isFloatingPointZero(SDValue Op) {
1643   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1644     return CFP->getValueAPF().isZero();
1645   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1646     // Maybe this has already been legalized into the constant pool?
1647     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1648       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1649         return CFP->getValueAPF().isZero();
1650   }
1651   return false;
1652 }
1653 
1654 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1655 /// true if Op is undef or if it matches the specified value.
1656 static bool isConstantOrUndef(int Op, int Val) {
1657   return Op < 0 || Op == Val;
1658 }
1659 
1660 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1661 /// VPKUHUM instruction.
1662 /// The ShuffleKind distinguishes between big-endian operations with
1663 /// two different inputs (0), either-endian operations with two identical
1664 /// inputs (1), and little-endian operations with two different inputs (2).
1665 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1666 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1667                                SelectionDAG &DAG) {
1668   bool IsLE = DAG.getDataLayout().isLittleEndian();
1669   if (ShuffleKind == 0) {
1670     if (IsLE)
1671       return false;
1672     for (unsigned i = 0; i != 16; ++i)
1673       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1674         return false;
1675   } else if (ShuffleKind == 2) {
1676     if (!IsLE)
1677       return false;
1678     for (unsigned i = 0; i != 16; ++i)
1679       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1680         return false;
1681   } else if (ShuffleKind == 1) {
1682     unsigned j = IsLE ? 0 : 1;
1683     for (unsigned i = 0; i != 8; ++i)
1684       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1685           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1686         return false;
1687   }
1688   return true;
1689 }
1690 
1691 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1692 /// VPKUWUM instruction.
1693 /// The ShuffleKind distinguishes between big-endian operations with
1694 /// two different inputs (0), either-endian operations with two identical
1695 /// inputs (1), and little-endian operations with two different inputs (2).
1696 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1697 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1698                                SelectionDAG &DAG) {
1699   bool IsLE = DAG.getDataLayout().isLittleEndian();
1700   if (ShuffleKind == 0) {
1701     if (IsLE)
1702       return false;
1703     for (unsigned i = 0; i != 16; i += 2)
1704       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1705           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1706         return false;
1707   } else if (ShuffleKind == 2) {
1708     if (!IsLE)
1709       return false;
1710     for (unsigned i = 0; i != 16; i += 2)
1711       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1712           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1713         return false;
1714   } else if (ShuffleKind == 1) {
1715     unsigned j = IsLE ? 0 : 2;
1716     for (unsigned i = 0; i != 8; i += 2)
1717       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1718           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1719           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1720           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1721         return false;
1722   }
1723   return true;
1724 }
1725 
1726 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1727 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1728 /// current subtarget.
1729 ///
1730 /// The ShuffleKind distinguishes between big-endian operations with
1731 /// two different inputs (0), either-endian operations with two identical
1732 /// inputs (1), and little-endian operations with two different inputs (2).
1733 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1734 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1735                                SelectionDAG &DAG) {
1736   const PPCSubtarget& Subtarget =
1737       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1738   if (!Subtarget.hasP8Vector())
1739     return false;
1740 
1741   bool IsLE = DAG.getDataLayout().isLittleEndian();
1742   if (ShuffleKind == 0) {
1743     if (IsLE)
1744       return false;
1745     for (unsigned i = 0; i != 16; i += 4)
1746       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1747           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1748           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1749           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1750         return false;
1751   } else if (ShuffleKind == 2) {
1752     if (!IsLE)
1753       return false;
1754     for (unsigned i = 0; i != 16; i += 4)
1755       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1756           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1757           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1758           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1759         return false;
1760   } else if (ShuffleKind == 1) {
1761     unsigned j = IsLE ? 0 : 4;
1762     for (unsigned i = 0; i != 8; i += 4)
1763       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1764           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1765           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1766           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1767           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1768           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1769           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1770           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1771         return false;
1772   }
1773   return true;
1774 }
1775 
1776 /// isVMerge - Common function, used to match vmrg* shuffles.
1777 ///
1778 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1779                      unsigned LHSStart, unsigned RHSStart) {
1780   if (N->getValueType(0) != MVT::v16i8)
1781     return false;
1782   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1783          "Unsupported merge size!");
1784 
1785   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1786     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1787       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1788                              LHSStart+j+i*UnitSize) ||
1789           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1790                              RHSStart+j+i*UnitSize))
1791         return false;
1792     }
1793   return true;
1794 }
1795 
1796 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1797 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1798 /// The ShuffleKind distinguishes between big-endian merges with two
1799 /// different inputs (0), either-endian merges with two identical inputs (1),
1800 /// and little-endian merges with two different inputs (2).  For the latter,
1801 /// the input operands are swapped (see PPCInstrAltivec.td).
1802 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1803                              unsigned ShuffleKind, SelectionDAG &DAG) {
1804   if (DAG.getDataLayout().isLittleEndian()) {
1805     if (ShuffleKind == 1) // unary
1806       return isVMerge(N, UnitSize, 0, 0);
1807     else if (ShuffleKind == 2) // swapped
1808       return isVMerge(N, UnitSize, 0, 16);
1809     else
1810       return false;
1811   } else {
1812     if (ShuffleKind == 1) // unary
1813       return isVMerge(N, UnitSize, 8, 8);
1814     else if (ShuffleKind == 0) // normal
1815       return isVMerge(N, UnitSize, 8, 24);
1816     else
1817       return false;
1818   }
1819 }
1820 
1821 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1822 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1823 /// The ShuffleKind distinguishes between big-endian merges with two
1824 /// different inputs (0), either-endian merges with two identical inputs (1),
1825 /// and little-endian merges with two different inputs (2).  For the latter,
1826 /// the input operands are swapped (see PPCInstrAltivec.td).
1827 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1828                              unsigned ShuffleKind, SelectionDAG &DAG) {
1829   if (DAG.getDataLayout().isLittleEndian()) {
1830     if (ShuffleKind == 1) // unary
1831       return isVMerge(N, UnitSize, 8, 8);
1832     else if (ShuffleKind == 2) // swapped
1833       return isVMerge(N, UnitSize, 8, 24);
1834     else
1835       return false;
1836   } else {
1837     if (ShuffleKind == 1) // unary
1838       return isVMerge(N, UnitSize, 0, 0);
1839     else if (ShuffleKind == 0) // normal
1840       return isVMerge(N, UnitSize, 0, 16);
1841     else
1842       return false;
1843   }
1844 }
1845 
1846 /**
1847  * Common function used to match vmrgew and vmrgow shuffles
1848  *
1849  * The indexOffset determines whether to look for even or odd words in
1850  * the shuffle mask. This is based on the of the endianness of the target
1851  * machine.
1852  *   - Little Endian:
1853  *     - Use offset of 0 to check for odd elements
1854  *     - Use offset of 4 to check for even elements
1855  *   - Big Endian:
1856  *     - Use offset of 0 to check for even elements
1857  *     - Use offset of 4 to check for odd elements
1858  * A detailed description of the vector element ordering for little endian and
1859  * big endian can be found at
1860  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1861  * Targeting your applications - what little endian and big endian IBM XL C/C++
1862  * compiler differences mean to you
1863  *
1864  * The mask to the shuffle vector instruction specifies the indices of the
1865  * elements from the two input vectors to place in the result. The elements are
1866  * numbered in array-access order, starting with the first vector. These vectors
1867  * are always of type v16i8, thus each vector will contain 16 elements of size
1868  * 8. More info on the shuffle vector can be found in the
1869  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1870  * Language Reference.
1871  *
1872  * The RHSStartValue indicates whether the same input vectors are used (unary)
1873  * or two different input vectors are used, based on the following:
1874  *   - If the instruction uses the same vector for both inputs, the range of the
1875  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1876  *     be 0.
1877  *   - If the instruction has two different vectors then the range of the
1878  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1879  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1880  *     to 31 specify elements in the second vector).
1881  *
1882  * \param[in] N The shuffle vector SD Node to analyze
1883  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1884  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1885  * vector to the shuffle_vector instruction
1886  * \return true iff this shuffle vector represents an even or odd word merge
1887  */
1888 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1889                      unsigned RHSStartValue) {
1890   if (N->getValueType(0) != MVT::v16i8)
1891     return false;
1892 
1893   for (unsigned i = 0; i < 2; ++i)
1894     for (unsigned j = 0; j < 4; ++j)
1895       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1896                              i*RHSStartValue+j+IndexOffset) ||
1897           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1898                              i*RHSStartValue+j+IndexOffset+8))
1899         return false;
1900   return true;
1901 }
1902 
1903 /**
1904  * Determine if the specified shuffle mask is suitable for the vmrgew or
1905  * vmrgow instructions.
1906  *
1907  * \param[in] N The shuffle vector SD Node to analyze
1908  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1909  * \param[in] ShuffleKind Identify the type of merge:
1910  *   - 0 = big-endian merge with two different inputs;
1911  *   - 1 = either-endian merge with two identical inputs;
1912  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1913  *     little-endian merges).
1914  * \param[in] DAG The current SelectionDAG
1915  * \return true iff this shuffle mask
1916  */
1917 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1918                               unsigned ShuffleKind, SelectionDAG &DAG) {
1919   if (DAG.getDataLayout().isLittleEndian()) {
1920     unsigned indexOffset = CheckEven ? 4 : 0;
1921     if (ShuffleKind == 1) // Unary
1922       return isVMerge(N, indexOffset, 0);
1923     else if (ShuffleKind == 2) // swapped
1924       return isVMerge(N, indexOffset, 16);
1925     else
1926       return false;
1927   }
1928   else {
1929     unsigned indexOffset = CheckEven ? 0 : 4;
1930     if (ShuffleKind == 1) // Unary
1931       return isVMerge(N, indexOffset, 0);
1932     else if (ShuffleKind == 0) // Normal
1933       return isVMerge(N, indexOffset, 16);
1934     else
1935       return false;
1936   }
1937   return false;
1938 }
1939 
1940 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1941 /// amount, otherwise return -1.
1942 /// The ShuffleKind distinguishes between big-endian operations with two
1943 /// different inputs (0), either-endian operations with two identical inputs
1944 /// (1), and little-endian operations with two different inputs (2).  For the
1945 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1946 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1947                              SelectionDAG &DAG) {
1948   if (N->getValueType(0) != MVT::v16i8)
1949     return -1;
1950 
1951   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1952 
1953   // Find the first non-undef value in the shuffle mask.
1954   unsigned i;
1955   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1956     /*search*/;
1957 
1958   if (i == 16) return -1;  // all undef.
1959 
1960   // Otherwise, check to see if the rest of the elements are consecutively
1961   // numbered from this value.
1962   unsigned ShiftAmt = SVOp->getMaskElt(i);
1963   if (ShiftAmt < i) return -1;
1964 
1965   ShiftAmt -= i;
1966   bool isLE = DAG.getDataLayout().isLittleEndian();
1967 
1968   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1969     // Check the rest of the elements to see if they are consecutive.
1970     for (++i; i != 16; ++i)
1971       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1972         return -1;
1973   } else if (ShuffleKind == 1) {
1974     // Check the rest of the elements to see if they are consecutive.
1975     for (++i; i != 16; ++i)
1976       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1977         return -1;
1978   } else
1979     return -1;
1980 
1981   if (isLE)
1982     ShiftAmt = 16 - ShiftAmt;
1983 
1984   return ShiftAmt;
1985 }
1986 
1987 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1988 /// specifies a splat of a single element that is suitable for input to
1989 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1990 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1991   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1992          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1993 
1994   // The consecutive indices need to specify an element, not part of two
1995   // different elements.  So abandon ship early if this isn't the case.
1996   if (N->getMaskElt(0) % EltSize != 0)
1997     return false;
1998 
1999   // This is a splat operation if each element of the permute is the same, and
2000   // if the value doesn't reference the second vector.
2001   unsigned ElementBase = N->getMaskElt(0);
2002 
2003   // FIXME: Handle UNDEF elements too!
2004   if (ElementBase >= 16)
2005     return false;
2006 
2007   // Check that the indices are consecutive, in the case of a multi-byte element
2008   // splatted with a v16i8 mask.
2009   for (unsigned i = 1; i != EltSize; ++i)
2010     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2011       return false;
2012 
2013   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2014     if (N->getMaskElt(i) < 0) continue;
2015     for (unsigned j = 0; j != EltSize; ++j)
2016       if (N->getMaskElt(i+j) != N->getMaskElt(j))
2017         return false;
2018   }
2019   return true;
2020 }
2021 
2022 /// Check that the mask is shuffling N byte elements. Within each N byte
2023 /// element of the mask, the indices could be either in increasing or
2024 /// decreasing order as long as they are consecutive.
2025 /// \param[in] N the shuffle vector SD Node to analyze
2026 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2027 /// Word/DoubleWord/QuadWord).
2028 /// \param[in] StepLen the delta indices number among the N byte element, if
2029 /// the mask is in increasing/decreasing order then it is 1/-1.
2030 /// \return true iff the mask is shuffling N byte elements.
2031 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2032                                    int StepLen) {
2033   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2034          "Unexpected element width.");
2035   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2036 
2037   unsigned NumOfElem = 16 / Width;
2038   unsigned MaskVal[16]; //  Width is never greater than 16
2039   for (unsigned i = 0; i < NumOfElem; ++i) {
2040     MaskVal[0] = N->getMaskElt(i * Width);
2041     if ((StepLen == 1) && (MaskVal[0] % Width)) {
2042       return false;
2043     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2044       return false;
2045     }
2046 
2047     for (unsigned int j = 1; j < Width; ++j) {
2048       MaskVal[j] = N->getMaskElt(i * Width + j);
2049       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2050         return false;
2051       }
2052     }
2053   }
2054 
2055   return true;
2056 }
2057 
2058 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2059                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2060   if (!isNByteElemShuffleMask(N, 4, 1))
2061     return false;
2062 
2063   // Now we look at mask elements 0,4,8,12
2064   unsigned M0 = N->getMaskElt(0) / 4;
2065   unsigned M1 = N->getMaskElt(4) / 4;
2066   unsigned M2 = N->getMaskElt(8) / 4;
2067   unsigned M3 = N->getMaskElt(12) / 4;
2068   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2069   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2070 
2071   // Below, let H and L be arbitrary elements of the shuffle mask
2072   // where H is in the range [4,7] and L is in the range [0,3].
2073   // H, 1, 2, 3 or L, 5, 6, 7
2074   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2075       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2076     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2077     InsertAtByte = IsLE ? 12 : 0;
2078     Swap = M0 < 4;
2079     return true;
2080   }
2081   // 0, H, 2, 3 or 4, L, 6, 7
2082   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2083       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2084     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2085     InsertAtByte = IsLE ? 8 : 4;
2086     Swap = M1 < 4;
2087     return true;
2088   }
2089   // 0, 1, H, 3 or 4, 5, L, 7
2090   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2091       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2092     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2093     InsertAtByte = IsLE ? 4 : 8;
2094     Swap = M2 < 4;
2095     return true;
2096   }
2097   // 0, 1, 2, H or 4, 5, 6, L
2098   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2099       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2100     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2101     InsertAtByte = IsLE ? 0 : 12;
2102     Swap = M3 < 4;
2103     return true;
2104   }
2105 
2106   // If both vector operands for the shuffle are the same vector, the mask will
2107   // contain only elements from the first one and the second one will be undef.
2108   if (N->getOperand(1).isUndef()) {
2109     ShiftElts = 0;
2110     Swap = true;
2111     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2112     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2113       InsertAtByte = IsLE ? 12 : 0;
2114       return true;
2115     }
2116     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2117       InsertAtByte = IsLE ? 8 : 4;
2118       return true;
2119     }
2120     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2121       InsertAtByte = IsLE ? 4 : 8;
2122       return true;
2123     }
2124     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2125       InsertAtByte = IsLE ? 0 : 12;
2126       return true;
2127     }
2128   }
2129 
2130   return false;
2131 }
2132 
2133 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2134                                bool &Swap, bool IsLE) {
2135   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2136   // Ensure each byte index of the word is consecutive.
2137   if (!isNByteElemShuffleMask(N, 4, 1))
2138     return false;
2139 
2140   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2141   unsigned M0 = N->getMaskElt(0) / 4;
2142   unsigned M1 = N->getMaskElt(4) / 4;
2143   unsigned M2 = N->getMaskElt(8) / 4;
2144   unsigned M3 = N->getMaskElt(12) / 4;
2145 
2146   // If both vector operands for the shuffle are the same vector, the mask will
2147   // contain only elements from the first one and the second one will be undef.
2148   if (N->getOperand(1).isUndef()) {
2149     assert(M0 < 4 && "Indexing into an undef vector?");
2150     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2151       return false;
2152 
2153     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2154     Swap = false;
2155     return true;
2156   }
2157 
2158   // Ensure each word index of the ShuffleVector Mask is consecutive.
2159   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2160     return false;
2161 
2162   if (IsLE) {
2163     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2164       // Input vectors don't need to be swapped if the leading element
2165       // of the result is one of the 3 left elements of the second vector
2166       // (or if there is no shift to be done at all).
2167       Swap = false;
2168       ShiftElts = (8 - M0) % 8;
2169     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2170       // Input vectors need to be swapped if the leading element
2171       // of the result is one of the 3 left elements of the first vector
2172       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2173       Swap = true;
2174       ShiftElts = (4 - M0) % 4;
2175     }
2176 
2177     return true;
2178   } else {                                          // BE
2179     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2180       // Input vectors don't need to be swapped if the leading element
2181       // of the result is one of the 4 elements of the first vector.
2182       Swap = false;
2183       ShiftElts = M0;
2184     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2185       // Input vectors need to be swapped if the leading element
2186       // of the result is one of the 4 elements of the right vector.
2187       Swap = true;
2188       ShiftElts = M0 - 4;
2189     }
2190 
2191     return true;
2192   }
2193 }
2194 
2195 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2196   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2197 
2198   if (!isNByteElemShuffleMask(N, Width, -1))
2199     return false;
2200 
2201   for (int i = 0; i < 16; i += Width)
2202     if (N->getMaskElt(i) != i + Width - 1)
2203       return false;
2204 
2205   return true;
2206 }
2207 
2208 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2209   return isXXBRShuffleMaskHelper(N, 2);
2210 }
2211 
2212 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2213   return isXXBRShuffleMaskHelper(N, 4);
2214 }
2215 
2216 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2217   return isXXBRShuffleMaskHelper(N, 8);
2218 }
2219 
2220 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2221   return isXXBRShuffleMaskHelper(N, 16);
2222 }
2223 
2224 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2225 /// if the inputs to the instruction should be swapped and set \p DM to the
2226 /// value for the immediate.
2227 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2228 /// AND element 0 of the result comes from the first input (LE) or second input
2229 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2230 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2231 /// mask.
2232 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2233                                bool &Swap, bool IsLE) {
2234   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2235 
2236   // Ensure each byte index of the double word is consecutive.
2237   if (!isNByteElemShuffleMask(N, 8, 1))
2238     return false;
2239 
2240   unsigned M0 = N->getMaskElt(0) / 8;
2241   unsigned M1 = N->getMaskElt(8) / 8;
2242   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2243 
2244   // If both vector operands for the shuffle are the same vector, the mask will
2245   // contain only elements from the first one and the second one will be undef.
2246   if (N->getOperand(1).isUndef()) {
2247     if ((M0 | M1) < 2) {
2248       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2249       Swap = false;
2250       return true;
2251     } else
2252       return false;
2253   }
2254 
2255   if (IsLE) {
2256     if (M0 > 1 && M1 < 2) {
2257       Swap = false;
2258     } else if (M0 < 2 && M1 > 1) {
2259       M0 = (M0 + 2) % 4;
2260       M1 = (M1 + 2) % 4;
2261       Swap = true;
2262     } else
2263       return false;
2264 
2265     // Note: if control flow comes here that means Swap is already set above
2266     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2267     return true;
2268   } else { // BE
2269     if (M0 < 2 && M1 > 1) {
2270       Swap = false;
2271     } else if (M0 > 1 && M1 < 2) {
2272       M0 = (M0 + 2) % 4;
2273       M1 = (M1 + 2) % 4;
2274       Swap = true;
2275     } else
2276       return false;
2277 
2278     // Note: if control flow comes here that means Swap is already set above
2279     DM = (M0 << 1) + (M1 & 1);
2280     return true;
2281   }
2282 }
2283 
2284 
2285 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2286 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2287 /// elements are counted from the left of the vector register).
2288 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2289                                          SelectionDAG &DAG) {
2290   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2291   assert(isSplatShuffleMask(SVOp, EltSize));
2292   if (DAG.getDataLayout().isLittleEndian())
2293     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2294   else
2295     return SVOp->getMaskElt(0) / EltSize;
2296 }
2297 
2298 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2299 /// by using a vspltis[bhw] instruction of the specified element size, return
2300 /// the constant being splatted.  The ByteSize field indicates the number of
2301 /// bytes of each element [124] -> [bhw].
2302 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2303   SDValue OpVal(nullptr, 0);
2304 
2305   // If ByteSize of the splat is bigger than the element size of the
2306   // build_vector, then we have a case where we are checking for a splat where
2307   // multiple elements of the buildvector are folded together into a single
2308   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2309   unsigned EltSize = 16/N->getNumOperands();
2310   if (EltSize < ByteSize) {
2311     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2312     SDValue UniquedVals[4];
2313     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2314 
2315     // See if all of the elements in the buildvector agree across.
2316     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2317       if (N->getOperand(i).isUndef()) continue;
2318       // If the element isn't a constant, bail fully out.
2319       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2320 
2321       if (!UniquedVals[i&(Multiple-1)].getNode())
2322         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2323       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2324         return SDValue();  // no match.
2325     }
2326 
2327     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2328     // either constant or undef values that are identical for each chunk.  See
2329     // if these chunks can form into a larger vspltis*.
2330 
2331     // Check to see if all of the leading entries are either 0 or -1.  If
2332     // neither, then this won't fit into the immediate field.
2333     bool LeadingZero = true;
2334     bool LeadingOnes = true;
2335     for (unsigned i = 0; i != Multiple-1; ++i) {
2336       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2337 
2338       LeadingZero &= isNullConstant(UniquedVals[i]);
2339       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2340     }
2341     // Finally, check the least significant entry.
2342     if (LeadingZero) {
2343       if (!UniquedVals[Multiple-1].getNode())
2344         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2345       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2346       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2347         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2348     }
2349     if (LeadingOnes) {
2350       if (!UniquedVals[Multiple-1].getNode())
2351         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2352       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2353       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2354         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2355     }
2356 
2357     return SDValue();
2358   }
2359 
2360   // Check to see if this buildvec has a single non-undef value in its elements.
2361   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2362     if (N->getOperand(i).isUndef()) continue;
2363     if (!OpVal.getNode())
2364       OpVal = N->getOperand(i);
2365     else if (OpVal != N->getOperand(i))
2366       return SDValue();
2367   }
2368 
2369   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2370 
2371   unsigned ValSizeInBytes = EltSize;
2372   uint64_t Value = 0;
2373   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2374     Value = CN->getZExtValue();
2375   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2376     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2377     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2378   }
2379 
2380   // If the splat value is larger than the element value, then we can never do
2381   // this splat.  The only case that we could fit the replicated bits into our
2382   // immediate field for would be zero, and we prefer to use vxor for it.
2383   if (ValSizeInBytes < ByteSize) return SDValue();
2384 
2385   // If the element value is larger than the splat value, check if it consists
2386   // of a repeated bit pattern of size ByteSize.
2387   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2388     return SDValue();
2389 
2390   // Properly sign extend the value.
2391   int MaskVal = SignExtend32(Value, ByteSize * 8);
2392 
2393   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2394   if (MaskVal == 0) return SDValue();
2395 
2396   // Finally, if this value fits in a 5 bit sext field, return it
2397   if (SignExtend32<5>(MaskVal) == MaskVal)
2398     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2399   return SDValue();
2400 }
2401 
2402 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2403 /// amount, otherwise return -1.
2404 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2405   EVT VT = N->getValueType(0);
2406   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2407     return -1;
2408 
2409   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2410 
2411   // Find the first non-undef value in the shuffle mask.
2412   unsigned i;
2413   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2414     /*search*/;
2415 
2416   if (i == 4) return -1;  // all undef.
2417 
2418   // Otherwise, check to see if the rest of the elements are consecutively
2419   // numbered from this value.
2420   unsigned ShiftAmt = SVOp->getMaskElt(i);
2421   if (ShiftAmt < i) return -1;
2422   ShiftAmt -= i;
2423 
2424   // Check the rest of the elements to see if they are consecutive.
2425   for (++i; i != 4; ++i)
2426     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2427       return -1;
2428 
2429   return ShiftAmt;
2430 }
2431 
2432 //===----------------------------------------------------------------------===//
2433 //  Addressing Mode Selection
2434 //===----------------------------------------------------------------------===//
2435 
2436 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2437 /// or 64-bit immediate, and if the value can be accurately represented as a
2438 /// sign extension from a 16-bit value.  If so, this returns true and the
2439 /// immediate.
2440 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2441   if (!isa<ConstantSDNode>(N))
2442     return false;
2443 
2444   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2445   if (N->getValueType(0) == MVT::i32)
2446     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2447   else
2448     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2449 }
2450 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2451   return isIntS16Immediate(Op.getNode(), Imm);
2452 }
2453 
2454 
2455 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2456 /// be represented as an indexed [r+r] operation.
2457 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2458                                                SDValue &Index,
2459                                                SelectionDAG &DAG) const {
2460   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2461       UI != E; ++UI) {
2462     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2463       if (Memop->getMemoryVT() == MVT::f64) {
2464           Base = N.getOperand(0);
2465           Index = N.getOperand(1);
2466           return true;
2467       }
2468     }
2469   }
2470   return false;
2471 }
2472 
2473 /// isIntS34Immediate - This method tests if value of node given can be
2474 /// accurately represented as a sign extension from a 34-bit value.  If so,
2475 /// this returns true and the immediate.
2476 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2477   if (!isa<ConstantSDNode>(N))
2478     return false;
2479 
2480   Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2481   return isInt<34>(Imm);
2482 }
2483 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2484   return isIntS34Immediate(Op.getNode(), Imm);
2485 }
2486 
2487 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2488 /// can be represented as an indexed [r+r] operation.  Returns false if it
2489 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2490 /// non-zero and N can be represented by a base register plus a signed 16-bit
2491 /// displacement, make a more precise judgement by checking (displacement % \p
2492 /// EncodingAlignment).
2493 bool PPCTargetLowering::SelectAddressRegReg(
2494     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2495     MaybeAlign EncodingAlignment) const {
2496   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2497   // a [pc+imm].
2498   if (SelectAddressPCRel(N, Base))
2499     return false;
2500 
2501   int16_t Imm = 0;
2502   if (N.getOpcode() == ISD::ADD) {
2503     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2504     // SPE load/store can only handle 8-bit offsets.
2505     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2506         return true;
2507     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2508         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2509       return false; // r+i
2510     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2511       return false;    // r+i
2512 
2513     Base = N.getOperand(0);
2514     Index = N.getOperand(1);
2515     return true;
2516   } else if (N.getOpcode() == ISD::OR) {
2517     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2518         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2519       return false; // r+i can fold it if we can.
2520 
2521     // If this is an or of disjoint bitfields, we can codegen this as an add
2522     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2523     // disjoint.
2524     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2525 
2526     if (LHSKnown.Zero.getBoolValue()) {
2527       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2528       // If all of the bits are known zero on the LHS or RHS, the add won't
2529       // carry.
2530       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2531         Base = N.getOperand(0);
2532         Index = N.getOperand(1);
2533         return true;
2534       }
2535     }
2536   }
2537 
2538   return false;
2539 }
2540 
2541 // If we happen to be doing an i64 load or store into a stack slot that has
2542 // less than a 4-byte alignment, then the frame-index elimination may need to
2543 // use an indexed load or store instruction (because the offset may not be a
2544 // multiple of 4). The extra register needed to hold the offset comes from the
2545 // register scavenger, and it is possible that the scavenger will need to use
2546 // an emergency spill slot. As a result, we need to make sure that a spill slot
2547 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2548 // stack slot.
2549 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2550   // FIXME: This does not handle the LWA case.
2551   if (VT != MVT::i64)
2552     return;
2553 
2554   // NOTE: We'll exclude negative FIs here, which come from argument
2555   // lowering, because there are no known test cases triggering this problem
2556   // using packed structures (or similar). We can remove this exclusion if
2557   // we find such a test case. The reason why this is so test-case driven is
2558   // because this entire 'fixup' is only to prevent crashes (from the
2559   // register scavenger) on not-really-valid inputs. For example, if we have:
2560   //   %a = alloca i1
2561   //   %b = bitcast i1* %a to i64*
2562   //   store i64* a, i64 b
2563   // then the store should really be marked as 'align 1', but is not. If it
2564   // were marked as 'align 1' then the indexed form would have been
2565   // instruction-selected initially, and the problem this 'fixup' is preventing
2566   // won't happen regardless.
2567   if (FrameIdx < 0)
2568     return;
2569 
2570   MachineFunction &MF = DAG.getMachineFunction();
2571   MachineFrameInfo &MFI = MF.getFrameInfo();
2572 
2573   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2574     return;
2575 
2576   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2577   FuncInfo->setHasNonRISpills();
2578 }
2579 
2580 /// Returns true if the address N can be represented by a base register plus
2581 /// a signed 16-bit displacement [r+imm], and if it is not better
2582 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2583 /// displacements that are multiples of that value.
2584 bool PPCTargetLowering::SelectAddressRegImm(
2585     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2586     MaybeAlign EncodingAlignment) const {
2587   // FIXME dl should come from parent load or store, not from address
2588   SDLoc dl(N);
2589 
2590   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2591   // a [pc+imm].
2592   if (SelectAddressPCRel(N, Base))
2593     return false;
2594 
2595   // If this can be more profitably realized as r+r, fail.
2596   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2597     return false;
2598 
2599   if (N.getOpcode() == ISD::ADD) {
2600     int16_t imm = 0;
2601     if (isIntS16Immediate(N.getOperand(1), imm) &&
2602         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2603       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2604       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2605         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2606         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2607       } else {
2608         Base = N.getOperand(0);
2609       }
2610       return true; // [r+i]
2611     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2612       // Match LOAD (ADD (X, Lo(G))).
2613       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2614              && "Cannot handle constant offsets yet!");
2615       Disp = N.getOperand(1).getOperand(0);  // The global address.
2616       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2617              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2618              Disp.getOpcode() == ISD::TargetConstantPool ||
2619              Disp.getOpcode() == ISD::TargetJumpTable);
2620       Base = N.getOperand(0);
2621       return true;  // [&g+r]
2622     }
2623   } else if (N.getOpcode() == ISD::OR) {
2624     int16_t imm = 0;
2625     if (isIntS16Immediate(N.getOperand(1), imm) &&
2626         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2627       // If this is an or of disjoint bitfields, we can codegen this as an add
2628       // (for better address arithmetic) if the LHS and RHS of the OR are
2629       // provably disjoint.
2630       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2631 
2632       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2633         // If all of the bits are known zero on the LHS or RHS, the add won't
2634         // carry.
2635         if (FrameIndexSDNode *FI =
2636               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2637           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2638           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2639         } else {
2640           Base = N.getOperand(0);
2641         }
2642         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2643         return true;
2644       }
2645     }
2646   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2647     // Loading from a constant address.
2648 
2649     // If this address fits entirely in a 16-bit sext immediate field, codegen
2650     // this as "d, 0"
2651     int16_t Imm;
2652     if (isIntS16Immediate(CN, Imm) &&
2653         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2654       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2655       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2656                              CN->getValueType(0));
2657       return true;
2658     }
2659 
2660     // Handle 32-bit sext immediates with LIS + addr mode.
2661     if ((CN->getValueType(0) == MVT::i32 ||
2662          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2663         (!EncodingAlignment ||
2664          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2665       int Addr = (int)CN->getZExtValue();
2666 
2667       // Otherwise, break this down into an LIS + disp.
2668       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2669 
2670       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2671                                    MVT::i32);
2672       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2673       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2674       return true;
2675     }
2676   }
2677 
2678   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2679   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2680     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2681     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2682   } else
2683     Base = N;
2684   return true;      // [r+0]
2685 }
2686 
2687 /// Similar to the 16-bit case but for instructions that take a 34-bit
2688 /// displacement field (prefixed loads/stores).
2689 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp,
2690                                               SDValue &Base,
2691                                               SelectionDAG &DAG) const {
2692   // Only on 64-bit targets.
2693   if (N.getValueType() != MVT::i64)
2694     return false;
2695 
2696   SDLoc dl(N);
2697   int64_t Imm = 0;
2698 
2699   if (N.getOpcode() == ISD::ADD) {
2700     if (!isIntS34Immediate(N.getOperand(1), Imm))
2701       return false;
2702     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2703     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2704       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2705     else
2706       Base = N.getOperand(0);
2707     return true;
2708   }
2709 
2710   if (N.getOpcode() == ISD::OR) {
2711     if (!isIntS34Immediate(N.getOperand(1), Imm))
2712       return false;
2713     // If this is an or of disjoint bitfields, we can codegen this as an add
2714     // (for better address arithmetic) if the LHS and RHS of the OR are
2715     // provably disjoint.
2716     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2717     if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2718       return false;
2719     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2720       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2721     else
2722       Base = N.getOperand(0);
2723     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2724     return true;
2725   }
2726 
2727   if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2728     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2729     Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2730     return true;
2731   }
2732 
2733   return false;
2734 }
2735 
2736 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2737 /// represented as an indexed [r+r] operation.
2738 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2739                                                 SDValue &Index,
2740                                                 SelectionDAG &DAG) const {
2741   // Check to see if we can easily represent this as an [r+r] address.  This
2742   // will fail if it thinks that the address is more profitably represented as
2743   // reg+imm, e.g. where imm = 0.
2744   if (SelectAddressRegReg(N, Base, Index, DAG))
2745     return true;
2746 
2747   // If the address is the result of an add, we will utilize the fact that the
2748   // address calculation includes an implicit add.  However, we can reduce
2749   // register pressure if we do not materialize a constant just for use as the
2750   // index register.  We only get rid of the add if it is not an add of a
2751   // value and a 16-bit signed constant and both have a single use.
2752   int16_t imm = 0;
2753   if (N.getOpcode() == ISD::ADD &&
2754       (!isIntS16Immediate(N.getOperand(1), imm) ||
2755        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2756     Base = N.getOperand(0);
2757     Index = N.getOperand(1);
2758     return true;
2759   }
2760 
2761   // Otherwise, do it the hard way, using R0 as the base register.
2762   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2763                          N.getValueType());
2764   Index = N;
2765   return true;
2766 }
2767 
2768 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2769   Ty *PCRelCand = dyn_cast<Ty>(N);
2770   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2771 }
2772 
2773 /// Returns true if this address is a PC Relative address.
2774 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2775 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2776 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2777   // This is a materialize PC Relative node. Always select this as PC Relative.
2778   Base = N;
2779   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2780     return true;
2781   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2782       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2783       isValidPCRelNode<JumpTableSDNode>(N) ||
2784       isValidPCRelNode<BlockAddressSDNode>(N))
2785     return true;
2786   return false;
2787 }
2788 
2789 /// Returns true if we should use a direct load into vector instruction
2790 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2791 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2792 
2793   // If there are any other uses other than scalar to vector, then we should
2794   // keep it as a scalar load -> direct move pattern to prevent multiple
2795   // loads.
2796   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2797   if (!LD)
2798     return false;
2799 
2800   EVT MemVT = LD->getMemoryVT();
2801   if (!MemVT.isSimple())
2802     return false;
2803   switch(MemVT.getSimpleVT().SimpleTy) {
2804   case MVT::i64:
2805     break;
2806   case MVT::i32:
2807     if (!ST.hasP8Vector())
2808       return false;
2809     break;
2810   case MVT::i16:
2811   case MVT::i8:
2812     if (!ST.hasP9Vector())
2813       return false;
2814     break;
2815   default:
2816     return false;
2817   }
2818 
2819   SDValue LoadedVal(N, 0);
2820   if (!LoadedVal.hasOneUse())
2821     return false;
2822 
2823   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2824        UI != UE; ++UI)
2825     if (UI.getUse().get().getResNo() == 0 &&
2826         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2827         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2828       return false;
2829 
2830   return true;
2831 }
2832 
2833 /// getPreIndexedAddressParts - returns true by value, base pointer and
2834 /// offset pointer and addressing mode by reference if the node's address
2835 /// can be legally represented as pre-indexed load / store address.
2836 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2837                                                   SDValue &Offset,
2838                                                   ISD::MemIndexedMode &AM,
2839                                                   SelectionDAG &DAG) const {
2840   if (DisablePPCPreinc) return false;
2841 
2842   bool isLoad = true;
2843   SDValue Ptr;
2844   EVT VT;
2845   unsigned Alignment;
2846   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2847     Ptr = LD->getBasePtr();
2848     VT = LD->getMemoryVT();
2849     Alignment = LD->getAlignment();
2850   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2851     Ptr = ST->getBasePtr();
2852     VT  = ST->getMemoryVT();
2853     Alignment = ST->getAlignment();
2854     isLoad = false;
2855   } else
2856     return false;
2857 
2858   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2859   // instructions because we can fold these into a more efficient instruction
2860   // instead, (such as LXSD).
2861   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2862     return false;
2863   }
2864 
2865   // PowerPC doesn't have preinc load/store instructions for vectors
2866   if (VT.isVector())
2867     return false;
2868 
2869   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2870     // Common code will reject creating a pre-inc form if the base pointer
2871     // is a frame index, or if N is a store and the base pointer is either
2872     // the same as or a predecessor of the value being stored.  Check for
2873     // those situations here, and try with swapped Base/Offset instead.
2874     bool Swap = false;
2875 
2876     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2877       Swap = true;
2878     else if (!isLoad) {
2879       SDValue Val = cast<StoreSDNode>(N)->getValue();
2880       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2881         Swap = true;
2882     }
2883 
2884     if (Swap)
2885       std::swap(Base, Offset);
2886 
2887     AM = ISD::PRE_INC;
2888     return true;
2889   }
2890 
2891   // LDU/STU can only handle immediates that are a multiple of 4.
2892   if (VT != MVT::i64) {
2893     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2894       return false;
2895   } else {
2896     // LDU/STU need an address with at least 4-byte alignment.
2897     if (Alignment < 4)
2898       return false;
2899 
2900     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
2901       return false;
2902   }
2903 
2904   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2905     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2906     // sext i32 to i64 when addr mode is r+i.
2907     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2908         LD->getExtensionType() == ISD::SEXTLOAD &&
2909         isa<ConstantSDNode>(Offset))
2910       return false;
2911   }
2912 
2913   AM = ISD::PRE_INC;
2914   return true;
2915 }
2916 
2917 //===----------------------------------------------------------------------===//
2918 //  LowerOperation implementation
2919 //===----------------------------------------------------------------------===//
2920 
2921 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2922 /// and LoOpFlags to the target MO flags.
2923 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2924                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2925                                const GlobalValue *GV = nullptr) {
2926   HiOpFlags = PPCII::MO_HA;
2927   LoOpFlags = PPCII::MO_LO;
2928 
2929   // Don't use the pic base if not in PIC relocation model.
2930   if (IsPIC) {
2931     HiOpFlags |= PPCII::MO_PIC_FLAG;
2932     LoOpFlags |= PPCII::MO_PIC_FLAG;
2933   }
2934 }
2935 
2936 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2937                              SelectionDAG &DAG) {
2938   SDLoc DL(HiPart);
2939   EVT PtrVT = HiPart.getValueType();
2940   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2941 
2942   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2943   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2944 
2945   // With PIC, the first instruction is actually "GR+hi(&G)".
2946   if (isPIC)
2947     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2948                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2949 
2950   // Generate non-pic code that has direct accesses to the constant pool.
2951   // The address of the global is just (hi(&g)+lo(&g)).
2952   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2953 }
2954 
2955 static void setUsesTOCBasePtr(MachineFunction &MF) {
2956   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2957   FuncInfo->setUsesTOCBasePtr();
2958 }
2959 
2960 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2961   setUsesTOCBasePtr(DAG.getMachineFunction());
2962 }
2963 
2964 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2965                                        SDValue GA) const {
2966   const bool Is64Bit = Subtarget.isPPC64();
2967   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2968   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2969                         : Subtarget.isAIXABI()
2970                               ? DAG.getRegister(PPC::R2, VT)
2971                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2972   SDValue Ops[] = { GA, Reg };
2973   return DAG.getMemIntrinsicNode(
2974       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2975       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2976       MachineMemOperand::MOLoad);
2977 }
2978 
2979 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2980                                              SelectionDAG &DAG) const {
2981   EVT PtrVT = Op.getValueType();
2982   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2983   const Constant *C = CP->getConstVal();
2984 
2985   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2986   // The actual address of the GlobalValue is stored in the TOC.
2987   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2988     if (Subtarget.isUsingPCRelativeCalls()) {
2989       SDLoc DL(CP);
2990       EVT Ty = getPointerTy(DAG.getDataLayout());
2991       SDValue ConstPool = DAG.getTargetConstantPool(
2992           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2993       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2994     }
2995     setUsesTOCBasePtr(DAG);
2996     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2997     return getTOCEntry(DAG, SDLoc(CP), GA);
2998   }
2999 
3000   unsigned MOHiFlag, MOLoFlag;
3001   bool IsPIC = isPositionIndependent();
3002   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3003 
3004   if (IsPIC && Subtarget.isSVR4ABI()) {
3005     SDValue GA =
3006         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
3007     return getTOCEntry(DAG, SDLoc(CP), GA);
3008   }
3009 
3010   SDValue CPIHi =
3011       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3012   SDValue CPILo =
3013       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3014   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3015 }
3016 
3017 // For 64-bit PowerPC, prefer the more compact relative encodings.
3018 // This trades 32 bits per jump table entry for one or two instructions
3019 // on the jump site.
3020 unsigned PPCTargetLowering::getJumpTableEncoding() const {
3021   if (isJumpTableRelative())
3022     return MachineJumpTableInfo::EK_LabelDifference32;
3023 
3024   return TargetLowering::getJumpTableEncoding();
3025 }
3026 
3027 bool PPCTargetLowering::isJumpTableRelative() const {
3028   if (UseAbsoluteJumpTables)
3029     return false;
3030   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3031     return true;
3032   return TargetLowering::isJumpTableRelative();
3033 }
3034 
3035 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
3036                                                     SelectionDAG &DAG) const {
3037   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3038     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3039 
3040   switch (getTargetMachine().getCodeModel()) {
3041   case CodeModel::Small:
3042   case CodeModel::Medium:
3043     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3044   default:
3045     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3046                        getPointerTy(DAG.getDataLayout()));
3047   }
3048 }
3049 
3050 const MCExpr *
3051 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
3052                                                 unsigned JTI,
3053                                                 MCContext &Ctx) const {
3054   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3055     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3056 
3057   switch (getTargetMachine().getCodeModel()) {
3058   case CodeModel::Small:
3059   case CodeModel::Medium:
3060     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3061   default:
3062     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3063   }
3064 }
3065 
3066 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3067   EVT PtrVT = Op.getValueType();
3068   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3069 
3070   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3071   if (Subtarget.isUsingPCRelativeCalls()) {
3072     SDLoc DL(JT);
3073     EVT Ty = getPointerTy(DAG.getDataLayout());
3074     SDValue GA =
3075         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3076     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3077     return MatAddr;
3078   }
3079 
3080   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3081   // The actual address of the GlobalValue is stored in the TOC.
3082   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3083     setUsesTOCBasePtr(DAG);
3084     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3085     return getTOCEntry(DAG, SDLoc(JT), GA);
3086   }
3087 
3088   unsigned MOHiFlag, MOLoFlag;
3089   bool IsPIC = isPositionIndependent();
3090   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3091 
3092   if (IsPIC && Subtarget.isSVR4ABI()) {
3093     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3094                                         PPCII::MO_PIC_FLAG);
3095     return getTOCEntry(DAG, SDLoc(GA), GA);
3096   }
3097 
3098   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3099   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3100   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3101 }
3102 
3103 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3104                                              SelectionDAG &DAG) const {
3105   EVT PtrVT = Op.getValueType();
3106   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3107   const BlockAddress *BA = BASDN->getBlockAddress();
3108 
3109   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3110   if (Subtarget.isUsingPCRelativeCalls()) {
3111     SDLoc DL(BASDN);
3112     EVT Ty = getPointerTy(DAG.getDataLayout());
3113     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3114                                            PPCII::MO_PCREL_FLAG);
3115     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3116     return MatAddr;
3117   }
3118 
3119   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3120   // The actual BlockAddress is stored in the TOC.
3121   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3122     setUsesTOCBasePtr(DAG);
3123     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3124     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3125   }
3126 
3127   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3128   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3129     return getTOCEntry(
3130         DAG, SDLoc(BASDN),
3131         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3132 
3133   unsigned MOHiFlag, MOLoFlag;
3134   bool IsPIC = isPositionIndependent();
3135   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3136   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3137   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3138   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3139 }
3140 
3141 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3142                                               SelectionDAG &DAG) const {
3143   // FIXME: TLS addresses currently use medium model code sequences,
3144   // which is the most useful form.  Eventually support for small and
3145   // large models could be added if users need it, at the cost of
3146   // additional complexity.
3147   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3148   if (DAG.getTarget().useEmulatedTLS())
3149     return LowerToTLSEmulatedModel(GA, DAG);
3150 
3151   SDLoc dl(GA);
3152   const GlobalValue *GV = GA->getGlobal();
3153   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3154   bool is64bit = Subtarget.isPPC64();
3155   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3156   PICLevel::Level picLevel = M->getPICLevel();
3157 
3158   const TargetMachine &TM = getTargetMachine();
3159   TLSModel::Model Model = TM.getTLSModel(GV);
3160 
3161   if (Model == TLSModel::LocalExec) {
3162     if (Subtarget.isUsingPCRelativeCalls()) {
3163       SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3164       SDValue TGA = DAG.getTargetGlobalAddress(
3165           GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3166       SDValue MatAddr =
3167           DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3168       return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3169     }
3170 
3171     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3172                                                PPCII::MO_TPREL_HA);
3173     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3174                                                PPCII::MO_TPREL_LO);
3175     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3176                              : DAG.getRegister(PPC::R2, MVT::i32);
3177 
3178     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3179     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3180   }
3181 
3182   if (Model == TLSModel::InitialExec) {
3183     bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3184     SDValue TGA = DAG.getTargetGlobalAddress(
3185         GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3186     SDValue TGATLS = DAG.getTargetGlobalAddress(
3187         GV, dl, PtrVT, 0,
3188         IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3189     SDValue TPOffset;
3190     if (IsPCRel) {
3191       SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3192       TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3193                              MachinePointerInfo());
3194     } else {
3195       SDValue GOTPtr;
3196       if (is64bit) {
3197         setUsesTOCBasePtr(DAG);
3198         SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3199         GOTPtr =
3200             DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3201       } else {
3202         if (!TM.isPositionIndependent())
3203           GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3204         else if (picLevel == PICLevel::SmallPIC)
3205           GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3206         else
3207           GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3208       }
3209       TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3210     }
3211     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3212   }
3213 
3214   if (Model == TLSModel::GeneralDynamic) {
3215     if (Subtarget.isUsingPCRelativeCalls()) {
3216       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3217                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3218       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3219     }
3220 
3221     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3222     SDValue GOTPtr;
3223     if (is64bit) {
3224       setUsesTOCBasePtr(DAG);
3225       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3226       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3227                                    GOTReg, TGA);
3228     } else {
3229       if (picLevel == PICLevel::SmallPIC)
3230         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3231       else
3232         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3233     }
3234     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3235                        GOTPtr, TGA, TGA);
3236   }
3237 
3238   if (Model == TLSModel::LocalDynamic) {
3239     if (Subtarget.isUsingPCRelativeCalls()) {
3240       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3241                                                PPCII::MO_GOT_TLSLD_PCREL_FLAG);
3242       SDValue MatPCRel =
3243           DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3244       return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3245     }
3246 
3247     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3248     SDValue GOTPtr;
3249     if (is64bit) {
3250       setUsesTOCBasePtr(DAG);
3251       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3252       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3253                            GOTReg, TGA);
3254     } else {
3255       if (picLevel == PICLevel::SmallPIC)
3256         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3257       else
3258         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3259     }
3260     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3261                                   PtrVT, GOTPtr, TGA, TGA);
3262     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3263                                       PtrVT, TLSAddr, TGA);
3264     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3265   }
3266 
3267   llvm_unreachable("Unknown TLS model!");
3268 }
3269 
3270 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3271                                               SelectionDAG &DAG) const {
3272   EVT PtrVT = Op.getValueType();
3273   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3274   SDLoc DL(GSDN);
3275   const GlobalValue *GV = GSDN->getGlobal();
3276 
3277   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3278   // The actual address of the GlobalValue is stored in the TOC.
3279   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3280     if (Subtarget.isUsingPCRelativeCalls()) {
3281       EVT Ty = getPointerTy(DAG.getDataLayout());
3282       if (isAccessedAsGotIndirect(Op)) {
3283         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3284                                                 PPCII::MO_PCREL_FLAG |
3285                                                     PPCII::MO_GOT_FLAG);
3286         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3287         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3288                                    MachinePointerInfo());
3289         return Load;
3290       } else {
3291         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3292                                                 PPCII::MO_PCREL_FLAG);
3293         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3294       }
3295     }
3296     setUsesTOCBasePtr(DAG);
3297     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3298     return getTOCEntry(DAG, DL, GA);
3299   }
3300 
3301   unsigned MOHiFlag, MOLoFlag;
3302   bool IsPIC = isPositionIndependent();
3303   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3304 
3305   if (IsPIC && Subtarget.isSVR4ABI()) {
3306     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3307                                             GSDN->getOffset(),
3308                                             PPCII::MO_PIC_FLAG);
3309     return getTOCEntry(DAG, DL, GA);
3310   }
3311 
3312   SDValue GAHi =
3313     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3314   SDValue GALo =
3315     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3316 
3317   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3318 }
3319 
3320 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3321   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3322   SDLoc dl(Op);
3323 
3324   if (Op.getValueType() == MVT::v2i64) {
3325     // When the operands themselves are v2i64 values, we need to do something
3326     // special because VSX has no underlying comparison operations for these.
3327     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3328       // Equality can be handled by casting to the legal type for Altivec
3329       // comparisons, everything else needs to be expanded.
3330       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3331         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3332                  DAG.getSetCC(dl, MVT::v4i32,
3333                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3334                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3335                    CC));
3336       }
3337 
3338       return SDValue();
3339     }
3340 
3341     // We handle most of these in the usual way.
3342     return Op;
3343   }
3344 
3345   // If we're comparing for equality to zero, expose the fact that this is
3346   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3347   // fold the new nodes.
3348   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3349     return V;
3350 
3351   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3352     // Leave comparisons against 0 and -1 alone for now, since they're usually
3353     // optimized.  FIXME: revisit this when we can custom lower all setcc
3354     // optimizations.
3355     if (C->isAllOnesValue() || C->isNullValue())
3356       return SDValue();
3357   }
3358 
3359   // If we have an integer seteq/setne, turn it into a compare against zero
3360   // by xor'ing the rhs with the lhs, which is faster than setting a
3361   // condition register, reading it back out, and masking the correct bit.  The
3362   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3363   // the result to other bit-twiddling opportunities.
3364   EVT LHSVT = Op.getOperand(0).getValueType();
3365   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3366     EVT VT = Op.getValueType();
3367     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3368                                 Op.getOperand(1));
3369     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3370   }
3371   return SDValue();
3372 }
3373 
3374 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3375   SDNode *Node = Op.getNode();
3376   EVT VT = Node->getValueType(0);
3377   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3378   SDValue InChain = Node->getOperand(0);
3379   SDValue VAListPtr = Node->getOperand(1);
3380   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3381   SDLoc dl(Node);
3382 
3383   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3384 
3385   // gpr_index
3386   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3387                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3388   InChain = GprIndex.getValue(1);
3389 
3390   if (VT == MVT::i64) {
3391     // Check if GprIndex is even
3392     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3393                                  DAG.getConstant(1, dl, MVT::i32));
3394     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3395                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3396     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3397                                           DAG.getConstant(1, dl, MVT::i32));
3398     // Align GprIndex to be even if it isn't
3399     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3400                            GprIndex);
3401   }
3402 
3403   // fpr index is 1 byte after gpr
3404   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3405                                DAG.getConstant(1, dl, MVT::i32));
3406 
3407   // fpr
3408   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3409                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3410   InChain = FprIndex.getValue(1);
3411 
3412   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3413                                        DAG.getConstant(8, dl, MVT::i32));
3414 
3415   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3416                                         DAG.getConstant(4, dl, MVT::i32));
3417 
3418   // areas
3419   SDValue OverflowArea =
3420       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3421   InChain = OverflowArea.getValue(1);
3422 
3423   SDValue RegSaveArea =
3424       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3425   InChain = RegSaveArea.getValue(1);
3426 
3427   // select overflow_area if index > 8
3428   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3429                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3430 
3431   // adjustment constant gpr_index * 4/8
3432   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3433                                     VT.isInteger() ? GprIndex : FprIndex,
3434                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3435                                                     MVT::i32));
3436 
3437   // OurReg = RegSaveArea + RegConstant
3438   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3439                                RegConstant);
3440 
3441   // Floating types are 32 bytes into RegSaveArea
3442   if (VT.isFloatingPoint())
3443     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3444                          DAG.getConstant(32, dl, MVT::i32));
3445 
3446   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3447   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3448                                    VT.isInteger() ? GprIndex : FprIndex,
3449                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3450                                                    MVT::i32));
3451 
3452   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3453                               VT.isInteger() ? VAListPtr : FprPtr,
3454                               MachinePointerInfo(SV), MVT::i8);
3455 
3456   // determine if we should load from reg_save_area or overflow_area
3457   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3458 
3459   // increase overflow_area by 4/8 if gpr/fpr > 8
3460   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3461                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3462                                           dl, MVT::i32));
3463 
3464   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3465                              OverflowAreaPlusN);
3466 
3467   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3468                               MachinePointerInfo(), MVT::i32);
3469 
3470   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3471 }
3472 
3473 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3474   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3475 
3476   // We have to copy the entire va_list struct:
3477   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3478   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3479                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3480                        false, true, false, MachinePointerInfo(),
3481                        MachinePointerInfo());
3482 }
3483 
3484 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3485                                                   SelectionDAG &DAG) const {
3486   if (Subtarget.isAIXABI())
3487     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3488 
3489   return Op.getOperand(0);
3490 }
3491 
3492 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3493                                                 SelectionDAG &DAG) const {
3494   if (Subtarget.isAIXABI())
3495     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3496 
3497   SDValue Chain = Op.getOperand(0);
3498   SDValue Trmp = Op.getOperand(1); // trampoline
3499   SDValue FPtr = Op.getOperand(2); // nested function
3500   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3501   SDLoc dl(Op);
3502 
3503   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3504   bool isPPC64 = (PtrVT == MVT::i64);
3505   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3506 
3507   TargetLowering::ArgListTy Args;
3508   TargetLowering::ArgListEntry Entry;
3509 
3510   Entry.Ty = IntPtrTy;
3511   Entry.Node = Trmp; Args.push_back(Entry);
3512 
3513   // TrampSize == (isPPC64 ? 48 : 40);
3514   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3515                                isPPC64 ? MVT::i64 : MVT::i32);
3516   Args.push_back(Entry);
3517 
3518   Entry.Node = FPtr; Args.push_back(Entry);
3519   Entry.Node = Nest; Args.push_back(Entry);
3520 
3521   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3522   TargetLowering::CallLoweringInfo CLI(DAG);
3523   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3524       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3525       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3526 
3527   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3528   return CallResult.second;
3529 }
3530 
3531 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3532   MachineFunction &MF = DAG.getMachineFunction();
3533   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3534   EVT PtrVT = getPointerTy(MF.getDataLayout());
3535 
3536   SDLoc dl(Op);
3537 
3538   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3539     // vastart just stores the address of the VarArgsFrameIndex slot into the
3540     // memory location argument.
3541     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3542     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3543     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3544                         MachinePointerInfo(SV));
3545   }
3546 
3547   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3548   // We suppose the given va_list is already allocated.
3549   //
3550   // typedef struct {
3551   //  char gpr;     /* index into the array of 8 GPRs
3552   //                 * stored in the register save area
3553   //                 * gpr=0 corresponds to r3,
3554   //                 * gpr=1 to r4, etc.
3555   //                 */
3556   //  char fpr;     /* index into the array of 8 FPRs
3557   //                 * stored in the register save area
3558   //                 * fpr=0 corresponds to f1,
3559   //                 * fpr=1 to f2, etc.
3560   //                 */
3561   //  char *overflow_arg_area;
3562   //                /* location on stack that holds
3563   //                 * the next overflow argument
3564   //                 */
3565   //  char *reg_save_area;
3566   //               /* where r3:r10 and f1:f8 (if saved)
3567   //                * are stored
3568   //                */
3569   // } va_list[1];
3570 
3571   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3572   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3573   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3574                                             PtrVT);
3575   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3576                                  PtrVT);
3577 
3578   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3579   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3580 
3581   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3582   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3583 
3584   uint64_t FPROffset = 1;
3585   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3586 
3587   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3588 
3589   // Store first byte : number of int regs
3590   SDValue firstStore =
3591       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3592                         MachinePointerInfo(SV), MVT::i8);
3593   uint64_t nextOffset = FPROffset;
3594   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3595                                   ConstFPROffset);
3596 
3597   // Store second byte : number of float regs
3598   SDValue secondStore =
3599       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3600                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3601   nextOffset += StackOffset;
3602   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3603 
3604   // Store second word : arguments given on stack
3605   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3606                                     MachinePointerInfo(SV, nextOffset));
3607   nextOffset += FrameOffset;
3608   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3609 
3610   // Store third word : arguments given in registers
3611   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3612                       MachinePointerInfo(SV, nextOffset));
3613 }
3614 
3615 /// FPR - The set of FP registers that should be allocated for arguments
3616 /// on Darwin and AIX.
3617 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3618                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3619                                 PPC::F11, PPC::F12, PPC::F13};
3620 
3621 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3622 /// the stack.
3623 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3624                                        unsigned PtrByteSize) {
3625   unsigned ArgSize = ArgVT.getStoreSize();
3626   if (Flags.isByVal())
3627     ArgSize = Flags.getByValSize();
3628 
3629   // Round up to multiples of the pointer size, except for array members,
3630   // which are always packed.
3631   if (!Flags.isInConsecutiveRegs())
3632     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3633 
3634   return ArgSize;
3635 }
3636 
3637 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3638 /// on the stack.
3639 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3640                                          ISD::ArgFlagsTy Flags,
3641                                          unsigned PtrByteSize) {
3642   Align Alignment(PtrByteSize);
3643 
3644   // Altivec parameters are padded to a 16 byte boundary.
3645   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3646       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3647       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3648       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3649     Alignment = Align(16);
3650 
3651   // ByVal parameters are aligned as requested.
3652   if (Flags.isByVal()) {
3653     auto BVAlign = Flags.getNonZeroByValAlign();
3654     if (BVAlign > PtrByteSize) {
3655       if (BVAlign.value() % PtrByteSize != 0)
3656         llvm_unreachable(
3657             "ByVal alignment is not a multiple of the pointer size");
3658 
3659       Alignment = BVAlign;
3660     }
3661   }
3662 
3663   // Array members are always packed to their original alignment.
3664   if (Flags.isInConsecutiveRegs()) {
3665     // If the array member was split into multiple registers, the first
3666     // needs to be aligned to the size of the full type.  (Except for
3667     // ppcf128, which is only aligned as its f64 components.)
3668     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3669       Alignment = Align(OrigVT.getStoreSize());
3670     else
3671       Alignment = Align(ArgVT.getStoreSize());
3672   }
3673 
3674   return Alignment;
3675 }
3676 
3677 /// CalculateStackSlotUsed - Return whether this argument will use its
3678 /// stack slot (instead of being passed in registers).  ArgOffset,
3679 /// AvailableFPRs, and AvailableVRs must hold the current argument
3680 /// position, and will be updated to account for this argument.
3681 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3682                                    unsigned PtrByteSize, unsigned LinkageSize,
3683                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3684                                    unsigned &AvailableFPRs,
3685                                    unsigned &AvailableVRs) {
3686   bool UseMemory = false;
3687 
3688   // Respect alignment of argument on the stack.
3689   Align Alignment =
3690       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3691   ArgOffset = alignTo(ArgOffset, Alignment);
3692   // If there's no space left in the argument save area, we must
3693   // use memory (this check also catches zero-sized arguments).
3694   if (ArgOffset >= LinkageSize + ParamAreaSize)
3695     UseMemory = true;
3696 
3697   // Allocate argument on the stack.
3698   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3699   if (Flags.isInConsecutiveRegsLast())
3700     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3701   // If we overran the argument save area, we must use memory
3702   // (this check catches arguments passed partially in memory)
3703   if (ArgOffset > LinkageSize + ParamAreaSize)
3704     UseMemory = true;
3705 
3706   // However, if the argument is actually passed in an FPR or a VR,
3707   // we don't use memory after all.
3708   if (!Flags.isByVal()) {
3709     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3710       if (AvailableFPRs > 0) {
3711         --AvailableFPRs;
3712         return false;
3713       }
3714     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3715         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3716         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3717         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3718       if (AvailableVRs > 0) {
3719         --AvailableVRs;
3720         return false;
3721       }
3722   }
3723 
3724   return UseMemory;
3725 }
3726 
3727 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3728 /// ensure minimum alignment required for target.
3729 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3730                                      unsigned NumBytes) {
3731   return alignTo(NumBytes, Lowering->getStackAlign());
3732 }
3733 
3734 SDValue PPCTargetLowering::LowerFormalArguments(
3735     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3736     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3737     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3738   if (Subtarget.isAIXABI())
3739     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3740                                     InVals);
3741   if (Subtarget.is64BitELFABI())
3742     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3743                                        InVals);
3744   if (Subtarget.is32BitELFABI())
3745     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3746                                        InVals);
3747 
3748   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3749                                      InVals);
3750 }
3751 
3752 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3753     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3754     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3755     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3756 
3757   // 32-bit SVR4 ABI Stack Frame Layout:
3758   //              +-----------------------------------+
3759   //        +-->  |            Back chain             |
3760   //        |     +-----------------------------------+
3761   //        |     | Floating-point register save area |
3762   //        |     +-----------------------------------+
3763   //        |     |    General register save area     |
3764   //        |     +-----------------------------------+
3765   //        |     |          CR save word             |
3766   //        |     +-----------------------------------+
3767   //        |     |         VRSAVE save word          |
3768   //        |     +-----------------------------------+
3769   //        |     |         Alignment padding         |
3770   //        |     +-----------------------------------+
3771   //        |     |     Vector register save area     |
3772   //        |     +-----------------------------------+
3773   //        |     |       Local variable space        |
3774   //        |     +-----------------------------------+
3775   //        |     |        Parameter list area        |
3776   //        |     +-----------------------------------+
3777   //        |     |           LR save word            |
3778   //        |     +-----------------------------------+
3779   // SP-->  +---  |            Back chain             |
3780   //              +-----------------------------------+
3781   //
3782   // Specifications:
3783   //   System V Application Binary Interface PowerPC Processor Supplement
3784   //   AltiVec Technology Programming Interface Manual
3785 
3786   MachineFunction &MF = DAG.getMachineFunction();
3787   MachineFrameInfo &MFI = MF.getFrameInfo();
3788   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3789 
3790   EVT PtrVT = getPointerTy(MF.getDataLayout());
3791   // Potential tail calls could cause overwriting of argument stack slots.
3792   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3793                        (CallConv == CallingConv::Fast));
3794   const Align PtrAlign(4);
3795 
3796   // Assign locations to all of the incoming arguments.
3797   SmallVector<CCValAssign, 16> ArgLocs;
3798   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3799                  *DAG.getContext());
3800 
3801   // Reserve space for the linkage area on the stack.
3802   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3803   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3804   if (useSoftFloat())
3805     CCInfo.PreAnalyzeFormalArguments(Ins);
3806 
3807   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3808   CCInfo.clearWasPPCF128();
3809 
3810   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3811     CCValAssign &VA = ArgLocs[i];
3812 
3813     // Arguments stored in registers.
3814     if (VA.isRegLoc()) {
3815       const TargetRegisterClass *RC;
3816       EVT ValVT = VA.getValVT();
3817 
3818       switch (ValVT.getSimpleVT().SimpleTy) {
3819         default:
3820           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3821         case MVT::i1:
3822         case MVT::i32:
3823           RC = &PPC::GPRCRegClass;
3824           break;
3825         case MVT::f32:
3826           if (Subtarget.hasP8Vector())
3827             RC = &PPC::VSSRCRegClass;
3828           else if (Subtarget.hasSPE())
3829             RC = &PPC::GPRCRegClass;
3830           else
3831             RC = &PPC::F4RCRegClass;
3832           break;
3833         case MVT::f64:
3834           if (Subtarget.hasVSX())
3835             RC = &PPC::VSFRCRegClass;
3836           else if (Subtarget.hasSPE())
3837             // SPE passes doubles in GPR pairs.
3838             RC = &PPC::GPRCRegClass;
3839           else
3840             RC = &PPC::F8RCRegClass;
3841           break;
3842         case MVT::v16i8:
3843         case MVT::v8i16:
3844         case MVT::v4i32:
3845           RC = &PPC::VRRCRegClass;
3846           break;
3847         case MVT::v4f32:
3848           RC = &PPC::VRRCRegClass;
3849           break;
3850         case MVT::v2f64:
3851         case MVT::v2i64:
3852           RC = &PPC::VRRCRegClass;
3853           break;
3854       }
3855 
3856       SDValue ArgValue;
3857       // Transform the arguments stored in physical registers into
3858       // virtual ones.
3859       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3860         assert(i + 1 < e && "No second half of double precision argument");
3861         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3862         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3863         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3864         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3865         if (!Subtarget.isLittleEndian())
3866           std::swap (ArgValueLo, ArgValueHi);
3867         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3868                                ArgValueHi);
3869       } else {
3870         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3871         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3872                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3873         if (ValVT == MVT::i1)
3874           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3875       }
3876 
3877       InVals.push_back(ArgValue);
3878     } else {
3879       // Argument stored in memory.
3880       assert(VA.isMemLoc());
3881 
3882       // Get the extended size of the argument type in stack
3883       unsigned ArgSize = VA.getLocVT().getStoreSize();
3884       // Get the actual size of the argument type
3885       unsigned ObjSize = VA.getValVT().getStoreSize();
3886       unsigned ArgOffset = VA.getLocMemOffset();
3887       // Stack objects in PPC32 are right justified.
3888       ArgOffset += ArgSize - ObjSize;
3889       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3890 
3891       // Create load nodes to retrieve arguments from the stack.
3892       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3893       InVals.push_back(
3894           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3895     }
3896   }
3897 
3898   // Assign locations to all of the incoming aggregate by value arguments.
3899   // Aggregates passed by value are stored in the local variable space of the
3900   // caller's stack frame, right above the parameter list area.
3901   SmallVector<CCValAssign, 16> ByValArgLocs;
3902   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3903                       ByValArgLocs, *DAG.getContext());
3904 
3905   // Reserve stack space for the allocations in CCInfo.
3906   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
3907 
3908   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3909 
3910   // Area that is at least reserved in the caller of this function.
3911   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3912   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3913 
3914   // Set the size that is at least reserved in caller of this function.  Tail
3915   // call optimized function's reserved stack space needs to be aligned so that
3916   // taking the difference between two stack areas will result in an aligned
3917   // stack.
3918   MinReservedArea =
3919       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3920   FuncInfo->setMinReservedArea(MinReservedArea);
3921 
3922   SmallVector<SDValue, 8> MemOps;
3923 
3924   // If the function takes variable number of arguments, make a frame index for
3925   // the start of the first vararg value... for expansion of llvm.va_start.
3926   if (isVarArg) {
3927     static const MCPhysReg GPArgRegs[] = {
3928       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3929       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3930     };
3931     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3932 
3933     static const MCPhysReg FPArgRegs[] = {
3934       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3935       PPC::F8
3936     };
3937     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3938 
3939     if (useSoftFloat() || hasSPE())
3940        NumFPArgRegs = 0;
3941 
3942     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3943     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3944 
3945     // Make room for NumGPArgRegs and NumFPArgRegs.
3946     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3947                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3948 
3949     FuncInfo->setVarArgsStackOffset(
3950       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3951                             CCInfo.getNextStackOffset(), true));
3952 
3953     FuncInfo->setVarArgsFrameIndex(
3954         MFI.CreateStackObject(Depth, Align(8), false));
3955     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3956 
3957     // The fixed integer arguments of a variadic function are stored to the
3958     // VarArgsFrameIndex on the stack so that they may be loaded by
3959     // dereferencing the result of va_next.
3960     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3961       // Get an existing live-in vreg, or add a new one.
3962       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3963       if (!VReg)
3964         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3965 
3966       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3967       SDValue Store =
3968           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3969       MemOps.push_back(Store);
3970       // Increment the address by four for the next argument to store
3971       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3972       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3973     }
3974 
3975     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3976     // is set.
3977     // The double arguments are stored to the VarArgsFrameIndex
3978     // on the stack.
3979     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3980       // Get an existing live-in vreg, or add a new one.
3981       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3982       if (!VReg)
3983         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3984 
3985       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3986       SDValue Store =
3987           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3988       MemOps.push_back(Store);
3989       // Increment the address by eight for the next argument to store
3990       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3991                                          PtrVT);
3992       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3993     }
3994   }
3995 
3996   if (!MemOps.empty())
3997     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3998 
3999   return Chain;
4000 }
4001 
4002 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4003 // value to MVT::i64 and then truncate to the correct register size.
4004 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
4005                                              EVT ObjectVT, SelectionDAG &DAG,
4006                                              SDValue ArgVal,
4007                                              const SDLoc &dl) const {
4008   if (Flags.isSExt())
4009     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
4010                          DAG.getValueType(ObjectVT));
4011   else if (Flags.isZExt())
4012     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
4013                          DAG.getValueType(ObjectVT));
4014 
4015   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
4016 }
4017 
4018 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
4019     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4020     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4021     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4022   // TODO: add description of PPC stack frame format, or at least some docs.
4023   //
4024   bool isELFv2ABI = Subtarget.isELFv2ABI();
4025   bool isLittleEndian = Subtarget.isLittleEndian();
4026   MachineFunction &MF = DAG.getMachineFunction();
4027   MachineFrameInfo &MFI = MF.getFrameInfo();
4028   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4029 
4030   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4031          "fastcc not supported on varargs functions");
4032 
4033   EVT PtrVT = getPointerTy(MF.getDataLayout());
4034   // Potential tail calls could cause overwriting of argument stack slots.
4035   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4036                        (CallConv == CallingConv::Fast));
4037   unsigned PtrByteSize = 8;
4038   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4039 
4040   static const MCPhysReg GPR[] = {
4041     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4042     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4043   };
4044   static const MCPhysReg VR[] = {
4045     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4046     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4047   };
4048 
4049   const unsigned Num_GPR_Regs = array_lengthof(GPR);
4050   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4051   const unsigned Num_VR_Regs  = array_lengthof(VR);
4052 
4053   // Do a first pass over the arguments to determine whether the ABI
4054   // guarantees that our caller has allocated the parameter save area
4055   // on its stack frame.  In the ELFv1 ABI, this is always the case;
4056   // in the ELFv2 ABI, it is true if this is a vararg function or if
4057   // any parameter is located in a stack slot.
4058 
4059   bool HasParameterArea = !isELFv2ABI || isVarArg;
4060   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4061   unsigned NumBytes = LinkageSize;
4062   unsigned AvailableFPRs = Num_FPR_Regs;
4063   unsigned AvailableVRs = Num_VR_Regs;
4064   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4065     if (Ins[i].Flags.isNest())
4066       continue;
4067 
4068     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
4069                                PtrByteSize, LinkageSize, ParamAreaSize,
4070                                NumBytes, AvailableFPRs, AvailableVRs))
4071       HasParameterArea = true;
4072   }
4073 
4074   // Add DAG nodes to load the arguments or copy them out of registers.  On
4075   // entry to a function on PPC, the arguments start after the linkage area,
4076   // although the first ones are often in registers.
4077 
4078   unsigned ArgOffset = LinkageSize;
4079   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4080   SmallVector<SDValue, 8> MemOps;
4081   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4082   unsigned CurArgIdx = 0;
4083   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4084     SDValue ArgVal;
4085     bool needsLoad = false;
4086     EVT ObjectVT = Ins[ArgNo].VT;
4087     EVT OrigVT = Ins[ArgNo].ArgVT;
4088     unsigned ObjSize = ObjectVT.getStoreSize();
4089     unsigned ArgSize = ObjSize;
4090     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4091     if (Ins[ArgNo].isOrigArg()) {
4092       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4093       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4094     }
4095     // We re-align the argument offset for each argument, except when using the
4096     // fast calling convention, when we need to make sure we do that only when
4097     // we'll actually use a stack slot.
4098     unsigned CurArgOffset;
4099     Align Alignment;
4100     auto ComputeArgOffset = [&]() {
4101       /* Respect alignment of argument on the stack.  */
4102       Alignment =
4103           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4104       ArgOffset = alignTo(ArgOffset, Alignment);
4105       CurArgOffset = ArgOffset;
4106     };
4107 
4108     if (CallConv != CallingConv::Fast) {
4109       ComputeArgOffset();
4110 
4111       /* Compute GPR index associated with argument offset.  */
4112       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4113       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4114     }
4115 
4116     // FIXME the codegen can be much improved in some cases.
4117     // We do not have to keep everything in memory.
4118     if (Flags.isByVal()) {
4119       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4120 
4121       if (CallConv == CallingConv::Fast)
4122         ComputeArgOffset();
4123 
4124       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4125       ObjSize = Flags.getByValSize();
4126       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4127       // Empty aggregate parameters do not take up registers.  Examples:
4128       //   struct { } a;
4129       //   union  { } b;
4130       //   int c[0];
4131       // etc.  However, we have to provide a place-holder in InVals, so
4132       // pretend we have an 8-byte item at the current address for that
4133       // purpose.
4134       if (!ObjSize) {
4135         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4136         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4137         InVals.push_back(FIN);
4138         continue;
4139       }
4140 
4141       // Create a stack object covering all stack doublewords occupied
4142       // by the argument.  If the argument is (fully or partially) on
4143       // the stack, or if the argument is fully in registers but the
4144       // caller has allocated the parameter save anyway, we can refer
4145       // directly to the caller's stack frame.  Otherwise, create a
4146       // local copy in our own frame.
4147       int FI;
4148       if (HasParameterArea ||
4149           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4150         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4151       else
4152         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4153       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4154 
4155       // Handle aggregates smaller than 8 bytes.
4156       if (ObjSize < PtrByteSize) {
4157         // The value of the object is its address, which differs from the
4158         // address of the enclosing doubleword on big-endian systems.
4159         SDValue Arg = FIN;
4160         if (!isLittleEndian) {
4161           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4162           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4163         }
4164         InVals.push_back(Arg);
4165 
4166         if (GPR_idx != Num_GPR_Regs) {
4167           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4168           FuncInfo->addLiveInAttr(VReg, Flags);
4169           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4170           SDValue Store;
4171 
4172           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
4173             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
4174                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
4175             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4176                                       MachinePointerInfo(&*FuncArg), ObjType);
4177           } else {
4178             // For sizes that don't fit a truncating store (3, 5, 6, 7),
4179             // store the whole register as-is to the parameter save area
4180             // slot.
4181             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4182                                  MachinePointerInfo(&*FuncArg));
4183           }
4184 
4185           MemOps.push_back(Store);
4186         }
4187         // Whether we copied from a register or not, advance the offset
4188         // into the parameter save area by a full doubleword.
4189         ArgOffset += PtrByteSize;
4190         continue;
4191       }
4192 
4193       // The value of the object is its address, which is the address of
4194       // its first stack doubleword.
4195       InVals.push_back(FIN);
4196 
4197       // Store whatever pieces of the object are in registers to memory.
4198       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4199         if (GPR_idx == Num_GPR_Regs)
4200           break;
4201 
4202         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4203         FuncInfo->addLiveInAttr(VReg, Flags);
4204         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4205         SDValue Addr = FIN;
4206         if (j) {
4207           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4208           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4209         }
4210         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4211                                      MachinePointerInfo(&*FuncArg, j));
4212         MemOps.push_back(Store);
4213         ++GPR_idx;
4214       }
4215       ArgOffset += ArgSize;
4216       continue;
4217     }
4218 
4219     switch (ObjectVT.getSimpleVT().SimpleTy) {
4220     default: llvm_unreachable("Unhandled argument type!");
4221     case MVT::i1:
4222     case MVT::i32:
4223     case MVT::i64:
4224       if (Flags.isNest()) {
4225         // The 'nest' parameter, if any, is passed in R11.
4226         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4227         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4228 
4229         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4230           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4231 
4232         break;
4233       }
4234 
4235       // These can be scalar arguments or elements of an integer array type
4236       // passed directly.  Clang may use those instead of "byval" aggregate
4237       // types to avoid forcing arguments to memory unnecessarily.
4238       if (GPR_idx != Num_GPR_Regs) {
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::i32 || ObjectVT == MVT::i1)
4244           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4245           // value to MVT::i64 and then truncate to the correct register size.
4246           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4247       } else {
4248         if (CallConv == CallingConv::Fast)
4249           ComputeArgOffset();
4250 
4251         needsLoad = true;
4252         ArgSize = PtrByteSize;
4253       }
4254       if (CallConv != CallingConv::Fast || needsLoad)
4255         ArgOffset += 8;
4256       break;
4257 
4258     case MVT::f32:
4259     case MVT::f64:
4260       // These can be scalar arguments or elements of a float array type
4261       // passed directly.  The latter are used to implement ELFv2 homogenous
4262       // float aggregates.
4263       if (FPR_idx != Num_FPR_Regs) {
4264         unsigned VReg;
4265 
4266         if (ObjectVT == MVT::f32)
4267           VReg = MF.addLiveIn(FPR[FPR_idx],
4268                               Subtarget.hasP8Vector()
4269                                   ? &PPC::VSSRCRegClass
4270                                   : &PPC::F4RCRegClass);
4271         else
4272           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4273                                                 ? &PPC::VSFRCRegClass
4274                                                 : &PPC::F8RCRegClass);
4275 
4276         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4277         ++FPR_idx;
4278       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4279         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4280         // once we support fp <-> gpr moves.
4281 
4282         // This can only ever happen in the presence of f32 array types,
4283         // since otherwise we never run out of FPRs before running out
4284         // of GPRs.
4285         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4286         FuncInfo->addLiveInAttr(VReg, Flags);
4287         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4288 
4289         if (ObjectVT == MVT::f32) {
4290           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4291             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4292                                  DAG.getConstant(32, dl, MVT::i32));
4293           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4294         }
4295 
4296         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4297       } else {
4298         if (CallConv == CallingConv::Fast)
4299           ComputeArgOffset();
4300 
4301         needsLoad = true;
4302       }
4303 
4304       // When passing an array of floats, the array occupies consecutive
4305       // space in the argument area; only round up to the next doubleword
4306       // at the end of the array.  Otherwise, each float takes 8 bytes.
4307       if (CallConv != CallingConv::Fast || needsLoad) {
4308         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4309         ArgOffset += ArgSize;
4310         if (Flags.isInConsecutiveRegsLast())
4311           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4312       }
4313       break;
4314     case MVT::v4f32:
4315     case MVT::v4i32:
4316     case MVT::v8i16:
4317     case MVT::v16i8:
4318     case MVT::v2f64:
4319     case MVT::v2i64:
4320     case MVT::v1i128:
4321     case MVT::f128:
4322       // These can be scalar arguments or elements of a vector array type
4323       // passed directly.  The latter are used to implement ELFv2 homogenous
4324       // vector aggregates.
4325       if (VR_idx != Num_VR_Regs) {
4326         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4327         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4328         ++VR_idx;
4329       } else {
4330         if (CallConv == CallingConv::Fast)
4331           ComputeArgOffset();
4332         needsLoad = true;
4333       }
4334       if (CallConv != CallingConv::Fast || needsLoad)
4335         ArgOffset += 16;
4336       break;
4337     }
4338 
4339     // We need to load the argument to a virtual register if we determined
4340     // above that we ran out of physical registers of the appropriate type.
4341     if (needsLoad) {
4342       if (ObjSize < ArgSize && !isLittleEndian)
4343         CurArgOffset += ArgSize - ObjSize;
4344       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4345       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4346       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4347     }
4348 
4349     InVals.push_back(ArgVal);
4350   }
4351 
4352   // Area that is at least reserved in the caller of this function.
4353   unsigned MinReservedArea;
4354   if (HasParameterArea)
4355     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4356   else
4357     MinReservedArea = LinkageSize;
4358 
4359   // Set the size that is at least reserved in caller of this function.  Tail
4360   // call optimized functions' reserved stack space needs to be aligned so that
4361   // taking the difference between two stack areas will result in an aligned
4362   // stack.
4363   MinReservedArea =
4364       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4365   FuncInfo->setMinReservedArea(MinReservedArea);
4366 
4367   // If the function takes variable number of arguments, make a frame index for
4368   // the start of the first vararg value... for expansion of llvm.va_start.
4369   // On ELFv2ABI spec, it writes:
4370   // C programs that are intended to be *portable* across different compilers
4371   // and architectures must use the header file <stdarg.h> to deal with variable
4372   // argument lists.
4373   if (isVarArg && MFI.hasVAStart()) {
4374     int Depth = ArgOffset;
4375 
4376     FuncInfo->setVarArgsFrameIndex(
4377       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4378     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4379 
4380     // If this function is vararg, store any remaining integer argument regs
4381     // to their spots on the stack so that they may be loaded by dereferencing
4382     // the result of va_next.
4383     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4384          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4385       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4386       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4387       SDValue Store =
4388           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4389       MemOps.push_back(Store);
4390       // Increment the address by four for the next argument to store
4391       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4392       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4393     }
4394   }
4395 
4396   if (!MemOps.empty())
4397     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4398 
4399   return Chain;
4400 }
4401 
4402 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4403     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4404     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4405     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4406   // TODO: add description of PPC stack frame format, or at least some docs.
4407   //
4408   MachineFunction &MF = DAG.getMachineFunction();
4409   MachineFrameInfo &MFI = MF.getFrameInfo();
4410   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4411 
4412   EVT PtrVT = getPointerTy(MF.getDataLayout());
4413   bool isPPC64 = PtrVT == MVT::i64;
4414   // Potential tail calls could cause overwriting of argument stack slots.
4415   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4416                        (CallConv == CallingConv::Fast));
4417   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4418   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4419   unsigned ArgOffset = LinkageSize;
4420   // Area that is at least reserved in caller of this function.
4421   unsigned MinReservedArea = ArgOffset;
4422 
4423   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4424     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4425     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4426   };
4427   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4428     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4429     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4430   };
4431   static const MCPhysReg VR[] = {
4432     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4433     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4434   };
4435 
4436   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4437   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4438   const unsigned Num_VR_Regs  = array_lengthof( VR);
4439 
4440   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4441 
4442   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4443 
4444   // In 32-bit non-varargs functions, the stack space for vectors is after the
4445   // stack space for non-vectors.  We do not use this space unless we have
4446   // too many vectors to fit in registers, something that only occurs in
4447   // constructed examples:), but we have to walk the arglist to figure
4448   // that out...for the pathological case, compute VecArgOffset as the
4449   // start of the vector parameter area.  Computing VecArgOffset is the
4450   // entire point of the following loop.
4451   unsigned VecArgOffset = ArgOffset;
4452   if (!isVarArg && !isPPC64) {
4453     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4454          ++ArgNo) {
4455       EVT ObjectVT = Ins[ArgNo].VT;
4456       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4457 
4458       if (Flags.isByVal()) {
4459         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4460         unsigned ObjSize = Flags.getByValSize();
4461         unsigned ArgSize =
4462                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4463         VecArgOffset += ArgSize;
4464         continue;
4465       }
4466 
4467       switch(ObjectVT.getSimpleVT().SimpleTy) {
4468       default: llvm_unreachable("Unhandled argument type!");
4469       case MVT::i1:
4470       case MVT::i32:
4471       case MVT::f32:
4472         VecArgOffset += 4;
4473         break;
4474       case MVT::i64:  // PPC64
4475       case MVT::f64:
4476         // FIXME: We are guaranteed to be !isPPC64 at this point.
4477         // Does MVT::i64 apply?
4478         VecArgOffset += 8;
4479         break;
4480       case MVT::v4f32:
4481       case MVT::v4i32:
4482       case MVT::v8i16:
4483       case MVT::v16i8:
4484         // Nothing to do, we're only looking at Nonvector args here.
4485         break;
4486       }
4487     }
4488   }
4489   // We've found where the vector parameter area in memory is.  Skip the
4490   // first 12 parameters; these don't use that memory.
4491   VecArgOffset = ((VecArgOffset+15)/16)*16;
4492   VecArgOffset += 12*16;
4493 
4494   // Add DAG nodes to load the arguments or copy them out of registers.  On
4495   // entry to a function on PPC, the arguments start after the linkage area,
4496   // although the first ones are often in registers.
4497 
4498   SmallVector<SDValue, 8> MemOps;
4499   unsigned nAltivecParamsAtEnd = 0;
4500   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4501   unsigned CurArgIdx = 0;
4502   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4503     SDValue ArgVal;
4504     bool needsLoad = false;
4505     EVT ObjectVT = Ins[ArgNo].VT;
4506     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4507     unsigned ArgSize = ObjSize;
4508     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4509     if (Ins[ArgNo].isOrigArg()) {
4510       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4511       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4512     }
4513     unsigned CurArgOffset = ArgOffset;
4514 
4515     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4516     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4517         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4518       if (isVarArg || isPPC64) {
4519         MinReservedArea = ((MinReservedArea+15)/16)*16;
4520         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4521                                                   Flags,
4522                                                   PtrByteSize);
4523       } else  nAltivecParamsAtEnd++;
4524     } else
4525       // Calculate min reserved area.
4526       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4527                                                 Flags,
4528                                                 PtrByteSize);
4529 
4530     // FIXME the codegen can be much improved in some cases.
4531     // We do not have to keep everything in memory.
4532     if (Flags.isByVal()) {
4533       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4534 
4535       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4536       ObjSize = Flags.getByValSize();
4537       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4538       // Objects of size 1 and 2 are right justified, everything else is
4539       // left justified.  This means the memory address is adjusted forwards.
4540       if (ObjSize==1 || ObjSize==2) {
4541         CurArgOffset = CurArgOffset + (4 - ObjSize);
4542       }
4543       // The value of the object is its address.
4544       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4545       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4546       InVals.push_back(FIN);
4547       if (ObjSize==1 || ObjSize==2) {
4548         if (GPR_idx != Num_GPR_Regs) {
4549           unsigned VReg;
4550           if (isPPC64)
4551             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4552           else
4553             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4554           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4555           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4556           SDValue Store =
4557               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4558                                 MachinePointerInfo(&*FuncArg), ObjType);
4559           MemOps.push_back(Store);
4560           ++GPR_idx;
4561         }
4562 
4563         ArgOffset += PtrByteSize;
4564 
4565         continue;
4566       }
4567       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4568         // Store whatever pieces of the object are in registers
4569         // to memory.  ArgOffset will be the address of the beginning
4570         // of the object.
4571         if (GPR_idx != Num_GPR_Regs) {
4572           unsigned VReg;
4573           if (isPPC64)
4574             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4575           else
4576             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4577           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4578           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4579           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4580           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4581                                        MachinePointerInfo(&*FuncArg, j));
4582           MemOps.push_back(Store);
4583           ++GPR_idx;
4584           ArgOffset += PtrByteSize;
4585         } else {
4586           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4587           break;
4588         }
4589       }
4590       continue;
4591     }
4592 
4593     switch (ObjectVT.getSimpleVT().SimpleTy) {
4594     default: llvm_unreachable("Unhandled argument type!");
4595     case MVT::i1:
4596     case MVT::i32:
4597       if (!isPPC64) {
4598         if (GPR_idx != Num_GPR_Regs) {
4599           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4600           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4601 
4602           if (ObjectVT == MVT::i1)
4603             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4604 
4605           ++GPR_idx;
4606         } else {
4607           needsLoad = true;
4608           ArgSize = PtrByteSize;
4609         }
4610         // All int arguments reserve stack space in the Darwin ABI.
4611         ArgOffset += PtrByteSize;
4612         break;
4613       }
4614       LLVM_FALLTHROUGH;
4615     case MVT::i64:  // PPC64
4616       if (GPR_idx != Num_GPR_Regs) {
4617         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4618         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4619 
4620         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4621           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4622           // value to MVT::i64 and then truncate to the correct register size.
4623           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4624 
4625         ++GPR_idx;
4626       } else {
4627         needsLoad = true;
4628         ArgSize = PtrByteSize;
4629       }
4630       // All int arguments reserve stack space in the Darwin ABI.
4631       ArgOffset += 8;
4632       break;
4633 
4634     case MVT::f32:
4635     case MVT::f64:
4636       // Every 4 bytes of argument space consumes one of the GPRs available for
4637       // argument passing.
4638       if (GPR_idx != Num_GPR_Regs) {
4639         ++GPR_idx;
4640         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4641           ++GPR_idx;
4642       }
4643       if (FPR_idx != Num_FPR_Regs) {
4644         unsigned VReg;
4645 
4646         if (ObjectVT == MVT::f32)
4647           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4648         else
4649           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4650 
4651         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4652         ++FPR_idx;
4653       } else {
4654         needsLoad = true;
4655       }
4656 
4657       // All FP arguments reserve stack space in the Darwin ABI.
4658       ArgOffset += isPPC64 ? 8 : ObjSize;
4659       break;
4660     case MVT::v4f32:
4661     case MVT::v4i32:
4662     case MVT::v8i16:
4663     case MVT::v16i8:
4664       // Note that vector arguments in registers don't reserve stack space,
4665       // except in varargs functions.
4666       if (VR_idx != Num_VR_Regs) {
4667         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4668         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4669         if (isVarArg) {
4670           while ((ArgOffset % 16) != 0) {
4671             ArgOffset += PtrByteSize;
4672             if (GPR_idx != Num_GPR_Regs)
4673               GPR_idx++;
4674           }
4675           ArgOffset += 16;
4676           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4677         }
4678         ++VR_idx;
4679       } else {
4680         if (!isVarArg && !isPPC64) {
4681           // Vectors go after all the nonvectors.
4682           CurArgOffset = VecArgOffset;
4683           VecArgOffset += 16;
4684         } else {
4685           // Vectors are aligned.
4686           ArgOffset = ((ArgOffset+15)/16)*16;
4687           CurArgOffset = ArgOffset;
4688           ArgOffset += 16;
4689         }
4690         needsLoad = true;
4691       }
4692       break;
4693     }
4694 
4695     // We need to load the argument to a virtual register if we determined above
4696     // that we ran out of physical registers of the appropriate type.
4697     if (needsLoad) {
4698       int FI = MFI.CreateFixedObject(ObjSize,
4699                                      CurArgOffset + (ArgSize - ObjSize),
4700                                      isImmutable);
4701       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4702       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4703     }
4704 
4705     InVals.push_back(ArgVal);
4706   }
4707 
4708   // Allow for Altivec parameters at the end, if needed.
4709   if (nAltivecParamsAtEnd) {
4710     MinReservedArea = ((MinReservedArea+15)/16)*16;
4711     MinReservedArea += 16*nAltivecParamsAtEnd;
4712   }
4713 
4714   // Area that is at least reserved in the caller of this function.
4715   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4716 
4717   // Set the size that is at least reserved in caller of this function.  Tail
4718   // call optimized functions' reserved stack space needs to be aligned so that
4719   // taking the difference between two stack areas will result in an aligned
4720   // stack.
4721   MinReservedArea =
4722       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4723   FuncInfo->setMinReservedArea(MinReservedArea);
4724 
4725   // If the function takes variable number of arguments, make a frame index for
4726   // the start of the first vararg value... for expansion of llvm.va_start.
4727   if (isVarArg) {
4728     int Depth = ArgOffset;
4729 
4730     FuncInfo->setVarArgsFrameIndex(
4731       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4732                             Depth, true));
4733     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4734 
4735     // If this function is vararg, store any remaining integer argument regs
4736     // to their spots on the stack so that they may be loaded by dereferencing
4737     // the result of va_next.
4738     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4739       unsigned VReg;
4740 
4741       if (isPPC64)
4742         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4743       else
4744         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4745 
4746       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4747       SDValue Store =
4748           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4749       MemOps.push_back(Store);
4750       // Increment the address by four for the next argument to store
4751       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4752       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4753     }
4754   }
4755 
4756   if (!MemOps.empty())
4757     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4758 
4759   return Chain;
4760 }
4761 
4762 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4763 /// adjusted to accommodate the arguments for the tailcall.
4764 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4765                                    unsigned ParamSize) {
4766 
4767   if (!isTailCall) return 0;
4768 
4769   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4770   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4771   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4772   // Remember only if the new adjustment is bigger.
4773   if (SPDiff < FI->getTailCallSPDelta())
4774     FI->setTailCallSPDelta(SPDiff);
4775 
4776   return SPDiff;
4777 }
4778 
4779 static bool isFunctionGlobalAddress(SDValue Callee);
4780 
4781 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4782                               const TargetMachine &TM) {
4783   // It does not make sense to call callsShareTOCBase() with a caller that
4784   // is PC Relative since PC Relative callers do not have a TOC.
4785 #ifndef NDEBUG
4786   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4787   assert(!STICaller->isUsingPCRelativeCalls() &&
4788          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4789 #endif
4790 
4791   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4792   // don't have enough information to determine if the caller and callee share
4793   // the same  TOC base, so we have to pessimistically assume they don't for
4794   // correctness.
4795   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4796   if (!G)
4797     return false;
4798 
4799   const GlobalValue *GV = G->getGlobal();
4800 
4801   // If the callee is preemptable, then the static linker will use a plt-stub
4802   // which saves the toc to the stack, and needs a nop after the call
4803   // instruction to convert to a toc-restore.
4804   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4805     return false;
4806 
4807   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4808   // We may need a TOC restore in the situation where the caller requires a
4809   // valid TOC but the callee is PC Relative and does not.
4810   const Function *F = dyn_cast<Function>(GV);
4811   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4812 
4813   // If we have an Alias we can try to get the function from there.
4814   if (Alias) {
4815     const GlobalObject *GlobalObj = Alias->getBaseObject();
4816     F = dyn_cast<Function>(GlobalObj);
4817   }
4818 
4819   // If we still have no valid function pointer we do not have enough
4820   // information to determine if the callee uses PC Relative calls so we must
4821   // assume that it does.
4822   if (!F)
4823     return false;
4824 
4825   // If the callee uses PC Relative we cannot guarantee that the callee won't
4826   // clobber the TOC of the caller and so we must assume that the two
4827   // functions do not share a TOC base.
4828   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4829   if (STICallee->isUsingPCRelativeCalls())
4830     return false;
4831 
4832   // If the GV is not a strong definition then we need to assume it can be
4833   // replaced by another function at link time. The function that replaces
4834   // it may not share the same TOC as the caller since the callee may be
4835   // replaced by a PC Relative version of the same function.
4836   if (!GV->isStrongDefinitionForLinker())
4837     return false;
4838 
4839   // The medium and large code models are expected to provide a sufficiently
4840   // large TOC to provide all data addressing needs of a module with a
4841   // single TOC.
4842   if (CodeModel::Medium == TM.getCodeModel() ||
4843       CodeModel::Large == TM.getCodeModel())
4844     return true;
4845 
4846   // Any explicitly-specified sections and section prefixes must also match.
4847   // Also, if we're using -ffunction-sections, then each function is always in
4848   // a different section (the same is true for COMDAT functions).
4849   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4850       GV->getSection() != Caller->getSection())
4851     return false;
4852   if (const auto *F = dyn_cast<Function>(GV)) {
4853     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4854       return false;
4855   }
4856 
4857   return true;
4858 }
4859 
4860 static bool
4861 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4862                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4863   assert(Subtarget.is64BitELFABI());
4864 
4865   const unsigned PtrByteSize = 8;
4866   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4867 
4868   static const MCPhysReg GPR[] = {
4869     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4870     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4871   };
4872   static const MCPhysReg VR[] = {
4873     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4874     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4875   };
4876 
4877   const unsigned NumGPRs = array_lengthof(GPR);
4878   const unsigned NumFPRs = 13;
4879   const unsigned NumVRs = array_lengthof(VR);
4880   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4881 
4882   unsigned NumBytes = LinkageSize;
4883   unsigned AvailableFPRs = NumFPRs;
4884   unsigned AvailableVRs = NumVRs;
4885 
4886   for (const ISD::OutputArg& Param : Outs) {
4887     if (Param.Flags.isNest()) continue;
4888 
4889     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4890                                LinkageSize, ParamAreaSize, NumBytes,
4891                                AvailableFPRs, AvailableVRs))
4892       return true;
4893   }
4894   return false;
4895 }
4896 
4897 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4898   if (CB.arg_size() != CallerFn->arg_size())
4899     return false;
4900 
4901   auto CalleeArgIter = CB.arg_begin();
4902   auto CalleeArgEnd = CB.arg_end();
4903   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4904 
4905   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4906     const Value* CalleeArg = *CalleeArgIter;
4907     const Value* CallerArg = &(*CallerArgIter);
4908     if (CalleeArg == CallerArg)
4909       continue;
4910 
4911     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4912     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4913     //      }
4914     // 1st argument of callee is undef and has the same type as caller.
4915     if (CalleeArg->getType() == CallerArg->getType() &&
4916         isa<UndefValue>(CalleeArg))
4917       continue;
4918 
4919     return false;
4920   }
4921 
4922   return true;
4923 }
4924 
4925 // Returns true if TCO is possible between the callers and callees
4926 // calling conventions.
4927 static bool
4928 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4929                                     CallingConv::ID CalleeCC) {
4930   // Tail calls are possible with fastcc and ccc.
4931   auto isTailCallableCC  = [] (CallingConv::ID CC){
4932       return  CC == CallingConv::C || CC == CallingConv::Fast;
4933   };
4934   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4935     return false;
4936 
4937   // We can safely tail call both fastcc and ccc callees from a c calling
4938   // convention caller. If the caller is fastcc, we may have less stack space
4939   // than a non-fastcc caller with the same signature so disable tail-calls in
4940   // that case.
4941   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4942 }
4943 
4944 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4945     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4946     const SmallVectorImpl<ISD::OutputArg> &Outs,
4947     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4948   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4949 
4950   if (DisableSCO && !TailCallOpt) return false;
4951 
4952   // Variadic argument functions are not supported.
4953   if (isVarArg) return false;
4954 
4955   auto &Caller = DAG.getMachineFunction().getFunction();
4956   // Check that the calling conventions are compatible for tco.
4957   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4958     return false;
4959 
4960   // Caller contains any byval parameter is not supported.
4961   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4962     return false;
4963 
4964   // Callee contains any byval parameter is not supported, too.
4965   // Note: This is a quick work around, because in some cases, e.g.
4966   // caller's stack size > callee's stack size, we are still able to apply
4967   // sibling call optimization. For example, gcc is able to do SCO for caller1
4968   // in the following example, but not for caller2.
4969   //   struct test {
4970   //     long int a;
4971   //     char ary[56];
4972   //   } gTest;
4973   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4974   //     b->a = v.a;
4975   //     return 0;
4976   //   }
4977   //   void caller1(struct test a, struct test c, struct test *b) {
4978   //     callee(gTest, b); }
4979   //   void caller2(struct test *b) { callee(gTest, b); }
4980   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4981     return false;
4982 
4983   // If callee and caller use different calling conventions, we cannot pass
4984   // parameters on stack since offsets for the parameter area may be different.
4985   if (Caller.getCallingConv() != CalleeCC &&
4986       needStackSlotPassParameters(Subtarget, Outs))
4987     return false;
4988 
4989   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4990   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4991   // callee potentially have different TOC bases then we cannot tail call since
4992   // we need to restore the TOC pointer after the call.
4993   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4994   // We cannot guarantee this for indirect calls or calls to external functions.
4995   // When PC-Relative addressing is used, the concept of the TOC is no longer
4996   // applicable so this check is not required.
4997   // Check first for indirect calls.
4998   if (!Subtarget.isUsingPCRelativeCalls() &&
4999       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
5000     return false;
5001 
5002   // Check if we share the TOC base.
5003   if (!Subtarget.isUsingPCRelativeCalls() &&
5004       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
5005     return false;
5006 
5007   // TCO allows altering callee ABI, so we don't have to check further.
5008   if (CalleeCC == CallingConv::Fast && TailCallOpt)
5009     return true;
5010 
5011   if (DisableSCO) return false;
5012 
5013   // If callee use the same argument list that caller is using, then we can
5014   // apply SCO on this case. If it is not, then we need to check if callee needs
5015   // stack for passing arguments.
5016   // PC Relative tail calls may not have a CallBase.
5017   // If there is no CallBase we cannot verify if we have the same argument
5018   // list so assume that we don't have the same argument list.
5019   if (CB && !hasSameArgumentList(&Caller, *CB) &&
5020       needStackSlotPassParameters(Subtarget, Outs))
5021     return false;
5022   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
5023     return false;
5024 
5025   return true;
5026 }
5027 
5028 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
5029 /// for tail call optimization. Targets which want to do tail call
5030 /// optimization should implement this function.
5031 bool
5032 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
5033                                                      CallingConv::ID CalleeCC,
5034                                                      bool isVarArg,
5035                                       const SmallVectorImpl<ISD::InputArg> &Ins,
5036                                                      SelectionDAG& DAG) const {
5037   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5038     return false;
5039 
5040   // Variable argument functions are not supported.
5041   if (isVarArg)
5042     return false;
5043 
5044   MachineFunction &MF = DAG.getMachineFunction();
5045   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
5046   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
5047     // Functions containing by val parameters are not supported.
5048     for (unsigned i = 0; i != Ins.size(); i++) {
5049        ISD::ArgFlagsTy Flags = Ins[i].Flags;
5050        if (Flags.isByVal()) return false;
5051     }
5052 
5053     // Non-PIC/GOT tail calls are supported.
5054     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
5055       return true;
5056 
5057     // At the moment we can only do local tail calls (in same module, hidden
5058     // or protected) if we are generating PIC.
5059     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
5060       return G->getGlobal()->hasHiddenVisibility()
5061           || G->getGlobal()->hasProtectedVisibility();
5062   }
5063 
5064   return false;
5065 }
5066 
5067 /// isCallCompatibleAddress - Return the immediate to use if the specified
5068 /// 32-bit value is representable in the immediate field of a BxA instruction.
5069 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
5070   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5071   if (!C) return nullptr;
5072 
5073   int Addr = C->getZExtValue();
5074   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
5075       SignExtend32<26>(Addr) != Addr)
5076     return nullptr;  // Top 6 bits have to be sext of immediate.
5077 
5078   return DAG
5079       .getConstant(
5080           (int)C->getZExtValue() >> 2, SDLoc(Op),
5081           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
5082       .getNode();
5083 }
5084 
5085 namespace {
5086 
5087 struct TailCallArgumentInfo {
5088   SDValue Arg;
5089   SDValue FrameIdxOp;
5090   int FrameIdx = 0;
5091 
5092   TailCallArgumentInfo() = default;
5093 };
5094 
5095 } // end anonymous namespace
5096 
5097 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
5098 static void StoreTailCallArgumentsToStackSlot(
5099     SelectionDAG &DAG, SDValue Chain,
5100     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
5101     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
5102   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
5103     SDValue Arg = TailCallArgs[i].Arg;
5104     SDValue FIN = TailCallArgs[i].FrameIdxOp;
5105     int FI = TailCallArgs[i].FrameIdx;
5106     // Store relative to framepointer.
5107     MemOpChains.push_back(DAG.getStore(
5108         Chain, dl, Arg, FIN,
5109         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
5110   }
5111 }
5112 
5113 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
5114 /// the appropriate stack slot for the tail call optimized function call.
5115 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
5116                                              SDValue OldRetAddr, SDValue OldFP,
5117                                              int SPDiff, const SDLoc &dl) {
5118   if (SPDiff) {
5119     // Calculate the new stack slot for the return address.
5120     MachineFunction &MF = DAG.getMachineFunction();
5121     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
5122     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
5123     bool isPPC64 = Subtarget.isPPC64();
5124     int SlotSize = isPPC64 ? 8 : 4;
5125     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
5126     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
5127                                                          NewRetAddrLoc, true);
5128     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5129     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
5130     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
5131                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
5132   }
5133   return Chain;
5134 }
5135 
5136 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5137 /// the position of the argument.
5138 static void
5139 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
5140                          SDValue Arg, int SPDiff, unsigned ArgOffset,
5141                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
5142   int Offset = ArgOffset + SPDiff;
5143   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5144   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5145   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5146   SDValue FIN = DAG.getFrameIndex(FI, VT);
5147   TailCallArgumentInfo Info;
5148   Info.Arg = Arg;
5149   Info.FrameIdxOp = FIN;
5150   Info.FrameIdx = FI;
5151   TailCallArguments.push_back(Info);
5152 }
5153 
5154 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5155 /// stack slot. Returns the chain as result and the loaded frame pointers in
5156 /// LROpOut/FPOpout. Used when tail calling.
5157 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5158     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5159     SDValue &FPOpOut, const SDLoc &dl) const {
5160   if (SPDiff) {
5161     // Load the LR and FP stack slot for later adjusting.
5162     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5163     LROpOut = getReturnAddrFrameIndex(DAG);
5164     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5165     Chain = SDValue(LROpOut.getNode(), 1);
5166   }
5167   return Chain;
5168 }
5169 
5170 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5171 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5172 /// specified by the specific parameter attribute. The copy will be passed as
5173 /// a byval function parameter.
5174 /// Sometimes what we are copying is the end of a larger object, the part that
5175 /// does not fit in registers.
5176 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5177                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5178                                          SelectionDAG &DAG, const SDLoc &dl) {
5179   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5180   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5181                        Flags.getNonZeroByValAlign(), false, false, false,
5182                        MachinePointerInfo(), MachinePointerInfo());
5183 }
5184 
5185 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5186 /// tail calls.
5187 static void LowerMemOpCallTo(
5188     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5189     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5190     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5191     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5192   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5193   if (!isTailCall) {
5194     if (isVector) {
5195       SDValue StackPtr;
5196       if (isPPC64)
5197         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5198       else
5199         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5200       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5201                            DAG.getConstant(ArgOffset, dl, PtrVT));
5202     }
5203     MemOpChains.push_back(
5204         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5205     // Calculate and remember argument location.
5206   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5207                                   TailCallArguments);
5208 }
5209 
5210 static void
5211 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5212                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5213                 SDValue FPOp,
5214                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5215   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5216   // might overwrite each other in case of tail call optimization.
5217   SmallVector<SDValue, 8> MemOpChains2;
5218   // Do not flag preceding copytoreg stuff together with the following stuff.
5219   InFlag = SDValue();
5220   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5221                                     MemOpChains2, dl);
5222   if (!MemOpChains2.empty())
5223     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5224 
5225   // Store the return address to the appropriate stack slot.
5226   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5227 
5228   // Emit callseq_end just before tailcall node.
5229   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5230                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5231   InFlag = Chain.getValue(1);
5232 }
5233 
5234 // Is this global address that of a function that can be called by name? (as
5235 // opposed to something that must hold a descriptor for an indirect call).
5236 static bool isFunctionGlobalAddress(SDValue Callee) {
5237   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5238     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5239         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5240       return false;
5241 
5242     return G->getGlobal()->getValueType()->isFunctionTy();
5243   }
5244 
5245   return false;
5246 }
5247 
5248 SDValue PPCTargetLowering::LowerCallResult(
5249     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5250     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5251     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5252   SmallVector<CCValAssign, 16> RVLocs;
5253   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5254                     *DAG.getContext());
5255 
5256   CCRetInfo.AnalyzeCallResult(
5257       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5258                ? RetCC_PPC_Cold
5259                : RetCC_PPC);
5260 
5261   // Copy all of the result registers out of their specified physreg.
5262   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5263     CCValAssign &VA = RVLocs[i];
5264     assert(VA.isRegLoc() && "Can only return in registers!");
5265 
5266     SDValue Val;
5267 
5268     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5269       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5270                                       InFlag);
5271       Chain = Lo.getValue(1);
5272       InFlag = Lo.getValue(2);
5273       VA = RVLocs[++i]; // skip ahead to next loc
5274       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5275                                       InFlag);
5276       Chain = Hi.getValue(1);
5277       InFlag = Hi.getValue(2);
5278       if (!Subtarget.isLittleEndian())
5279         std::swap (Lo, Hi);
5280       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5281     } else {
5282       Val = DAG.getCopyFromReg(Chain, dl,
5283                                VA.getLocReg(), VA.getLocVT(), InFlag);
5284       Chain = Val.getValue(1);
5285       InFlag = Val.getValue(2);
5286     }
5287 
5288     switch (VA.getLocInfo()) {
5289     default: llvm_unreachable("Unknown loc info!");
5290     case CCValAssign::Full: break;
5291     case CCValAssign::AExt:
5292       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5293       break;
5294     case CCValAssign::ZExt:
5295       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5296                         DAG.getValueType(VA.getValVT()));
5297       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5298       break;
5299     case CCValAssign::SExt:
5300       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5301                         DAG.getValueType(VA.getValVT()));
5302       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5303       break;
5304     }
5305 
5306     InVals.push_back(Val);
5307   }
5308 
5309   return Chain;
5310 }
5311 
5312 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5313                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5314   // PatchPoint calls are not indirect.
5315   if (isPatchPoint)
5316     return false;
5317 
5318   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5319     return false;
5320 
5321   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5322   // becuase the immediate function pointer points to a descriptor instead of
5323   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5324   // pointer immediate points to the global entry point, while the BLA would
5325   // need to jump to the local entry point (see rL211174).
5326   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5327       isBLACompatibleAddress(Callee, DAG))
5328     return false;
5329 
5330   return true;
5331 }
5332 
5333 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5334 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5335   return Subtarget.isAIXABI() ||
5336          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5337 }
5338 
5339 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5340                               const Function &Caller,
5341                               const SDValue &Callee,
5342                               const PPCSubtarget &Subtarget,
5343                               const TargetMachine &TM) {
5344   if (CFlags.IsTailCall)
5345     return PPCISD::TC_RETURN;
5346 
5347   // This is a call through a function pointer.
5348   if (CFlags.IsIndirect) {
5349     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5350     // indirect calls. The save of the caller's TOC pointer to the stack will be
5351     // inserted into the DAG as part of call lowering. The restore of the TOC
5352     // pointer is modeled by using a pseudo instruction for the call opcode that
5353     // represents the 2 instruction sequence of an indirect branch and link,
5354     // immediately followed by a load of the TOC pointer from the the stack save
5355     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5356     // as it is not saved or used.
5357     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5358                                                : PPCISD::BCTRL;
5359   }
5360 
5361   if (Subtarget.isUsingPCRelativeCalls()) {
5362     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5363     return PPCISD::CALL_NOTOC;
5364   }
5365 
5366   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5367   // immediately following the call instruction if the caller and callee may
5368   // have different TOC bases. At link time if the linker determines the calls
5369   // may not share a TOC base, the call is redirected to a trampoline inserted
5370   // by the linker. The trampoline will (among other things) save the callers
5371   // TOC pointer at an ABI designated offset in the linkage area and the linker
5372   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5373   // into gpr2.
5374   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5375     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5376                                                   : PPCISD::CALL_NOP;
5377 
5378   return PPCISD::CALL;
5379 }
5380 
5381 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5382                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5383   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5384     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5385       return SDValue(Dest, 0);
5386 
5387   // Returns true if the callee is local, and false otherwise.
5388   auto isLocalCallee = [&]() {
5389     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5390     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5391     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5392 
5393     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5394            !dyn_cast_or_null<GlobalIFunc>(GV);
5395   };
5396 
5397   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5398   // a static relocation model causes some versions of GNU LD (2.17.50, at
5399   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5400   // built with secure-PLT.
5401   bool UsePlt =
5402       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5403       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5404 
5405   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5406     const TargetMachine &TM = Subtarget.getTargetMachine();
5407     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5408     MCSymbolXCOFF *S =
5409         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5410 
5411     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5412     return DAG.getMCSymbol(S, PtrVT);
5413   };
5414 
5415   if (isFunctionGlobalAddress(Callee)) {
5416     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5417 
5418     if (Subtarget.isAIXABI()) {
5419       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5420       return getAIXFuncEntryPointSymbolSDNode(GV);
5421     }
5422     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5423                                       UsePlt ? PPCII::MO_PLT : 0);
5424   }
5425 
5426   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5427     const char *SymName = S->getSymbol();
5428     if (Subtarget.isAIXABI()) {
5429       // If there exists a user-declared function whose name is the same as the
5430       // ExternalSymbol's, then we pick up the user-declared version.
5431       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5432       if (const Function *F =
5433               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5434         return getAIXFuncEntryPointSymbolSDNode(F);
5435 
5436       // On AIX, direct function calls reference the symbol for the function's
5437       // entry point, which is named by prepending a "." before the function's
5438       // C-linkage name. A Qualname is returned here because an external
5439       // function entry point is a csect with XTY_ER property.
5440       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5441         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5442         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5443             (Twine(".") + Twine(SymName)).str(), XCOFF::XMC_PR, XCOFF::XTY_ER,
5444             SectionKind::getMetadata());
5445         return Sec->getQualNameSymbol();
5446       };
5447 
5448       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5449     }
5450     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5451                                        UsePlt ? PPCII::MO_PLT : 0);
5452   }
5453 
5454   // No transformation needed.
5455   assert(Callee.getNode() && "What no callee?");
5456   return Callee;
5457 }
5458 
5459 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5460   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5461          "Expected a CALLSEQ_STARTSDNode.");
5462 
5463   // The last operand is the chain, except when the node has glue. If the node
5464   // has glue, then the last operand is the glue, and the chain is the second
5465   // last operand.
5466   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5467   if (LastValue.getValueType() != MVT::Glue)
5468     return LastValue;
5469 
5470   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5471 }
5472 
5473 // Creates the node that moves a functions address into the count register
5474 // to prepare for an indirect call instruction.
5475 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5476                                 SDValue &Glue, SDValue &Chain,
5477                                 const SDLoc &dl) {
5478   SDValue MTCTROps[] = {Chain, Callee, Glue};
5479   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5480   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5481                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5482   // The glue is the second value produced.
5483   Glue = Chain.getValue(1);
5484 }
5485 
5486 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5487                                           SDValue &Glue, SDValue &Chain,
5488                                           SDValue CallSeqStart,
5489                                           const CallBase *CB, const SDLoc &dl,
5490                                           bool hasNest,
5491                                           const PPCSubtarget &Subtarget) {
5492   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5493   // entry point, but to the function descriptor (the function entry point
5494   // address is part of the function descriptor though).
5495   // The function descriptor is a three doubleword structure with the
5496   // following fields: function entry point, TOC base address and
5497   // environment pointer.
5498   // Thus for a call through a function pointer, the following actions need
5499   // to be performed:
5500   //   1. Save the TOC of the caller in the TOC save area of its stack
5501   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5502   //   2. Load the address of the function entry point from the function
5503   //      descriptor.
5504   //   3. Load the TOC of the callee from the function descriptor into r2.
5505   //   4. Load the environment pointer from the function descriptor into
5506   //      r11.
5507   //   5. Branch to the function entry point address.
5508   //   6. On return of the callee, the TOC of the caller needs to be
5509   //      restored (this is done in FinishCall()).
5510   //
5511   // The loads are scheduled at the beginning of the call sequence, and the
5512   // register copies are flagged together to ensure that no other
5513   // operations can be scheduled in between. E.g. without flagging the
5514   // copies together, a TOC access in the caller could be scheduled between
5515   // the assignment of the callee TOC and the branch to the callee, which leads
5516   // to incorrect code.
5517 
5518   // Start by loading the function address from the descriptor.
5519   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5520   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5521                       ? (MachineMemOperand::MODereferenceable |
5522                          MachineMemOperand::MOInvariant)
5523                       : MachineMemOperand::MONone;
5524 
5525   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5526 
5527   // Registers used in building the DAG.
5528   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5529   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5530 
5531   // Offsets of descriptor members.
5532   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5533   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5534 
5535   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5536   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5537 
5538   // One load for the functions entry point address.
5539   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5540                                     Alignment, MMOFlags);
5541 
5542   // One for loading the TOC anchor for the module that contains the called
5543   // function.
5544   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5545   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5546   SDValue TOCPtr =
5547       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5548                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5549 
5550   // One for loading the environment pointer.
5551   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5552   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5553   SDValue LoadEnvPtr =
5554       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5555                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5556 
5557 
5558   // Then copy the newly loaded TOC anchor to the TOC pointer.
5559   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5560   Chain = TOCVal.getValue(0);
5561   Glue = TOCVal.getValue(1);
5562 
5563   // If the function call has an explicit 'nest' parameter, it takes the
5564   // place of the environment pointer.
5565   assert((!hasNest || !Subtarget.isAIXABI()) &&
5566          "Nest parameter is not supported on AIX.");
5567   if (!hasNest) {
5568     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5569     Chain = EnvVal.getValue(0);
5570     Glue = EnvVal.getValue(1);
5571   }
5572 
5573   // The rest of the indirect call sequence is the same as the non-descriptor
5574   // DAG.
5575   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5576 }
5577 
5578 static void
5579 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5580                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5581                   SelectionDAG &DAG,
5582                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5583                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5584                   const PPCSubtarget &Subtarget) {
5585   const bool IsPPC64 = Subtarget.isPPC64();
5586   // MVT for a general purpose register.
5587   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5588 
5589   // First operand is always the chain.
5590   Ops.push_back(Chain);
5591 
5592   // If it's a direct call pass the callee as the second operand.
5593   if (!CFlags.IsIndirect)
5594     Ops.push_back(Callee);
5595   else {
5596     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5597 
5598     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5599     // on the stack (this would have been done in `LowerCall_64SVR4` or
5600     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5601     // represents both the indirect branch and a load that restores the TOC
5602     // pointer from the linkage area. The operand for the TOC restore is an add
5603     // of the TOC save offset to the stack pointer. This must be the second
5604     // operand: after the chain input but before any other variadic arguments.
5605     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5606     // saved or used.
5607     if (isTOCSaveRestoreRequired(Subtarget)) {
5608       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5609 
5610       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5611       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5612       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5613       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5614       Ops.push_back(AddTOC);
5615     }
5616 
5617     // Add the register used for the environment pointer.
5618     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5619       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5620                                     RegVT));
5621 
5622 
5623     // Add CTR register as callee so a bctr can be emitted later.
5624     if (CFlags.IsTailCall)
5625       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5626   }
5627 
5628   // If this is a tail call add stack pointer delta.
5629   if (CFlags.IsTailCall)
5630     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5631 
5632   // Add argument registers to the end of the list so that they are known live
5633   // into the call.
5634   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5635     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5636                                   RegsToPass[i].second.getValueType()));
5637 
5638   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5639   // no way to mark dependencies as implicit here.
5640   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5641   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5642        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5643     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5644 
5645   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5646   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5647     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5648 
5649   // Add a register mask operand representing the call-preserved registers.
5650   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5651   const uint32_t *Mask =
5652       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5653   assert(Mask && "Missing call preserved mask for calling convention");
5654   Ops.push_back(DAG.getRegisterMask(Mask));
5655 
5656   // If the glue is valid, it is the last operand.
5657   if (Glue.getNode())
5658     Ops.push_back(Glue);
5659 }
5660 
5661 SDValue PPCTargetLowering::FinishCall(
5662     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5663     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5664     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5665     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5666     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5667 
5668   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5669       Subtarget.isAIXABI())
5670     setUsesTOCBasePtr(DAG);
5671 
5672   unsigned CallOpc =
5673       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5674                     Subtarget, DAG.getTarget());
5675 
5676   if (!CFlags.IsIndirect)
5677     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5678   else if (Subtarget.usesFunctionDescriptors())
5679     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5680                                   dl, CFlags.HasNest, Subtarget);
5681   else
5682     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5683 
5684   // Build the operand list for the call instruction.
5685   SmallVector<SDValue, 8> Ops;
5686   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5687                     SPDiff, Subtarget);
5688 
5689   // Emit tail call.
5690   if (CFlags.IsTailCall) {
5691     // Indirect tail call when using PC Relative calls do not have the same
5692     // constraints.
5693     assert(((Callee.getOpcode() == ISD::Register &&
5694              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5695             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5696             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5697             isa<ConstantSDNode>(Callee) ||
5698             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5699            "Expecting a global address, external symbol, absolute value, "
5700            "register or an indirect tail call when PC Relative calls are "
5701            "used.");
5702     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5703     assert(CallOpc == PPCISD::TC_RETURN &&
5704            "Unexpected call opcode for a tail call.");
5705     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5706     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5707   }
5708 
5709   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5710   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5711   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5712   Glue = Chain.getValue(1);
5713 
5714   // When performing tail call optimization the callee pops its arguments off
5715   // the stack. Account for this here so these bytes can be pushed back on in
5716   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5717   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5718                          getTargetMachine().Options.GuaranteedTailCallOpt)
5719                             ? NumBytes
5720                             : 0;
5721 
5722   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5723                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5724                              Glue, dl);
5725   Glue = Chain.getValue(1);
5726 
5727   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5728                          DAG, InVals);
5729 }
5730 
5731 SDValue
5732 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5733                              SmallVectorImpl<SDValue> &InVals) const {
5734   SelectionDAG &DAG                     = CLI.DAG;
5735   SDLoc &dl                             = CLI.DL;
5736   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5737   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5738   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5739   SDValue Chain                         = CLI.Chain;
5740   SDValue Callee                        = CLI.Callee;
5741   bool &isTailCall                      = CLI.IsTailCall;
5742   CallingConv::ID CallConv              = CLI.CallConv;
5743   bool isVarArg                         = CLI.IsVarArg;
5744   bool isPatchPoint                     = CLI.IsPatchPoint;
5745   const CallBase *CB                    = CLI.CB;
5746 
5747   if (isTailCall) {
5748     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5749       isTailCall = false;
5750     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5751       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5752           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5753     else
5754       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5755                                                      Ins, DAG);
5756     if (isTailCall) {
5757       ++NumTailCalls;
5758       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5759         ++NumSiblingCalls;
5760 
5761       // PC Relative calls no longer guarantee that the callee is a Global
5762       // Address Node. The callee could be an indirect tail call in which
5763       // case the SDValue for the callee could be a load (to load the address
5764       // of a function pointer) or it may be a register copy (to move the
5765       // address of the callee from a function parameter into a virtual
5766       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5767       assert((Subtarget.isUsingPCRelativeCalls() ||
5768               isa<GlobalAddressSDNode>(Callee)) &&
5769              "Callee should be an llvm::Function object.");
5770 
5771       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5772                         << "\nTCO callee: ");
5773       LLVM_DEBUG(Callee.dump());
5774     }
5775   }
5776 
5777   if (!isTailCall && CB && CB->isMustTailCall())
5778     report_fatal_error("failed to perform tail call elimination on a call "
5779                        "site marked musttail");
5780 
5781   // When long calls (i.e. indirect calls) are always used, calls are always
5782   // made via function pointer. If we have a function name, first translate it
5783   // into a pointer.
5784   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5785       !isTailCall)
5786     Callee = LowerGlobalAddress(Callee, DAG);
5787 
5788   CallFlags CFlags(
5789       CallConv, isTailCall, isVarArg, isPatchPoint,
5790       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5791       // hasNest
5792       Subtarget.is64BitELFABI() &&
5793           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5794       CLI.NoMerge);
5795 
5796   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5797     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5798                             InVals, CB);
5799 
5800   if (Subtarget.isSVR4ABI())
5801     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5802                             InVals, CB);
5803 
5804   if (Subtarget.isAIXABI())
5805     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5806                          InVals, CB);
5807 
5808   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5809                           InVals, CB);
5810 }
5811 
5812 SDValue PPCTargetLowering::LowerCall_32SVR4(
5813     SDValue Chain, SDValue Callee, CallFlags CFlags,
5814     const SmallVectorImpl<ISD::OutputArg> &Outs,
5815     const SmallVectorImpl<SDValue> &OutVals,
5816     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5817     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5818     const CallBase *CB) const {
5819   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5820   // of the 32-bit SVR4 ABI stack frame layout.
5821 
5822   const CallingConv::ID CallConv = CFlags.CallConv;
5823   const bool IsVarArg = CFlags.IsVarArg;
5824   const bool IsTailCall = CFlags.IsTailCall;
5825 
5826   assert((CallConv == CallingConv::C ||
5827           CallConv == CallingConv::Cold ||
5828           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5829 
5830   const Align PtrAlign(4);
5831 
5832   MachineFunction &MF = DAG.getMachineFunction();
5833 
5834   // Mark this function as potentially containing a function that contains a
5835   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5836   // and restoring the callers stack pointer in this functions epilog. This is
5837   // done because by tail calling the called function might overwrite the value
5838   // in this function's (MF) stack pointer stack slot 0(SP).
5839   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5840       CallConv == CallingConv::Fast)
5841     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5842 
5843   // Count how many bytes are to be pushed on the stack, including the linkage
5844   // area, parameter list area and the part of the local variable space which
5845   // contains copies of aggregates which are passed by value.
5846 
5847   // Assign locations to all of the outgoing arguments.
5848   SmallVector<CCValAssign, 16> ArgLocs;
5849   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5850 
5851   // Reserve space for the linkage area on the stack.
5852   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5853                        PtrAlign);
5854   if (useSoftFloat())
5855     CCInfo.PreAnalyzeCallOperands(Outs);
5856 
5857   if (IsVarArg) {
5858     // Handle fixed and variable vector arguments differently.
5859     // Fixed vector arguments go into registers as long as registers are
5860     // available. Variable vector arguments always go into memory.
5861     unsigned NumArgs = Outs.size();
5862 
5863     for (unsigned i = 0; i != NumArgs; ++i) {
5864       MVT ArgVT = Outs[i].VT;
5865       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5866       bool Result;
5867 
5868       if (Outs[i].IsFixed) {
5869         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5870                                CCInfo);
5871       } else {
5872         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5873                                       ArgFlags, CCInfo);
5874       }
5875 
5876       if (Result) {
5877 #ifndef NDEBUG
5878         errs() << "Call operand #" << i << " has unhandled type "
5879              << EVT(ArgVT).getEVTString() << "\n";
5880 #endif
5881         llvm_unreachable(nullptr);
5882       }
5883     }
5884   } else {
5885     // All arguments are treated the same.
5886     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5887   }
5888   CCInfo.clearWasPPCF128();
5889 
5890   // Assign locations to all of the outgoing aggregate by value arguments.
5891   SmallVector<CCValAssign, 16> ByValArgLocs;
5892   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5893 
5894   // Reserve stack space for the allocations in CCInfo.
5895   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5896 
5897   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5898 
5899   // Size of the linkage area, parameter list area and the part of the local
5900   // space variable where copies of aggregates which are passed by value are
5901   // stored.
5902   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5903 
5904   // Calculate by how many bytes the stack has to be adjusted in case of tail
5905   // call optimization.
5906   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5907 
5908   // Adjust the stack pointer for the new arguments...
5909   // These operations are automatically eliminated by the prolog/epilog pass
5910   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5911   SDValue CallSeqStart = Chain;
5912 
5913   // Load the return address and frame pointer so it can be moved somewhere else
5914   // later.
5915   SDValue LROp, FPOp;
5916   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5917 
5918   // Set up a copy of the stack pointer for use loading and storing any
5919   // arguments that may not fit in the registers available for argument
5920   // passing.
5921   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5922 
5923   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5924   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5925   SmallVector<SDValue, 8> MemOpChains;
5926 
5927   bool seenFloatArg = false;
5928   // Walk the register/memloc assignments, inserting copies/loads.
5929   // i - Tracks the index into the list of registers allocated for the call
5930   // RealArgIdx - Tracks the index into the list of actual function arguments
5931   // j - Tracks the index into the list of byval arguments
5932   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5933        i != e;
5934        ++i, ++RealArgIdx) {
5935     CCValAssign &VA = ArgLocs[i];
5936     SDValue Arg = OutVals[RealArgIdx];
5937     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5938 
5939     if (Flags.isByVal()) {
5940       // Argument is an aggregate which is passed by value, thus we need to
5941       // create a copy of it in the local variable space of the current stack
5942       // frame (which is the stack frame of the caller) and pass the address of
5943       // this copy to the callee.
5944       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5945       CCValAssign &ByValVA = ByValArgLocs[j++];
5946       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5947 
5948       // Memory reserved in the local variable space of the callers stack frame.
5949       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5950 
5951       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5952       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5953                            StackPtr, PtrOff);
5954 
5955       // Create a copy of the argument in the local area of the current
5956       // stack frame.
5957       SDValue MemcpyCall =
5958         CreateCopyOfByValArgument(Arg, PtrOff,
5959                                   CallSeqStart.getNode()->getOperand(0),
5960                                   Flags, DAG, dl);
5961 
5962       // This must go outside the CALLSEQ_START..END.
5963       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5964                                                      SDLoc(MemcpyCall));
5965       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5966                              NewCallSeqStart.getNode());
5967       Chain = CallSeqStart = NewCallSeqStart;
5968 
5969       // Pass the address of the aggregate copy on the stack either in a
5970       // physical register or in the parameter list area of the current stack
5971       // frame to the callee.
5972       Arg = PtrOff;
5973     }
5974 
5975     // When useCRBits() is true, there can be i1 arguments.
5976     // It is because getRegisterType(MVT::i1) => MVT::i1,
5977     // and for other integer types getRegisterType() => MVT::i32.
5978     // Extend i1 and ensure callee will get i32.
5979     if (Arg.getValueType() == MVT::i1)
5980       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5981                         dl, MVT::i32, Arg);
5982 
5983     if (VA.isRegLoc()) {
5984       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5985       // Put argument in a physical register.
5986       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5987         bool IsLE = Subtarget.isLittleEndian();
5988         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5989                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5990         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5991         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5992                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5993         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5994                              SVal.getValue(0)));
5995       } else
5996         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5997     } else {
5998       // Put argument in the parameter list area of the current stack frame.
5999       assert(VA.isMemLoc());
6000       unsigned LocMemOffset = VA.getLocMemOffset();
6001 
6002       if (!IsTailCall) {
6003         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
6004         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
6005                              StackPtr, PtrOff);
6006 
6007         MemOpChains.push_back(
6008             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
6009       } else {
6010         // Calculate and remember argument location.
6011         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
6012                                  TailCallArguments);
6013       }
6014     }
6015   }
6016 
6017   if (!MemOpChains.empty())
6018     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6019 
6020   // Build a sequence of copy-to-reg nodes chained together with token chain
6021   // and flag operands which copy the outgoing args into the appropriate regs.
6022   SDValue InFlag;
6023   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6024     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6025                              RegsToPass[i].second, InFlag);
6026     InFlag = Chain.getValue(1);
6027   }
6028 
6029   // Set CR bit 6 to true if this is a vararg call with floating args passed in
6030   // registers.
6031   if (IsVarArg) {
6032     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
6033     SDValue Ops[] = { Chain, InFlag };
6034 
6035     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
6036                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
6037 
6038     InFlag = Chain.getValue(1);
6039   }
6040 
6041   if (IsTailCall)
6042     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6043                     TailCallArguments);
6044 
6045   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6046                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6047 }
6048 
6049 // Copy an argument into memory, being careful to do this outside the
6050 // call sequence for the call to which the argument belongs.
6051 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
6052     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
6053     SelectionDAG &DAG, const SDLoc &dl) const {
6054   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
6055                         CallSeqStart.getNode()->getOperand(0),
6056                         Flags, DAG, dl);
6057   // The MEMCPY must go outside the CALLSEQ_START..END.
6058   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
6059   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
6060                                                  SDLoc(MemcpyCall));
6061   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
6062                          NewCallSeqStart.getNode());
6063   return NewCallSeqStart;
6064 }
6065 
6066 SDValue PPCTargetLowering::LowerCall_64SVR4(
6067     SDValue Chain, SDValue Callee, CallFlags CFlags,
6068     const SmallVectorImpl<ISD::OutputArg> &Outs,
6069     const SmallVectorImpl<SDValue> &OutVals,
6070     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6071     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6072     const CallBase *CB) const {
6073   bool isELFv2ABI = Subtarget.isELFv2ABI();
6074   bool isLittleEndian = Subtarget.isLittleEndian();
6075   unsigned NumOps = Outs.size();
6076   bool IsSibCall = false;
6077   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
6078 
6079   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6080   unsigned PtrByteSize = 8;
6081 
6082   MachineFunction &MF = DAG.getMachineFunction();
6083 
6084   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
6085     IsSibCall = true;
6086 
6087   // Mark this function as potentially containing a function that contains a
6088   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6089   // and restoring the callers stack pointer in this functions epilog. This is
6090   // done because by tail calling the called function might overwrite the value
6091   // in this function's (MF) stack pointer stack slot 0(SP).
6092   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6093     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6094 
6095   assert(!(IsFastCall && CFlags.IsVarArg) &&
6096          "fastcc not supported on varargs functions");
6097 
6098   // Count how many bytes are to be pushed on the stack, including the linkage
6099   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
6100   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
6101   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
6102   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6103   unsigned NumBytes = LinkageSize;
6104   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6105 
6106   static const MCPhysReg GPR[] = {
6107     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6108     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6109   };
6110   static const MCPhysReg VR[] = {
6111     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6112     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6113   };
6114 
6115   const unsigned NumGPRs = array_lengthof(GPR);
6116   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
6117   const unsigned NumVRs  = array_lengthof(VR);
6118 
6119   // On ELFv2, we can avoid allocating the parameter area if all the arguments
6120   // can be passed to the callee in registers.
6121   // For the fast calling convention, there is another check below.
6122   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6123   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6124   if (!HasParameterArea) {
6125     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6126     unsigned AvailableFPRs = NumFPRs;
6127     unsigned AvailableVRs = NumVRs;
6128     unsigned NumBytesTmp = NumBytes;
6129     for (unsigned i = 0; i != NumOps; ++i) {
6130       if (Outs[i].Flags.isNest()) continue;
6131       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6132                                  PtrByteSize, LinkageSize, ParamAreaSize,
6133                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
6134         HasParameterArea = true;
6135     }
6136   }
6137 
6138   // When using the fast calling convention, we don't provide backing for
6139   // arguments that will be in registers.
6140   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6141 
6142   // Avoid allocating parameter area for fastcc functions if all the arguments
6143   // can be passed in the registers.
6144   if (IsFastCall)
6145     HasParameterArea = false;
6146 
6147   // Add up all the space actually used.
6148   for (unsigned i = 0; i != NumOps; ++i) {
6149     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6150     EVT ArgVT = Outs[i].VT;
6151     EVT OrigVT = Outs[i].ArgVT;
6152 
6153     if (Flags.isNest())
6154       continue;
6155 
6156     if (IsFastCall) {
6157       if (Flags.isByVal()) {
6158         NumGPRsUsed += (Flags.getByValSize()+7)/8;
6159         if (NumGPRsUsed > NumGPRs)
6160           HasParameterArea = true;
6161       } else {
6162         switch (ArgVT.getSimpleVT().SimpleTy) {
6163         default: llvm_unreachable("Unexpected ValueType for argument!");
6164         case MVT::i1:
6165         case MVT::i32:
6166         case MVT::i64:
6167           if (++NumGPRsUsed <= NumGPRs)
6168             continue;
6169           break;
6170         case MVT::v4i32:
6171         case MVT::v8i16:
6172         case MVT::v16i8:
6173         case MVT::v2f64:
6174         case MVT::v2i64:
6175         case MVT::v1i128:
6176         case MVT::f128:
6177           if (++NumVRsUsed <= NumVRs)
6178             continue;
6179           break;
6180         case MVT::v4f32:
6181           if (++NumVRsUsed <= NumVRs)
6182             continue;
6183           break;
6184         case MVT::f32:
6185         case MVT::f64:
6186           if (++NumFPRsUsed <= NumFPRs)
6187             continue;
6188           break;
6189         }
6190         HasParameterArea = true;
6191       }
6192     }
6193 
6194     /* Respect alignment of argument on the stack.  */
6195     auto Alignement =
6196         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6197     NumBytes = alignTo(NumBytes, Alignement);
6198 
6199     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6200     if (Flags.isInConsecutiveRegsLast())
6201       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6202   }
6203 
6204   unsigned NumBytesActuallyUsed = NumBytes;
6205 
6206   // In the old ELFv1 ABI,
6207   // the prolog code of the callee may store up to 8 GPR argument registers to
6208   // the stack, allowing va_start to index over them in memory if its varargs.
6209   // Because we cannot tell if this is needed on the caller side, we have to
6210   // conservatively assume that it is needed.  As such, make sure we have at
6211   // least enough stack space for the caller to store the 8 GPRs.
6212   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6213   // really requires memory operands, e.g. a vararg function.
6214   if (HasParameterArea)
6215     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6216   else
6217     NumBytes = LinkageSize;
6218 
6219   // Tail call needs the stack to be aligned.
6220   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6221     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6222 
6223   int SPDiff = 0;
6224 
6225   // Calculate by how many bytes the stack has to be adjusted in case of tail
6226   // call optimization.
6227   if (!IsSibCall)
6228     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6229 
6230   // To protect arguments on the stack from being clobbered in a tail call,
6231   // force all the loads to happen before doing any other lowering.
6232   if (CFlags.IsTailCall)
6233     Chain = DAG.getStackArgumentTokenFactor(Chain);
6234 
6235   // Adjust the stack pointer for the new arguments...
6236   // These operations are automatically eliminated by the prolog/epilog pass
6237   if (!IsSibCall)
6238     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6239   SDValue CallSeqStart = Chain;
6240 
6241   // Load the return address and frame pointer so it can be move somewhere else
6242   // later.
6243   SDValue LROp, FPOp;
6244   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6245 
6246   // Set up a copy of the stack pointer for use loading and storing any
6247   // arguments that may not fit in the registers available for argument
6248   // passing.
6249   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6250 
6251   // Figure out which arguments are going to go in registers, and which in
6252   // memory.  Also, if this is a vararg function, floating point operations
6253   // must be stored to our stack, and loaded into integer regs as well, if
6254   // any integer regs are available for argument passing.
6255   unsigned ArgOffset = LinkageSize;
6256 
6257   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6258   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6259 
6260   SmallVector<SDValue, 8> MemOpChains;
6261   for (unsigned i = 0; i != NumOps; ++i) {
6262     SDValue Arg = OutVals[i];
6263     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6264     EVT ArgVT = Outs[i].VT;
6265     EVT OrigVT = Outs[i].ArgVT;
6266 
6267     // PtrOff will be used to store the current argument to the stack if a
6268     // register cannot be found for it.
6269     SDValue PtrOff;
6270 
6271     // We re-align the argument offset for each argument, except when using the
6272     // fast calling convention, when we need to make sure we do that only when
6273     // we'll actually use a stack slot.
6274     auto ComputePtrOff = [&]() {
6275       /* Respect alignment of argument on the stack.  */
6276       auto Alignment =
6277           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6278       ArgOffset = alignTo(ArgOffset, Alignment);
6279 
6280       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6281 
6282       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6283     };
6284 
6285     if (!IsFastCall) {
6286       ComputePtrOff();
6287 
6288       /* Compute GPR index associated with argument offset.  */
6289       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6290       GPR_idx = std::min(GPR_idx, NumGPRs);
6291     }
6292 
6293     // Promote integers to 64-bit values.
6294     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6295       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6296       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6297       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6298     }
6299 
6300     // FIXME memcpy is used way more than necessary.  Correctness first.
6301     // Note: "by value" is code for passing a structure by value, not
6302     // basic types.
6303     if (Flags.isByVal()) {
6304       // Note: Size includes alignment padding, so
6305       //   struct x { short a; char b; }
6306       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6307       // These are the proper values we need for right-justifying the
6308       // aggregate in a parameter register.
6309       unsigned Size = Flags.getByValSize();
6310 
6311       // An empty aggregate parameter takes up no storage and no
6312       // registers.
6313       if (Size == 0)
6314         continue;
6315 
6316       if (IsFastCall)
6317         ComputePtrOff();
6318 
6319       // All aggregates smaller than 8 bytes must be passed right-justified.
6320       if (Size==1 || Size==2 || Size==4) {
6321         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6322         if (GPR_idx != NumGPRs) {
6323           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6324                                         MachinePointerInfo(), VT);
6325           MemOpChains.push_back(Load.getValue(1));
6326           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6327 
6328           ArgOffset += PtrByteSize;
6329           continue;
6330         }
6331       }
6332 
6333       if (GPR_idx == NumGPRs && Size < 8) {
6334         SDValue AddPtr = PtrOff;
6335         if (!isLittleEndian) {
6336           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6337                                           PtrOff.getValueType());
6338           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6339         }
6340         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6341                                                           CallSeqStart,
6342                                                           Flags, DAG, dl);
6343         ArgOffset += PtrByteSize;
6344         continue;
6345       }
6346       // Copy entire object into memory.  There are cases where gcc-generated
6347       // code assumes it is there, even if it could be put entirely into
6348       // registers.  (This is not what the doc says.)
6349 
6350       // FIXME: The above statement is likely due to a misunderstanding of the
6351       // documents.  All arguments must be copied into the parameter area BY
6352       // THE CALLEE in the event that the callee takes the address of any
6353       // formal argument.  That has not yet been implemented.  However, it is
6354       // reasonable to use the stack area as a staging area for the register
6355       // load.
6356 
6357       // Skip this for small aggregates, as we will use the same slot for a
6358       // right-justified copy, below.
6359       if (Size >= 8)
6360         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6361                                                           CallSeqStart,
6362                                                           Flags, DAG, dl);
6363 
6364       // When a register is available, pass a small aggregate right-justified.
6365       if (Size < 8 && GPR_idx != NumGPRs) {
6366         // The easiest way to get this right-justified in a register
6367         // is to copy the structure into the rightmost portion of a
6368         // local variable slot, then load the whole slot into the
6369         // register.
6370         // FIXME: The memcpy seems to produce pretty awful code for
6371         // small aggregates, particularly for packed ones.
6372         // FIXME: It would be preferable to use the slot in the
6373         // parameter save area instead of a new local variable.
6374         SDValue AddPtr = PtrOff;
6375         if (!isLittleEndian) {
6376           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6377           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6378         }
6379         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6380                                                           CallSeqStart,
6381                                                           Flags, DAG, dl);
6382 
6383         // Load the slot into the register.
6384         SDValue Load =
6385             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6386         MemOpChains.push_back(Load.getValue(1));
6387         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6388 
6389         // Done with this argument.
6390         ArgOffset += PtrByteSize;
6391         continue;
6392       }
6393 
6394       // For aggregates larger than PtrByteSize, copy the pieces of the
6395       // object that fit into registers from the parameter save area.
6396       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6397         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6398         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6399         if (GPR_idx != NumGPRs) {
6400           SDValue Load =
6401               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6402           MemOpChains.push_back(Load.getValue(1));
6403           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6404           ArgOffset += PtrByteSize;
6405         } else {
6406           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6407           break;
6408         }
6409       }
6410       continue;
6411     }
6412 
6413     switch (Arg.getSimpleValueType().SimpleTy) {
6414     default: llvm_unreachable("Unexpected ValueType for argument!");
6415     case MVT::i1:
6416     case MVT::i32:
6417     case MVT::i64:
6418       if (Flags.isNest()) {
6419         // The 'nest' parameter, if any, is passed in R11.
6420         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6421         break;
6422       }
6423 
6424       // These can be scalar arguments or elements of an integer array type
6425       // passed directly.  Clang may use those instead of "byval" aggregate
6426       // types to avoid forcing arguments to memory unnecessarily.
6427       if (GPR_idx != NumGPRs) {
6428         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6429       } else {
6430         if (IsFastCall)
6431           ComputePtrOff();
6432 
6433         assert(HasParameterArea &&
6434                "Parameter area must exist to pass an argument in memory.");
6435         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6436                          true, CFlags.IsTailCall, false, MemOpChains,
6437                          TailCallArguments, dl);
6438         if (IsFastCall)
6439           ArgOffset += PtrByteSize;
6440       }
6441       if (!IsFastCall)
6442         ArgOffset += PtrByteSize;
6443       break;
6444     case MVT::f32:
6445     case MVT::f64: {
6446       // These can be scalar arguments or elements of a float array type
6447       // passed directly.  The latter are used to implement ELFv2 homogenous
6448       // float aggregates.
6449 
6450       // Named arguments go into FPRs first, and once they overflow, the
6451       // remaining arguments go into GPRs and then the parameter save area.
6452       // Unnamed arguments for vararg functions always go to GPRs and
6453       // then the parameter save area.  For now, put all arguments to vararg
6454       // routines always in both locations (FPR *and* GPR or stack slot).
6455       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6456       bool NeededLoad = false;
6457 
6458       // First load the argument into the next available FPR.
6459       if (FPR_idx != NumFPRs)
6460         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6461 
6462       // Next, load the argument into GPR or stack slot if needed.
6463       if (!NeedGPROrStack)
6464         ;
6465       else if (GPR_idx != NumGPRs && !IsFastCall) {
6466         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6467         // once we support fp <-> gpr moves.
6468 
6469         // In the non-vararg case, this can only ever happen in the
6470         // presence of f32 array types, since otherwise we never run
6471         // out of FPRs before running out of GPRs.
6472         SDValue ArgVal;
6473 
6474         // Double values are always passed in a single GPR.
6475         if (Arg.getValueType() != MVT::f32) {
6476           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6477 
6478         // Non-array float values are extended and passed in a GPR.
6479         } else if (!Flags.isInConsecutiveRegs()) {
6480           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6481           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6482 
6483         // If we have an array of floats, we collect every odd element
6484         // together with its predecessor into one GPR.
6485         } else if (ArgOffset % PtrByteSize != 0) {
6486           SDValue Lo, Hi;
6487           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6488           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6489           if (!isLittleEndian)
6490             std::swap(Lo, Hi);
6491           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6492 
6493         // The final element, if even, goes into the first half of a GPR.
6494         } else if (Flags.isInConsecutiveRegsLast()) {
6495           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6496           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6497           if (!isLittleEndian)
6498             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6499                                  DAG.getConstant(32, dl, MVT::i32));
6500 
6501         // Non-final even elements are skipped; they will be handled
6502         // together the with subsequent argument on the next go-around.
6503         } else
6504           ArgVal = SDValue();
6505 
6506         if (ArgVal.getNode())
6507           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6508       } else {
6509         if (IsFastCall)
6510           ComputePtrOff();
6511 
6512         // Single-precision floating-point values are mapped to the
6513         // second (rightmost) word of the stack doubleword.
6514         if (Arg.getValueType() == MVT::f32 &&
6515             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6516           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6517           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6518         }
6519 
6520         assert(HasParameterArea &&
6521                "Parameter area must exist to pass an argument in memory.");
6522         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6523                          true, CFlags.IsTailCall, false, MemOpChains,
6524                          TailCallArguments, dl);
6525 
6526         NeededLoad = true;
6527       }
6528       // When passing an array of floats, the array occupies consecutive
6529       // space in the argument area; only round up to the next doubleword
6530       // at the end of the array.  Otherwise, each float takes 8 bytes.
6531       if (!IsFastCall || NeededLoad) {
6532         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6533                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6534         if (Flags.isInConsecutiveRegsLast())
6535           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6536       }
6537       break;
6538     }
6539     case MVT::v4f32:
6540     case MVT::v4i32:
6541     case MVT::v8i16:
6542     case MVT::v16i8:
6543     case MVT::v2f64:
6544     case MVT::v2i64:
6545     case MVT::v1i128:
6546     case MVT::f128:
6547       // These can be scalar arguments or elements of a vector array type
6548       // passed directly.  The latter are used to implement ELFv2 homogenous
6549       // vector aggregates.
6550 
6551       // For a varargs call, named arguments go into VRs or on the stack as
6552       // usual; unnamed arguments always go to the stack or the corresponding
6553       // GPRs when within range.  For now, we always put the value in both
6554       // locations (or even all three).
6555       if (CFlags.IsVarArg) {
6556         assert(HasParameterArea &&
6557                "Parameter area must exist if we have a varargs call.");
6558         // We could elide this store in the case where the object fits
6559         // entirely in R registers.  Maybe later.
6560         SDValue Store =
6561             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6562         MemOpChains.push_back(Store);
6563         if (VR_idx != NumVRs) {
6564           SDValue Load =
6565               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6566           MemOpChains.push_back(Load.getValue(1));
6567           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6568         }
6569         ArgOffset += 16;
6570         for (unsigned i=0; i<16; i+=PtrByteSize) {
6571           if (GPR_idx == NumGPRs)
6572             break;
6573           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6574                                    DAG.getConstant(i, dl, PtrVT));
6575           SDValue Load =
6576               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6577           MemOpChains.push_back(Load.getValue(1));
6578           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6579         }
6580         break;
6581       }
6582 
6583       // Non-varargs Altivec params go into VRs or on the stack.
6584       if (VR_idx != NumVRs) {
6585         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6586       } else {
6587         if (IsFastCall)
6588           ComputePtrOff();
6589 
6590         assert(HasParameterArea &&
6591                "Parameter area must exist to pass an argument in memory.");
6592         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6593                          true, CFlags.IsTailCall, true, MemOpChains,
6594                          TailCallArguments, dl);
6595         if (IsFastCall)
6596           ArgOffset += 16;
6597       }
6598 
6599       if (!IsFastCall)
6600         ArgOffset += 16;
6601       break;
6602     }
6603   }
6604 
6605   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6606          "mismatch in size of parameter area");
6607   (void)NumBytesActuallyUsed;
6608 
6609   if (!MemOpChains.empty())
6610     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6611 
6612   // Check if this is an indirect call (MTCTR/BCTRL).
6613   // See prepareDescriptorIndirectCall and buildCallOperands for more
6614   // information about calls through function pointers in the 64-bit SVR4 ABI.
6615   if (CFlags.IsIndirect) {
6616     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6617     // caller in the TOC save area.
6618     if (isTOCSaveRestoreRequired(Subtarget)) {
6619       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6620       // Load r2 into a virtual register and store it to the TOC save area.
6621       setUsesTOCBasePtr(DAG);
6622       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6623       // TOC save area offset.
6624       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6625       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6626       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6627       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6628                            MachinePointerInfo::getStack(
6629                                DAG.getMachineFunction(), TOCSaveOffset));
6630     }
6631     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6632     // This does not mean the MTCTR instruction must use R12; it's easier
6633     // to model this as an extra parameter, so do that.
6634     if (isELFv2ABI && !CFlags.IsPatchPoint)
6635       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6636   }
6637 
6638   // Build a sequence of copy-to-reg nodes chained together with token chain
6639   // and flag operands which copy the outgoing args into the appropriate regs.
6640   SDValue InFlag;
6641   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6642     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6643                              RegsToPass[i].second, InFlag);
6644     InFlag = Chain.getValue(1);
6645   }
6646 
6647   if (CFlags.IsTailCall && !IsSibCall)
6648     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6649                     TailCallArguments);
6650 
6651   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6652                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6653 }
6654 
6655 SDValue PPCTargetLowering::LowerCall_Darwin(
6656     SDValue Chain, SDValue Callee, CallFlags CFlags,
6657     const SmallVectorImpl<ISD::OutputArg> &Outs,
6658     const SmallVectorImpl<SDValue> &OutVals,
6659     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6660     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6661     const CallBase *CB) const {
6662   unsigned NumOps = Outs.size();
6663 
6664   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6665   bool isPPC64 = PtrVT == MVT::i64;
6666   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6667 
6668   MachineFunction &MF = DAG.getMachineFunction();
6669 
6670   // Mark this function as potentially containing a function that contains a
6671   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6672   // and restoring the callers stack pointer in this functions epilog. This is
6673   // done because by tail calling the called function might overwrite the value
6674   // in this function's (MF) stack pointer stack slot 0(SP).
6675   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6676       CFlags.CallConv == CallingConv::Fast)
6677     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6678 
6679   // Count how many bytes are to be pushed on the stack, including the linkage
6680   // area, and parameter passing area.  We start with 24/48 bytes, which is
6681   // prereserved space for [SP][CR][LR][3 x unused].
6682   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6683   unsigned NumBytes = LinkageSize;
6684 
6685   // Add up all the space actually used.
6686   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6687   // they all go in registers, but we must reserve stack space for them for
6688   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6689   // assigned stack space in order, with padding so Altivec parameters are
6690   // 16-byte aligned.
6691   unsigned nAltivecParamsAtEnd = 0;
6692   for (unsigned i = 0; i != NumOps; ++i) {
6693     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6694     EVT ArgVT = Outs[i].VT;
6695     // Varargs Altivec parameters are padded to a 16 byte boundary.
6696     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6697         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6698         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6699       if (!CFlags.IsVarArg && !isPPC64) {
6700         // Non-varargs Altivec parameters go after all the non-Altivec
6701         // parameters; handle those later so we know how much padding we need.
6702         nAltivecParamsAtEnd++;
6703         continue;
6704       }
6705       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6706       NumBytes = ((NumBytes+15)/16)*16;
6707     }
6708     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6709   }
6710 
6711   // Allow for Altivec parameters at the end, if needed.
6712   if (nAltivecParamsAtEnd) {
6713     NumBytes = ((NumBytes+15)/16)*16;
6714     NumBytes += 16*nAltivecParamsAtEnd;
6715   }
6716 
6717   // The prolog code of the callee may store up to 8 GPR argument registers to
6718   // the stack, allowing va_start to index over them in memory if its varargs.
6719   // Because we cannot tell if this is needed on the caller side, we have to
6720   // conservatively assume that it is needed.  As such, make sure we have at
6721   // least enough stack space for the caller to store the 8 GPRs.
6722   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6723 
6724   // Tail call needs the stack to be aligned.
6725   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6726       CFlags.CallConv == CallingConv::Fast)
6727     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6728 
6729   // Calculate by how many bytes the stack has to be adjusted in case of tail
6730   // call optimization.
6731   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6732 
6733   // To protect arguments on the stack from being clobbered in a tail call,
6734   // force all the loads to happen before doing any other lowering.
6735   if (CFlags.IsTailCall)
6736     Chain = DAG.getStackArgumentTokenFactor(Chain);
6737 
6738   // Adjust the stack pointer for the new arguments...
6739   // These operations are automatically eliminated by the prolog/epilog pass
6740   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6741   SDValue CallSeqStart = Chain;
6742 
6743   // Load the return address and frame pointer so it can be move somewhere else
6744   // later.
6745   SDValue LROp, FPOp;
6746   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6747 
6748   // Set up a copy of the stack pointer for use loading and storing any
6749   // arguments that may not fit in the registers available for argument
6750   // passing.
6751   SDValue StackPtr;
6752   if (isPPC64)
6753     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6754   else
6755     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6756 
6757   // Figure out which arguments are going to go in registers, and which in
6758   // memory.  Also, if this is a vararg function, floating point operations
6759   // must be stored to our stack, and loaded into integer regs as well, if
6760   // any integer regs are available for argument passing.
6761   unsigned ArgOffset = LinkageSize;
6762   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6763 
6764   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6765     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6766     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6767   };
6768   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6769     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6770     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6771   };
6772   static const MCPhysReg VR[] = {
6773     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6774     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6775   };
6776   const unsigned NumGPRs = array_lengthof(GPR_32);
6777   const unsigned NumFPRs = 13;
6778   const unsigned NumVRs  = array_lengthof(VR);
6779 
6780   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6781 
6782   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6783   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6784 
6785   SmallVector<SDValue, 8> MemOpChains;
6786   for (unsigned i = 0; i != NumOps; ++i) {
6787     SDValue Arg = OutVals[i];
6788     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6789 
6790     // PtrOff will be used to store the current argument to the stack if a
6791     // register cannot be found for it.
6792     SDValue PtrOff;
6793 
6794     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6795 
6796     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6797 
6798     // On PPC64, promote integers to 64-bit values.
6799     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6800       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6801       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6802       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6803     }
6804 
6805     // FIXME memcpy is used way more than necessary.  Correctness first.
6806     // Note: "by value" is code for passing a structure by value, not
6807     // basic types.
6808     if (Flags.isByVal()) {
6809       unsigned Size = Flags.getByValSize();
6810       // Very small objects are passed right-justified.  Everything else is
6811       // passed left-justified.
6812       if (Size==1 || Size==2) {
6813         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6814         if (GPR_idx != NumGPRs) {
6815           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6816                                         MachinePointerInfo(), VT);
6817           MemOpChains.push_back(Load.getValue(1));
6818           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6819 
6820           ArgOffset += PtrByteSize;
6821         } else {
6822           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6823                                           PtrOff.getValueType());
6824           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6825           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6826                                                             CallSeqStart,
6827                                                             Flags, DAG, dl);
6828           ArgOffset += PtrByteSize;
6829         }
6830         continue;
6831       }
6832       // Copy entire object into memory.  There are cases where gcc-generated
6833       // code assumes it is there, even if it could be put entirely into
6834       // registers.  (This is not what the doc says.)
6835       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6836                                                         CallSeqStart,
6837                                                         Flags, DAG, dl);
6838 
6839       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6840       // copy the pieces of the object that fit into registers from the
6841       // parameter save area.
6842       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6843         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6844         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6845         if (GPR_idx != NumGPRs) {
6846           SDValue Load =
6847               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6848           MemOpChains.push_back(Load.getValue(1));
6849           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6850           ArgOffset += PtrByteSize;
6851         } else {
6852           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6853           break;
6854         }
6855       }
6856       continue;
6857     }
6858 
6859     switch (Arg.getSimpleValueType().SimpleTy) {
6860     default: llvm_unreachable("Unexpected ValueType for argument!");
6861     case MVT::i1:
6862     case MVT::i32:
6863     case MVT::i64:
6864       if (GPR_idx != NumGPRs) {
6865         if (Arg.getValueType() == MVT::i1)
6866           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6867 
6868         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6869       } else {
6870         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6871                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6872                          TailCallArguments, dl);
6873       }
6874       ArgOffset += PtrByteSize;
6875       break;
6876     case MVT::f32:
6877     case MVT::f64:
6878       if (FPR_idx != NumFPRs) {
6879         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6880 
6881         if (CFlags.IsVarArg) {
6882           SDValue Store =
6883               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6884           MemOpChains.push_back(Store);
6885 
6886           // Float varargs are always shadowed in available integer registers
6887           if (GPR_idx != NumGPRs) {
6888             SDValue Load =
6889                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6890             MemOpChains.push_back(Load.getValue(1));
6891             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6892           }
6893           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6894             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6895             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6896             SDValue Load =
6897                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6898             MemOpChains.push_back(Load.getValue(1));
6899             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6900           }
6901         } else {
6902           // If we have any FPRs remaining, we may also have GPRs remaining.
6903           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6904           // GPRs.
6905           if (GPR_idx != NumGPRs)
6906             ++GPR_idx;
6907           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6908               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6909             ++GPR_idx;
6910         }
6911       } else
6912         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6913                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6914                          TailCallArguments, dl);
6915       if (isPPC64)
6916         ArgOffset += 8;
6917       else
6918         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6919       break;
6920     case MVT::v4f32:
6921     case MVT::v4i32:
6922     case MVT::v8i16:
6923     case MVT::v16i8:
6924       if (CFlags.IsVarArg) {
6925         // These go aligned on the stack, or in the corresponding R registers
6926         // when within range.  The Darwin PPC ABI doc claims they also go in
6927         // V registers; in fact gcc does this only for arguments that are
6928         // prototyped, not for those that match the ...  We do it for all
6929         // arguments, seems to work.
6930         while (ArgOffset % 16 !=0) {
6931           ArgOffset += PtrByteSize;
6932           if (GPR_idx != NumGPRs)
6933             GPR_idx++;
6934         }
6935         // We could elide this store in the case where the object fits
6936         // entirely in R registers.  Maybe later.
6937         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6938                              DAG.getConstant(ArgOffset, dl, PtrVT));
6939         SDValue Store =
6940             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6941         MemOpChains.push_back(Store);
6942         if (VR_idx != NumVRs) {
6943           SDValue Load =
6944               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6945           MemOpChains.push_back(Load.getValue(1));
6946           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6947         }
6948         ArgOffset += 16;
6949         for (unsigned i=0; i<16; i+=PtrByteSize) {
6950           if (GPR_idx == NumGPRs)
6951             break;
6952           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6953                                    DAG.getConstant(i, dl, PtrVT));
6954           SDValue Load =
6955               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6956           MemOpChains.push_back(Load.getValue(1));
6957           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6958         }
6959         break;
6960       }
6961 
6962       // Non-varargs Altivec params generally go in registers, but have
6963       // stack space allocated at the end.
6964       if (VR_idx != NumVRs) {
6965         // Doesn't have GPR space allocated.
6966         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6967       } else if (nAltivecParamsAtEnd==0) {
6968         // We are emitting Altivec params in order.
6969         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6970                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6971                          TailCallArguments, dl);
6972         ArgOffset += 16;
6973       }
6974       break;
6975     }
6976   }
6977   // If all Altivec parameters fit in registers, as they usually do,
6978   // they get stack space following the non-Altivec parameters.  We
6979   // don't track this here because nobody below needs it.
6980   // If there are more Altivec parameters than fit in registers emit
6981   // the stores here.
6982   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6983     unsigned j = 0;
6984     // Offset is aligned; skip 1st 12 params which go in V registers.
6985     ArgOffset = ((ArgOffset+15)/16)*16;
6986     ArgOffset += 12*16;
6987     for (unsigned i = 0; i != NumOps; ++i) {
6988       SDValue Arg = OutVals[i];
6989       EVT ArgType = Outs[i].VT;
6990       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6991           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6992         if (++j > NumVRs) {
6993           SDValue PtrOff;
6994           // We are emitting Altivec params in order.
6995           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6996                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6997                            TailCallArguments, dl);
6998           ArgOffset += 16;
6999         }
7000       }
7001     }
7002   }
7003 
7004   if (!MemOpChains.empty())
7005     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7006 
7007   // On Darwin, R12 must contain the address of an indirect callee.  This does
7008   // not mean the MTCTR instruction must use R12; it's easier to model this as
7009   // an extra parameter, so do that.
7010   if (CFlags.IsIndirect) {
7011     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7012     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
7013                                                    PPC::R12), Callee));
7014   }
7015 
7016   // Build a sequence of copy-to-reg nodes chained together with token chain
7017   // and flag operands which copy the outgoing args into the appropriate regs.
7018   SDValue InFlag;
7019   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
7020     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
7021                              RegsToPass[i].second, InFlag);
7022     InFlag = Chain.getValue(1);
7023   }
7024 
7025   if (CFlags.IsTailCall)
7026     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
7027                     TailCallArguments);
7028 
7029   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7030                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7031 }
7032 
7033 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
7034                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
7035                    CCState &State) {
7036 
7037   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
7038       State.getMachineFunction().getSubtarget());
7039   const bool IsPPC64 = Subtarget.isPPC64();
7040   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
7041   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
7042 
7043   if (ValVT.isVector() && !State.getMachineFunction()
7044                                .getTarget()
7045                                .Options.EnableAIXExtendedAltivecABI)
7046     report_fatal_error("the default Altivec AIX ABI is not yet supported");
7047 
7048   if (ValVT == MVT::f128)
7049     report_fatal_error("f128 is unimplemented on AIX.");
7050 
7051   if (ArgFlags.isNest())
7052     report_fatal_error("Nest arguments are unimplemented.");
7053 
7054   static const MCPhysReg GPR_32[] = {// 32-bit registers.
7055                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7056                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7057   static const MCPhysReg GPR_64[] = {// 64-bit registers.
7058                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7059                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7060 
7061   static const MCPhysReg VR[] = {// Vector registers.
7062                                  PPC::V2,  PPC::V3,  PPC::V4,  PPC::V5,
7063                                  PPC::V6,  PPC::V7,  PPC::V8,  PPC::V9,
7064                                  PPC::V10, PPC::V11, PPC::V12, PPC::V13};
7065 
7066   if (ArgFlags.isByVal()) {
7067     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
7068       report_fatal_error("Pass-by-value arguments with alignment greater than "
7069                          "register width are not supported.");
7070 
7071     const unsigned ByValSize = ArgFlags.getByValSize();
7072 
7073     // An empty aggregate parameter takes up no storage and no registers,
7074     // but needs a MemLoc for a stack slot for the formal arguments side.
7075     if (ByValSize == 0) {
7076       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
7077                                        State.getNextStackOffset(), RegVT,
7078                                        LocInfo));
7079       return false;
7080     }
7081 
7082     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
7083     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
7084     for (const unsigned E = Offset + StackSize; Offset < E;
7085          Offset += PtrAlign.value()) {
7086       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
7087         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7088       else {
7089         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
7090                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
7091                                          LocInfo));
7092         break;
7093       }
7094     }
7095     return false;
7096   }
7097 
7098   // Arguments always reserve parameter save area.
7099   switch (ValVT.SimpleTy) {
7100   default:
7101     report_fatal_error("Unhandled value type for argument.");
7102   case MVT::i64:
7103     // i64 arguments should have been split to i32 for PPC32.
7104     assert(IsPPC64 && "PPC32 should have split i64 values.");
7105     LLVM_FALLTHROUGH;
7106   case MVT::i1:
7107   case MVT::i32: {
7108     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
7109     // AIX integer arguments are always passed in register width.
7110     if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
7111       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
7112                                   : CCValAssign::LocInfo::ZExt;
7113     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
7114       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7115     else
7116       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
7117 
7118     return false;
7119   }
7120   case MVT::f32:
7121   case MVT::f64: {
7122     // Parameter save area (PSA) is reserved even if the float passes in fpr.
7123     const unsigned StoreSize = LocVT.getStoreSize();
7124     // Floats are always 4-byte aligned in the PSA on AIX.
7125     // This includes f64 in 64-bit mode for ABI compatibility.
7126     const unsigned Offset =
7127         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
7128     unsigned FReg = State.AllocateReg(FPR);
7129     if (FReg)
7130       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
7131 
7132     // Reserve and initialize GPRs or initialize the PSA as required.
7133     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
7134       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
7135         assert(FReg && "An FPR should be available when a GPR is reserved.");
7136         if (State.isVarArg()) {
7137           // Successfully reserved GPRs are only initialized for vararg calls.
7138           // Custom handling is required for:
7139           //   f64 in PPC32 needs to be split into 2 GPRs.
7140           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
7141           State.addLoc(
7142               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7143         }
7144       } else {
7145         // If there are insufficient GPRs, the PSA needs to be initialized.
7146         // Initialization occurs even if an FPR was initialized for
7147         // compatibility with the AIX XL compiler. The full memory for the
7148         // argument will be initialized even if a prior word is saved in GPR.
7149         // A custom memLoc is used when the argument also passes in FPR so
7150         // that the callee handling can skip over it easily.
7151         State.addLoc(
7152             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
7153                                              LocInfo)
7154                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7155         break;
7156       }
7157     }
7158 
7159     return false;
7160   }
7161   case MVT::v4f32:
7162   case MVT::v4i32:
7163   case MVT::v8i16:
7164   case MVT::v16i8:
7165   case MVT::v2i64:
7166   case MVT::v2f64:
7167   case MVT::v1i128: {
7168     if (State.isVarArg())
7169       report_fatal_error(
7170           "variadic arguments for vector types are unimplemented for AIX");
7171 
7172     if (unsigned VReg = State.AllocateReg(VR))
7173       State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
7174     else {
7175       report_fatal_error(
7176           "passing vector parameters to the stack is unimplemented for AIX");
7177     }
7178     return false;
7179   }
7180   }
7181   return true;
7182 }
7183 
7184 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
7185                                                     bool IsPPC64) {
7186   assert((IsPPC64 || SVT != MVT::i64) &&
7187          "i64 should have been split for 32-bit codegen.");
7188 
7189   switch (SVT) {
7190   default:
7191     report_fatal_error("Unexpected value type for formal argument");
7192   case MVT::i1:
7193   case MVT::i32:
7194   case MVT::i64:
7195     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7196   case MVT::f32:
7197     return &PPC::F4RCRegClass;
7198   case MVT::f64:
7199     return &PPC::F8RCRegClass;
7200   case MVT::v4f32:
7201   case MVT::v4i32:
7202   case MVT::v8i16:
7203   case MVT::v16i8:
7204   case MVT::v2i64:
7205   case MVT::v2f64:
7206   case MVT::v1i128:
7207     return &PPC::VRRCRegClass;
7208   }
7209 }
7210 
7211 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
7212                                         SelectionDAG &DAG, SDValue ArgValue,
7213                                         MVT LocVT, const SDLoc &dl) {
7214   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7215   assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
7216 
7217   if (Flags.isSExt())
7218     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7219                            DAG.getValueType(ValVT));
7220   else if (Flags.isZExt())
7221     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7222                            DAG.getValueType(ValVT));
7223 
7224   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7225 }
7226 
7227 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7228   const unsigned LASize = FL->getLinkageSize();
7229 
7230   if (PPC::GPRCRegClass.contains(Reg)) {
7231     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7232            "Reg must be a valid argument register!");
7233     return LASize + 4 * (Reg - PPC::R3);
7234   }
7235 
7236   if (PPC::G8RCRegClass.contains(Reg)) {
7237     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7238            "Reg must be a valid argument register!");
7239     return LASize + 8 * (Reg - PPC::X3);
7240   }
7241 
7242   llvm_unreachable("Only general purpose registers expected.");
7243 }
7244 
7245 //   AIX ABI Stack Frame Layout:
7246 //
7247 //   Low Memory +--------------------------------------------+
7248 //   SP   +---> | Back chain                                 | ---+
7249 //        |     +--------------------------------------------+    |
7250 //        |     | Saved Condition Register                   |    |
7251 //        |     +--------------------------------------------+    |
7252 //        |     | Saved Linkage Register                     |    |
7253 //        |     +--------------------------------------------+    | Linkage Area
7254 //        |     | Reserved for compilers                     |    |
7255 //        |     +--------------------------------------------+    |
7256 //        |     | Reserved for binders                       |    |
7257 //        |     +--------------------------------------------+    |
7258 //        |     | Saved TOC pointer                          | ---+
7259 //        |     +--------------------------------------------+
7260 //        |     | Parameter save area                        |
7261 //        |     +--------------------------------------------+
7262 //        |     | Alloca space                               |
7263 //        |     +--------------------------------------------+
7264 //        |     | Local variable space                       |
7265 //        |     +--------------------------------------------+
7266 //        |     | Float/int conversion temporary             |
7267 //        |     +--------------------------------------------+
7268 //        |     | Save area for AltiVec registers            |
7269 //        |     +--------------------------------------------+
7270 //        |     | AltiVec alignment padding                  |
7271 //        |     +--------------------------------------------+
7272 //        |     | Save area for VRSAVE register              |
7273 //        |     +--------------------------------------------+
7274 //        |     | Save area for General Purpose registers    |
7275 //        |     +--------------------------------------------+
7276 //        |     | Save area for Floating Point registers     |
7277 //        |     +--------------------------------------------+
7278 //        +---- | Back chain                                 |
7279 // High Memory  +--------------------------------------------+
7280 //
7281 //  Specifications:
7282 //  AIX 7.2 Assembler Language Reference
7283 //  Subroutine linkage convention
7284 
7285 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7286     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7287     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7288     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7289 
7290   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7291           CallConv == CallingConv::Fast) &&
7292          "Unexpected calling convention!");
7293 
7294   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7295     report_fatal_error("Tail call support is unimplemented on AIX.");
7296 
7297   if (useSoftFloat())
7298     report_fatal_error("Soft float support is unimplemented on AIX.");
7299 
7300   const PPCSubtarget &Subtarget =
7301       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7302 
7303   const bool IsPPC64 = Subtarget.isPPC64();
7304   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7305 
7306   // Assign locations to all of the incoming arguments.
7307   SmallVector<CCValAssign, 16> ArgLocs;
7308   MachineFunction &MF = DAG.getMachineFunction();
7309   MachineFrameInfo &MFI = MF.getFrameInfo();
7310   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7311   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7312 
7313   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7314   // Reserve space for the linkage area on the stack.
7315   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7316   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7317   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7318 
7319   SmallVector<SDValue, 8> MemOps;
7320 
7321   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7322     CCValAssign &VA = ArgLocs[I++];
7323     MVT LocVT = VA.getLocVT();
7324     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7325     if (VA.isMemLoc() && VA.getValVT().isVector())
7326       report_fatal_error(
7327           "passing vector parameters to the stack is unimplemented for AIX");
7328 
7329     // For compatibility with the AIX XL compiler, the float args in the
7330     // parameter save area are initialized even if the argument is available
7331     // in register.  The caller is required to initialize both the register
7332     // and memory, however, the callee can choose to expect it in either.
7333     // The memloc is dismissed here because the argument is retrieved from
7334     // the register.
7335     if (VA.isMemLoc() && VA.needsCustom())
7336       continue;
7337 
7338     if (VA.isRegLoc()) {
7339       if (VA.getValVT().isScalarInteger())
7340         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7341       else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector())
7342         FuncInfo->appendParameterType(VA.getValVT().SimpleTy == MVT::f32
7343                                           ? PPCFunctionInfo::ShortFloatPoint
7344                                           : PPCFunctionInfo::LongFloatPoint);
7345     }
7346 
7347     if (Flags.isByVal() && VA.isMemLoc()) {
7348       const unsigned Size =
7349           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7350                   PtrByteSize);
7351       const int FI = MF.getFrameInfo().CreateFixedObject(
7352           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7353           /* IsAliased */ true);
7354       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7355       InVals.push_back(FIN);
7356 
7357       continue;
7358     }
7359 
7360     if (Flags.isByVal()) {
7361       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7362 
7363       const MCPhysReg ArgReg = VA.getLocReg();
7364       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7365 
7366       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7367         report_fatal_error("Over aligned byvals not supported yet.");
7368 
7369       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7370       const int FI = MF.getFrameInfo().CreateFixedObject(
7371           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7372           /* IsAliased */ true);
7373       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7374       InVals.push_back(FIN);
7375 
7376       // Add live ins for all the RegLocs for the same ByVal.
7377       const TargetRegisterClass *RegClass =
7378           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7379 
7380       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7381                                                unsigned Offset) {
7382         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7383         // Since the callers side has left justified the aggregate in the
7384         // register, we can simply store the entire register into the stack
7385         // slot.
7386         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7387         // The store to the fixedstack object is needed becuase accessing a
7388         // field of the ByVal will use a gep and load. Ideally we will optimize
7389         // to extracting the value from the register directly, and elide the
7390         // stores when the arguments address is not taken, but that will need to
7391         // be future work.
7392         SDValue Store = DAG.getStore(
7393             CopyFrom.getValue(1), dl, CopyFrom,
7394             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7395             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7396 
7397         MemOps.push_back(Store);
7398       };
7399 
7400       unsigned Offset = 0;
7401       HandleRegLoc(VA.getLocReg(), Offset);
7402       Offset += PtrByteSize;
7403       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7404            Offset += PtrByteSize) {
7405         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7406                "RegLocs should be for ByVal argument.");
7407 
7408         const CCValAssign RL = ArgLocs[I++];
7409         HandleRegLoc(RL.getLocReg(), Offset);
7410         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7411       }
7412 
7413       if (Offset != StackSize) {
7414         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7415                "Expected MemLoc for remaining bytes.");
7416         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7417         // Consume the MemLoc.The InVal has already been emitted, so nothing
7418         // more needs to be done.
7419         ++I;
7420       }
7421 
7422       continue;
7423     }
7424 
7425     EVT ValVT = VA.getValVT();
7426     if (VA.isRegLoc() && !VA.needsCustom()) {
7427       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7428       unsigned VReg =
7429           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7430       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7431       if (ValVT.isScalarInteger() &&
7432           (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7433         ArgValue =
7434             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7435       }
7436       InVals.push_back(ArgValue);
7437       continue;
7438     }
7439     if (VA.isMemLoc()) {
7440       const unsigned LocSize = LocVT.getStoreSize();
7441       const unsigned ValSize = ValVT.getStoreSize();
7442       assert((ValSize <= LocSize) &&
7443              "Object size is larger than size of MemLoc");
7444       int CurArgOffset = VA.getLocMemOffset();
7445       // Objects are right-justified because AIX is big-endian.
7446       if (LocSize > ValSize)
7447         CurArgOffset += LocSize - ValSize;
7448       // Potential tail calls could cause overwriting of argument stack slots.
7449       const bool IsImmutable =
7450           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7451             (CallConv == CallingConv::Fast));
7452       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7453       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7454       SDValue ArgValue =
7455           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7456       InVals.push_back(ArgValue);
7457       continue;
7458     }
7459   }
7460 
7461   // On AIX a minimum of 8 words is saved to the parameter save area.
7462   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7463   // Area that is at least reserved in the caller of this function.
7464   unsigned CallerReservedArea =
7465       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7466 
7467   // Set the size that is at least reserved in caller of this function. Tail
7468   // call optimized function's reserved stack space needs to be aligned so
7469   // that taking the difference between two stack areas will result in an
7470   // aligned stack.
7471   CallerReservedArea =
7472       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7473   FuncInfo->setMinReservedArea(CallerReservedArea);
7474 
7475   if (isVarArg) {
7476     FuncInfo->setVarArgsFrameIndex(
7477         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7478     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7479 
7480     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7481                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7482 
7483     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7484                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7485     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7486 
7487     // The fixed integer arguments of a variadic function are stored to the
7488     // VarArgsFrameIndex on the stack so that they may be loaded by
7489     // dereferencing the result of va_next.
7490     for (unsigned GPRIndex =
7491              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7492          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7493 
7494       const unsigned VReg =
7495           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7496                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7497 
7498       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7499       SDValue Store =
7500           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7501       MemOps.push_back(Store);
7502       // Increment the address for the next argument to store.
7503       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7504       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7505     }
7506   }
7507 
7508   if (!MemOps.empty())
7509     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7510 
7511   return Chain;
7512 }
7513 
7514 SDValue PPCTargetLowering::LowerCall_AIX(
7515     SDValue Chain, SDValue Callee, CallFlags CFlags,
7516     const SmallVectorImpl<ISD::OutputArg> &Outs,
7517     const SmallVectorImpl<SDValue> &OutVals,
7518     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7519     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7520     const CallBase *CB) const {
7521   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7522   // AIX ABI stack frame layout.
7523 
7524   assert((CFlags.CallConv == CallingConv::C ||
7525           CFlags.CallConv == CallingConv::Cold ||
7526           CFlags.CallConv == CallingConv::Fast) &&
7527          "Unexpected calling convention!");
7528 
7529   if (CFlags.IsPatchPoint)
7530     report_fatal_error("This call type is unimplemented on AIX.");
7531 
7532   const PPCSubtarget& Subtarget =
7533       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7534 
7535   MachineFunction &MF = DAG.getMachineFunction();
7536   SmallVector<CCValAssign, 16> ArgLocs;
7537   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7538                  *DAG.getContext());
7539 
7540   // Reserve space for the linkage save area (LSA) on the stack.
7541   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7542   //   [SP][CR][LR][2 x reserved][TOC].
7543   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7544   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7545   const bool IsPPC64 = Subtarget.isPPC64();
7546   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7547   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7548   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7549   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7550 
7551   // The prolog code of the callee may store up to 8 GPR argument registers to
7552   // the stack, allowing va_start to index over them in memory if the callee
7553   // is variadic.
7554   // Because we cannot tell if this is needed on the caller side, we have to
7555   // conservatively assume that it is needed.  As such, make sure we have at
7556   // least enough stack space for the caller to store the 8 GPRs.
7557   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7558   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7559                                      CCInfo.getNextStackOffset());
7560 
7561   // Adjust the stack pointer for the new arguments...
7562   // These operations are automatically eliminated by the prolog/epilog pass.
7563   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7564   SDValue CallSeqStart = Chain;
7565 
7566   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7567   SmallVector<SDValue, 8> MemOpChains;
7568 
7569   // Set up a copy of the stack pointer for loading and storing any
7570   // arguments that may not fit in the registers available for argument
7571   // passing.
7572   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7573                                    : DAG.getRegister(PPC::R1, MVT::i32);
7574 
7575   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7576     const unsigned ValNo = ArgLocs[I].getValNo();
7577     SDValue Arg = OutVals[ValNo];
7578     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7579 
7580     if (Flags.isByVal()) {
7581       const unsigned ByValSize = Flags.getByValSize();
7582 
7583       // Nothing to do for zero-sized ByVals on the caller side.
7584       if (!ByValSize) {
7585         ++I;
7586         continue;
7587       }
7588 
7589       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7590         return DAG.getExtLoad(
7591             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7592             (LoadOffset != 0)
7593                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7594                 : Arg,
7595             MachinePointerInfo(), VT);
7596       };
7597 
7598       unsigned LoadOffset = 0;
7599 
7600       // Initialize registers, which are fully occupied by the by-val argument.
7601       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7602         SDValue Load = GetLoad(PtrVT, LoadOffset);
7603         MemOpChains.push_back(Load.getValue(1));
7604         LoadOffset += PtrByteSize;
7605         const CCValAssign &ByValVA = ArgLocs[I++];
7606         assert(ByValVA.getValNo() == ValNo &&
7607                "Unexpected location for pass-by-value argument.");
7608         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7609       }
7610 
7611       if (LoadOffset == ByValSize)
7612         continue;
7613 
7614       // There must be one more loc to handle the remainder.
7615       assert(ArgLocs[I].getValNo() == ValNo &&
7616              "Expected additional location for by-value argument.");
7617 
7618       if (ArgLocs[I].isMemLoc()) {
7619         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7620         const CCValAssign &ByValVA = ArgLocs[I++];
7621         ISD::ArgFlagsTy MemcpyFlags = Flags;
7622         // Only memcpy the bytes that don't pass in register.
7623         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7624         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7625             (LoadOffset != 0)
7626                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7627                 : Arg,
7628             DAG.getObjectPtrOffset(dl, StackPtr,
7629                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7630             CallSeqStart, MemcpyFlags, DAG, dl);
7631         continue;
7632       }
7633 
7634       // Initialize the final register residue.
7635       // Any residue that occupies the final by-val arg register must be
7636       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7637       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7638       // 2 and 1 byte loads.
7639       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7640       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7641              "Unexpected register residue for by-value argument.");
7642       SDValue ResidueVal;
7643       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7644         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7645         const MVT VT =
7646             N == 1 ? MVT::i8
7647                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7648         SDValue Load = GetLoad(VT, LoadOffset);
7649         MemOpChains.push_back(Load.getValue(1));
7650         LoadOffset += N;
7651         Bytes += N;
7652 
7653         // By-val arguments are passed left-justfied in register.
7654         // Every load here needs to be shifted, otherwise a full register load
7655         // should have been used.
7656         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7657                "Unexpected load emitted during handling of pass-by-value "
7658                "argument.");
7659         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7660         EVT ShiftAmountTy =
7661             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7662         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7663         SDValue ShiftedLoad =
7664             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7665         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7666                                               ShiftedLoad)
7667                                 : ShiftedLoad;
7668       }
7669 
7670       const CCValAssign &ByValVA = ArgLocs[I++];
7671       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7672       continue;
7673     }
7674 
7675     CCValAssign &VA = ArgLocs[I++];
7676     const MVT LocVT = VA.getLocVT();
7677     const MVT ValVT = VA.getValVT();
7678 
7679     if (VA.isMemLoc() && VA.getValVT().isVector())
7680       report_fatal_error(
7681           "passing vector parameters to the stack is unimplemented for AIX");
7682 
7683     switch (VA.getLocInfo()) {
7684     default:
7685       report_fatal_error("Unexpected argument extension type.");
7686     case CCValAssign::Full:
7687       break;
7688     case CCValAssign::ZExt:
7689       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7690       break;
7691     case CCValAssign::SExt:
7692       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7693       break;
7694     }
7695 
7696     if (VA.isRegLoc() && !VA.needsCustom()) {
7697       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7698       continue;
7699     }
7700 
7701     if (VA.isMemLoc()) {
7702       SDValue PtrOff =
7703           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7704       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7705       MemOpChains.push_back(
7706           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7707 
7708       continue;
7709     }
7710 
7711     // Custom handling is used for GPR initializations for vararg float
7712     // arguments.
7713     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7714            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7715            "Unexpected register handling for calling convention.");
7716 
7717     SDValue ArgAsInt =
7718         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7719 
7720     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7721       // f32 in 32-bit GPR
7722       // f64 in 64-bit GPR
7723       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7724     else if (Arg.getValueType().getFixedSizeInBits() <
7725              LocVT.getFixedSizeInBits())
7726       // f32 in 64-bit GPR.
7727       RegsToPass.push_back(std::make_pair(
7728           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7729     else {
7730       // f64 in two 32-bit GPRs
7731       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7732       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7733              "Unexpected custom register for argument!");
7734       CCValAssign &GPR1 = VA;
7735       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7736                                      DAG.getConstant(32, dl, MVT::i8));
7737       RegsToPass.push_back(std::make_pair(
7738           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7739 
7740       if (I != E) {
7741         // If only 1 GPR was available, there will only be one custom GPR and
7742         // the argument will also pass in memory.
7743         CCValAssign &PeekArg = ArgLocs[I];
7744         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7745           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7746           CCValAssign &GPR2 = ArgLocs[I++];
7747           RegsToPass.push_back(std::make_pair(
7748               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7749         }
7750       }
7751     }
7752   }
7753 
7754   if (!MemOpChains.empty())
7755     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7756 
7757   // For indirect calls, we need to save the TOC base to the stack for
7758   // restoration after the call.
7759   if (CFlags.IsIndirect) {
7760     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7761     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7762     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7763     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7764     const unsigned TOCSaveOffset =
7765         Subtarget.getFrameLowering()->getTOCSaveOffset();
7766 
7767     setUsesTOCBasePtr(DAG);
7768     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7769     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7770     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7771     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7772     Chain = DAG.getStore(
7773         Val.getValue(1), dl, Val, AddPtr,
7774         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7775   }
7776 
7777   // Build a sequence of copy-to-reg nodes chained together with token chain
7778   // and flag operands which copy the outgoing args into the appropriate regs.
7779   SDValue InFlag;
7780   for (auto Reg : RegsToPass) {
7781     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7782     InFlag = Chain.getValue(1);
7783   }
7784 
7785   const int SPDiff = 0;
7786   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7787                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7788 }
7789 
7790 bool
7791 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7792                                   MachineFunction &MF, bool isVarArg,
7793                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7794                                   LLVMContext &Context) const {
7795   SmallVector<CCValAssign, 16> RVLocs;
7796   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7797   return CCInfo.CheckReturn(
7798       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7799                 ? RetCC_PPC_Cold
7800                 : RetCC_PPC);
7801 }
7802 
7803 SDValue
7804 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7805                                bool isVarArg,
7806                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7807                                const SmallVectorImpl<SDValue> &OutVals,
7808                                const SDLoc &dl, SelectionDAG &DAG) const {
7809   SmallVector<CCValAssign, 16> RVLocs;
7810   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7811                  *DAG.getContext());
7812   CCInfo.AnalyzeReturn(Outs,
7813                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7814                            ? RetCC_PPC_Cold
7815                            : RetCC_PPC);
7816 
7817   SDValue Flag;
7818   SmallVector<SDValue, 4> RetOps(1, Chain);
7819 
7820   // Copy the result values into the output registers.
7821   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7822     CCValAssign &VA = RVLocs[i];
7823     assert(VA.isRegLoc() && "Can only return in registers!");
7824 
7825     SDValue Arg = OutVals[RealResIdx];
7826 
7827     switch (VA.getLocInfo()) {
7828     default: llvm_unreachable("Unknown loc info!");
7829     case CCValAssign::Full: break;
7830     case CCValAssign::AExt:
7831       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7832       break;
7833     case CCValAssign::ZExt:
7834       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7835       break;
7836     case CCValAssign::SExt:
7837       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7838       break;
7839     }
7840     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7841       bool isLittleEndian = Subtarget.isLittleEndian();
7842       // Legalize ret f64 -> ret 2 x i32.
7843       SDValue SVal =
7844           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7845                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7846       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7847       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7848       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7849                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7850       Flag = Chain.getValue(1);
7851       VA = RVLocs[++i]; // skip ahead to next loc
7852       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7853     } else
7854       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7855     Flag = Chain.getValue(1);
7856     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7857   }
7858 
7859   RetOps[0] = Chain;  // Update chain.
7860 
7861   // Add the flag if we have it.
7862   if (Flag.getNode())
7863     RetOps.push_back(Flag);
7864 
7865   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7866 }
7867 
7868 SDValue
7869 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7870                                                 SelectionDAG &DAG) const {
7871   SDLoc dl(Op);
7872 
7873   // Get the correct type for integers.
7874   EVT IntVT = Op.getValueType();
7875 
7876   // Get the inputs.
7877   SDValue Chain = Op.getOperand(0);
7878   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7879   // Build a DYNAREAOFFSET node.
7880   SDValue Ops[2] = {Chain, FPSIdx};
7881   SDVTList VTs = DAG.getVTList(IntVT);
7882   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7883 }
7884 
7885 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7886                                              SelectionDAG &DAG) const {
7887   // When we pop the dynamic allocation we need to restore the SP link.
7888   SDLoc dl(Op);
7889 
7890   // Get the correct type for pointers.
7891   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7892 
7893   // Construct the stack pointer operand.
7894   bool isPPC64 = Subtarget.isPPC64();
7895   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7896   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7897 
7898   // Get the operands for the STACKRESTORE.
7899   SDValue Chain = Op.getOperand(0);
7900   SDValue SaveSP = Op.getOperand(1);
7901 
7902   // Load the old link SP.
7903   SDValue LoadLinkSP =
7904       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7905 
7906   // Restore the stack pointer.
7907   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7908 
7909   // Store the old link SP.
7910   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7911 }
7912 
7913 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7914   MachineFunction &MF = DAG.getMachineFunction();
7915   bool isPPC64 = Subtarget.isPPC64();
7916   EVT PtrVT = getPointerTy(MF.getDataLayout());
7917 
7918   // Get current frame pointer save index.  The users of this index will be
7919   // primarily DYNALLOC instructions.
7920   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7921   int RASI = FI->getReturnAddrSaveIndex();
7922 
7923   // If the frame pointer save index hasn't been defined yet.
7924   if (!RASI) {
7925     // Find out what the fix offset of the frame pointer save area.
7926     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7927     // Allocate the frame index for frame pointer save area.
7928     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7929     // Save the result.
7930     FI->setReturnAddrSaveIndex(RASI);
7931   }
7932   return DAG.getFrameIndex(RASI, PtrVT);
7933 }
7934 
7935 SDValue
7936 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7937   MachineFunction &MF = DAG.getMachineFunction();
7938   bool isPPC64 = Subtarget.isPPC64();
7939   EVT PtrVT = getPointerTy(MF.getDataLayout());
7940 
7941   // Get current frame pointer save index.  The users of this index will be
7942   // primarily DYNALLOC instructions.
7943   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7944   int FPSI = FI->getFramePointerSaveIndex();
7945 
7946   // If the frame pointer save index hasn't been defined yet.
7947   if (!FPSI) {
7948     // Find out what the fix offset of the frame pointer save area.
7949     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7950     // Allocate the frame index for frame pointer save area.
7951     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7952     // Save the result.
7953     FI->setFramePointerSaveIndex(FPSI);
7954   }
7955   return DAG.getFrameIndex(FPSI, PtrVT);
7956 }
7957 
7958 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7959                                                    SelectionDAG &DAG) const {
7960   MachineFunction &MF = DAG.getMachineFunction();
7961   // Get the inputs.
7962   SDValue Chain = Op.getOperand(0);
7963   SDValue Size  = Op.getOperand(1);
7964   SDLoc dl(Op);
7965 
7966   // Get the correct type for pointers.
7967   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7968   // Negate the size.
7969   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7970                                 DAG.getConstant(0, dl, PtrVT), Size);
7971   // Construct a node for the frame pointer save index.
7972   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7973   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7974   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7975   if (hasInlineStackProbe(MF))
7976     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7977   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7978 }
7979 
7980 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7981                                                      SelectionDAG &DAG) const {
7982   MachineFunction &MF = DAG.getMachineFunction();
7983 
7984   bool isPPC64 = Subtarget.isPPC64();
7985   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7986 
7987   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7988   return DAG.getFrameIndex(FI, PtrVT);
7989 }
7990 
7991 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7992                                                SelectionDAG &DAG) const {
7993   SDLoc DL(Op);
7994   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7995                      DAG.getVTList(MVT::i32, MVT::Other),
7996                      Op.getOperand(0), Op.getOperand(1));
7997 }
7998 
7999 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
8000                                                 SelectionDAG &DAG) const {
8001   SDLoc DL(Op);
8002   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
8003                      Op.getOperand(0), Op.getOperand(1));
8004 }
8005 
8006 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8007   if (Op.getValueType().isVector())
8008     return LowerVectorLoad(Op, DAG);
8009 
8010   assert(Op.getValueType() == MVT::i1 &&
8011          "Custom lowering only for i1 loads");
8012 
8013   // First, load 8 bits into 32 bits, then truncate to 1 bit.
8014 
8015   SDLoc dl(Op);
8016   LoadSDNode *LD = cast<LoadSDNode>(Op);
8017 
8018   SDValue Chain = LD->getChain();
8019   SDValue BasePtr = LD->getBasePtr();
8020   MachineMemOperand *MMO = LD->getMemOperand();
8021 
8022   SDValue NewLD =
8023       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
8024                      BasePtr, MVT::i8, MMO);
8025   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
8026 
8027   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
8028   return DAG.getMergeValues(Ops, dl);
8029 }
8030 
8031 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8032   if (Op.getOperand(1).getValueType().isVector())
8033     return LowerVectorStore(Op, DAG);
8034 
8035   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
8036          "Custom lowering only for i1 stores");
8037 
8038   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
8039 
8040   SDLoc dl(Op);
8041   StoreSDNode *ST = cast<StoreSDNode>(Op);
8042 
8043   SDValue Chain = ST->getChain();
8044   SDValue BasePtr = ST->getBasePtr();
8045   SDValue Value = ST->getValue();
8046   MachineMemOperand *MMO = ST->getMemOperand();
8047 
8048   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
8049                       Value);
8050   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
8051 }
8052 
8053 // FIXME: Remove this once the ANDI glue bug is fixed:
8054 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8055   assert(Op.getValueType() == MVT::i1 &&
8056          "Custom lowering only for i1 results");
8057 
8058   SDLoc DL(Op);
8059   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
8060 }
8061 
8062 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
8063                                                SelectionDAG &DAG) const {
8064 
8065   // Implements a vector truncate that fits in a vector register as a shuffle.
8066   // We want to legalize vector truncates down to where the source fits in
8067   // a vector register (and target is therefore smaller than vector register
8068   // size).  At that point legalization will try to custom lower the sub-legal
8069   // result and get here - where we can contain the truncate as a single target
8070   // operation.
8071 
8072   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
8073   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
8074   //
8075   // We will implement it for big-endian ordering as this (where x denotes
8076   // undefined):
8077   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
8078   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
8079   //
8080   // The same operation in little-endian ordering will be:
8081   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
8082   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
8083 
8084   EVT TrgVT = Op.getValueType();
8085   assert(TrgVT.isVector() && "Vector type expected.");
8086   unsigned TrgNumElts = TrgVT.getVectorNumElements();
8087   EVT EltVT = TrgVT.getVectorElementType();
8088   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
8089       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
8090       !isPowerOf2_32(EltVT.getSizeInBits()))
8091     return SDValue();
8092 
8093   SDValue N1 = Op.getOperand(0);
8094   EVT SrcVT = N1.getValueType();
8095   unsigned SrcSize = SrcVT.getSizeInBits();
8096   if (SrcSize > 256 ||
8097       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
8098       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
8099     return SDValue();
8100   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
8101     return SDValue();
8102 
8103   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8104   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8105 
8106   SDLoc DL(Op);
8107   SDValue Op1, Op2;
8108   if (SrcSize == 256) {
8109     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
8110     EVT SplitVT =
8111         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
8112     unsigned SplitNumElts = SplitVT.getVectorNumElements();
8113     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
8114                       DAG.getConstant(0, DL, VecIdxTy));
8115     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
8116                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
8117   }
8118   else {
8119     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
8120     Op2 = DAG.getUNDEF(WideVT);
8121   }
8122 
8123   // First list the elements we want to keep.
8124   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
8125   SmallVector<int, 16> ShuffV;
8126   if (Subtarget.isLittleEndian())
8127     for (unsigned i = 0; i < TrgNumElts; ++i)
8128       ShuffV.push_back(i * SizeMult);
8129   else
8130     for (unsigned i = 1; i <= TrgNumElts; ++i)
8131       ShuffV.push_back(i * SizeMult - 1);
8132 
8133   // Populate the remaining elements with undefs.
8134   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
8135     // ShuffV.push_back(i + WideNumElts);
8136     ShuffV.push_back(WideNumElts + 1);
8137 
8138   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
8139   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
8140   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
8141 }
8142 
8143 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
8144 /// possible.
8145 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
8146   // Not FP, or using SPE? Not a fsel.
8147   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
8148       !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE())
8149     return Op;
8150 
8151   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
8152 
8153   EVT ResVT = Op.getValueType();
8154   EVT CmpVT = Op.getOperand(0).getValueType();
8155   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8156   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
8157   SDLoc dl(Op);
8158   SDNodeFlags Flags = Op.getNode()->getFlags();
8159 
8160   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
8161   // presence of infinities.
8162   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
8163     switch (CC) {
8164     default:
8165       break;
8166     case ISD::SETOGT:
8167     case ISD::SETGT:
8168       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
8169     case ISD::SETOLT:
8170     case ISD::SETLT:
8171       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
8172     }
8173   }
8174 
8175   // We might be able to do better than this under some circumstances, but in
8176   // general, fsel-based lowering of select is a finite-math-only optimization.
8177   // For more information, see section F.3 of the 2.06 ISA specification.
8178   // With ISA 3.0
8179   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
8180       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
8181     return Op;
8182 
8183   // If the RHS of the comparison is a 0.0, we don't need to do the
8184   // subtraction at all.
8185   SDValue Sel1;
8186   if (isFloatingPointZero(RHS))
8187     switch (CC) {
8188     default: break;       // SETUO etc aren't handled by fsel.
8189     case ISD::SETNE:
8190       std::swap(TV, FV);
8191       LLVM_FALLTHROUGH;
8192     case ISD::SETEQ:
8193       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8194         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8195       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8196       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8197         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8198       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8199                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
8200     case ISD::SETULT:
8201     case ISD::SETLT:
8202       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8203       LLVM_FALLTHROUGH;
8204     case ISD::SETOGE:
8205     case ISD::SETGE:
8206       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8207         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8208       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8209     case ISD::SETUGT:
8210     case ISD::SETGT:
8211       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8212       LLVM_FALLTHROUGH;
8213     case ISD::SETOLE:
8214     case ISD::SETLE:
8215       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8216         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8217       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8218                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
8219     }
8220 
8221   SDValue Cmp;
8222   switch (CC) {
8223   default: break;       // SETUO etc aren't handled by fsel.
8224   case ISD::SETNE:
8225     std::swap(TV, FV);
8226     LLVM_FALLTHROUGH;
8227   case ISD::SETEQ:
8228     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8229     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8230       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8231     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8232     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8233       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8234     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8235                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8236   case ISD::SETULT:
8237   case ISD::SETLT:
8238     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8239     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8240       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8241     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8242   case ISD::SETOGE:
8243   case ISD::SETGE:
8244     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8245     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8246       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8247     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8248   case ISD::SETUGT:
8249   case ISD::SETGT:
8250     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8251     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8252       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8253     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8254   case ISD::SETOLE:
8255   case ISD::SETLE:
8256     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8257     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8258       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8259     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8260   }
8261   return Op;
8262 }
8263 
8264 static unsigned getPPCStrictOpcode(unsigned Opc) {
8265   switch (Opc) {
8266   default:
8267     llvm_unreachable("No strict version of this opcode!");
8268   case PPCISD::FCTIDZ:
8269     return PPCISD::STRICT_FCTIDZ;
8270   case PPCISD::FCTIWZ:
8271     return PPCISD::STRICT_FCTIWZ;
8272   case PPCISD::FCTIDUZ:
8273     return PPCISD::STRICT_FCTIDUZ;
8274   case PPCISD::FCTIWUZ:
8275     return PPCISD::STRICT_FCTIWUZ;
8276   case PPCISD::FCFID:
8277     return PPCISD::STRICT_FCFID;
8278   case PPCISD::FCFIDU:
8279     return PPCISD::STRICT_FCFIDU;
8280   case PPCISD::FCFIDS:
8281     return PPCISD::STRICT_FCFIDS;
8282   case PPCISD::FCFIDUS:
8283     return PPCISD::STRICT_FCFIDUS;
8284   }
8285 }
8286 
8287 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
8288                               const PPCSubtarget &Subtarget) {
8289   SDLoc dl(Op);
8290   bool IsStrict = Op->isStrictFPOpcode();
8291   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8292                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8293 
8294   // TODO: Any other flags to propagate?
8295   SDNodeFlags Flags;
8296   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8297 
8298   // For strict nodes, source is the second operand.
8299   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8300   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8301   assert(Src.getValueType().isFloatingPoint());
8302   if (Src.getValueType() == MVT::f32) {
8303     if (IsStrict) {
8304       Src =
8305           DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
8306                       DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
8307       Chain = Src.getValue(1);
8308     } else
8309       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8310   }
8311   SDValue Conv;
8312   unsigned Opc = ISD::DELETED_NODE;
8313   switch (Op.getSimpleValueType().SimpleTy) {
8314   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8315   case MVT::i32:
8316     Opc = IsSigned ? PPCISD::FCTIWZ
8317                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8318     break;
8319   case MVT::i64:
8320     assert((IsSigned || Subtarget.hasFPCVT()) &&
8321            "i64 FP_TO_UINT is supported only with FPCVT");
8322     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8323   }
8324   if (IsStrict) {
8325     Opc = getPPCStrictOpcode(Opc);
8326     Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
8327                        {Chain, Src}, Flags);
8328   } else {
8329     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8330   }
8331   return Conv;
8332 }
8333 
8334 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8335                                                SelectionDAG &DAG,
8336                                                const SDLoc &dl) const {
8337   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8338   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8339                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8340   bool IsStrict = Op->isStrictFPOpcode();
8341 
8342   // Convert the FP value to an int value through memory.
8343   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8344                   (IsSigned || Subtarget.hasFPCVT());
8345   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8346   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8347   MachinePointerInfo MPI =
8348       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8349 
8350   // Emit a store to the stack slot.
8351   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8352   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8353   if (i32Stack) {
8354     MachineFunction &MF = DAG.getMachineFunction();
8355     Alignment = Align(4);
8356     MachineMemOperand *MMO =
8357         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8358     SDValue Ops[] = { Chain, Tmp, FIPtr };
8359     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8360               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8361   } else
8362     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8363 
8364   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8365   // add in a bias on big endian.
8366   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8367     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8368                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8369     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8370   }
8371 
8372   RLI.Chain = Chain;
8373   RLI.Ptr = FIPtr;
8374   RLI.MPI = MPI;
8375   RLI.Alignment = Alignment;
8376 }
8377 
8378 /// Custom lowers floating point to integer conversions to use
8379 /// the direct move instructions available in ISA 2.07 to avoid the
8380 /// need for load/store combinations.
8381 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8382                                                     SelectionDAG &DAG,
8383                                                     const SDLoc &dl) const {
8384   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8385   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8386   if (Op->isStrictFPOpcode())
8387     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8388   else
8389     return Mov;
8390 }
8391 
8392 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8393                                           const SDLoc &dl) const {
8394   bool IsStrict = Op->isStrictFPOpcode();
8395   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8396                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8397   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8398   EVT SrcVT = Src.getValueType();
8399   EVT DstVT = Op.getValueType();
8400 
8401   // FP to INT conversions are legal for f128.
8402   if (SrcVT == MVT::f128)
8403     return Subtarget.hasP9Vector() ? Op : SDValue();
8404 
8405   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8406   // PPC (the libcall is not available).
8407   if (SrcVT == MVT::ppcf128) {
8408     if (DstVT == MVT::i32) {
8409       // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8410       // set other fast-math flags to FP operations in both strict and
8411       // non-strict cases. (FP_TO_SINT, FSUB)
8412       SDNodeFlags Flags;
8413       Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8414 
8415       if (IsSigned) {
8416         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8417                                  DAG.getIntPtrConstant(0, dl));
8418         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8419                                  DAG.getIntPtrConstant(1, dl));
8420 
8421         // Add the two halves of the long double in round-to-zero mode, and use
8422         // a smaller FP_TO_SINT.
8423         if (IsStrict) {
8424           SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8425                                     DAG.getVTList(MVT::f64, MVT::Other),
8426                                     {Op.getOperand(0), Lo, Hi}, Flags);
8427           return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8428                              DAG.getVTList(MVT::i32, MVT::Other),
8429                              {Res.getValue(1), Res}, Flags);
8430         } else {
8431           SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8432           return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8433         }
8434       } else {
8435         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8436         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8437         SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8438         SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8439         if (IsStrict) {
8440           // Sel = Src < 0x80000000
8441           // FltOfs = select Sel, 0.0, 0x80000000
8442           // IntOfs = select Sel, 0, 0x80000000
8443           // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8444           SDValue Chain = Op.getOperand(0);
8445           EVT SetCCVT =
8446               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8447           EVT DstSetCCVT =
8448               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8449           SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8450                                      Chain, true);
8451           Chain = Sel.getValue(1);
8452 
8453           SDValue FltOfs = DAG.getSelect(
8454               dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8455           Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8456 
8457           SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8458                                     DAG.getVTList(SrcVT, MVT::Other),
8459                                     {Chain, Src, FltOfs}, Flags);
8460           Chain = Val.getValue(1);
8461           SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8462                                      DAG.getVTList(DstVT, MVT::Other),
8463                                      {Chain, Val}, Flags);
8464           Chain = SInt.getValue(1);
8465           SDValue IntOfs = DAG.getSelect(
8466               dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8467           SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8468           return DAG.getMergeValues({Result, Chain}, dl);
8469         } else {
8470           // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8471           // FIXME: generated code sucks.
8472           SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8473           True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8474           True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8475           SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8476           return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8477         }
8478       }
8479     }
8480 
8481     return SDValue();
8482   }
8483 
8484   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8485     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8486 
8487   ReuseLoadInfo RLI;
8488   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8489 
8490   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8491                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8492 }
8493 
8494 // We're trying to insert a regular store, S, and then a load, L. If the
8495 // incoming value, O, is a load, we might just be able to have our load use the
8496 // address used by O. However, we don't know if anything else will store to
8497 // that address before we can load from it. To prevent this situation, we need
8498 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8499 // the same chain operand as O, we create a token factor from the chain results
8500 // of O and L, and we replace all uses of O's chain result with that token
8501 // factor (see spliceIntoChain below for this last part).
8502 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8503                                             ReuseLoadInfo &RLI,
8504                                             SelectionDAG &DAG,
8505                                             ISD::LoadExtType ET) const {
8506   // Conservatively skip reusing for constrained FP nodes.
8507   if (Op->isStrictFPOpcode())
8508     return false;
8509 
8510   SDLoc dl(Op);
8511   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8512                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8513   if (ET == ISD::NON_EXTLOAD &&
8514       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8515       isOperationLegalOrCustom(Op.getOpcode(),
8516                                Op.getOperand(0).getValueType())) {
8517 
8518     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8519     return true;
8520   }
8521 
8522   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8523   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8524       LD->isNonTemporal())
8525     return false;
8526   if (LD->getMemoryVT() != MemVT)
8527     return false;
8528 
8529   // If the result of the load is an illegal type, then we can't build a
8530   // valid chain for reuse since the legalised loads and token factor node that
8531   // ties the legalised loads together uses a different output chain then the
8532   // illegal load.
8533   if (!isTypeLegal(LD->getValueType(0)))
8534     return false;
8535 
8536   RLI.Ptr = LD->getBasePtr();
8537   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8538     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8539            "Non-pre-inc AM on PPC?");
8540     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8541                           LD->getOffset());
8542   }
8543 
8544   RLI.Chain = LD->getChain();
8545   RLI.MPI = LD->getPointerInfo();
8546   RLI.IsDereferenceable = LD->isDereferenceable();
8547   RLI.IsInvariant = LD->isInvariant();
8548   RLI.Alignment = LD->getAlign();
8549   RLI.AAInfo = LD->getAAInfo();
8550   RLI.Ranges = LD->getRanges();
8551 
8552   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8553   return true;
8554 }
8555 
8556 // Given the head of the old chain, ResChain, insert a token factor containing
8557 // it and NewResChain, and make users of ResChain now be users of that token
8558 // factor.
8559 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8560 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8561                                         SDValue NewResChain,
8562                                         SelectionDAG &DAG) const {
8563   if (!ResChain)
8564     return;
8565 
8566   SDLoc dl(NewResChain);
8567 
8568   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8569                            NewResChain, DAG.getUNDEF(MVT::Other));
8570   assert(TF.getNode() != NewResChain.getNode() &&
8571          "A new TF really is required here");
8572 
8573   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8574   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8575 }
8576 
8577 /// Analyze profitability of direct move
8578 /// prefer float load to int load plus direct move
8579 /// when there is no integer use of int load
8580 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8581   SDNode *Origin = Op.getOperand(0).getNode();
8582   if (Origin->getOpcode() != ISD::LOAD)
8583     return true;
8584 
8585   // If there is no LXSIBZX/LXSIHZX, like Power8,
8586   // prefer direct move if the memory size is 1 or 2 bytes.
8587   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8588   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8589     return true;
8590 
8591   for (SDNode::use_iterator UI = Origin->use_begin(),
8592                             UE = Origin->use_end();
8593        UI != UE; ++UI) {
8594 
8595     // Only look at the users of the loaded value.
8596     if (UI.getUse().get().getResNo() != 0)
8597       continue;
8598 
8599     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8600         UI->getOpcode() != ISD::UINT_TO_FP &&
8601         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8602         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8603       return true;
8604   }
8605 
8606   return false;
8607 }
8608 
8609 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8610                               const PPCSubtarget &Subtarget,
8611                               SDValue Chain = SDValue()) {
8612   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8613                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8614   SDLoc dl(Op);
8615 
8616   // TODO: Any other flags to propagate?
8617   SDNodeFlags Flags;
8618   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8619 
8620   // If we have FCFIDS, then use it when converting to single-precision.
8621   // Otherwise, convert to double-precision and then round.
8622   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8623   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8624                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8625   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8626   if (Op->isStrictFPOpcode()) {
8627     if (!Chain)
8628       Chain = Op.getOperand(0);
8629     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8630                        DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8631   } else
8632     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8633 }
8634 
8635 /// Custom lowers integer to floating point conversions to use
8636 /// the direct move instructions available in ISA 2.07 to avoid the
8637 /// need for load/store combinations.
8638 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8639                                                     SelectionDAG &DAG,
8640                                                     const SDLoc &dl) const {
8641   assert((Op.getValueType() == MVT::f32 ||
8642           Op.getValueType() == MVT::f64) &&
8643          "Invalid floating point type as target of conversion");
8644   assert(Subtarget.hasFPCVT() &&
8645          "Int to FP conversions with direct moves require FPCVT");
8646   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8647   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8648   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8649                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8650   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8651   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8652   return convertIntToFP(Op, Mov, DAG, Subtarget);
8653 }
8654 
8655 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8656 
8657   EVT VecVT = Vec.getValueType();
8658   assert(VecVT.isVector() && "Expected a vector type.");
8659   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8660 
8661   EVT EltVT = VecVT.getVectorElementType();
8662   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8663   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8664 
8665   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8666   SmallVector<SDValue, 16> Ops(NumConcat);
8667   Ops[0] = Vec;
8668   SDValue UndefVec = DAG.getUNDEF(VecVT);
8669   for (unsigned i = 1; i < NumConcat; ++i)
8670     Ops[i] = UndefVec;
8671 
8672   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8673 }
8674 
8675 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8676                                                 const SDLoc &dl) const {
8677   bool IsStrict = Op->isStrictFPOpcode();
8678   unsigned Opc = Op.getOpcode();
8679   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8680   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8681           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8682          "Unexpected conversion type");
8683   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8684          "Supports conversions to v2f64/v4f32 only.");
8685 
8686   // TODO: Any other flags to propagate?
8687   SDNodeFlags Flags;
8688   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8689 
8690   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8691   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8692 
8693   SDValue Wide = widenVec(DAG, Src, dl);
8694   EVT WideVT = Wide.getValueType();
8695   unsigned WideNumElts = WideVT.getVectorNumElements();
8696   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8697 
8698   SmallVector<int, 16> ShuffV;
8699   for (unsigned i = 0; i < WideNumElts; ++i)
8700     ShuffV.push_back(i + WideNumElts);
8701 
8702   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8703   int SaveElts = FourEltRes ? 4 : 2;
8704   if (Subtarget.isLittleEndian())
8705     for (int i = 0; i < SaveElts; i++)
8706       ShuffV[i * Stride] = i;
8707   else
8708     for (int i = 1; i <= SaveElts; i++)
8709       ShuffV[i * Stride - 1] = i - 1;
8710 
8711   SDValue ShuffleSrc2 =
8712       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8713   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8714 
8715   SDValue Extend;
8716   if (SignedConv) {
8717     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8718     EVT ExtVT = Src.getValueType();
8719     if (Subtarget.hasP9Altivec())
8720       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8721                                IntermediateVT.getVectorNumElements());
8722 
8723     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8724                          DAG.getValueType(ExtVT));
8725   } else
8726     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8727 
8728   if (IsStrict)
8729     return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8730                        {Op.getOperand(0), Extend}, Flags);
8731 
8732   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8733 }
8734 
8735 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8736                                           SelectionDAG &DAG) const {
8737   SDLoc dl(Op);
8738   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8739                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8740   bool IsStrict = Op->isStrictFPOpcode();
8741   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8742   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8743 
8744   // TODO: Any other flags to propagate?
8745   SDNodeFlags Flags;
8746   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8747 
8748   EVT InVT = Src.getValueType();
8749   EVT OutVT = Op.getValueType();
8750   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8751       isOperationCustom(Op.getOpcode(), InVT))
8752     return LowerINT_TO_FPVector(Op, DAG, dl);
8753 
8754   // Conversions to f128 are legal.
8755   if (Op.getValueType() == MVT::f128)
8756     return Subtarget.hasP9Vector() ? Op : SDValue();
8757 
8758   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8759   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8760     return SDValue();
8761 
8762   if (Src.getValueType() == MVT::i1) {
8763     SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8764                               DAG.getConstantFP(1.0, dl, Op.getValueType()),
8765                               DAG.getConstantFP(0.0, dl, Op.getValueType()));
8766     if (IsStrict)
8767       return DAG.getMergeValues({Sel, Chain}, dl);
8768     else
8769       return Sel;
8770   }
8771 
8772   // If we have direct moves, we can do all the conversion, skip the store/load
8773   // however, without FPCVT we can't do most conversions.
8774   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8775       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8776     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8777 
8778   assert((IsSigned || Subtarget.hasFPCVT()) &&
8779          "UINT_TO_FP is supported only with FPCVT");
8780 
8781   if (Src.getValueType() == MVT::i64) {
8782     SDValue SINT = Src;
8783     // When converting to single-precision, we actually need to convert
8784     // to double-precision first and then round to single-precision.
8785     // To avoid double-rounding effects during that operation, we have
8786     // to prepare the input operand.  Bits that might be truncated when
8787     // converting to double-precision are replaced by a bit that won't
8788     // be lost at this stage, but is below the single-precision rounding
8789     // position.
8790     //
8791     // However, if -enable-unsafe-fp-math is in effect, accept double
8792     // rounding to avoid the extra overhead.
8793     if (Op.getValueType() == MVT::f32 &&
8794         !Subtarget.hasFPCVT() &&
8795         !DAG.getTarget().Options.UnsafeFPMath) {
8796 
8797       // Twiddle input to make sure the low 11 bits are zero.  (If this
8798       // is the case, we are guaranteed the value will fit into the 53 bit
8799       // mantissa of an IEEE double-precision value without rounding.)
8800       // If any of those low 11 bits were not zero originally, make sure
8801       // bit 12 (value 2048) is set instead, so that the final rounding
8802       // to single-precision gets the correct result.
8803       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8804                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8805       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8806                           Round, DAG.getConstant(2047, dl, MVT::i64));
8807       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8808       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8809                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8810 
8811       // However, we cannot use that value unconditionally: if the magnitude
8812       // of the input value is small, the bit-twiddling we did above might
8813       // end up visibly changing the output.  Fortunately, in that case, we
8814       // don't need to twiddle bits since the original input will convert
8815       // exactly to double-precision floating-point already.  Therefore,
8816       // construct a conditional to use the original value if the top 11
8817       // bits are all sign-bit copies, and use the rounded value computed
8818       // above otherwise.
8819       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8820                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8821       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8822                          Cond, DAG.getConstant(1, dl, MVT::i64));
8823       Cond = DAG.getSetCC(
8824           dl,
8825           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8826           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8827 
8828       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8829     }
8830 
8831     ReuseLoadInfo RLI;
8832     SDValue Bits;
8833 
8834     MachineFunction &MF = DAG.getMachineFunction();
8835     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8836       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8837                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8838       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8839     } else if (Subtarget.hasLFIWAX() &&
8840                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8841       MachineMemOperand *MMO =
8842         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8843                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8844       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8845       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8846                                      DAG.getVTList(MVT::f64, MVT::Other),
8847                                      Ops, MVT::i32, MMO);
8848       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8849     } else if (Subtarget.hasFPCVT() &&
8850                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8851       MachineMemOperand *MMO =
8852         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8853                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8854       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8855       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8856                                      DAG.getVTList(MVT::f64, MVT::Other),
8857                                      Ops, MVT::i32, MMO);
8858       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8859     } else if (((Subtarget.hasLFIWAX() &&
8860                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8861                 (Subtarget.hasFPCVT() &&
8862                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8863                SINT.getOperand(0).getValueType() == MVT::i32) {
8864       MachineFrameInfo &MFI = MF.getFrameInfo();
8865       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8866 
8867       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8868       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8869 
8870       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8871                                    MachinePointerInfo::getFixedStack(
8872                                        DAG.getMachineFunction(), FrameIdx));
8873       Chain = Store;
8874 
8875       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8876              "Expected an i32 store");
8877 
8878       RLI.Ptr = FIdx;
8879       RLI.Chain = Chain;
8880       RLI.MPI =
8881           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8882       RLI.Alignment = Align(4);
8883 
8884       MachineMemOperand *MMO =
8885         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8886                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8887       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8888       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8889                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8890                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8891                                      Ops, MVT::i32, MMO);
8892       Chain = Bits.getValue(1);
8893     } else
8894       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8895 
8896     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8897     if (IsStrict)
8898       Chain = FP.getValue(1);
8899 
8900     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8901       if (IsStrict)
8902         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8903                          DAG.getVTList(MVT::f32, MVT::Other),
8904                          {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8905       else
8906         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8907                          DAG.getIntPtrConstant(0, dl));
8908     }
8909     return FP;
8910   }
8911 
8912   assert(Src.getValueType() == MVT::i32 &&
8913          "Unhandled INT_TO_FP type in custom expander!");
8914   // Since we only generate this in 64-bit mode, we can take advantage of
8915   // 64-bit registers.  In particular, sign extend the input value into the
8916   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8917   // then lfd it and fcfid it.
8918   MachineFunction &MF = DAG.getMachineFunction();
8919   MachineFrameInfo &MFI = MF.getFrameInfo();
8920   EVT PtrVT = getPointerTy(MF.getDataLayout());
8921 
8922   SDValue Ld;
8923   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8924     ReuseLoadInfo RLI;
8925     bool ReusingLoad;
8926     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8927       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8928       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8929 
8930       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8931                                    MachinePointerInfo::getFixedStack(
8932                                        DAG.getMachineFunction(), FrameIdx));
8933       Chain = Store;
8934 
8935       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8936              "Expected an i32 store");
8937 
8938       RLI.Ptr = FIdx;
8939       RLI.Chain = Chain;
8940       RLI.MPI =
8941           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8942       RLI.Alignment = Align(4);
8943     }
8944 
8945     MachineMemOperand *MMO =
8946       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8947                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8948     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8949     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8950                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8951                                  MVT::i32, MMO);
8952     Chain = Ld.getValue(1);
8953     if (ReusingLoad)
8954       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8955   } else {
8956     assert(Subtarget.isPPC64() &&
8957            "i32->FP without LFIWAX supported only on PPC64");
8958 
8959     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8960     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8961 
8962     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8963 
8964     // STD the extended value into the stack slot.
8965     SDValue Store = DAG.getStore(
8966         Chain, dl, Ext64, FIdx,
8967         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8968     Chain = Store;
8969 
8970     // Load the value as a double.
8971     Ld = DAG.getLoad(
8972         MVT::f64, dl, Chain, FIdx,
8973         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8974     Chain = Ld.getValue(1);
8975   }
8976 
8977   // FCFID it and return it.
8978   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8979   if (IsStrict)
8980     Chain = FP.getValue(1);
8981   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8982     if (IsStrict)
8983       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8984                        DAG.getVTList(MVT::f32, MVT::Other),
8985                        {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8986     else
8987       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8988                        DAG.getIntPtrConstant(0, dl));
8989   }
8990   return FP;
8991 }
8992 
8993 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8994                                             SelectionDAG &DAG) const {
8995   SDLoc dl(Op);
8996   /*
8997    The rounding mode is in bits 30:31 of FPSR, and has the following
8998    settings:
8999      00 Round to nearest
9000      01 Round to 0
9001      10 Round to +inf
9002      11 Round to -inf
9003 
9004   FLT_ROUNDS, on the other hand, expects the following:
9005     -1 Undefined
9006      0 Round to 0
9007      1 Round to nearest
9008      2 Round to +inf
9009      3 Round to -inf
9010 
9011   To perform the conversion, we do:
9012     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
9013   */
9014 
9015   MachineFunction &MF = DAG.getMachineFunction();
9016   EVT VT = Op.getValueType();
9017   EVT PtrVT = getPointerTy(MF.getDataLayout());
9018 
9019   // Save FP Control Word to register
9020   SDValue Chain = Op.getOperand(0);
9021   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
9022   Chain = MFFS.getValue(1);
9023 
9024   SDValue CWD;
9025   if (isTypeLegal(MVT::i64)) {
9026     CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
9027                       DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
9028   } else {
9029     // Save FP register to stack slot
9030     int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
9031     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
9032     Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
9033 
9034     // Load FP Control Word from low 32 bits of stack slot.
9035     assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) &&
9036            "Stack slot adjustment is valid only on big endian subtargets!");
9037     SDValue Four = DAG.getConstant(4, dl, PtrVT);
9038     SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
9039     CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
9040     Chain = CWD.getValue(1);
9041   }
9042 
9043   // Transform as necessary
9044   SDValue CWD1 =
9045     DAG.getNode(ISD::AND, dl, MVT::i32,
9046                 CWD, DAG.getConstant(3, dl, MVT::i32));
9047   SDValue CWD2 =
9048     DAG.getNode(ISD::SRL, dl, MVT::i32,
9049                 DAG.getNode(ISD::AND, dl, MVT::i32,
9050                             DAG.getNode(ISD::XOR, dl, MVT::i32,
9051                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
9052                             DAG.getConstant(3, dl, MVT::i32)),
9053                 DAG.getConstant(1, dl, MVT::i32));
9054 
9055   SDValue RetVal =
9056     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
9057 
9058   RetVal =
9059       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
9060                   dl, VT, RetVal);
9061 
9062   return DAG.getMergeValues({RetVal, Chain}, dl);
9063 }
9064 
9065 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
9066   EVT VT = Op.getValueType();
9067   unsigned BitWidth = VT.getSizeInBits();
9068   SDLoc dl(Op);
9069   assert(Op.getNumOperands() == 3 &&
9070          VT == Op.getOperand(1).getValueType() &&
9071          "Unexpected SHL!");
9072 
9073   // Expand into a bunch of logical ops.  Note that these ops
9074   // depend on the PPC behavior for oversized shift amounts.
9075   SDValue Lo = Op.getOperand(0);
9076   SDValue Hi = Op.getOperand(1);
9077   SDValue Amt = Op.getOperand(2);
9078   EVT AmtVT = Amt.getValueType();
9079 
9080   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
9081                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
9082   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
9083   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
9084   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
9085   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
9086                              DAG.getConstant(-BitWidth, dl, AmtVT));
9087   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
9088   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
9089   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
9090   SDValue OutOps[] = { OutLo, OutHi };
9091   return DAG.getMergeValues(OutOps, dl);
9092 }
9093 
9094 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
9095   EVT VT = Op.getValueType();
9096   SDLoc dl(Op);
9097   unsigned BitWidth = VT.getSizeInBits();
9098   assert(Op.getNumOperands() == 3 &&
9099          VT == Op.getOperand(1).getValueType() &&
9100          "Unexpected SRL!");
9101 
9102   // Expand into a bunch of logical ops.  Note that these ops
9103   // depend on the PPC behavior for oversized shift amounts.
9104   SDValue Lo = Op.getOperand(0);
9105   SDValue Hi = Op.getOperand(1);
9106   SDValue Amt = Op.getOperand(2);
9107   EVT AmtVT = Amt.getValueType();
9108 
9109   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
9110                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
9111   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
9112   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
9113   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
9114   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
9115                              DAG.getConstant(-BitWidth, dl, AmtVT));
9116   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
9117   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
9118   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
9119   SDValue OutOps[] = { OutLo, OutHi };
9120   return DAG.getMergeValues(OutOps, dl);
9121 }
9122 
9123 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
9124   SDLoc dl(Op);
9125   EVT VT = Op.getValueType();
9126   unsigned BitWidth = VT.getSizeInBits();
9127   assert(Op.getNumOperands() == 3 &&
9128          VT == Op.getOperand(1).getValueType() &&
9129          "Unexpected SRA!");
9130 
9131   // Expand into a bunch of logical ops, followed by a select_cc.
9132   SDValue Lo = Op.getOperand(0);
9133   SDValue Hi = Op.getOperand(1);
9134   SDValue Amt = Op.getOperand(2);
9135   EVT AmtVT = Amt.getValueType();
9136 
9137   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
9138                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
9139   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
9140   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
9141   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
9142   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
9143                              DAG.getConstant(-BitWidth, dl, AmtVT));
9144   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
9145   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
9146   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
9147                                   Tmp4, Tmp6, ISD::SETLE);
9148   SDValue OutOps[] = { OutLo, OutHi };
9149   return DAG.getMergeValues(OutOps, dl);
9150 }
9151 
9152 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
9153                                             SelectionDAG &DAG) const {
9154   SDLoc dl(Op);
9155   EVT VT = Op.getValueType();
9156   unsigned BitWidth = VT.getSizeInBits();
9157 
9158   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
9159   SDValue X = Op.getOperand(0);
9160   SDValue Y = Op.getOperand(1);
9161   SDValue Z = Op.getOperand(2);
9162   EVT AmtVT = Z.getValueType();
9163 
9164   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
9165   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
9166   // This is simpler than TargetLowering::expandFunnelShift because we can rely
9167   // on PowerPC shift by BW being well defined.
9168   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
9169                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
9170   SDValue SubZ =
9171       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
9172   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
9173   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
9174   return DAG.getNode(ISD::OR, dl, VT, X, Y);
9175 }
9176 
9177 //===----------------------------------------------------------------------===//
9178 // Vector related lowering.
9179 //
9180 
9181 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
9182 /// element size of SplatSize. Cast the result to VT.
9183 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
9184                                       SelectionDAG &DAG, const SDLoc &dl) {
9185   static const MVT VTys[] = { // canonical VT to use for each size.
9186     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
9187   };
9188 
9189   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
9190 
9191   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
9192   if (Val == ((1LU << (SplatSize * 8)) - 1)) {
9193     SplatSize = 1;
9194     Val = 0xFF;
9195   }
9196 
9197   EVT CanonicalVT = VTys[SplatSize-1];
9198 
9199   // Build a canonical splat for this value.
9200   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
9201 }
9202 
9203 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
9204 /// specified intrinsic ID.
9205 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
9206                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
9207   if (DestVT == MVT::Other) DestVT = Op.getValueType();
9208   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9209                      DAG.getConstant(IID, dl, MVT::i32), Op);
9210 }
9211 
9212 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
9213 /// specified intrinsic ID.
9214 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
9215                                 SelectionDAG &DAG, const SDLoc &dl,
9216                                 EVT DestVT = MVT::Other) {
9217   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
9218   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9219                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
9220 }
9221 
9222 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
9223 /// specified intrinsic ID.
9224 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
9225                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
9226                                 EVT DestVT = MVT::Other) {
9227   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
9228   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9229                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
9230 }
9231 
9232 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
9233 /// amount.  The result has the specified value type.
9234 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
9235                            SelectionDAG &DAG, const SDLoc &dl) {
9236   // Force LHS/RHS to be the right type.
9237   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
9238   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
9239 
9240   int Ops[16];
9241   for (unsigned i = 0; i != 16; ++i)
9242     Ops[i] = i + Amt;
9243   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
9244   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9245 }
9246 
9247 /// Do we have an efficient pattern in a .td file for this node?
9248 ///
9249 /// \param V - pointer to the BuildVectorSDNode being matched
9250 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
9251 ///
9252 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
9253 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
9254 /// the opposite is true (expansion is beneficial) are:
9255 /// - The node builds a vector out of integers that are not 32 or 64-bits
9256 /// - The node builds a vector out of constants
9257 /// - The node is a "load-and-splat"
9258 /// In all other cases, we will choose to keep the BUILD_VECTOR.
9259 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
9260                                             bool HasDirectMove,
9261                                             bool HasP8Vector) {
9262   EVT VecVT = V->getValueType(0);
9263   bool RightType = VecVT == MVT::v2f64 ||
9264     (HasP8Vector && VecVT == MVT::v4f32) ||
9265     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
9266   if (!RightType)
9267     return false;
9268 
9269   bool IsSplat = true;
9270   bool IsLoad = false;
9271   SDValue Op0 = V->getOperand(0);
9272 
9273   // This function is called in a block that confirms the node is not a constant
9274   // splat. So a constant BUILD_VECTOR here means the vector is built out of
9275   // different constants.
9276   if (V->isConstant())
9277     return false;
9278   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9279     if (V->getOperand(i).isUndef())
9280       return false;
9281     // We want to expand nodes that represent load-and-splat even if the
9282     // loaded value is a floating point truncation or conversion to int.
9283     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9284         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9285          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9286         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9287          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9288         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9289          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9290       IsLoad = true;
9291     // If the operands are different or the input is not a load and has more
9292     // uses than just this BV node, then it isn't a splat.
9293     if (V->getOperand(i) != Op0 ||
9294         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9295       IsSplat = false;
9296   }
9297   return !(IsSplat && IsLoad);
9298 }
9299 
9300 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9301 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9302 
9303   SDLoc dl(Op);
9304   SDValue Op0 = Op->getOperand(0);
9305 
9306   if ((Op.getValueType() != MVT::f128) ||
9307       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9308       (Op0.getOperand(0).getValueType() != MVT::i64) ||
9309       (Op0.getOperand(1).getValueType() != MVT::i64))
9310     return SDValue();
9311 
9312   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9313                      Op0.getOperand(1));
9314 }
9315 
9316 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9317   const SDValue *InputLoad = &Op;
9318   if (InputLoad->getOpcode() == ISD::BITCAST)
9319     InputLoad = &InputLoad->getOperand(0);
9320   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9321       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9322     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9323     InputLoad = &InputLoad->getOperand(0);
9324   }
9325   if (InputLoad->getOpcode() != ISD::LOAD)
9326     return nullptr;
9327   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9328   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9329 }
9330 
9331 // Convert the argument APFloat to a single precision APFloat if there is no
9332 // loss in information during the conversion to single precision APFloat and the
9333 // resulting number is not a denormal number. Return true if successful.
9334 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9335   APFloat APFloatToConvert = ArgAPFloat;
9336   bool LosesInfo = true;
9337   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9338                            &LosesInfo);
9339   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9340   if (Success)
9341     ArgAPFloat = APFloatToConvert;
9342   return Success;
9343 }
9344 
9345 // Bitcast the argument APInt to a double and convert it to a single precision
9346 // APFloat, bitcast the APFloat to an APInt and assign it to the original
9347 // argument if there is no loss in information during the conversion from
9348 // double to single precision APFloat and the resulting number is not a denormal
9349 // number. Return true if successful.
9350 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9351   double DpValue = ArgAPInt.bitsToDouble();
9352   APFloat APFloatDp(DpValue);
9353   bool Success = convertToNonDenormSingle(APFloatDp);
9354   if (Success)
9355     ArgAPInt = APFloatDp.bitcastToAPInt();
9356   return Success;
9357 }
9358 
9359 // If this is a case we can't handle, return null and let the default
9360 // expansion code take care of it.  If we CAN select this case, and if it
9361 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9362 // this case more efficiently than a constant pool load, lower it to the
9363 // sequence of ops that should be used.
9364 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9365                                              SelectionDAG &DAG) const {
9366   SDLoc dl(Op);
9367   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9368   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9369 
9370   // Check if this is a splat of a constant value.
9371   APInt APSplatBits, APSplatUndef;
9372   unsigned SplatBitSize;
9373   bool HasAnyUndefs;
9374   bool BVNIsConstantSplat =
9375       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9376                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9377 
9378   // If it is a splat of a double, check if we can shrink it to a 32 bit
9379   // non-denormal float which when converted back to double gives us the same
9380   // double. This is to exploit the XXSPLTIDP instruction.
9381   if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() &&
9382       (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) &&
9383       convertToNonDenormSingle(APSplatBits)) {
9384     SDValue SplatNode = DAG.getNode(
9385         PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9386         DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9387     return DAG.getBitcast(Op.getValueType(), SplatNode);
9388   }
9389 
9390   if (!BVNIsConstantSplat || SplatBitSize > 32) {
9391 
9392     bool IsPermutedLoad = false;
9393     const SDValue *InputLoad =
9394         getNormalLoadInput(Op.getOperand(0), IsPermutedLoad);
9395     // Handle load-and-splat patterns as we have instructions that will do this
9396     // in one go.
9397     if (InputLoad && DAG.isSplatValue(Op, true)) {
9398       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9399 
9400       // We have handling for 4 and 8 byte elements.
9401       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9402 
9403       // Checking for a single use of this load, we have to check for vector
9404       // width (128 bits) / ElementSize uses (since each operand of the
9405       // BUILD_VECTOR is a separate use of the value.
9406       unsigned NumUsesOfInputLD = 128 / ElementSize;
9407       for (SDValue BVInOp : Op->ops())
9408         if (BVInOp.isUndef())
9409           NumUsesOfInputLD--;
9410       assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
9411       if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
9412           ((Subtarget.hasVSX() && ElementSize == 64) ||
9413            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9414         SDValue Ops[] = {
9415           LD->getChain(),    // Chain
9416           LD->getBasePtr(),  // Ptr
9417           DAG.getValueType(Op.getValueType()) // VT
9418         };
9419         SDValue LdSplt = DAG.getMemIntrinsicNode(
9420             PPCISD::LD_SPLAT, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
9421             Ops, LD->getMemoryVT(), LD->getMemOperand());
9422         // Replace all uses of the output chain of the original load with the
9423         // output chain of the new load.
9424         DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
9425                                       LdSplt.getValue(1));
9426         return LdSplt;
9427       }
9428     }
9429 
9430     // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
9431     // 32-bits can be lowered to VSX instructions under certain conditions.
9432     // Without VSX, there is no pattern more efficient than expanding the node.
9433     if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
9434         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9435                                         Subtarget.hasP8Vector()))
9436       return Op;
9437     return SDValue();
9438   }
9439 
9440   uint64_t SplatBits = APSplatBits.getZExtValue();
9441   uint64_t SplatUndef = APSplatUndef.getZExtValue();
9442   unsigned SplatSize = SplatBitSize / 8;
9443 
9444   // First, handle single instruction cases.
9445 
9446   // All zeros?
9447   if (SplatBits == 0) {
9448     // Canonicalize all zero vectors to be v4i32.
9449     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9450       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9451       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9452     }
9453     return Op;
9454   }
9455 
9456   // We have XXSPLTIW for constant splats four bytes wide.
9457   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9458   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9459   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9460   // turned into a 4-byte splat of 0xABABABAB.
9461   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9462     return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
9463                                   Op.getValueType(), DAG, dl);
9464 
9465   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9466     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9467                                   dl);
9468 
9469   // We have XXSPLTIB for constant splats one byte wide.
9470   if (Subtarget.hasP9Vector() && SplatSize == 1)
9471     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9472                                   dl);
9473 
9474   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9475   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9476                     (32-SplatBitSize));
9477   if (SextVal >= -16 && SextVal <= 15)
9478     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9479                                   dl);
9480 
9481   // Two instruction sequences.
9482 
9483   // If this value is in the range [-32,30] and is even, use:
9484   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9485   // If this value is in the range [17,31] and is odd, use:
9486   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9487   // If this value is in the range [-31,-17] and is odd, use:
9488   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9489   // Note the last two are three-instruction sequences.
9490   if (SextVal >= -32 && SextVal <= 31) {
9491     // To avoid having these optimizations undone by constant folding,
9492     // we convert to a pseudo that will be expanded later into one of
9493     // the above forms.
9494     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9495     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9496               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9497     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9498     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9499     if (VT == Op.getValueType())
9500       return RetVal;
9501     else
9502       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9503   }
9504 
9505   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9506   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9507   // for fneg/fabs.
9508   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9509     // Make -1 and vspltisw -1:
9510     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9511 
9512     // Make the VSLW intrinsic, computing 0x8000_0000.
9513     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9514                                    OnesV, DAG, dl);
9515 
9516     // xor by OnesV to invert it.
9517     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9518     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9519   }
9520 
9521   // Check to see if this is a wide variety of vsplti*, binop self cases.
9522   static const signed char SplatCsts[] = {
9523     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9524     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9525   };
9526 
9527   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9528     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9529     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9530     int i = SplatCsts[idx];
9531 
9532     // Figure out what shift amount will be used by altivec if shifted by i in
9533     // this splat size.
9534     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9535 
9536     // vsplti + shl self.
9537     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9538       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9539       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9540         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9541         Intrinsic::ppc_altivec_vslw
9542       };
9543       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9544       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9545     }
9546 
9547     // vsplti + srl self.
9548     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9549       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9550       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9551         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9552         Intrinsic::ppc_altivec_vsrw
9553       };
9554       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9555       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9556     }
9557 
9558     // vsplti + sra self.
9559     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9560       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9561       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9562         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9563         Intrinsic::ppc_altivec_vsraw
9564       };
9565       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9566       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9567     }
9568 
9569     // vsplti + rol self.
9570     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9571                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9572       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9573       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9574         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9575         Intrinsic::ppc_altivec_vrlw
9576       };
9577       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9578       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9579     }
9580 
9581     // t = vsplti c, result = vsldoi t, t, 1
9582     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9583       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9584       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9585       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9586     }
9587     // t = vsplti c, result = vsldoi t, t, 2
9588     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9589       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9590       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9591       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9592     }
9593     // t = vsplti c, result = vsldoi t, t, 3
9594     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9595       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9596       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9597       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9598     }
9599   }
9600 
9601   return SDValue();
9602 }
9603 
9604 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9605 /// the specified operations to build the shuffle.
9606 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9607                                       SDValue RHS, SelectionDAG &DAG,
9608                                       const SDLoc &dl) {
9609   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9610   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9611   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9612 
9613   enum {
9614     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9615     OP_VMRGHW,
9616     OP_VMRGLW,
9617     OP_VSPLTISW0,
9618     OP_VSPLTISW1,
9619     OP_VSPLTISW2,
9620     OP_VSPLTISW3,
9621     OP_VSLDOI4,
9622     OP_VSLDOI8,
9623     OP_VSLDOI12
9624   };
9625 
9626   if (OpNum == OP_COPY) {
9627     if (LHSID == (1*9+2)*9+3) return LHS;
9628     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9629     return RHS;
9630   }
9631 
9632   SDValue OpLHS, OpRHS;
9633   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9634   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9635 
9636   int ShufIdxs[16];
9637   switch (OpNum) {
9638   default: llvm_unreachable("Unknown i32 permute!");
9639   case OP_VMRGHW:
9640     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9641     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9642     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9643     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9644     break;
9645   case OP_VMRGLW:
9646     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9647     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9648     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9649     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9650     break;
9651   case OP_VSPLTISW0:
9652     for (unsigned i = 0; i != 16; ++i)
9653       ShufIdxs[i] = (i&3)+0;
9654     break;
9655   case OP_VSPLTISW1:
9656     for (unsigned i = 0; i != 16; ++i)
9657       ShufIdxs[i] = (i&3)+4;
9658     break;
9659   case OP_VSPLTISW2:
9660     for (unsigned i = 0; i != 16; ++i)
9661       ShufIdxs[i] = (i&3)+8;
9662     break;
9663   case OP_VSPLTISW3:
9664     for (unsigned i = 0; i != 16; ++i)
9665       ShufIdxs[i] = (i&3)+12;
9666     break;
9667   case OP_VSLDOI4:
9668     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9669   case OP_VSLDOI8:
9670     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9671   case OP_VSLDOI12:
9672     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9673   }
9674   EVT VT = OpLHS.getValueType();
9675   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9676   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9677   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9678   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9679 }
9680 
9681 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9682 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9683 /// SDValue.
9684 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9685                                            SelectionDAG &DAG) const {
9686   const unsigned BytesInVector = 16;
9687   bool IsLE = Subtarget.isLittleEndian();
9688   SDLoc dl(N);
9689   SDValue V1 = N->getOperand(0);
9690   SDValue V2 = N->getOperand(1);
9691   unsigned ShiftElts = 0, InsertAtByte = 0;
9692   bool Swap = false;
9693 
9694   // Shifts required to get the byte we want at element 7.
9695   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9696                                    0, 15, 14, 13, 12, 11, 10, 9};
9697   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9698                                 1, 2,  3,  4,  5,  6,  7,  8};
9699 
9700   ArrayRef<int> Mask = N->getMask();
9701   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9702 
9703   // For each mask element, find out if we're just inserting something
9704   // from V2 into V1 or vice versa.
9705   // Possible permutations inserting an element from V2 into V1:
9706   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9707   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9708   //   ...
9709   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9710   // Inserting from V1 into V2 will be similar, except mask range will be
9711   // [16,31].
9712 
9713   bool FoundCandidate = false;
9714   // If both vector operands for the shuffle are the same vector, the mask
9715   // will contain only elements from the first one and the second one will be
9716   // undef.
9717   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9718   // Go through the mask of half-words to find an element that's being moved
9719   // from one vector to the other.
9720   for (unsigned i = 0; i < BytesInVector; ++i) {
9721     unsigned CurrentElement = Mask[i];
9722     // If 2nd operand is undefined, we should only look for element 7 in the
9723     // Mask.
9724     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9725       continue;
9726 
9727     bool OtherElementsInOrder = true;
9728     // Examine the other elements in the Mask to see if they're in original
9729     // order.
9730     for (unsigned j = 0; j < BytesInVector; ++j) {
9731       if (j == i)
9732         continue;
9733       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9734       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9735       // in which we always assume we're always picking from the 1st operand.
9736       int MaskOffset =
9737           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9738       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9739         OtherElementsInOrder = false;
9740         break;
9741       }
9742     }
9743     // If other elements are in original order, we record the number of shifts
9744     // we need to get the element we want into element 7. Also record which byte
9745     // in the vector we should insert into.
9746     if (OtherElementsInOrder) {
9747       // If 2nd operand is undefined, we assume no shifts and no swapping.
9748       if (V2.isUndef()) {
9749         ShiftElts = 0;
9750         Swap = false;
9751       } else {
9752         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9753         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9754                          : BigEndianShifts[CurrentElement & 0xF];
9755         Swap = CurrentElement < BytesInVector;
9756       }
9757       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9758       FoundCandidate = true;
9759       break;
9760     }
9761   }
9762 
9763   if (!FoundCandidate)
9764     return SDValue();
9765 
9766   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9767   // optionally with VECSHL if shift is required.
9768   if (Swap)
9769     std::swap(V1, V2);
9770   if (V2.isUndef())
9771     V2 = V1;
9772   if (ShiftElts) {
9773     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9774                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9775     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9776                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9777   }
9778   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9779                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9780 }
9781 
9782 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9783 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9784 /// SDValue.
9785 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9786                                            SelectionDAG &DAG) const {
9787   const unsigned NumHalfWords = 8;
9788   const unsigned BytesInVector = NumHalfWords * 2;
9789   // Check that the shuffle is on half-words.
9790   if (!isNByteElemShuffleMask(N, 2, 1))
9791     return SDValue();
9792 
9793   bool IsLE = Subtarget.isLittleEndian();
9794   SDLoc dl(N);
9795   SDValue V1 = N->getOperand(0);
9796   SDValue V2 = N->getOperand(1);
9797   unsigned ShiftElts = 0, InsertAtByte = 0;
9798   bool Swap = false;
9799 
9800   // Shifts required to get the half-word we want at element 3.
9801   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9802   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9803 
9804   uint32_t Mask = 0;
9805   uint32_t OriginalOrderLow = 0x1234567;
9806   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9807   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9808   // 32-bit space, only need 4-bit nibbles per element.
9809   for (unsigned i = 0; i < NumHalfWords; ++i) {
9810     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9811     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9812   }
9813 
9814   // For each mask element, find out if we're just inserting something
9815   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9816   // from V2 into V1:
9817   //   X, 1, 2, 3, 4, 5, 6, 7
9818   //   0, X, 2, 3, 4, 5, 6, 7
9819   //   0, 1, X, 3, 4, 5, 6, 7
9820   //   0, 1, 2, X, 4, 5, 6, 7
9821   //   0, 1, 2, 3, X, 5, 6, 7
9822   //   0, 1, 2, 3, 4, X, 6, 7
9823   //   0, 1, 2, 3, 4, 5, X, 7
9824   //   0, 1, 2, 3, 4, 5, 6, X
9825   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9826 
9827   bool FoundCandidate = false;
9828   // Go through the mask of half-words to find an element that's being moved
9829   // from one vector to the other.
9830   for (unsigned i = 0; i < NumHalfWords; ++i) {
9831     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9832     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9833     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9834     uint32_t TargetOrder = 0x0;
9835 
9836     // If both vector operands for the shuffle are the same vector, the mask
9837     // will contain only elements from the first one and the second one will be
9838     // undef.
9839     if (V2.isUndef()) {
9840       ShiftElts = 0;
9841       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9842       TargetOrder = OriginalOrderLow;
9843       Swap = false;
9844       // Skip if not the correct element or mask of other elements don't equal
9845       // to our expected order.
9846       if (MaskOneElt == VINSERTHSrcElem &&
9847           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9848         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9849         FoundCandidate = true;
9850         break;
9851       }
9852     } else { // If both operands are defined.
9853       // Target order is [8,15] if the current mask is between [0,7].
9854       TargetOrder =
9855           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9856       // Skip if mask of other elements don't equal our expected order.
9857       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9858         // We only need the last 3 bits for the number of shifts.
9859         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9860                          : BigEndianShifts[MaskOneElt & 0x7];
9861         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9862         Swap = MaskOneElt < NumHalfWords;
9863         FoundCandidate = true;
9864         break;
9865       }
9866     }
9867   }
9868 
9869   if (!FoundCandidate)
9870     return SDValue();
9871 
9872   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9873   // optionally with VECSHL if shift is required.
9874   if (Swap)
9875     std::swap(V1, V2);
9876   if (V2.isUndef())
9877     V2 = V1;
9878   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9879   if (ShiftElts) {
9880     // Double ShiftElts because we're left shifting on v16i8 type.
9881     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9882                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9883     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9884     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9885                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9886     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9887   }
9888   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9889   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9890                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9891   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9892 }
9893 
9894 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9895 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9896 /// return the default SDValue.
9897 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9898                                               SelectionDAG &DAG) const {
9899   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9900   // to v16i8. Peek through the bitcasts to get the actual operands.
9901   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9902   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9903 
9904   auto ShuffleMask = SVN->getMask();
9905   SDValue VecShuffle(SVN, 0);
9906   SDLoc DL(SVN);
9907 
9908   // Check that we have a four byte shuffle.
9909   if (!isNByteElemShuffleMask(SVN, 4, 1))
9910     return SDValue();
9911 
9912   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9913   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9914     std::swap(LHS, RHS);
9915     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9916     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9917   }
9918 
9919   // Ensure that the RHS is a vector of constants.
9920   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9921   if (!BVN)
9922     return SDValue();
9923 
9924   // Check if RHS is a splat of 4-bytes (or smaller).
9925   APInt APSplatValue, APSplatUndef;
9926   unsigned SplatBitSize;
9927   bool HasAnyUndefs;
9928   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9929                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9930       SplatBitSize > 32)
9931     return SDValue();
9932 
9933   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9934   // The instruction splats a constant C into two words of the source vector
9935   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9936   // Thus we check that the shuffle mask is the equivalent  of
9937   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9938   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9939   // within each word are consecutive, so we only need to check the first byte.
9940   SDValue Index;
9941   bool IsLE = Subtarget.isLittleEndian();
9942   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9943       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9944        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9945     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9946   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9947            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9948             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9949     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9950   else
9951     return SDValue();
9952 
9953   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9954   // for XXSPLTI32DX.
9955   unsigned SplatVal = APSplatValue.getZExtValue();
9956   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9957     SplatVal |= (SplatVal << SplatBitSize);
9958 
9959   SDValue SplatNode = DAG.getNode(
9960       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9961       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9962   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9963 }
9964 
9965 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9966 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9967 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9968 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9969 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9970   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9971   assert(Op.getValueType() == MVT::v1i128 &&
9972          "Only set v1i128 as custom, other type shouldn't reach here!");
9973   SDLoc dl(Op);
9974   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9975   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9976   unsigned SHLAmt = N1.getConstantOperandVal(0);
9977   if (SHLAmt % 8 == 0) {
9978     SmallVector<int, 16> Mask(16, 0);
9979     std::iota(Mask.begin(), Mask.end(), 0);
9980     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9981     if (SDValue Shuffle =
9982             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9983                                  DAG.getUNDEF(MVT::v16i8), Mask))
9984       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9985   }
9986   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9987   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9988                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9989   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9990                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9991   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9992   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9993 }
9994 
9995 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9996 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9997 /// return the code it can be lowered into.  Worst case, it can always be
9998 /// lowered into a vperm.
9999 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
10000                                                SelectionDAG &DAG) const {
10001   SDLoc dl(Op);
10002   SDValue V1 = Op.getOperand(0);
10003   SDValue V2 = Op.getOperand(1);
10004   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10005 
10006   // Any nodes that were combined in the target-independent combiner prior
10007   // to vector legalization will not be sent to the target combine. Try to
10008   // combine it here.
10009   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
10010     if (!isa<ShuffleVectorSDNode>(NewShuffle))
10011       return NewShuffle;
10012     Op = NewShuffle;
10013     SVOp = cast<ShuffleVectorSDNode>(Op);
10014     V1 = Op.getOperand(0);
10015     V2 = Op.getOperand(1);
10016   }
10017   EVT VT = Op.getValueType();
10018   bool isLittleEndian = Subtarget.isLittleEndian();
10019 
10020   unsigned ShiftElts, InsertAtByte;
10021   bool Swap = false;
10022 
10023   // If this is a load-and-splat, we can do that with a single instruction
10024   // in some cases. However if the load has multiple uses, we don't want to
10025   // combine it because that will just produce multiple loads.
10026   bool IsPermutedLoad = false;
10027   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
10028   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
10029       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
10030       InputLoad->hasOneUse()) {
10031     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
10032     int SplatIdx =
10033       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
10034 
10035     // The splat index for permuted loads will be in the left half of the vector
10036     // which is strictly wider than the loaded value by 8 bytes. So we need to
10037     // adjust the splat index to point to the correct address in memory.
10038     if (IsPermutedLoad) {
10039       assert(isLittleEndian && "Unexpected permuted load on big endian target");
10040       SplatIdx += IsFourByte ? 2 : 1;
10041       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
10042              "Splat of a value outside of the loaded memory");
10043     }
10044 
10045     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
10046     // For 4-byte load-and-splat, we need Power9.
10047     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
10048       uint64_t Offset = 0;
10049       if (IsFourByte)
10050         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
10051       else
10052         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
10053 
10054       SDValue BasePtr = LD->getBasePtr();
10055       if (Offset != 0)
10056         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
10057                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
10058       SDValue Ops[] = {
10059         LD->getChain(),    // Chain
10060         BasePtr,           // BasePtr
10061         DAG.getValueType(Op.getValueType()) // VT
10062       };
10063       SDVTList VTL =
10064         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
10065       SDValue LdSplt =
10066         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
10067                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
10068       DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
10069       if (LdSplt.getValueType() != SVOp->getValueType(0))
10070         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
10071       return LdSplt;
10072     }
10073   }
10074   if (Subtarget.hasP9Vector() &&
10075       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
10076                            isLittleEndian)) {
10077     if (Swap)
10078       std::swap(V1, V2);
10079     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10080     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
10081     if (ShiftElts) {
10082       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
10083                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
10084       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
10085                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10086       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
10087     }
10088     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
10089                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
10090     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
10091   }
10092 
10093   if (Subtarget.hasPrefixInstrs()) {
10094     SDValue SplatInsertNode;
10095     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
10096       return SplatInsertNode;
10097   }
10098 
10099   if (Subtarget.hasP9Altivec()) {
10100     SDValue NewISDNode;
10101     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
10102       return NewISDNode;
10103 
10104     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
10105       return NewISDNode;
10106   }
10107 
10108   if (Subtarget.hasVSX() &&
10109       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
10110     if (Swap)
10111       std::swap(V1, V2);
10112     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10113     SDValue Conv2 =
10114         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
10115 
10116     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
10117                               DAG.getConstant(ShiftElts, dl, MVT::i32));
10118     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
10119   }
10120 
10121   if (Subtarget.hasVSX() &&
10122     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
10123     if (Swap)
10124       std::swap(V1, V2);
10125     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10126     SDValue Conv2 =
10127         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
10128 
10129     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
10130                               DAG.getConstant(ShiftElts, dl, MVT::i32));
10131     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
10132   }
10133 
10134   if (Subtarget.hasP9Vector()) {
10135      if (PPC::isXXBRHShuffleMask(SVOp)) {
10136       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10137       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
10138       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
10139     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
10140       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10141       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
10142       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
10143     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
10144       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10145       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
10146       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
10147     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
10148       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
10149       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
10150       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
10151     }
10152   }
10153 
10154   if (Subtarget.hasVSX()) {
10155     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
10156       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
10157 
10158       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10159       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
10160                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
10161       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
10162     }
10163 
10164     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
10165     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
10166       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
10167       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
10168       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
10169     }
10170   }
10171 
10172   // Cases that are handled by instructions that take permute immediates
10173   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
10174   // selected by the instruction selector.
10175   if (V2.isUndef()) {
10176     if (PPC::isSplatShuffleMask(SVOp, 1) ||
10177         PPC::isSplatShuffleMask(SVOp, 2) ||
10178         PPC::isSplatShuffleMask(SVOp, 4) ||
10179         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
10180         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
10181         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
10182         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
10183         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
10184         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
10185         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
10186         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
10187         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
10188         (Subtarget.hasP8Altivec() && (
10189          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
10190          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
10191          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
10192       return Op;
10193     }
10194   }
10195 
10196   // Altivec has a variety of "shuffle immediates" that take two vector inputs
10197   // and produce a fixed permutation.  If any of these match, do not lower to
10198   // VPERM.
10199   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
10200   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10201       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10202       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
10203       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10204       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10205       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10206       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10207       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10208       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10209       (Subtarget.hasP8Altivec() && (
10210        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10211        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
10212        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
10213     return Op;
10214 
10215   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
10216   // perfect shuffle table to emit an optimal matching sequence.
10217   ArrayRef<int> PermMask = SVOp->getMask();
10218 
10219   unsigned PFIndexes[4];
10220   bool isFourElementShuffle = true;
10221   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
10222     unsigned EltNo = 8;   // Start out undef.
10223     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
10224       if (PermMask[i*4+j] < 0)
10225         continue;   // Undef, ignore it.
10226 
10227       unsigned ByteSource = PermMask[i*4+j];
10228       if ((ByteSource & 3) != j) {
10229         isFourElementShuffle = false;
10230         break;
10231       }
10232 
10233       if (EltNo == 8) {
10234         EltNo = ByteSource/4;
10235       } else if (EltNo != ByteSource/4) {
10236         isFourElementShuffle = false;
10237         break;
10238       }
10239     }
10240     PFIndexes[i] = EltNo;
10241   }
10242 
10243   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
10244   // perfect shuffle vector to determine if it is cost effective to do this as
10245   // discrete instructions, or whether we should use a vperm.
10246   // For now, we skip this for little endian until such time as we have a
10247   // little-endian perfect shuffle table.
10248   if (isFourElementShuffle && !isLittleEndian) {
10249     // Compute the index in the perfect shuffle table.
10250     unsigned PFTableIndex =
10251       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
10252 
10253     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10254     unsigned Cost  = (PFEntry >> 30);
10255 
10256     // Determining when to avoid vperm is tricky.  Many things affect the cost
10257     // of vperm, particularly how many times the perm mask needs to be computed.
10258     // For example, if the perm mask can be hoisted out of a loop or is already
10259     // used (perhaps because there are multiple permutes with the same shuffle
10260     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
10261     // the loop requires an extra register.
10262     //
10263     // As a compromise, we only emit discrete instructions if the shuffle can be
10264     // generated in 3 or fewer operations.  When we have loop information
10265     // available, if this block is within a loop, we should avoid using vperm
10266     // for 3-operation perms and use a constant pool load instead.
10267     if (Cost < 3)
10268       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10269   }
10270 
10271   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10272   // vector that will get spilled to the constant pool.
10273   if (V2.isUndef()) V2 = V1;
10274 
10275   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10276   // that it is in input element units, not in bytes.  Convert now.
10277 
10278   // For little endian, the order of the input vectors is reversed, and
10279   // the permutation mask is complemented with respect to 31.  This is
10280   // necessary to produce proper semantics with the big-endian-biased vperm
10281   // instruction.
10282   EVT EltVT = V1.getValueType().getVectorElementType();
10283   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
10284 
10285   SmallVector<SDValue, 16> ResultMask;
10286   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10287     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10288 
10289     for (unsigned j = 0; j != BytesPerElement; ++j)
10290       if (isLittleEndian)
10291         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
10292                                              dl, MVT::i32));
10293       else
10294         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
10295                                              MVT::i32));
10296   }
10297 
10298   ShufflesHandledWithVPERM++;
10299   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10300   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
10301   LLVM_DEBUG(SVOp->dump());
10302   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
10303   LLVM_DEBUG(VPermMask.dump());
10304 
10305   if (isLittleEndian)
10306     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10307                        V2, V1, VPermMask);
10308   else
10309     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10310                        V1, V2, VPermMask);
10311 }
10312 
10313 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10314 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10315 /// information about the intrinsic.
10316 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10317                                  bool &isDot, const PPCSubtarget &Subtarget) {
10318   unsigned IntrinsicID =
10319       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10320   CompareOpc = -1;
10321   isDot = false;
10322   switch (IntrinsicID) {
10323   default:
10324     return false;
10325   // Comparison predicates.
10326   case Intrinsic::ppc_altivec_vcmpbfp_p:
10327     CompareOpc = 966;
10328     isDot = true;
10329     break;
10330   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10331     CompareOpc = 198;
10332     isDot = true;
10333     break;
10334   case Intrinsic::ppc_altivec_vcmpequb_p:
10335     CompareOpc = 6;
10336     isDot = true;
10337     break;
10338   case Intrinsic::ppc_altivec_vcmpequh_p:
10339     CompareOpc = 70;
10340     isDot = true;
10341     break;
10342   case Intrinsic::ppc_altivec_vcmpequw_p:
10343     CompareOpc = 134;
10344     isDot = true;
10345     break;
10346   case Intrinsic::ppc_altivec_vcmpequd_p:
10347     if (Subtarget.hasP8Altivec()) {
10348       CompareOpc = 199;
10349       isDot = true;
10350     } else
10351       return false;
10352     break;
10353   case Intrinsic::ppc_altivec_vcmpneb_p:
10354   case Intrinsic::ppc_altivec_vcmpneh_p:
10355   case Intrinsic::ppc_altivec_vcmpnew_p:
10356   case Intrinsic::ppc_altivec_vcmpnezb_p:
10357   case Intrinsic::ppc_altivec_vcmpnezh_p:
10358   case Intrinsic::ppc_altivec_vcmpnezw_p:
10359     if (Subtarget.hasP9Altivec()) {
10360       switch (IntrinsicID) {
10361       default:
10362         llvm_unreachable("Unknown comparison intrinsic.");
10363       case Intrinsic::ppc_altivec_vcmpneb_p:
10364         CompareOpc = 7;
10365         break;
10366       case Intrinsic::ppc_altivec_vcmpneh_p:
10367         CompareOpc = 71;
10368         break;
10369       case Intrinsic::ppc_altivec_vcmpnew_p:
10370         CompareOpc = 135;
10371         break;
10372       case Intrinsic::ppc_altivec_vcmpnezb_p:
10373         CompareOpc = 263;
10374         break;
10375       case Intrinsic::ppc_altivec_vcmpnezh_p:
10376         CompareOpc = 327;
10377         break;
10378       case Intrinsic::ppc_altivec_vcmpnezw_p:
10379         CompareOpc = 391;
10380         break;
10381       }
10382       isDot = true;
10383     } else
10384       return false;
10385     break;
10386   case Intrinsic::ppc_altivec_vcmpgefp_p:
10387     CompareOpc = 454;
10388     isDot = true;
10389     break;
10390   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10391     CompareOpc = 710;
10392     isDot = true;
10393     break;
10394   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10395     CompareOpc = 774;
10396     isDot = true;
10397     break;
10398   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10399     CompareOpc = 838;
10400     isDot = true;
10401     break;
10402   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10403     CompareOpc = 902;
10404     isDot = true;
10405     break;
10406   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10407     if (Subtarget.hasP8Altivec()) {
10408       CompareOpc = 967;
10409       isDot = true;
10410     } else
10411       return false;
10412     break;
10413   case Intrinsic::ppc_altivec_vcmpgtub_p:
10414     CompareOpc = 518;
10415     isDot = true;
10416     break;
10417   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10418     CompareOpc = 582;
10419     isDot = true;
10420     break;
10421   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10422     CompareOpc = 646;
10423     isDot = true;
10424     break;
10425   case Intrinsic::ppc_altivec_vcmpgtud_p:
10426     if (Subtarget.hasP8Altivec()) {
10427       CompareOpc = 711;
10428       isDot = true;
10429     } else
10430       return false;
10431     break;
10432 
10433   case Intrinsic::ppc_altivec_vcmpequq:
10434   case Intrinsic::ppc_altivec_vcmpgtsq:
10435   case Intrinsic::ppc_altivec_vcmpgtuq:
10436     if (!Subtarget.isISA3_1())
10437       return false;
10438     switch (IntrinsicID) {
10439     default:
10440       llvm_unreachable("Unknown comparison intrinsic.");
10441     case Intrinsic::ppc_altivec_vcmpequq:
10442       CompareOpc = 455;
10443       break;
10444     case Intrinsic::ppc_altivec_vcmpgtsq:
10445       CompareOpc = 903;
10446       break;
10447     case Intrinsic::ppc_altivec_vcmpgtuq:
10448       CompareOpc = 647;
10449       break;
10450     }
10451     break;
10452 
10453   // VSX predicate comparisons use the same infrastructure
10454   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10455   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10456   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10457   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10458   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10459   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10460     if (Subtarget.hasVSX()) {
10461       switch (IntrinsicID) {
10462       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10463         CompareOpc = 99;
10464         break;
10465       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10466         CompareOpc = 115;
10467         break;
10468       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10469         CompareOpc = 107;
10470         break;
10471       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10472         CompareOpc = 67;
10473         break;
10474       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10475         CompareOpc = 83;
10476         break;
10477       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10478         CompareOpc = 75;
10479         break;
10480       }
10481       isDot = true;
10482     } else
10483       return false;
10484     break;
10485 
10486   // Normal Comparisons.
10487   case Intrinsic::ppc_altivec_vcmpbfp:
10488     CompareOpc = 966;
10489     break;
10490   case Intrinsic::ppc_altivec_vcmpeqfp:
10491     CompareOpc = 198;
10492     break;
10493   case Intrinsic::ppc_altivec_vcmpequb:
10494     CompareOpc = 6;
10495     break;
10496   case Intrinsic::ppc_altivec_vcmpequh:
10497     CompareOpc = 70;
10498     break;
10499   case Intrinsic::ppc_altivec_vcmpequw:
10500     CompareOpc = 134;
10501     break;
10502   case Intrinsic::ppc_altivec_vcmpequd:
10503     if (Subtarget.hasP8Altivec())
10504       CompareOpc = 199;
10505     else
10506       return false;
10507     break;
10508   case Intrinsic::ppc_altivec_vcmpneb:
10509   case Intrinsic::ppc_altivec_vcmpneh:
10510   case Intrinsic::ppc_altivec_vcmpnew:
10511   case Intrinsic::ppc_altivec_vcmpnezb:
10512   case Intrinsic::ppc_altivec_vcmpnezh:
10513   case Intrinsic::ppc_altivec_vcmpnezw:
10514     if (Subtarget.hasP9Altivec())
10515       switch (IntrinsicID) {
10516       default:
10517         llvm_unreachable("Unknown comparison intrinsic.");
10518       case Intrinsic::ppc_altivec_vcmpneb:
10519         CompareOpc = 7;
10520         break;
10521       case Intrinsic::ppc_altivec_vcmpneh:
10522         CompareOpc = 71;
10523         break;
10524       case Intrinsic::ppc_altivec_vcmpnew:
10525         CompareOpc = 135;
10526         break;
10527       case Intrinsic::ppc_altivec_vcmpnezb:
10528         CompareOpc = 263;
10529         break;
10530       case Intrinsic::ppc_altivec_vcmpnezh:
10531         CompareOpc = 327;
10532         break;
10533       case Intrinsic::ppc_altivec_vcmpnezw:
10534         CompareOpc = 391;
10535         break;
10536       }
10537     else
10538       return false;
10539     break;
10540   case Intrinsic::ppc_altivec_vcmpgefp:
10541     CompareOpc = 454;
10542     break;
10543   case Intrinsic::ppc_altivec_vcmpgtfp:
10544     CompareOpc = 710;
10545     break;
10546   case Intrinsic::ppc_altivec_vcmpgtsb:
10547     CompareOpc = 774;
10548     break;
10549   case Intrinsic::ppc_altivec_vcmpgtsh:
10550     CompareOpc = 838;
10551     break;
10552   case Intrinsic::ppc_altivec_vcmpgtsw:
10553     CompareOpc = 902;
10554     break;
10555   case Intrinsic::ppc_altivec_vcmpgtsd:
10556     if (Subtarget.hasP8Altivec())
10557       CompareOpc = 967;
10558     else
10559       return false;
10560     break;
10561   case Intrinsic::ppc_altivec_vcmpgtub:
10562     CompareOpc = 518;
10563     break;
10564   case Intrinsic::ppc_altivec_vcmpgtuh:
10565     CompareOpc = 582;
10566     break;
10567   case Intrinsic::ppc_altivec_vcmpgtuw:
10568     CompareOpc = 646;
10569     break;
10570   case Intrinsic::ppc_altivec_vcmpgtud:
10571     if (Subtarget.hasP8Altivec())
10572       CompareOpc = 711;
10573     else
10574       return false;
10575     break;
10576   case Intrinsic::ppc_altivec_vcmpequq_p:
10577   case Intrinsic::ppc_altivec_vcmpgtsq_p:
10578   case Intrinsic::ppc_altivec_vcmpgtuq_p:
10579     if (!Subtarget.isISA3_1())
10580       return false;
10581     switch (IntrinsicID) {
10582     default:
10583       llvm_unreachable("Unknown comparison intrinsic.");
10584     case Intrinsic::ppc_altivec_vcmpequq_p:
10585       CompareOpc = 455;
10586       break;
10587     case Intrinsic::ppc_altivec_vcmpgtsq_p:
10588       CompareOpc = 903;
10589       break;
10590     case Intrinsic::ppc_altivec_vcmpgtuq_p:
10591       CompareOpc = 647;
10592       break;
10593     }
10594     isDot = true;
10595     break;
10596   }
10597   return true;
10598 }
10599 
10600 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10601 /// lower, do it, otherwise return null.
10602 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10603                                                    SelectionDAG &DAG) const {
10604   unsigned IntrinsicID =
10605     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10606 
10607   SDLoc dl(Op);
10608 
10609   switch (IntrinsicID) {
10610   case Intrinsic::thread_pointer:
10611     // Reads the thread pointer register, used for __builtin_thread_pointer.
10612     if (Subtarget.isPPC64())
10613       return DAG.getRegister(PPC::X13, MVT::i64);
10614     return DAG.getRegister(PPC::R2, MVT::i32);
10615 
10616   case Intrinsic::ppc_mma_disassemble_acc:
10617   case Intrinsic::ppc_mma_disassemble_pair: {
10618     int NumVecs = 2;
10619     SDValue WideVec = Op.getOperand(1);
10620     if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
10621       NumVecs = 4;
10622       WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
10623     }
10624     SmallVector<SDValue, 4> RetOps;
10625     for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
10626       SDValue Extract = DAG.getNode(
10627           PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
10628           DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
10629                                                      : VecNo,
10630                           dl, MVT::i64));
10631       RetOps.push_back(Extract);
10632     }
10633     return DAG.getMergeValues(RetOps, dl);
10634   }
10635   }
10636 
10637   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10638   // opcode number of the comparison.
10639   int CompareOpc;
10640   bool isDot;
10641   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10642     return SDValue();    // Don't custom lower most intrinsics.
10643 
10644   // If this is a non-dot comparison, make the VCMP node and we are done.
10645   if (!isDot) {
10646     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10647                               Op.getOperand(1), Op.getOperand(2),
10648                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10649     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10650   }
10651 
10652   // Create the PPCISD altivec 'dot' comparison node.
10653   SDValue Ops[] = {
10654     Op.getOperand(2),  // LHS
10655     Op.getOperand(3),  // RHS
10656     DAG.getConstant(CompareOpc, dl, MVT::i32)
10657   };
10658   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10659   SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
10660 
10661   // Now that we have the comparison, emit a copy from the CR to a GPR.
10662   // This is flagged to the above dot comparison.
10663   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10664                                 DAG.getRegister(PPC::CR6, MVT::i32),
10665                                 CompNode.getValue(1));
10666 
10667   // Unpack the result based on how the target uses it.
10668   unsigned BitNo;   // Bit # of CR6.
10669   bool InvertBit;   // Invert result?
10670   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10671   default:  // Can't happen, don't crash on invalid number though.
10672   case 0:   // Return the value of the EQ bit of CR6.
10673     BitNo = 0; InvertBit = false;
10674     break;
10675   case 1:   // Return the inverted value of the EQ bit of CR6.
10676     BitNo = 0; InvertBit = true;
10677     break;
10678   case 2:   // Return the value of the LT bit of CR6.
10679     BitNo = 2; InvertBit = false;
10680     break;
10681   case 3:   // Return the inverted value of the LT bit of CR6.
10682     BitNo = 2; InvertBit = true;
10683     break;
10684   }
10685 
10686   // Shift the bit into the low position.
10687   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10688                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10689   // Isolate the bit.
10690   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10691                       DAG.getConstant(1, dl, MVT::i32));
10692 
10693   // If we are supposed to, toggle the bit.
10694   if (InvertBit)
10695     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10696                         DAG.getConstant(1, dl, MVT::i32));
10697   return Flags;
10698 }
10699 
10700 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10701                                                SelectionDAG &DAG) const {
10702   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10703   // the beginning of the argument list.
10704   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10705   SDLoc DL(Op);
10706   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10707   case Intrinsic::ppc_cfence: {
10708     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10709     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10710     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10711                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10712                                                   Op.getOperand(ArgStart + 1)),
10713                                       Op.getOperand(0)),
10714                    0);
10715   }
10716   default:
10717     break;
10718   }
10719   return SDValue();
10720 }
10721 
10722 // Lower scalar BSWAP64 to xxbrd.
10723 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10724   SDLoc dl(Op);
10725   // MTVSRDD
10726   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10727                    Op.getOperand(0));
10728   // XXBRD
10729   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10730   // MFVSRD
10731   int VectorIndex = 0;
10732   if (Subtarget.isLittleEndian())
10733     VectorIndex = 1;
10734   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10735                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10736   return Op;
10737 }
10738 
10739 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10740 // compared to a value that is atomically loaded (atomic loads zero-extend).
10741 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10742                                                 SelectionDAG &DAG) const {
10743   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10744          "Expecting an atomic compare-and-swap here.");
10745   SDLoc dl(Op);
10746   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10747   EVT MemVT = AtomicNode->getMemoryVT();
10748   if (MemVT.getSizeInBits() >= 32)
10749     return Op;
10750 
10751   SDValue CmpOp = Op.getOperand(2);
10752   // If this is already correctly zero-extended, leave it alone.
10753   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10754   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10755     return Op;
10756 
10757   // Clear the high bits of the compare operand.
10758   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10759   SDValue NewCmpOp =
10760     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10761                 DAG.getConstant(MaskVal, dl, MVT::i32));
10762 
10763   // Replace the existing compare operand with the properly zero-extended one.
10764   SmallVector<SDValue, 4> Ops;
10765   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10766     Ops.push_back(AtomicNode->getOperand(i));
10767   Ops[2] = NewCmpOp;
10768   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10769   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10770   auto NodeTy =
10771     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10772   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10773 }
10774 
10775 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10776                                                  SelectionDAG &DAG) const {
10777   SDLoc dl(Op);
10778   // Create a stack slot that is 16-byte aligned.
10779   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10780   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10781   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10782   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10783 
10784   // Store the input value into Value#0 of the stack slot.
10785   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10786                                MachinePointerInfo());
10787   // Load it out.
10788   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10789 }
10790 
10791 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10792                                                   SelectionDAG &DAG) const {
10793   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10794          "Should only be called for ISD::INSERT_VECTOR_ELT");
10795 
10796   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10797   // We have legal lowering for constant indices but not for variable ones.
10798   if (!C)
10799     return SDValue();
10800 
10801   EVT VT = Op.getValueType();
10802   SDLoc dl(Op);
10803   SDValue V1 = Op.getOperand(0);
10804   SDValue V2 = Op.getOperand(1);
10805   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10806   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10807     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10808     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10809     unsigned InsertAtElement = C->getZExtValue();
10810     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10811     if (Subtarget.isLittleEndian()) {
10812       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10813     }
10814     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10815                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10816   }
10817   return Op;
10818 }
10819 
10820 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10821                                            SelectionDAG &DAG) const {
10822   SDLoc dl(Op);
10823   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10824   SDValue LoadChain = LN->getChain();
10825   SDValue BasePtr = LN->getBasePtr();
10826   EVT VT = Op.getValueType();
10827 
10828   if (VT != MVT::v256i1 && VT != MVT::v512i1)
10829     return Op;
10830 
10831   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10832   // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
10833   // 2 or 4 vsx registers.
10834   assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
10835          "Type unsupported without MMA");
10836   assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10837          "Type unsupported without paired vector support");
10838   Align Alignment = LN->getAlign();
10839   SmallVector<SDValue, 4> Loads;
10840   SmallVector<SDValue, 4> LoadChains;
10841   unsigned NumVecs = VT.getSizeInBits() / 128;
10842   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10843     SDValue Load =
10844         DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
10845                     LN->getPointerInfo().getWithOffset(Idx * 16),
10846                     commonAlignment(Alignment, Idx * 16),
10847                     LN->getMemOperand()->getFlags(), LN->getAAInfo());
10848     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10849                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10850     Loads.push_back(Load);
10851     LoadChains.push_back(Load.getValue(1));
10852   }
10853   if (Subtarget.isLittleEndian()) {
10854     std::reverse(Loads.begin(), Loads.end());
10855     std::reverse(LoadChains.begin(), LoadChains.end());
10856   }
10857   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10858   SDValue Value =
10859       DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
10860                   dl, VT, Loads);
10861   SDValue RetOps[] = {Value, TF};
10862   return DAG.getMergeValues(RetOps, dl);
10863 }
10864 
10865 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10866                                             SelectionDAG &DAG) const {
10867   SDLoc dl(Op);
10868   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10869   SDValue StoreChain = SN->getChain();
10870   SDValue BasePtr = SN->getBasePtr();
10871   SDValue Value = SN->getValue();
10872   EVT StoreVT = Value.getValueType();
10873 
10874   if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
10875     return Op;
10876 
10877   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10878   // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
10879   // underlying registers individually.
10880   assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
10881          "Type unsupported without MMA");
10882   assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10883          "Type unsupported without paired vector support");
10884   Align Alignment = SN->getAlign();
10885   SmallVector<SDValue, 4> Stores;
10886   unsigned NumVecs = 2;
10887   if (StoreVT == MVT::v512i1) {
10888     Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
10889     NumVecs = 4;
10890   }
10891   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10892     unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
10893     SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
10894                               DAG.getConstant(VecNum, dl, MVT::i64));
10895     SDValue Store =
10896         DAG.getStore(StoreChain, dl, Elt, BasePtr,
10897                      SN->getPointerInfo().getWithOffset(Idx * 16),
10898                      commonAlignment(Alignment, Idx * 16),
10899                      SN->getMemOperand()->getFlags(), SN->getAAInfo());
10900     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10901                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10902     Stores.push_back(Store);
10903   }
10904   SDValue TF = DAG.getTokenFactor(dl, Stores);
10905   return TF;
10906 }
10907 
10908 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10909   SDLoc dl(Op);
10910   if (Op.getValueType() == MVT::v4i32) {
10911     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10912 
10913     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10914     // +16 as shift amt.
10915     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10916     SDValue RHSSwap =   // = vrlw RHS, 16
10917       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10918 
10919     // Shrinkify inputs to v8i16.
10920     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10921     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10922     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10923 
10924     // Low parts multiplied together, generating 32-bit results (we ignore the
10925     // top parts).
10926     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10927                                         LHS, RHS, DAG, dl, MVT::v4i32);
10928 
10929     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10930                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10931     // Shift the high parts up 16 bits.
10932     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10933                               Neg16, DAG, dl);
10934     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10935   } else if (Op.getValueType() == MVT::v16i8) {
10936     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10937     bool isLittleEndian = Subtarget.isLittleEndian();
10938 
10939     // Multiply the even 8-bit parts, producing 16-bit sums.
10940     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10941                                            LHS, RHS, DAG, dl, MVT::v8i16);
10942     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10943 
10944     // Multiply the odd 8-bit parts, producing 16-bit sums.
10945     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10946                                           LHS, RHS, DAG, dl, MVT::v8i16);
10947     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10948 
10949     // Merge the results together.  Because vmuleub and vmuloub are
10950     // instructions with a big-endian bias, we must reverse the
10951     // element numbering and reverse the meaning of "odd" and "even"
10952     // when generating little endian code.
10953     int Ops[16];
10954     for (unsigned i = 0; i != 8; ++i) {
10955       if (isLittleEndian) {
10956         Ops[i*2  ] = 2*i;
10957         Ops[i*2+1] = 2*i+16;
10958       } else {
10959         Ops[i*2  ] = 2*i+1;
10960         Ops[i*2+1] = 2*i+1+16;
10961       }
10962     }
10963     if (isLittleEndian)
10964       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10965     else
10966       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10967   } else {
10968     llvm_unreachable("Unknown mul to lower!");
10969   }
10970 }
10971 
10972 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10973   bool IsStrict = Op->isStrictFPOpcode();
10974   if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
10975       !Subtarget.hasP9Vector())
10976     return SDValue();
10977 
10978   return Op;
10979 }
10980 
10981 // Custom lowering for fpext vf32 to v2f64
10982 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10983 
10984   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10985          "Should only be called for ISD::FP_EXTEND");
10986 
10987   // FIXME: handle extends from half precision float vectors on P9.
10988   // We only want to custom lower an extend from v2f32 to v2f64.
10989   if (Op.getValueType() != MVT::v2f64 ||
10990       Op.getOperand(0).getValueType() != MVT::v2f32)
10991     return SDValue();
10992 
10993   SDLoc dl(Op);
10994   SDValue Op0 = Op.getOperand(0);
10995 
10996   switch (Op0.getOpcode()) {
10997   default:
10998     return SDValue();
10999   case ISD::EXTRACT_SUBVECTOR: {
11000     assert(Op0.getNumOperands() == 2 &&
11001            isa<ConstantSDNode>(Op0->getOperand(1)) &&
11002            "Node should have 2 operands with second one being a constant!");
11003 
11004     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
11005       return SDValue();
11006 
11007     // Custom lower is only done for high or low doubleword.
11008     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
11009     if (Idx % 2 != 0)
11010       return SDValue();
11011 
11012     // Since input is v4f32, at this point Idx is either 0 or 2.
11013     // Shift to get the doubleword position we want.
11014     int DWord = Idx >> 1;
11015 
11016     // High and low word positions are different on little endian.
11017     if (Subtarget.isLittleEndian())
11018       DWord ^= 0x1;
11019 
11020     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
11021                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
11022   }
11023   case ISD::FADD:
11024   case ISD::FMUL:
11025   case ISD::FSUB: {
11026     SDValue NewLoad[2];
11027     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
11028       // Ensure both input are loads.
11029       SDValue LdOp = Op0.getOperand(i);
11030       if (LdOp.getOpcode() != ISD::LOAD)
11031         return SDValue();
11032       // Generate new load node.
11033       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
11034       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11035       NewLoad[i] = DAG.getMemIntrinsicNode(
11036           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11037           LD->getMemoryVT(), LD->getMemOperand());
11038     }
11039     SDValue NewOp =
11040         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
11041                     NewLoad[1], Op0.getNode()->getFlags());
11042     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
11043                        DAG.getConstant(0, dl, MVT::i32));
11044   }
11045   case ISD::LOAD: {
11046     LoadSDNode *LD = cast<LoadSDNode>(Op0);
11047     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11048     SDValue NewLd = DAG.getMemIntrinsicNode(
11049         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11050         LD->getMemoryVT(), LD->getMemOperand());
11051     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
11052                        DAG.getConstant(0, dl, MVT::i32));
11053   }
11054   }
11055   llvm_unreachable("ERROR:Should return for all cases within swtich.");
11056 }
11057 
11058 /// LowerOperation - Provide custom lowering hooks for some operations.
11059 ///
11060 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11061   switch (Op.getOpcode()) {
11062   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
11063   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11064   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11065   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11066   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11067   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11068   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11069   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11070   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11071 
11072   // Variable argument lowering.
11073   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11074   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11075   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11076 
11077   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
11078   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11079   case ISD::GET_DYNAMIC_AREA_OFFSET:
11080     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
11081 
11082   // Exception handling lowering.
11083   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
11084   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11085   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11086 
11087   case ISD::LOAD:               return LowerLOAD(Op, DAG);
11088   case ISD::STORE:              return LowerSTORE(Op, DAG);
11089   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
11090   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
11091   case ISD::STRICT_FP_TO_UINT:
11092   case ISD::STRICT_FP_TO_SINT:
11093   case ISD::FP_TO_UINT:
11094   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
11095   case ISD::STRICT_UINT_TO_FP:
11096   case ISD::STRICT_SINT_TO_FP:
11097   case ISD::UINT_TO_FP:
11098   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
11099   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11100 
11101   // Lower 64-bit shifts.
11102   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
11103   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
11104   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
11105 
11106   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
11107   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
11108 
11109   // Vector-related lowering.
11110   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11111   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11112   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11113   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11114   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11115   case ISD::MUL:                return LowerMUL(Op, DAG);
11116   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
11117   case ISD::STRICT_FP_ROUND:
11118   case ISD::FP_ROUND:
11119     return LowerFP_ROUND(Op, DAG);
11120   case ISD::ROTL:               return LowerROTL(Op, DAG);
11121 
11122   // For counter-based loop handling.
11123   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
11124 
11125   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11126 
11127   // Frame & Return address.
11128   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11129   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11130 
11131   case ISD::INTRINSIC_VOID:
11132     return LowerINTRINSIC_VOID(Op, DAG);
11133   case ISD::BSWAP:
11134     return LowerBSWAP(Op, DAG);
11135   case ISD::ATOMIC_CMP_SWAP:
11136     return LowerATOMIC_CMP_SWAP(Op, DAG);
11137   }
11138 }
11139 
11140 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
11141                                            SmallVectorImpl<SDValue>&Results,
11142                                            SelectionDAG &DAG) const {
11143   SDLoc dl(N);
11144   switch (N->getOpcode()) {
11145   default:
11146     llvm_unreachable("Do not know how to custom type legalize this operation!");
11147   case ISD::READCYCLECOUNTER: {
11148     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11149     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
11150 
11151     Results.push_back(
11152         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
11153     Results.push_back(RTB.getValue(2));
11154     break;
11155   }
11156   case ISD::INTRINSIC_W_CHAIN: {
11157     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
11158         Intrinsic::loop_decrement)
11159       break;
11160 
11161     assert(N->getValueType(0) == MVT::i1 &&
11162            "Unexpected result type for CTR decrement intrinsic");
11163     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11164                                  N->getValueType(0));
11165     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
11166     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
11167                                  N->getOperand(1));
11168 
11169     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
11170     Results.push_back(NewInt.getValue(1));
11171     break;
11172   }
11173   case ISD::VAARG: {
11174     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
11175       return;
11176 
11177     EVT VT = N->getValueType(0);
11178 
11179     if (VT == MVT::i64) {
11180       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
11181 
11182       Results.push_back(NewNode);
11183       Results.push_back(NewNode.getValue(1));
11184     }
11185     return;
11186   }
11187   case ISD::STRICT_FP_TO_SINT:
11188   case ISD::STRICT_FP_TO_UINT:
11189   case ISD::FP_TO_SINT:
11190   case ISD::FP_TO_UINT:
11191     // LowerFP_TO_INT() can only handle f32 and f64.
11192     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
11193         MVT::ppcf128)
11194       return;
11195     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
11196     return;
11197   case ISD::TRUNCATE: {
11198     if (!N->getValueType(0).isVector())
11199       return;
11200     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
11201     if (Lowered)
11202       Results.push_back(Lowered);
11203     return;
11204   }
11205   case ISD::FSHL:
11206   case ISD::FSHR:
11207     // Don't handle funnel shifts here.
11208     return;
11209   case ISD::BITCAST:
11210     // Don't handle bitcast here.
11211     return;
11212   case ISD::FP_EXTEND:
11213     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
11214     if (Lowered)
11215       Results.push_back(Lowered);
11216     return;
11217   }
11218 }
11219 
11220 //===----------------------------------------------------------------------===//
11221 //  Other Lowering Code
11222 //===----------------------------------------------------------------------===//
11223 
11224 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
11225   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11226   Function *Func = Intrinsic::getDeclaration(M, Id);
11227   return Builder.CreateCall(Func, {});
11228 }
11229 
11230 // The mappings for emitLeading/TrailingFence is taken from
11231 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11232 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11233                                                  Instruction *Inst,
11234                                                  AtomicOrdering Ord) const {
11235   if (Ord == AtomicOrdering::SequentiallyConsistent)
11236     return callIntrinsic(Builder, Intrinsic::ppc_sync);
11237   if (isReleaseOrStronger(Ord))
11238     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11239   return nullptr;
11240 }
11241 
11242 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11243                                                   Instruction *Inst,
11244                                                   AtomicOrdering Ord) const {
11245   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11246     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11247     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11248     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11249     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11250       return Builder.CreateCall(
11251           Intrinsic::getDeclaration(
11252               Builder.GetInsertBlock()->getParent()->getParent(),
11253               Intrinsic::ppc_cfence, {Inst->getType()}),
11254           {Inst});
11255     // FIXME: Can use isync for rmw operation.
11256     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11257   }
11258   return nullptr;
11259 }
11260 
11261 MachineBasicBlock *
11262 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11263                                     unsigned AtomicSize,
11264                                     unsigned BinOpcode,
11265                                     unsigned CmpOpcode,
11266                                     unsigned CmpPred) const {
11267   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11268   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11269 
11270   auto LoadMnemonic = PPC::LDARX;
11271   auto StoreMnemonic = PPC::STDCX;
11272   switch (AtomicSize) {
11273   default:
11274     llvm_unreachable("Unexpected size of atomic entity");
11275   case 1:
11276     LoadMnemonic = PPC::LBARX;
11277     StoreMnemonic = PPC::STBCX;
11278     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11279     break;
11280   case 2:
11281     LoadMnemonic = PPC::LHARX;
11282     StoreMnemonic = PPC::STHCX;
11283     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11284     break;
11285   case 4:
11286     LoadMnemonic = PPC::LWARX;
11287     StoreMnemonic = PPC::STWCX;
11288     break;
11289   case 8:
11290     LoadMnemonic = PPC::LDARX;
11291     StoreMnemonic = PPC::STDCX;
11292     break;
11293   }
11294 
11295   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11296   MachineFunction *F = BB->getParent();
11297   MachineFunction::iterator It = ++BB->getIterator();
11298 
11299   Register dest = MI.getOperand(0).getReg();
11300   Register ptrA = MI.getOperand(1).getReg();
11301   Register ptrB = MI.getOperand(2).getReg();
11302   Register incr = MI.getOperand(3).getReg();
11303   DebugLoc dl = MI.getDebugLoc();
11304 
11305   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11306   MachineBasicBlock *loop2MBB =
11307     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11308   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11309   F->insert(It, loopMBB);
11310   if (CmpOpcode)
11311     F->insert(It, loop2MBB);
11312   F->insert(It, exitMBB);
11313   exitMBB->splice(exitMBB->begin(), BB,
11314                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11315   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11316 
11317   MachineRegisterInfo &RegInfo = F->getRegInfo();
11318   Register TmpReg = (!BinOpcode) ? incr :
11319     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11320                                            : &PPC::GPRCRegClass);
11321 
11322   //  thisMBB:
11323   //   ...
11324   //   fallthrough --> loopMBB
11325   BB->addSuccessor(loopMBB);
11326 
11327   //  loopMBB:
11328   //   l[wd]arx dest, ptr
11329   //   add r0, dest, incr
11330   //   st[wd]cx. r0, ptr
11331   //   bne- loopMBB
11332   //   fallthrough --> exitMBB
11333 
11334   // For max/min...
11335   //  loopMBB:
11336   //   l[wd]arx dest, ptr
11337   //   cmpl?[wd] incr, dest
11338   //   bgt exitMBB
11339   //  loop2MBB:
11340   //   st[wd]cx. dest, ptr
11341   //   bne- loopMBB
11342   //   fallthrough --> exitMBB
11343 
11344   BB = loopMBB;
11345   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11346     .addReg(ptrA).addReg(ptrB);
11347   if (BinOpcode)
11348     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11349   if (CmpOpcode) {
11350     // Signed comparisons of byte or halfword values must be sign-extended.
11351     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11352       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11353       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11354               ExtReg).addReg(dest);
11355       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11356         .addReg(incr).addReg(ExtReg);
11357     } else
11358       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11359         .addReg(incr).addReg(dest);
11360 
11361     BuildMI(BB, dl, TII->get(PPC::BCC))
11362       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11363     BB->addSuccessor(loop2MBB);
11364     BB->addSuccessor(exitMBB);
11365     BB = loop2MBB;
11366   }
11367   BuildMI(BB, dl, TII->get(StoreMnemonic))
11368     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11369   BuildMI(BB, dl, TII->get(PPC::BCC))
11370     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11371   BB->addSuccessor(loopMBB);
11372   BB->addSuccessor(exitMBB);
11373 
11374   //  exitMBB:
11375   //   ...
11376   BB = exitMBB;
11377   return BB;
11378 }
11379 
11380 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11381     MachineInstr &MI, MachineBasicBlock *BB,
11382     bool is8bit, // operation
11383     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11384   // If we support part-word atomic mnemonics, just use them
11385   if (Subtarget.hasPartwordAtomics())
11386     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11387                             CmpPred);
11388 
11389   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11390   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11391   // In 64 bit mode we have to use 64 bits for addresses, even though the
11392   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11393   // registers without caring whether they're 32 or 64, but here we're
11394   // doing actual arithmetic on the addresses.
11395   bool is64bit = Subtarget.isPPC64();
11396   bool isLittleEndian = Subtarget.isLittleEndian();
11397   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11398 
11399   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11400   MachineFunction *F = BB->getParent();
11401   MachineFunction::iterator It = ++BB->getIterator();
11402 
11403   Register dest = MI.getOperand(0).getReg();
11404   Register ptrA = MI.getOperand(1).getReg();
11405   Register ptrB = MI.getOperand(2).getReg();
11406   Register incr = MI.getOperand(3).getReg();
11407   DebugLoc dl = MI.getDebugLoc();
11408 
11409   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11410   MachineBasicBlock *loop2MBB =
11411       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11412   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11413   F->insert(It, loopMBB);
11414   if (CmpOpcode)
11415     F->insert(It, loop2MBB);
11416   F->insert(It, exitMBB);
11417   exitMBB->splice(exitMBB->begin(), BB,
11418                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11419   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11420 
11421   MachineRegisterInfo &RegInfo = F->getRegInfo();
11422   const TargetRegisterClass *RC =
11423       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11424   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11425 
11426   Register PtrReg = RegInfo.createVirtualRegister(RC);
11427   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11428   Register ShiftReg =
11429       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11430   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11431   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11432   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11433   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11434   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11435   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11436   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11437   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11438   Register Ptr1Reg;
11439   Register TmpReg =
11440       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11441 
11442   //  thisMBB:
11443   //   ...
11444   //   fallthrough --> loopMBB
11445   BB->addSuccessor(loopMBB);
11446 
11447   // The 4-byte load must be aligned, while a char or short may be
11448   // anywhere in the word.  Hence all this nasty bookkeeping code.
11449   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11450   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11451   //   xori shift, shift1, 24 [16]
11452   //   rlwinm ptr, ptr1, 0, 0, 29
11453   //   slw incr2, incr, shift
11454   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11455   //   slw mask, mask2, shift
11456   //  loopMBB:
11457   //   lwarx tmpDest, ptr
11458   //   add tmp, tmpDest, incr2
11459   //   andc tmp2, tmpDest, mask
11460   //   and tmp3, tmp, mask
11461   //   or tmp4, tmp3, tmp2
11462   //   stwcx. tmp4, ptr
11463   //   bne- loopMBB
11464   //   fallthrough --> exitMBB
11465   //   srw dest, tmpDest, shift
11466   if (ptrA != ZeroReg) {
11467     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11468     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11469         .addReg(ptrA)
11470         .addReg(ptrB);
11471   } else {
11472     Ptr1Reg = ptrB;
11473   }
11474   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11475   // mode.
11476   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11477       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11478       .addImm(3)
11479       .addImm(27)
11480       .addImm(is8bit ? 28 : 27);
11481   if (!isLittleEndian)
11482     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11483         .addReg(Shift1Reg)
11484         .addImm(is8bit ? 24 : 16);
11485   if (is64bit)
11486     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11487         .addReg(Ptr1Reg)
11488         .addImm(0)
11489         .addImm(61);
11490   else
11491     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11492         .addReg(Ptr1Reg)
11493         .addImm(0)
11494         .addImm(0)
11495         .addImm(29);
11496   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11497   if (is8bit)
11498     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11499   else {
11500     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11501     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11502         .addReg(Mask3Reg)
11503         .addImm(65535);
11504   }
11505   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11506       .addReg(Mask2Reg)
11507       .addReg(ShiftReg);
11508 
11509   BB = loopMBB;
11510   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11511       .addReg(ZeroReg)
11512       .addReg(PtrReg);
11513   if (BinOpcode)
11514     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11515         .addReg(Incr2Reg)
11516         .addReg(TmpDestReg);
11517   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11518       .addReg(TmpDestReg)
11519       .addReg(MaskReg);
11520   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11521   if (CmpOpcode) {
11522     // For unsigned comparisons, we can directly compare the shifted values.
11523     // For signed comparisons we shift and sign extend.
11524     Register SReg = RegInfo.createVirtualRegister(GPRC);
11525     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11526         .addReg(TmpDestReg)
11527         .addReg(MaskReg);
11528     unsigned ValueReg = SReg;
11529     unsigned CmpReg = Incr2Reg;
11530     if (CmpOpcode == PPC::CMPW) {
11531       ValueReg = RegInfo.createVirtualRegister(GPRC);
11532       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11533           .addReg(SReg)
11534           .addReg(ShiftReg);
11535       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11536       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11537           .addReg(ValueReg);
11538       ValueReg = ValueSReg;
11539       CmpReg = incr;
11540     }
11541     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11542         .addReg(CmpReg)
11543         .addReg(ValueReg);
11544     BuildMI(BB, dl, TII->get(PPC::BCC))
11545         .addImm(CmpPred)
11546         .addReg(PPC::CR0)
11547         .addMBB(exitMBB);
11548     BB->addSuccessor(loop2MBB);
11549     BB->addSuccessor(exitMBB);
11550     BB = loop2MBB;
11551   }
11552   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11553   BuildMI(BB, dl, TII->get(PPC::STWCX))
11554       .addReg(Tmp4Reg)
11555       .addReg(ZeroReg)
11556       .addReg(PtrReg);
11557   BuildMI(BB, dl, TII->get(PPC::BCC))
11558       .addImm(PPC::PRED_NE)
11559       .addReg(PPC::CR0)
11560       .addMBB(loopMBB);
11561   BB->addSuccessor(loopMBB);
11562   BB->addSuccessor(exitMBB);
11563 
11564   //  exitMBB:
11565   //   ...
11566   BB = exitMBB;
11567   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11568       .addReg(TmpDestReg)
11569       .addReg(ShiftReg);
11570   return BB;
11571 }
11572 
11573 llvm::MachineBasicBlock *
11574 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11575                                     MachineBasicBlock *MBB) const {
11576   DebugLoc DL = MI.getDebugLoc();
11577   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11578   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11579 
11580   MachineFunction *MF = MBB->getParent();
11581   MachineRegisterInfo &MRI = MF->getRegInfo();
11582 
11583   const BasicBlock *BB = MBB->getBasicBlock();
11584   MachineFunction::iterator I = ++MBB->getIterator();
11585 
11586   Register DstReg = MI.getOperand(0).getReg();
11587   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11588   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11589   Register mainDstReg = MRI.createVirtualRegister(RC);
11590   Register restoreDstReg = MRI.createVirtualRegister(RC);
11591 
11592   MVT PVT = getPointerTy(MF->getDataLayout());
11593   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11594          "Invalid Pointer Size!");
11595   // For v = setjmp(buf), we generate
11596   //
11597   // thisMBB:
11598   //  SjLjSetup mainMBB
11599   //  bl mainMBB
11600   //  v_restore = 1
11601   //  b sinkMBB
11602   //
11603   // mainMBB:
11604   //  buf[LabelOffset] = LR
11605   //  v_main = 0
11606   //
11607   // sinkMBB:
11608   //  v = phi(main, restore)
11609   //
11610 
11611   MachineBasicBlock *thisMBB = MBB;
11612   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11613   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11614   MF->insert(I, mainMBB);
11615   MF->insert(I, sinkMBB);
11616 
11617   MachineInstrBuilder MIB;
11618 
11619   // Transfer the remainder of BB and its successor edges to sinkMBB.
11620   sinkMBB->splice(sinkMBB->begin(), MBB,
11621                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11622   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11623 
11624   // Note that the structure of the jmp_buf used here is not compatible
11625   // with that used by libc, and is not designed to be. Specifically, it
11626   // stores only those 'reserved' registers that LLVM does not otherwise
11627   // understand how to spill. Also, by convention, by the time this
11628   // intrinsic is called, Clang has already stored the frame address in the
11629   // first slot of the buffer and stack address in the third. Following the
11630   // X86 target code, we'll store the jump address in the second slot. We also
11631   // need to save the TOC pointer (R2) to handle jumps between shared
11632   // libraries, and that will be stored in the fourth slot. The thread
11633   // identifier (R13) is not affected.
11634 
11635   // thisMBB:
11636   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11637   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11638   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11639 
11640   // Prepare IP either in reg.
11641   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11642   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11643   Register BufReg = MI.getOperand(1).getReg();
11644 
11645   if (Subtarget.is64BitELFABI()) {
11646     setUsesTOCBasePtr(*MBB->getParent());
11647     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11648               .addReg(PPC::X2)
11649               .addImm(TOCOffset)
11650               .addReg(BufReg)
11651               .cloneMemRefs(MI);
11652   }
11653 
11654   // Naked functions never have a base pointer, and so we use r1. For all
11655   // other functions, this decision must be delayed until during PEI.
11656   unsigned BaseReg;
11657   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11658     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11659   else
11660     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11661 
11662   MIB = BuildMI(*thisMBB, MI, DL,
11663                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11664             .addReg(BaseReg)
11665             .addImm(BPOffset)
11666             .addReg(BufReg)
11667             .cloneMemRefs(MI);
11668 
11669   // Setup
11670   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11671   MIB.addRegMask(TRI->getNoPreservedMask());
11672 
11673   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11674 
11675   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11676           .addMBB(mainMBB);
11677   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11678 
11679   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11680   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11681 
11682   // mainMBB:
11683   //  mainDstReg = 0
11684   MIB =
11685       BuildMI(mainMBB, DL,
11686               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11687 
11688   // Store IP
11689   if (Subtarget.isPPC64()) {
11690     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11691             .addReg(LabelReg)
11692             .addImm(LabelOffset)
11693             .addReg(BufReg);
11694   } else {
11695     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11696             .addReg(LabelReg)
11697             .addImm(LabelOffset)
11698             .addReg(BufReg);
11699   }
11700   MIB.cloneMemRefs(MI);
11701 
11702   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11703   mainMBB->addSuccessor(sinkMBB);
11704 
11705   // sinkMBB:
11706   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11707           TII->get(PPC::PHI), DstReg)
11708     .addReg(mainDstReg).addMBB(mainMBB)
11709     .addReg(restoreDstReg).addMBB(thisMBB);
11710 
11711   MI.eraseFromParent();
11712   return sinkMBB;
11713 }
11714 
11715 MachineBasicBlock *
11716 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11717                                      MachineBasicBlock *MBB) const {
11718   DebugLoc DL = MI.getDebugLoc();
11719   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11720 
11721   MachineFunction *MF = MBB->getParent();
11722   MachineRegisterInfo &MRI = MF->getRegInfo();
11723 
11724   MVT PVT = getPointerTy(MF->getDataLayout());
11725   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11726          "Invalid Pointer Size!");
11727 
11728   const TargetRegisterClass *RC =
11729     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11730   Register Tmp = MRI.createVirtualRegister(RC);
11731   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11732   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11733   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11734   unsigned BP =
11735       (PVT == MVT::i64)
11736           ? PPC::X30
11737           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11738                                                               : PPC::R30);
11739 
11740   MachineInstrBuilder MIB;
11741 
11742   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11743   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11744   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11745   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11746 
11747   Register BufReg = MI.getOperand(0).getReg();
11748 
11749   // Reload FP (the jumped-to function may not have had a
11750   // frame pointer, and if so, then its r31 will be restored
11751   // as necessary).
11752   if (PVT == MVT::i64) {
11753     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11754             .addImm(0)
11755             .addReg(BufReg);
11756   } else {
11757     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11758             .addImm(0)
11759             .addReg(BufReg);
11760   }
11761   MIB.cloneMemRefs(MI);
11762 
11763   // Reload IP
11764   if (PVT == MVT::i64) {
11765     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11766             .addImm(LabelOffset)
11767             .addReg(BufReg);
11768   } else {
11769     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11770             .addImm(LabelOffset)
11771             .addReg(BufReg);
11772   }
11773   MIB.cloneMemRefs(MI);
11774 
11775   // Reload SP
11776   if (PVT == MVT::i64) {
11777     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11778             .addImm(SPOffset)
11779             .addReg(BufReg);
11780   } else {
11781     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11782             .addImm(SPOffset)
11783             .addReg(BufReg);
11784   }
11785   MIB.cloneMemRefs(MI);
11786 
11787   // Reload BP
11788   if (PVT == MVT::i64) {
11789     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11790             .addImm(BPOffset)
11791             .addReg(BufReg);
11792   } else {
11793     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11794             .addImm(BPOffset)
11795             .addReg(BufReg);
11796   }
11797   MIB.cloneMemRefs(MI);
11798 
11799   // Reload TOC
11800   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11801     setUsesTOCBasePtr(*MBB->getParent());
11802     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11803               .addImm(TOCOffset)
11804               .addReg(BufReg)
11805               .cloneMemRefs(MI);
11806   }
11807 
11808   // Jump
11809   BuildMI(*MBB, MI, DL,
11810           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11811   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11812 
11813   MI.eraseFromParent();
11814   return MBB;
11815 }
11816 
11817 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11818   // If the function specifically requests inline stack probes, emit them.
11819   if (MF.getFunction().hasFnAttribute("probe-stack"))
11820     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11821            "inline-asm";
11822   return false;
11823 }
11824 
11825 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11826   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11827   unsigned StackAlign = TFI->getStackAlignment();
11828   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11829          "Unexpected stack alignment");
11830   // The default stack probe size is 4096 if the function has no
11831   // stack-probe-size attribute.
11832   unsigned StackProbeSize = 4096;
11833   const Function &Fn = MF.getFunction();
11834   if (Fn.hasFnAttribute("stack-probe-size"))
11835     Fn.getFnAttribute("stack-probe-size")
11836         .getValueAsString()
11837         .getAsInteger(0, StackProbeSize);
11838   // Round down to the stack alignment.
11839   StackProbeSize &= ~(StackAlign - 1);
11840   return StackProbeSize ? StackProbeSize : StackAlign;
11841 }
11842 
11843 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11844 // into three phases. In the first phase, it uses pseudo instruction
11845 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11846 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11847 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11848 // MaxCallFrameSize so that it can calculate correct data area pointer.
11849 MachineBasicBlock *
11850 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11851                                     MachineBasicBlock *MBB) const {
11852   const bool isPPC64 = Subtarget.isPPC64();
11853   MachineFunction *MF = MBB->getParent();
11854   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11855   DebugLoc DL = MI.getDebugLoc();
11856   const unsigned ProbeSize = getStackProbeSize(*MF);
11857   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11858   MachineRegisterInfo &MRI = MF->getRegInfo();
11859   // The CFG of probing stack looks as
11860   //         +-----+
11861   //         | MBB |
11862   //         +--+--+
11863   //            |
11864   //       +----v----+
11865   //  +--->+ TestMBB +---+
11866   //  |    +----+----+   |
11867   //  |         |        |
11868   //  |   +-----v----+   |
11869   //  +---+ BlockMBB |   |
11870   //      +----------+   |
11871   //                     |
11872   //       +---------+   |
11873   //       | TailMBB +<--+
11874   //       +---------+
11875   // In MBB, calculate previous frame pointer and final stack pointer.
11876   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11877   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11878   // TailMBB is spliced via \p MI.
11879   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11880   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11881   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11882 
11883   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11884   MF->insert(MBBIter, TestMBB);
11885   MF->insert(MBBIter, BlockMBB);
11886   MF->insert(MBBIter, TailMBB);
11887 
11888   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11889   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11890 
11891   Register DstReg = MI.getOperand(0).getReg();
11892   Register NegSizeReg = MI.getOperand(1).getReg();
11893   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11894   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11895   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11896   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11897 
11898   // Since value of NegSizeReg might be realigned in prologepilog, insert a
11899   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
11900   // NegSize.
11901   unsigned ProbeOpc;
11902   if (!MRI.hasOneNonDBGUse(NegSizeReg))
11903     ProbeOpc =
11904         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
11905   else
11906     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
11907     // and NegSizeReg will be allocated in the same phyreg to avoid
11908     // redundant copy when NegSizeReg has only one use which is current MI and
11909     // will be replaced by PREPARE_PROBED_ALLOCA then.
11910     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
11911                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
11912   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
11913       .addDef(ActualNegSizeReg)
11914       .addReg(NegSizeReg)
11915       .add(MI.getOperand(2))
11916       .add(MI.getOperand(3));
11917 
11918   // Calculate final stack pointer, which equals to SP + ActualNegSize.
11919   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
11920           FinalStackPtr)
11921       .addReg(SPReg)
11922       .addReg(ActualNegSizeReg);
11923 
11924   // Materialize a scratch register for update.
11925   int64_t NegProbeSize = -(int64_t)ProbeSize;
11926   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
11927   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11928   if (!isInt<16>(NegProbeSize)) {
11929     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11930     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
11931         .addImm(NegProbeSize >> 16);
11932     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
11933             ScratchReg)
11934         .addReg(TempReg)
11935         .addImm(NegProbeSize & 0xFFFF);
11936   } else
11937     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
11938         .addImm(NegProbeSize);
11939 
11940   {
11941     // Probing leading residual part.
11942     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11943     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
11944         .addReg(ActualNegSizeReg)
11945         .addReg(ScratchReg);
11946     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11947     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
11948         .addReg(Div)
11949         .addReg(ScratchReg);
11950     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11951     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
11952         .addReg(Mul)
11953         .addReg(ActualNegSizeReg);
11954     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11955         .addReg(FramePointer)
11956         .addReg(SPReg)
11957         .addReg(NegMod);
11958   }
11959 
11960   {
11961     // Remaining part should be multiple of ProbeSize.
11962     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
11963     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
11964         .addReg(SPReg)
11965         .addReg(FinalStackPtr);
11966     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
11967         .addImm(PPC::PRED_EQ)
11968         .addReg(CmpResult)
11969         .addMBB(TailMBB);
11970     TestMBB->addSuccessor(BlockMBB);
11971     TestMBB->addSuccessor(TailMBB);
11972   }
11973 
11974   {
11975     // Touch the block.
11976     // |P...|P...|P...
11977     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11978         .addReg(FramePointer)
11979         .addReg(SPReg)
11980         .addReg(ScratchReg);
11981     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
11982     BlockMBB->addSuccessor(TestMBB);
11983   }
11984 
11985   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
11986   // DYNAREAOFFSET pseudo instruction to get the future result.
11987   Register MaxCallFrameSizeReg =
11988       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11989   BuildMI(TailMBB, DL,
11990           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
11991           MaxCallFrameSizeReg)
11992       .add(MI.getOperand(2))
11993       .add(MI.getOperand(3));
11994   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
11995       .addReg(SPReg)
11996       .addReg(MaxCallFrameSizeReg);
11997 
11998   // Splice instructions after MI to TailMBB.
11999   TailMBB->splice(TailMBB->end(), MBB,
12000                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
12001   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
12002   MBB->addSuccessor(TestMBB);
12003 
12004   // Delete the pseudo instruction.
12005   MI.eraseFromParent();
12006 
12007   ++NumDynamicAllocaProbed;
12008   return TailMBB;
12009 }
12010 
12011 MachineBasicBlock *
12012 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
12013                                                MachineBasicBlock *BB) const {
12014   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
12015       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
12016     if (Subtarget.is64BitELFABI() &&
12017         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
12018         !Subtarget.isUsingPCRelativeCalls()) {
12019       // Call lowering should have added an r2 operand to indicate a dependence
12020       // on the TOC base pointer value. It can't however, because there is no
12021       // way to mark the dependence as implicit there, and so the stackmap code
12022       // will confuse it with a regular operand. Instead, add the dependence
12023       // here.
12024       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
12025     }
12026 
12027     return emitPatchPoint(MI, BB);
12028   }
12029 
12030   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
12031       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
12032     return emitEHSjLjSetJmp(MI, BB);
12033   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
12034              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
12035     return emitEHSjLjLongJmp(MI, BB);
12036   }
12037 
12038   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12039 
12040   // To "insert" these instructions we actually have to insert their
12041   // control-flow patterns.
12042   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12043   MachineFunction::iterator It = ++BB->getIterator();
12044 
12045   MachineFunction *F = BB->getParent();
12046 
12047   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12048       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
12049       MI.getOpcode() == PPC::SELECT_I8) {
12050     SmallVector<MachineOperand, 2> Cond;
12051     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12052         MI.getOpcode() == PPC::SELECT_CC_I8)
12053       Cond.push_back(MI.getOperand(4));
12054     else
12055       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
12056     Cond.push_back(MI.getOperand(1));
12057 
12058     DebugLoc dl = MI.getDebugLoc();
12059     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
12060                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
12061   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
12062              MI.getOpcode() == PPC::SELECT_CC_F8 ||
12063              MI.getOpcode() == PPC::SELECT_CC_F16 ||
12064              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
12065              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
12066              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
12067              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
12068              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
12069              MI.getOpcode() == PPC::SELECT_CC_SPE ||
12070              MI.getOpcode() == PPC::SELECT_F4 ||
12071              MI.getOpcode() == PPC::SELECT_F8 ||
12072              MI.getOpcode() == PPC::SELECT_F16 ||
12073              MI.getOpcode() == PPC::SELECT_SPE ||
12074              MI.getOpcode() == PPC::SELECT_SPE4 ||
12075              MI.getOpcode() == PPC::SELECT_VRRC ||
12076              MI.getOpcode() == PPC::SELECT_VSFRC ||
12077              MI.getOpcode() == PPC::SELECT_VSSRC ||
12078              MI.getOpcode() == PPC::SELECT_VSRC) {
12079     // The incoming instruction knows the destination vreg to set, the
12080     // condition code register to branch on, the true/false values to
12081     // select between, and a branch opcode to use.
12082 
12083     //  thisMBB:
12084     //  ...
12085     //   TrueVal = ...
12086     //   cmpTY ccX, r1, r2
12087     //   bCC copy1MBB
12088     //   fallthrough --> copy0MBB
12089     MachineBasicBlock *thisMBB = BB;
12090     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12091     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12092     DebugLoc dl = MI.getDebugLoc();
12093     F->insert(It, copy0MBB);
12094     F->insert(It, sinkMBB);
12095 
12096     // Transfer the remainder of BB and its successor edges to sinkMBB.
12097     sinkMBB->splice(sinkMBB->begin(), BB,
12098                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12099     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12100 
12101     // Next, add the true and fallthrough blocks as its successors.
12102     BB->addSuccessor(copy0MBB);
12103     BB->addSuccessor(sinkMBB);
12104 
12105     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
12106         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
12107         MI.getOpcode() == PPC::SELECT_F16 ||
12108         MI.getOpcode() == PPC::SELECT_SPE4 ||
12109         MI.getOpcode() == PPC::SELECT_SPE ||
12110         MI.getOpcode() == PPC::SELECT_VRRC ||
12111         MI.getOpcode() == PPC::SELECT_VSFRC ||
12112         MI.getOpcode() == PPC::SELECT_VSSRC ||
12113         MI.getOpcode() == PPC::SELECT_VSRC) {
12114       BuildMI(BB, dl, TII->get(PPC::BC))
12115           .addReg(MI.getOperand(1).getReg())
12116           .addMBB(sinkMBB);
12117     } else {
12118       unsigned SelectPred = MI.getOperand(4).getImm();
12119       BuildMI(BB, dl, TII->get(PPC::BCC))
12120           .addImm(SelectPred)
12121           .addReg(MI.getOperand(1).getReg())
12122           .addMBB(sinkMBB);
12123     }
12124 
12125     //  copy0MBB:
12126     //   %FalseValue = ...
12127     //   # fallthrough to sinkMBB
12128     BB = copy0MBB;
12129 
12130     // Update machine-CFG edges
12131     BB->addSuccessor(sinkMBB);
12132 
12133     //  sinkMBB:
12134     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12135     //  ...
12136     BB = sinkMBB;
12137     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
12138         .addReg(MI.getOperand(3).getReg())
12139         .addMBB(copy0MBB)
12140         .addReg(MI.getOperand(2).getReg())
12141         .addMBB(thisMBB);
12142   } else if (MI.getOpcode() == PPC::ReadTB) {
12143     // To read the 64-bit time-base register on a 32-bit target, we read the
12144     // two halves. Should the counter have wrapped while it was being read, we
12145     // need to try again.
12146     // ...
12147     // readLoop:
12148     // mfspr Rx,TBU # load from TBU
12149     // mfspr Ry,TB  # load from TB
12150     // mfspr Rz,TBU # load from TBU
12151     // cmpw crX,Rx,Rz # check if 'old'='new'
12152     // bne readLoop   # branch if they're not equal
12153     // ...
12154 
12155     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
12156     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12157     DebugLoc dl = MI.getDebugLoc();
12158     F->insert(It, readMBB);
12159     F->insert(It, sinkMBB);
12160 
12161     // Transfer the remainder of BB and its successor edges to sinkMBB.
12162     sinkMBB->splice(sinkMBB->begin(), BB,
12163                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12164     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12165 
12166     BB->addSuccessor(readMBB);
12167     BB = readMBB;
12168 
12169     MachineRegisterInfo &RegInfo = F->getRegInfo();
12170     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
12171     Register LoReg = MI.getOperand(0).getReg();
12172     Register HiReg = MI.getOperand(1).getReg();
12173 
12174     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
12175     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
12176     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
12177 
12178     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12179 
12180     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
12181         .addReg(HiReg)
12182         .addReg(ReadAgainReg);
12183     BuildMI(BB, dl, TII->get(PPC::BCC))
12184         .addImm(PPC::PRED_NE)
12185         .addReg(CmpReg)
12186         .addMBB(readMBB);
12187 
12188     BB->addSuccessor(readMBB);
12189     BB->addSuccessor(sinkMBB);
12190   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
12191     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
12192   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
12193     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
12194   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
12195     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
12196   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
12197     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
12198 
12199   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
12200     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
12201   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
12202     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
12203   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
12204     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
12205   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
12206     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
12207 
12208   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
12209     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
12210   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
12211     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
12212   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
12213     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
12214   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
12215     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
12216 
12217   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
12218     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
12219   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
12220     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
12221   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
12222     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
12223   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
12224     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
12225 
12226   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
12227     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
12228   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
12229     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
12230   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
12231     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
12232   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
12233     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
12234 
12235   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
12236     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
12237   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
12238     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
12239   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
12240     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
12241   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
12242     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
12243 
12244   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
12245     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
12246   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
12247     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
12248   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
12249     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
12250   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
12251     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
12252 
12253   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
12254     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
12255   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
12256     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
12257   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
12258     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
12259   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
12260     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
12261 
12262   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
12263     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
12264   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
12265     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
12266   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
12267     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
12268   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
12269     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
12270 
12271   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
12272     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
12273   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
12274     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
12275   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
12276     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
12277   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
12278     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
12279 
12280   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
12281     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
12282   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
12283     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
12284   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
12285     BB = EmitAtomicBinary(MI, BB, 4, 0);
12286   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
12287     BB = EmitAtomicBinary(MI, BB, 8, 0);
12288   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
12289            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
12290            (Subtarget.hasPartwordAtomics() &&
12291             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
12292            (Subtarget.hasPartwordAtomics() &&
12293             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
12294     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
12295 
12296     auto LoadMnemonic = PPC::LDARX;
12297     auto StoreMnemonic = PPC::STDCX;
12298     switch (MI.getOpcode()) {
12299     default:
12300       llvm_unreachable("Compare and swap of unknown size");
12301     case PPC::ATOMIC_CMP_SWAP_I8:
12302       LoadMnemonic = PPC::LBARX;
12303       StoreMnemonic = PPC::STBCX;
12304       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12305       break;
12306     case PPC::ATOMIC_CMP_SWAP_I16:
12307       LoadMnemonic = PPC::LHARX;
12308       StoreMnemonic = PPC::STHCX;
12309       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12310       break;
12311     case PPC::ATOMIC_CMP_SWAP_I32:
12312       LoadMnemonic = PPC::LWARX;
12313       StoreMnemonic = PPC::STWCX;
12314       break;
12315     case PPC::ATOMIC_CMP_SWAP_I64:
12316       LoadMnemonic = PPC::LDARX;
12317       StoreMnemonic = PPC::STDCX;
12318       break;
12319     }
12320     Register dest = MI.getOperand(0).getReg();
12321     Register ptrA = MI.getOperand(1).getReg();
12322     Register ptrB = MI.getOperand(2).getReg();
12323     Register oldval = MI.getOperand(3).getReg();
12324     Register newval = MI.getOperand(4).getReg();
12325     DebugLoc dl = MI.getDebugLoc();
12326 
12327     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12328     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12329     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12330     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12331     F->insert(It, loop1MBB);
12332     F->insert(It, loop2MBB);
12333     F->insert(It, midMBB);
12334     F->insert(It, exitMBB);
12335     exitMBB->splice(exitMBB->begin(), BB,
12336                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12337     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12338 
12339     //  thisMBB:
12340     //   ...
12341     //   fallthrough --> loopMBB
12342     BB->addSuccessor(loop1MBB);
12343 
12344     // loop1MBB:
12345     //   l[bhwd]arx dest, ptr
12346     //   cmp[wd] dest, oldval
12347     //   bne- midMBB
12348     // loop2MBB:
12349     //   st[bhwd]cx. newval, ptr
12350     //   bne- loopMBB
12351     //   b exitBB
12352     // midMBB:
12353     //   st[bhwd]cx. dest, ptr
12354     // exitBB:
12355     BB = loop1MBB;
12356     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12357     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12358         .addReg(oldval)
12359         .addReg(dest);
12360     BuildMI(BB, dl, TII->get(PPC::BCC))
12361         .addImm(PPC::PRED_NE)
12362         .addReg(PPC::CR0)
12363         .addMBB(midMBB);
12364     BB->addSuccessor(loop2MBB);
12365     BB->addSuccessor(midMBB);
12366 
12367     BB = loop2MBB;
12368     BuildMI(BB, dl, TII->get(StoreMnemonic))
12369         .addReg(newval)
12370         .addReg(ptrA)
12371         .addReg(ptrB);
12372     BuildMI(BB, dl, TII->get(PPC::BCC))
12373         .addImm(PPC::PRED_NE)
12374         .addReg(PPC::CR0)
12375         .addMBB(loop1MBB);
12376     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12377     BB->addSuccessor(loop1MBB);
12378     BB->addSuccessor(exitMBB);
12379 
12380     BB = midMBB;
12381     BuildMI(BB, dl, TII->get(StoreMnemonic))
12382         .addReg(dest)
12383         .addReg(ptrA)
12384         .addReg(ptrB);
12385     BB->addSuccessor(exitMBB);
12386 
12387     //  exitMBB:
12388     //   ...
12389     BB = exitMBB;
12390   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12391              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12392     // We must use 64-bit registers for addresses when targeting 64-bit,
12393     // since we're actually doing arithmetic on them.  Other registers
12394     // can be 32-bit.
12395     bool is64bit = Subtarget.isPPC64();
12396     bool isLittleEndian = Subtarget.isLittleEndian();
12397     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12398 
12399     Register dest = MI.getOperand(0).getReg();
12400     Register ptrA = MI.getOperand(1).getReg();
12401     Register ptrB = MI.getOperand(2).getReg();
12402     Register oldval = MI.getOperand(3).getReg();
12403     Register newval = MI.getOperand(4).getReg();
12404     DebugLoc dl = MI.getDebugLoc();
12405 
12406     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12407     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12408     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12409     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12410     F->insert(It, loop1MBB);
12411     F->insert(It, loop2MBB);
12412     F->insert(It, midMBB);
12413     F->insert(It, exitMBB);
12414     exitMBB->splice(exitMBB->begin(), BB,
12415                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12416     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12417 
12418     MachineRegisterInfo &RegInfo = F->getRegInfo();
12419     const TargetRegisterClass *RC =
12420         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12421     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12422 
12423     Register PtrReg = RegInfo.createVirtualRegister(RC);
12424     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12425     Register ShiftReg =
12426         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12427     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12428     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12429     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12430     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12431     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12432     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12433     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12434     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12435     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12436     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12437     Register Ptr1Reg;
12438     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12439     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12440     //  thisMBB:
12441     //   ...
12442     //   fallthrough --> loopMBB
12443     BB->addSuccessor(loop1MBB);
12444 
12445     // The 4-byte load must be aligned, while a char or short may be
12446     // anywhere in the word.  Hence all this nasty bookkeeping code.
12447     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12448     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12449     //   xori shift, shift1, 24 [16]
12450     //   rlwinm ptr, ptr1, 0, 0, 29
12451     //   slw newval2, newval, shift
12452     //   slw oldval2, oldval,shift
12453     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12454     //   slw mask, mask2, shift
12455     //   and newval3, newval2, mask
12456     //   and oldval3, oldval2, mask
12457     // loop1MBB:
12458     //   lwarx tmpDest, ptr
12459     //   and tmp, tmpDest, mask
12460     //   cmpw tmp, oldval3
12461     //   bne- midMBB
12462     // loop2MBB:
12463     //   andc tmp2, tmpDest, mask
12464     //   or tmp4, tmp2, newval3
12465     //   stwcx. tmp4, ptr
12466     //   bne- loop1MBB
12467     //   b exitBB
12468     // midMBB:
12469     //   stwcx. tmpDest, ptr
12470     // exitBB:
12471     //   srw dest, tmpDest, shift
12472     if (ptrA != ZeroReg) {
12473       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12474       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12475           .addReg(ptrA)
12476           .addReg(ptrB);
12477     } else {
12478       Ptr1Reg = ptrB;
12479     }
12480 
12481     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12482     // mode.
12483     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12484         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12485         .addImm(3)
12486         .addImm(27)
12487         .addImm(is8bit ? 28 : 27);
12488     if (!isLittleEndian)
12489       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12490           .addReg(Shift1Reg)
12491           .addImm(is8bit ? 24 : 16);
12492     if (is64bit)
12493       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12494           .addReg(Ptr1Reg)
12495           .addImm(0)
12496           .addImm(61);
12497     else
12498       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12499           .addReg(Ptr1Reg)
12500           .addImm(0)
12501           .addImm(0)
12502           .addImm(29);
12503     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12504         .addReg(newval)
12505         .addReg(ShiftReg);
12506     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12507         .addReg(oldval)
12508         .addReg(ShiftReg);
12509     if (is8bit)
12510       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12511     else {
12512       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12513       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12514           .addReg(Mask3Reg)
12515           .addImm(65535);
12516     }
12517     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12518         .addReg(Mask2Reg)
12519         .addReg(ShiftReg);
12520     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12521         .addReg(NewVal2Reg)
12522         .addReg(MaskReg);
12523     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12524         .addReg(OldVal2Reg)
12525         .addReg(MaskReg);
12526 
12527     BB = loop1MBB;
12528     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12529         .addReg(ZeroReg)
12530         .addReg(PtrReg);
12531     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12532         .addReg(TmpDestReg)
12533         .addReg(MaskReg);
12534     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12535         .addReg(TmpReg)
12536         .addReg(OldVal3Reg);
12537     BuildMI(BB, dl, TII->get(PPC::BCC))
12538         .addImm(PPC::PRED_NE)
12539         .addReg(PPC::CR0)
12540         .addMBB(midMBB);
12541     BB->addSuccessor(loop2MBB);
12542     BB->addSuccessor(midMBB);
12543 
12544     BB = loop2MBB;
12545     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12546         .addReg(TmpDestReg)
12547         .addReg(MaskReg);
12548     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12549         .addReg(Tmp2Reg)
12550         .addReg(NewVal3Reg);
12551     BuildMI(BB, dl, TII->get(PPC::STWCX))
12552         .addReg(Tmp4Reg)
12553         .addReg(ZeroReg)
12554         .addReg(PtrReg);
12555     BuildMI(BB, dl, TII->get(PPC::BCC))
12556         .addImm(PPC::PRED_NE)
12557         .addReg(PPC::CR0)
12558         .addMBB(loop1MBB);
12559     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12560     BB->addSuccessor(loop1MBB);
12561     BB->addSuccessor(exitMBB);
12562 
12563     BB = midMBB;
12564     BuildMI(BB, dl, TII->get(PPC::STWCX))
12565         .addReg(TmpDestReg)
12566         .addReg(ZeroReg)
12567         .addReg(PtrReg);
12568     BB->addSuccessor(exitMBB);
12569 
12570     //  exitMBB:
12571     //   ...
12572     BB = exitMBB;
12573     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12574         .addReg(TmpReg)
12575         .addReg(ShiftReg);
12576   } else if (MI.getOpcode() == PPC::FADDrtz) {
12577     // This pseudo performs an FADD with rounding mode temporarily forced
12578     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12579     // is not modeled at the SelectionDAG level.
12580     Register Dest = MI.getOperand(0).getReg();
12581     Register Src1 = MI.getOperand(1).getReg();
12582     Register Src2 = MI.getOperand(2).getReg();
12583     DebugLoc dl = MI.getDebugLoc();
12584 
12585     MachineRegisterInfo &RegInfo = F->getRegInfo();
12586     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12587 
12588     // Save FPSCR value.
12589     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12590 
12591     // Set rounding mode to round-to-zero.
12592     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12593         .addImm(31)
12594         .addReg(PPC::RM, RegState::ImplicitDefine);
12595 
12596     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12597         .addImm(30)
12598         .addReg(PPC::RM, RegState::ImplicitDefine);
12599 
12600     // Perform addition.
12601     auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
12602                    .addReg(Src1)
12603                    .addReg(Src2);
12604     if (MI.getFlag(MachineInstr::NoFPExcept))
12605       MIB.setMIFlag(MachineInstr::NoFPExcept);
12606 
12607     // Restore FPSCR value.
12608     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12609   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12610              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12611              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12612              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12613     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12614                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12615                           ? PPC::ANDI8_rec
12616                           : PPC::ANDI_rec;
12617     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12618                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12619 
12620     MachineRegisterInfo &RegInfo = F->getRegInfo();
12621     Register Dest = RegInfo.createVirtualRegister(
12622         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12623 
12624     DebugLoc Dl = MI.getDebugLoc();
12625     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12626         .addReg(MI.getOperand(1).getReg())
12627         .addImm(1);
12628     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12629             MI.getOperand(0).getReg())
12630         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12631   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12632     DebugLoc Dl = MI.getDebugLoc();
12633     MachineRegisterInfo &RegInfo = F->getRegInfo();
12634     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12635     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12636     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12637             MI.getOperand(0).getReg())
12638         .addReg(CRReg);
12639   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12640     DebugLoc Dl = MI.getDebugLoc();
12641     unsigned Imm = MI.getOperand(1).getImm();
12642     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12643     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12644             MI.getOperand(0).getReg())
12645         .addReg(PPC::CR0EQ);
12646   } else if (MI.getOpcode() == PPC::SETRNDi) {
12647     DebugLoc dl = MI.getDebugLoc();
12648     Register OldFPSCRReg = MI.getOperand(0).getReg();
12649 
12650     // Save FPSCR value.
12651     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12652 
12653     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12654     // the following settings:
12655     //   00 Round to nearest
12656     //   01 Round to 0
12657     //   10 Round to +inf
12658     //   11 Round to -inf
12659 
12660     // When the operand is immediate, using the two least significant bits of
12661     // the immediate to set the bits 62:63 of FPSCR.
12662     unsigned Mode = MI.getOperand(1).getImm();
12663     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12664         .addImm(31)
12665         .addReg(PPC::RM, RegState::ImplicitDefine);
12666 
12667     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12668         .addImm(30)
12669         .addReg(PPC::RM, RegState::ImplicitDefine);
12670   } else if (MI.getOpcode() == PPC::SETRND) {
12671     DebugLoc dl = MI.getDebugLoc();
12672 
12673     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12674     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12675     // If the target doesn't have DirectMove, we should use stack to do the
12676     // conversion, because the target doesn't have the instructions like mtvsrd
12677     // or mfvsrd to do this conversion directly.
12678     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12679       if (Subtarget.hasDirectMove()) {
12680         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12681           .addReg(SrcReg);
12682       } else {
12683         // Use stack to do the register copy.
12684         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12685         MachineRegisterInfo &RegInfo = F->getRegInfo();
12686         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12687         if (RC == &PPC::F8RCRegClass) {
12688           // Copy register from F8RCRegClass to G8RCRegclass.
12689           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12690                  "Unsupported RegClass.");
12691 
12692           StoreOp = PPC::STFD;
12693           LoadOp = PPC::LD;
12694         } else {
12695           // Copy register from G8RCRegClass to F8RCRegclass.
12696           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12697                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12698                  "Unsupported RegClass.");
12699         }
12700 
12701         MachineFrameInfo &MFI = F->getFrameInfo();
12702         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12703 
12704         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12705             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12706             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12707             MFI.getObjectAlign(FrameIdx));
12708 
12709         // Store the SrcReg into the stack.
12710         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12711           .addReg(SrcReg)
12712           .addImm(0)
12713           .addFrameIndex(FrameIdx)
12714           .addMemOperand(MMOStore);
12715 
12716         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12717             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12718             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12719             MFI.getObjectAlign(FrameIdx));
12720 
12721         // Load from the stack where SrcReg is stored, and save to DestReg,
12722         // so we have done the RegClass conversion from RegClass::SrcReg to
12723         // RegClass::DestReg.
12724         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12725           .addImm(0)
12726           .addFrameIndex(FrameIdx)
12727           .addMemOperand(MMOLoad);
12728       }
12729     };
12730 
12731     Register OldFPSCRReg = MI.getOperand(0).getReg();
12732 
12733     // Save FPSCR value.
12734     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12735 
12736     // When the operand is gprc register, use two least significant bits of the
12737     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12738     //
12739     // copy OldFPSCRTmpReg, OldFPSCRReg
12740     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12741     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12742     // copy NewFPSCRReg, NewFPSCRTmpReg
12743     // mtfsf 255, NewFPSCRReg
12744     MachineOperand SrcOp = MI.getOperand(1);
12745     MachineRegisterInfo &RegInfo = F->getRegInfo();
12746     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12747 
12748     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12749 
12750     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12751     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12752 
12753     // The first operand of INSERT_SUBREG should be a register which has
12754     // subregisters, we only care about its RegClass, so we should use an
12755     // IMPLICIT_DEF register.
12756     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12757     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12758       .addReg(ImDefReg)
12759       .add(SrcOp)
12760       .addImm(1);
12761 
12762     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12763     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12764       .addReg(OldFPSCRTmpReg)
12765       .addReg(ExtSrcReg)
12766       .addImm(0)
12767       .addImm(62);
12768 
12769     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12770     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12771 
12772     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12773     // bits of FPSCR.
12774     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12775       .addImm(255)
12776       .addReg(NewFPSCRReg)
12777       .addImm(0)
12778       .addImm(0);
12779   } else if (MI.getOpcode() == PPC::SETFLM) {
12780     DebugLoc Dl = MI.getDebugLoc();
12781 
12782     // Result of setflm is previous FPSCR content, so we need to save it first.
12783     Register OldFPSCRReg = MI.getOperand(0).getReg();
12784     BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12785 
12786     // Put bits in 32:63 to FPSCR.
12787     Register NewFPSCRReg = MI.getOperand(1).getReg();
12788     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12789         .addImm(255)
12790         .addReg(NewFPSCRReg)
12791         .addImm(0)
12792         .addImm(0);
12793   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12794              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12795     return emitProbedAlloca(MI, BB);
12796   } else {
12797     llvm_unreachable("Unexpected instr type to insert");
12798   }
12799 
12800   MI.eraseFromParent(); // The pseudo instruction is gone now.
12801   return BB;
12802 }
12803 
12804 //===----------------------------------------------------------------------===//
12805 // Target Optimization Hooks
12806 //===----------------------------------------------------------------------===//
12807 
12808 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12809   // For the estimates, convergence is quadratic, so we essentially double the
12810   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12811   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12812   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12813   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12814   if (VT.getScalarType() == MVT::f64)
12815     RefinementSteps++;
12816   return RefinementSteps;
12817 }
12818 
12819 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
12820                                             const DenormalMode &Mode) const {
12821   // We only have VSX Vector Test for software Square Root.
12822   EVT VT = Op.getValueType();
12823   if (!isTypeLegal(MVT::i1) ||
12824       (VT != MVT::f64 &&
12825        ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
12826     return SDValue();
12827 
12828   SDLoc DL(Op);
12829   // The output register of FTSQRT is CR field.
12830   SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
12831   // ftsqrt BF,FRB
12832   // Let e_b be the unbiased exponent of the double-precision
12833   // floating-point operand in register FRB.
12834   // fe_flag is set to 1 if either of the following conditions occurs.
12835   //   - The double-precision floating-point operand in register FRB is a zero,
12836   //     a NaN, or an infinity, or a negative value.
12837   //   - e_b is less than or equal to -970.
12838   // Otherwise fe_flag is set to 0.
12839   // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
12840   // not eligible for iteration. (zero/negative/infinity/nan or unbiased
12841   // exponent is less than -970)
12842   SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
12843   return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
12844                                     FTSQRT, SRIdxVal),
12845                  0);
12846 }
12847 
12848 SDValue
12849 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
12850                                                SelectionDAG &DAG) const {
12851   // We only have VSX Vector Square Root.
12852   EVT VT = Op.getValueType();
12853   if (VT != MVT::f64 &&
12854       ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
12855     return TargetLowering::getSqrtResultForDenormInput(Op, DAG);
12856 
12857   return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
12858 }
12859 
12860 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12861                                            int Enabled, int &RefinementSteps,
12862                                            bool &UseOneConstNR,
12863                                            bool Reciprocal) const {
12864   EVT VT = Operand.getValueType();
12865   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12866       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12867       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12868       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12869     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12870       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12871 
12872     // The Newton-Raphson computation with a single constant does not provide
12873     // enough accuracy on some CPUs.
12874     UseOneConstNR = !Subtarget.needsTwoConstNR();
12875     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12876   }
12877   return SDValue();
12878 }
12879 
12880 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12881                                             int Enabled,
12882                                             int &RefinementSteps) const {
12883   EVT VT = Operand.getValueType();
12884   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12885       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12886       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12887       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12888     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12889       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12890     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12891   }
12892   return SDValue();
12893 }
12894 
12895 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12896   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12897   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12898   // enabled for division), this functionality is redundant with the default
12899   // combiner logic (once the division -> reciprocal/multiply transformation
12900   // has taken place). As a result, this matters more for older cores than for
12901   // newer ones.
12902 
12903   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12904   // reciprocal if there are two or more FDIVs (for embedded cores with only
12905   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12906   switch (Subtarget.getCPUDirective()) {
12907   default:
12908     return 3;
12909   case PPC::DIR_440:
12910   case PPC::DIR_A2:
12911   case PPC::DIR_E500:
12912   case PPC::DIR_E500mc:
12913   case PPC::DIR_E5500:
12914     return 2;
12915   }
12916 }
12917 
12918 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12919 // collapsed, and so we need to look through chains of them.
12920 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12921                                      int64_t& Offset, SelectionDAG &DAG) {
12922   if (DAG.isBaseWithConstantOffset(Loc)) {
12923     Base = Loc.getOperand(0);
12924     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12925 
12926     // The base might itself be a base plus an offset, and if so, accumulate
12927     // that as well.
12928     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12929   }
12930 }
12931 
12932 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12933                             unsigned Bytes, int Dist,
12934                             SelectionDAG &DAG) {
12935   if (VT.getSizeInBits() / 8 != Bytes)
12936     return false;
12937 
12938   SDValue BaseLoc = Base->getBasePtr();
12939   if (Loc.getOpcode() == ISD::FrameIndex) {
12940     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12941       return false;
12942     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12943     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12944     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12945     int FS  = MFI.getObjectSize(FI);
12946     int BFS = MFI.getObjectSize(BFI);
12947     if (FS != BFS || FS != (int)Bytes) return false;
12948     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12949   }
12950 
12951   SDValue Base1 = Loc, Base2 = BaseLoc;
12952   int64_t Offset1 = 0, Offset2 = 0;
12953   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12954   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12955   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12956     return true;
12957 
12958   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12959   const GlobalValue *GV1 = nullptr;
12960   const GlobalValue *GV2 = nullptr;
12961   Offset1 = 0;
12962   Offset2 = 0;
12963   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12964   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12965   if (isGA1 && isGA2 && GV1 == GV2)
12966     return Offset1 == (Offset2 + Dist*Bytes);
12967   return false;
12968 }
12969 
12970 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12971 // not enforce equality of the chain operands.
12972 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12973                             unsigned Bytes, int Dist,
12974                             SelectionDAG &DAG) {
12975   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12976     EVT VT = LS->getMemoryVT();
12977     SDValue Loc = LS->getBasePtr();
12978     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12979   }
12980 
12981   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12982     EVT VT;
12983     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12984     default: return false;
12985     case Intrinsic::ppc_altivec_lvx:
12986     case Intrinsic::ppc_altivec_lvxl:
12987     case Intrinsic::ppc_vsx_lxvw4x:
12988     case Intrinsic::ppc_vsx_lxvw4x_be:
12989       VT = MVT::v4i32;
12990       break;
12991     case Intrinsic::ppc_vsx_lxvd2x:
12992     case Intrinsic::ppc_vsx_lxvd2x_be:
12993       VT = MVT::v2f64;
12994       break;
12995     case Intrinsic::ppc_altivec_lvebx:
12996       VT = MVT::i8;
12997       break;
12998     case Intrinsic::ppc_altivec_lvehx:
12999       VT = MVT::i16;
13000       break;
13001     case Intrinsic::ppc_altivec_lvewx:
13002       VT = MVT::i32;
13003       break;
13004     }
13005 
13006     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
13007   }
13008 
13009   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
13010     EVT VT;
13011     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13012     default: return false;
13013     case Intrinsic::ppc_altivec_stvx:
13014     case Intrinsic::ppc_altivec_stvxl:
13015     case Intrinsic::ppc_vsx_stxvw4x:
13016       VT = MVT::v4i32;
13017       break;
13018     case Intrinsic::ppc_vsx_stxvd2x:
13019       VT = MVT::v2f64;
13020       break;
13021     case Intrinsic::ppc_vsx_stxvw4x_be:
13022       VT = MVT::v4i32;
13023       break;
13024     case Intrinsic::ppc_vsx_stxvd2x_be:
13025       VT = MVT::v2f64;
13026       break;
13027     case Intrinsic::ppc_altivec_stvebx:
13028       VT = MVT::i8;
13029       break;
13030     case Intrinsic::ppc_altivec_stvehx:
13031       VT = MVT::i16;
13032       break;
13033     case Intrinsic::ppc_altivec_stvewx:
13034       VT = MVT::i32;
13035       break;
13036     }
13037 
13038     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
13039   }
13040 
13041   return false;
13042 }
13043 
13044 // Return true is there is a nearyby consecutive load to the one provided
13045 // (regardless of alignment). We search up and down the chain, looking though
13046 // token factors and other loads (but nothing else). As a result, a true result
13047 // indicates that it is safe to create a new consecutive load adjacent to the
13048 // load provided.
13049 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
13050   SDValue Chain = LD->getChain();
13051   EVT VT = LD->getMemoryVT();
13052 
13053   SmallSet<SDNode *, 16> LoadRoots;
13054   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
13055   SmallSet<SDNode *, 16> Visited;
13056 
13057   // First, search up the chain, branching to follow all token-factor operands.
13058   // If we find a consecutive load, then we're done, otherwise, record all
13059   // nodes just above the top-level loads and token factors.
13060   while (!Queue.empty()) {
13061     SDNode *ChainNext = Queue.pop_back_val();
13062     if (!Visited.insert(ChainNext).second)
13063       continue;
13064 
13065     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
13066       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13067         return true;
13068 
13069       if (!Visited.count(ChainLD->getChain().getNode()))
13070         Queue.push_back(ChainLD->getChain().getNode());
13071     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
13072       for (const SDUse &O : ChainNext->ops())
13073         if (!Visited.count(O.getNode()))
13074           Queue.push_back(O.getNode());
13075     } else
13076       LoadRoots.insert(ChainNext);
13077   }
13078 
13079   // Second, search down the chain, starting from the top-level nodes recorded
13080   // in the first phase. These top-level nodes are the nodes just above all
13081   // loads and token factors. Starting with their uses, recursively look though
13082   // all loads (just the chain uses) and token factors to find a consecutive
13083   // load.
13084   Visited.clear();
13085   Queue.clear();
13086 
13087   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
13088        IE = LoadRoots.end(); I != IE; ++I) {
13089     Queue.push_back(*I);
13090 
13091     while (!Queue.empty()) {
13092       SDNode *LoadRoot = Queue.pop_back_val();
13093       if (!Visited.insert(LoadRoot).second)
13094         continue;
13095 
13096       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
13097         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13098           return true;
13099 
13100       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
13101            UE = LoadRoot->use_end(); UI != UE; ++UI)
13102         if (((isa<MemSDNode>(*UI) &&
13103             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
13104             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
13105           Queue.push_back(*UI);
13106     }
13107   }
13108 
13109   return false;
13110 }
13111 
13112 /// This function is called when we have proved that a SETCC node can be replaced
13113 /// by subtraction (and other supporting instructions) so that the result of
13114 /// comparison is kept in a GPR instead of CR. This function is purely for
13115 /// codegen purposes and has some flags to guide the codegen process.
13116 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
13117                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
13118   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13119 
13120   // Zero extend the operands to the largest legal integer. Originally, they
13121   // must be of a strictly smaller size.
13122   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
13123                          DAG.getConstant(Size, DL, MVT::i32));
13124   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
13125                          DAG.getConstant(Size, DL, MVT::i32));
13126 
13127   // Swap if needed. Depends on the condition code.
13128   if (Swap)
13129     std::swap(Op0, Op1);
13130 
13131   // Subtract extended integers.
13132   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
13133 
13134   // Move the sign bit to the least significant position and zero out the rest.
13135   // Now the least significant bit carries the result of original comparison.
13136   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
13137                              DAG.getConstant(Size - 1, DL, MVT::i32));
13138   auto Final = Shifted;
13139 
13140   // Complement the result if needed. Based on the condition code.
13141   if (Complement)
13142     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
13143                         DAG.getConstant(1, DL, MVT::i64));
13144 
13145   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
13146 }
13147 
13148 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
13149                                                   DAGCombinerInfo &DCI) const {
13150   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13151 
13152   SelectionDAG &DAG = DCI.DAG;
13153   SDLoc DL(N);
13154 
13155   // Size of integers being compared has a critical role in the following
13156   // analysis, so we prefer to do this when all types are legal.
13157   if (!DCI.isAfterLegalizeDAG())
13158     return SDValue();
13159 
13160   // If all users of SETCC extend its value to a legal integer type
13161   // then we replace SETCC with a subtraction
13162   for (SDNode::use_iterator UI = N->use_begin(),
13163        UE = N->use_end(); UI != UE; ++UI) {
13164     if (UI->getOpcode() != ISD::ZERO_EXTEND)
13165       return SDValue();
13166   }
13167 
13168   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13169   auto OpSize = N->getOperand(0).getValueSizeInBits();
13170 
13171   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
13172 
13173   if (OpSize < Size) {
13174     switch (CC) {
13175     default: break;
13176     case ISD::SETULT:
13177       return generateEquivalentSub(N, Size, false, false, DL, DAG);
13178     case ISD::SETULE:
13179       return generateEquivalentSub(N, Size, true, true, DL, DAG);
13180     case ISD::SETUGT:
13181       return generateEquivalentSub(N, Size, false, true, DL, DAG);
13182     case ISD::SETUGE:
13183       return generateEquivalentSub(N, Size, true, false, DL, DAG);
13184     }
13185   }
13186 
13187   return SDValue();
13188 }
13189 
13190 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
13191                                                   DAGCombinerInfo &DCI) const {
13192   SelectionDAG &DAG = DCI.DAG;
13193   SDLoc dl(N);
13194 
13195   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
13196   // If we're tracking CR bits, we need to be careful that we don't have:
13197   //   trunc(binary-ops(zext(x), zext(y)))
13198   // or
13199   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
13200   // such that we're unnecessarily moving things into GPRs when it would be
13201   // better to keep them in CR bits.
13202 
13203   // Note that trunc here can be an actual i1 trunc, or can be the effective
13204   // truncation that comes from a setcc or select_cc.
13205   if (N->getOpcode() == ISD::TRUNCATE &&
13206       N->getValueType(0) != MVT::i1)
13207     return SDValue();
13208 
13209   if (N->getOperand(0).getValueType() != MVT::i32 &&
13210       N->getOperand(0).getValueType() != MVT::i64)
13211     return SDValue();
13212 
13213   if (N->getOpcode() == ISD::SETCC ||
13214       N->getOpcode() == ISD::SELECT_CC) {
13215     // If we're looking at a comparison, then we need to make sure that the
13216     // high bits (all except for the first) don't matter the result.
13217     ISD::CondCode CC =
13218       cast<CondCodeSDNode>(N->getOperand(
13219         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
13220     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
13221 
13222     if (ISD::isSignedIntSetCC(CC)) {
13223       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
13224           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
13225         return SDValue();
13226     } else if (ISD::isUnsignedIntSetCC(CC)) {
13227       if (!DAG.MaskedValueIsZero(N->getOperand(0),
13228                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
13229           !DAG.MaskedValueIsZero(N->getOperand(1),
13230                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
13231         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
13232                                              : SDValue());
13233     } else {
13234       // This is neither a signed nor an unsigned comparison, just make sure
13235       // that the high bits are equal.
13236       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
13237       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
13238 
13239       // We don't really care about what is known about the first bit (if
13240       // anything), so clear it in all masks prior to comparing them.
13241       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
13242       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
13243 
13244       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
13245         return SDValue();
13246     }
13247   }
13248 
13249   // We now know that the higher-order bits are irrelevant, we just need to
13250   // make sure that all of the intermediate operations are bit operations, and
13251   // all inputs are extensions.
13252   if (N->getOperand(0).getOpcode() != ISD::AND &&
13253       N->getOperand(0).getOpcode() != ISD::OR  &&
13254       N->getOperand(0).getOpcode() != ISD::XOR &&
13255       N->getOperand(0).getOpcode() != ISD::SELECT &&
13256       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
13257       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
13258       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
13259       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
13260       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
13261     return SDValue();
13262 
13263   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
13264       N->getOperand(1).getOpcode() != ISD::AND &&
13265       N->getOperand(1).getOpcode() != ISD::OR  &&
13266       N->getOperand(1).getOpcode() != ISD::XOR &&
13267       N->getOperand(1).getOpcode() != ISD::SELECT &&
13268       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
13269       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
13270       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
13271       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
13272       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
13273     return SDValue();
13274 
13275   SmallVector<SDValue, 4> Inputs;
13276   SmallVector<SDValue, 8> BinOps, PromOps;
13277   SmallPtrSet<SDNode *, 16> Visited;
13278 
13279   for (unsigned i = 0; i < 2; ++i) {
13280     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13281           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13282           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13283           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13284         isa<ConstantSDNode>(N->getOperand(i)))
13285       Inputs.push_back(N->getOperand(i));
13286     else
13287       BinOps.push_back(N->getOperand(i));
13288 
13289     if (N->getOpcode() == ISD::TRUNCATE)
13290       break;
13291   }
13292 
13293   // Visit all inputs, collect all binary operations (and, or, xor and
13294   // select) that are all fed by extensions.
13295   while (!BinOps.empty()) {
13296     SDValue BinOp = BinOps.back();
13297     BinOps.pop_back();
13298 
13299     if (!Visited.insert(BinOp.getNode()).second)
13300       continue;
13301 
13302     PromOps.push_back(BinOp);
13303 
13304     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13305       // The condition of the select is not promoted.
13306       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13307         continue;
13308       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13309         continue;
13310 
13311       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13312             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13313             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13314            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13315           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13316         Inputs.push_back(BinOp.getOperand(i));
13317       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13318                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13319                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13320                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13321                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
13322                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13323                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13324                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13325                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
13326         BinOps.push_back(BinOp.getOperand(i));
13327       } else {
13328         // We have an input that is not an extension or another binary
13329         // operation; we'll abort this transformation.
13330         return SDValue();
13331       }
13332     }
13333   }
13334 
13335   // Make sure that this is a self-contained cluster of operations (which
13336   // is not quite the same thing as saying that everything has only one
13337   // use).
13338   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13339     if (isa<ConstantSDNode>(Inputs[i]))
13340       continue;
13341 
13342     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13343                               UE = Inputs[i].getNode()->use_end();
13344          UI != UE; ++UI) {
13345       SDNode *User = *UI;
13346       if (User != N && !Visited.count(User))
13347         return SDValue();
13348 
13349       // Make sure that we're not going to promote the non-output-value
13350       // operand(s) or SELECT or SELECT_CC.
13351       // FIXME: Although we could sometimes handle this, and it does occur in
13352       // practice that one of the condition inputs to the select is also one of
13353       // the outputs, we currently can't deal with this.
13354       if (User->getOpcode() == ISD::SELECT) {
13355         if (User->getOperand(0) == Inputs[i])
13356           return SDValue();
13357       } else if (User->getOpcode() == ISD::SELECT_CC) {
13358         if (User->getOperand(0) == Inputs[i] ||
13359             User->getOperand(1) == Inputs[i])
13360           return SDValue();
13361       }
13362     }
13363   }
13364 
13365   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13366     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13367                               UE = PromOps[i].getNode()->use_end();
13368          UI != UE; ++UI) {
13369       SDNode *User = *UI;
13370       if (User != N && !Visited.count(User))
13371         return SDValue();
13372 
13373       // Make sure that we're not going to promote the non-output-value
13374       // operand(s) or SELECT or SELECT_CC.
13375       // FIXME: Although we could sometimes handle this, and it does occur in
13376       // practice that one of the condition inputs to the select is also one of
13377       // the outputs, we currently can't deal with this.
13378       if (User->getOpcode() == ISD::SELECT) {
13379         if (User->getOperand(0) == PromOps[i])
13380           return SDValue();
13381       } else if (User->getOpcode() == ISD::SELECT_CC) {
13382         if (User->getOperand(0) == PromOps[i] ||
13383             User->getOperand(1) == PromOps[i])
13384           return SDValue();
13385       }
13386     }
13387   }
13388 
13389   // Replace all inputs with the extension operand.
13390   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13391     // Constants may have users outside the cluster of to-be-promoted nodes,
13392     // and so we need to replace those as we do the promotions.
13393     if (isa<ConstantSDNode>(Inputs[i]))
13394       continue;
13395     else
13396       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13397   }
13398 
13399   std::list<HandleSDNode> PromOpHandles;
13400   for (auto &PromOp : PromOps)
13401     PromOpHandles.emplace_back(PromOp);
13402 
13403   // Replace all operations (these are all the same, but have a different
13404   // (i1) return type). DAG.getNode will validate that the types of
13405   // a binary operator match, so go through the list in reverse so that
13406   // we've likely promoted both operands first. Any intermediate truncations or
13407   // extensions disappear.
13408   while (!PromOpHandles.empty()) {
13409     SDValue PromOp = PromOpHandles.back().getValue();
13410     PromOpHandles.pop_back();
13411 
13412     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13413         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13414         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13415         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13416       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13417           PromOp.getOperand(0).getValueType() != MVT::i1) {
13418         // The operand is not yet ready (see comment below).
13419         PromOpHandles.emplace_front(PromOp);
13420         continue;
13421       }
13422 
13423       SDValue RepValue = PromOp.getOperand(0);
13424       if (isa<ConstantSDNode>(RepValue))
13425         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13426 
13427       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13428       continue;
13429     }
13430 
13431     unsigned C;
13432     switch (PromOp.getOpcode()) {
13433     default:             C = 0; break;
13434     case ISD::SELECT:    C = 1; break;
13435     case ISD::SELECT_CC: C = 2; break;
13436     }
13437 
13438     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13439          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13440         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13441          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13442       // The to-be-promoted operands of this node have not yet been
13443       // promoted (this should be rare because we're going through the
13444       // list backward, but if one of the operands has several users in
13445       // this cluster of to-be-promoted nodes, it is possible).
13446       PromOpHandles.emplace_front(PromOp);
13447       continue;
13448     }
13449 
13450     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13451                                 PromOp.getNode()->op_end());
13452 
13453     // If there are any constant inputs, make sure they're replaced now.
13454     for (unsigned i = 0; i < 2; ++i)
13455       if (isa<ConstantSDNode>(Ops[C+i]))
13456         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13457 
13458     DAG.ReplaceAllUsesOfValueWith(PromOp,
13459       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13460   }
13461 
13462   // Now we're left with the initial truncation itself.
13463   if (N->getOpcode() == ISD::TRUNCATE)
13464     return N->getOperand(0);
13465 
13466   // Otherwise, this is a comparison. The operands to be compared have just
13467   // changed type (to i1), but everything else is the same.
13468   return SDValue(N, 0);
13469 }
13470 
13471 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13472                                                   DAGCombinerInfo &DCI) const {
13473   SelectionDAG &DAG = DCI.DAG;
13474   SDLoc dl(N);
13475 
13476   // If we're tracking CR bits, we need to be careful that we don't have:
13477   //   zext(binary-ops(trunc(x), trunc(y)))
13478   // or
13479   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13480   // such that we're unnecessarily moving things into CR bits that can more
13481   // efficiently stay in GPRs. Note that if we're not certain that the high
13482   // bits are set as required by the final extension, we still may need to do
13483   // some masking to get the proper behavior.
13484 
13485   // This same functionality is important on PPC64 when dealing with
13486   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13487   // the return values of functions. Because it is so similar, it is handled
13488   // here as well.
13489 
13490   if (N->getValueType(0) != MVT::i32 &&
13491       N->getValueType(0) != MVT::i64)
13492     return SDValue();
13493 
13494   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13495         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13496     return SDValue();
13497 
13498   if (N->getOperand(0).getOpcode() != ISD::AND &&
13499       N->getOperand(0).getOpcode() != ISD::OR  &&
13500       N->getOperand(0).getOpcode() != ISD::XOR &&
13501       N->getOperand(0).getOpcode() != ISD::SELECT &&
13502       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13503     return SDValue();
13504 
13505   SmallVector<SDValue, 4> Inputs;
13506   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13507   SmallPtrSet<SDNode *, 16> Visited;
13508 
13509   // Visit all inputs, collect all binary operations (and, or, xor and
13510   // select) that are all fed by truncations.
13511   while (!BinOps.empty()) {
13512     SDValue BinOp = BinOps.back();
13513     BinOps.pop_back();
13514 
13515     if (!Visited.insert(BinOp.getNode()).second)
13516       continue;
13517 
13518     PromOps.push_back(BinOp);
13519 
13520     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13521       // The condition of the select is not promoted.
13522       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13523         continue;
13524       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13525         continue;
13526 
13527       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13528           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13529         Inputs.push_back(BinOp.getOperand(i));
13530       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13531                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13532                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13533                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13534                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13535         BinOps.push_back(BinOp.getOperand(i));
13536       } else {
13537         // We have an input that is not a truncation or another binary
13538         // operation; we'll abort this transformation.
13539         return SDValue();
13540       }
13541     }
13542   }
13543 
13544   // The operands of a select that must be truncated when the select is
13545   // promoted because the operand is actually part of the to-be-promoted set.
13546   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13547 
13548   // Make sure that this is a self-contained cluster of operations (which
13549   // is not quite the same thing as saying that everything has only one
13550   // use).
13551   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13552     if (isa<ConstantSDNode>(Inputs[i]))
13553       continue;
13554 
13555     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13556                               UE = Inputs[i].getNode()->use_end();
13557          UI != UE; ++UI) {
13558       SDNode *User = *UI;
13559       if (User != N && !Visited.count(User))
13560         return SDValue();
13561 
13562       // If we're going to promote the non-output-value operand(s) or SELECT or
13563       // SELECT_CC, record them for truncation.
13564       if (User->getOpcode() == ISD::SELECT) {
13565         if (User->getOperand(0) == Inputs[i])
13566           SelectTruncOp[0].insert(std::make_pair(User,
13567                                     User->getOperand(0).getValueType()));
13568       } else if (User->getOpcode() == ISD::SELECT_CC) {
13569         if (User->getOperand(0) == Inputs[i])
13570           SelectTruncOp[0].insert(std::make_pair(User,
13571                                     User->getOperand(0).getValueType()));
13572         if (User->getOperand(1) == Inputs[i])
13573           SelectTruncOp[1].insert(std::make_pair(User,
13574                                     User->getOperand(1).getValueType()));
13575       }
13576     }
13577   }
13578 
13579   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13580     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13581                               UE = PromOps[i].getNode()->use_end();
13582          UI != UE; ++UI) {
13583       SDNode *User = *UI;
13584       if (User != N && !Visited.count(User))
13585         return SDValue();
13586 
13587       // If we're going to promote the non-output-value operand(s) or SELECT or
13588       // SELECT_CC, record them for truncation.
13589       if (User->getOpcode() == ISD::SELECT) {
13590         if (User->getOperand(0) == PromOps[i])
13591           SelectTruncOp[0].insert(std::make_pair(User,
13592                                     User->getOperand(0).getValueType()));
13593       } else if (User->getOpcode() == ISD::SELECT_CC) {
13594         if (User->getOperand(0) == PromOps[i])
13595           SelectTruncOp[0].insert(std::make_pair(User,
13596                                     User->getOperand(0).getValueType()));
13597         if (User->getOperand(1) == PromOps[i])
13598           SelectTruncOp[1].insert(std::make_pair(User,
13599                                     User->getOperand(1).getValueType()));
13600       }
13601     }
13602   }
13603 
13604   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13605   bool ReallyNeedsExt = false;
13606   if (N->getOpcode() != ISD::ANY_EXTEND) {
13607     // If all of the inputs are not already sign/zero extended, then
13608     // we'll still need to do that at the end.
13609     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13610       if (isa<ConstantSDNode>(Inputs[i]))
13611         continue;
13612 
13613       unsigned OpBits =
13614         Inputs[i].getOperand(0).getValueSizeInBits();
13615       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13616 
13617       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13618            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13619                                   APInt::getHighBitsSet(OpBits,
13620                                                         OpBits-PromBits))) ||
13621           (N->getOpcode() == ISD::SIGN_EXTEND &&
13622            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13623              (OpBits-(PromBits-1)))) {
13624         ReallyNeedsExt = true;
13625         break;
13626       }
13627     }
13628   }
13629 
13630   // Replace all inputs, either with the truncation operand, or a
13631   // truncation or extension to the final output type.
13632   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13633     // Constant inputs need to be replaced with the to-be-promoted nodes that
13634     // use them because they might have users outside of the cluster of
13635     // promoted nodes.
13636     if (isa<ConstantSDNode>(Inputs[i]))
13637       continue;
13638 
13639     SDValue InSrc = Inputs[i].getOperand(0);
13640     if (Inputs[i].getValueType() == N->getValueType(0))
13641       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13642     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13643       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13644         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13645     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13646       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13647         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13648     else
13649       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13650         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13651   }
13652 
13653   std::list<HandleSDNode> PromOpHandles;
13654   for (auto &PromOp : PromOps)
13655     PromOpHandles.emplace_back(PromOp);
13656 
13657   // Replace all operations (these are all the same, but have a different
13658   // (promoted) return type). DAG.getNode will validate that the types of
13659   // a binary operator match, so go through the list in reverse so that
13660   // we've likely promoted both operands first.
13661   while (!PromOpHandles.empty()) {
13662     SDValue PromOp = PromOpHandles.back().getValue();
13663     PromOpHandles.pop_back();
13664 
13665     unsigned C;
13666     switch (PromOp.getOpcode()) {
13667     default:             C = 0; break;
13668     case ISD::SELECT:    C = 1; break;
13669     case ISD::SELECT_CC: C = 2; break;
13670     }
13671 
13672     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13673          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13674         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13675          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13676       // The to-be-promoted operands of this node have not yet been
13677       // promoted (this should be rare because we're going through the
13678       // list backward, but if one of the operands has several users in
13679       // this cluster of to-be-promoted nodes, it is possible).
13680       PromOpHandles.emplace_front(PromOp);
13681       continue;
13682     }
13683 
13684     // For SELECT and SELECT_CC nodes, we do a similar check for any
13685     // to-be-promoted comparison inputs.
13686     if (PromOp.getOpcode() == ISD::SELECT ||
13687         PromOp.getOpcode() == ISD::SELECT_CC) {
13688       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13689            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13690           (SelectTruncOp[1].count(PromOp.getNode()) &&
13691            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13692         PromOpHandles.emplace_front(PromOp);
13693         continue;
13694       }
13695     }
13696 
13697     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13698                                 PromOp.getNode()->op_end());
13699 
13700     // If this node has constant inputs, then they'll need to be promoted here.
13701     for (unsigned i = 0; i < 2; ++i) {
13702       if (!isa<ConstantSDNode>(Ops[C+i]))
13703         continue;
13704       if (Ops[C+i].getValueType() == N->getValueType(0))
13705         continue;
13706 
13707       if (N->getOpcode() == ISD::SIGN_EXTEND)
13708         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13709       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13710         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13711       else
13712         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13713     }
13714 
13715     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13716     // truncate them again to the original value type.
13717     if (PromOp.getOpcode() == ISD::SELECT ||
13718         PromOp.getOpcode() == ISD::SELECT_CC) {
13719       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13720       if (SI0 != SelectTruncOp[0].end())
13721         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13722       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13723       if (SI1 != SelectTruncOp[1].end())
13724         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13725     }
13726 
13727     DAG.ReplaceAllUsesOfValueWith(PromOp,
13728       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13729   }
13730 
13731   // Now we're left with the initial extension itself.
13732   if (!ReallyNeedsExt)
13733     return N->getOperand(0);
13734 
13735   // To zero extend, just mask off everything except for the first bit (in the
13736   // i1 case).
13737   if (N->getOpcode() == ISD::ZERO_EXTEND)
13738     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13739                        DAG.getConstant(APInt::getLowBitsSet(
13740                                          N->getValueSizeInBits(0), PromBits),
13741                                        dl, N->getValueType(0)));
13742 
13743   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13744          "Invalid extension type");
13745   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13746   SDValue ShiftCst =
13747       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13748   return DAG.getNode(
13749       ISD::SRA, dl, N->getValueType(0),
13750       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13751       ShiftCst);
13752 }
13753 
13754 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13755                                         DAGCombinerInfo &DCI) const {
13756   assert(N->getOpcode() == ISD::SETCC &&
13757          "Should be called with a SETCC node");
13758 
13759   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13760   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13761     SDValue LHS = N->getOperand(0);
13762     SDValue RHS = N->getOperand(1);
13763 
13764     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13765     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13766         LHS.hasOneUse())
13767       std::swap(LHS, RHS);
13768 
13769     // x == 0-y --> x+y == 0
13770     // x != 0-y --> x+y != 0
13771     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13772         RHS.hasOneUse()) {
13773       SDLoc DL(N);
13774       SelectionDAG &DAG = DCI.DAG;
13775       EVT VT = N->getValueType(0);
13776       EVT OpVT = LHS.getValueType();
13777       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13778       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13779     }
13780   }
13781 
13782   return DAGCombineTruncBoolExt(N, DCI);
13783 }
13784 
13785 // Is this an extending load from an f32 to an f64?
13786 static bool isFPExtLoad(SDValue Op) {
13787   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13788     return LD->getExtensionType() == ISD::EXTLOAD &&
13789       Op.getValueType() == MVT::f64;
13790   return false;
13791 }
13792 
13793 /// Reduces the number of fp-to-int conversion when building a vector.
13794 ///
13795 /// If this vector is built out of floating to integer conversions,
13796 /// transform it to a vector built out of floating point values followed by a
13797 /// single floating to integer conversion of the vector.
13798 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13799 /// becomes (fptosi (build_vector ($A, $B, ...)))
13800 SDValue PPCTargetLowering::
13801 combineElementTruncationToVectorTruncation(SDNode *N,
13802                                            DAGCombinerInfo &DCI) const {
13803   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13804          "Should be called with a BUILD_VECTOR node");
13805 
13806   SelectionDAG &DAG = DCI.DAG;
13807   SDLoc dl(N);
13808 
13809   SDValue FirstInput = N->getOperand(0);
13810   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13811          "The input operand must be an fp-to-int conversion.");
13812 
13813   // This combine happens after legalization so the fp_to_[su]i nodes are
13814   // already converted to PPCSISD nodes.
13815   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13816   if (FirstConversion == PPCISD::FCTIDZ ||
13817       FirstConversion == PPCISD::FCTIDUZ ||
13818       FirstConversion == PPCISD::FCTIWZ ||
13819       FirstConversion == PPCISD::FCTIWUZ) {
13820     bool IsSplat = true;
13821     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13822       FirstConversion == PPCISD::FCTIWUZ;
13823     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13824     SmallVector<SDValue, 4> Ops;
13825     EVT TargetVT = N->getValueType(0);
13826     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13827       SDValue NextOp = N->getOperand(i);
13828       if (NextOp.getOpcode() != PPCISD::MFVSR)
13829         return SDValue();
13830       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13831       if (NextConversion != FirstConversion)
13832         return SDValue();
13833       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13834       // This is not valid if the input was originally double precision. It is
13835       // also not profitable to do unless this is an extending load in which
13836       // case doing this combine will allow us to combine consecutive loads.
13837       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13838         return SDValue();
13839       if (N->getOperand(i) != FirstInput)
13840         IsSplat = false;
13841     }
13842 
13843     // If this is a splat, we leave it as-is since there will be only a single
13844     // fp-to-int conversion followed by a splat of the integer. This is better
13845     // for 32-bit and smaller ints and neutral for 64-bit ints.
13846     if (IsSplat)
13847       return SDValue();
13848 
13849     // Now that we know we have the right type of node, get its operands
13850     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13851       SDValue In = N->getOperand(i).getOperand(0);
13852       if (Is32Bit) {
13853         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13854         // here, we know that all inputs are extending loads so this is safe).
13855         if (In.isUndef())
13856           Ops.push_back(DAG.getUNDEF(SrcVT));
13857         else {
13858           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13859                                       MVT::f32, In.getOperand(0),
13860                                       DAG.getIntPtrConstant(1, dl));
13861           Ops.push_back(Trunc);
13862         }
13863       } else
13864         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13865     }
13866 
13867     unsigned Opcode;
13868     if (FirstConversion == PPCISD::FCTIDZ ||
13869         FirstConversion == PPCISD::FCTIWZ)
13870       Opcode = ISD::FP_TO_SINT;
13871     else
13872       Opcode = ISD::FP_TO_UINT;
13873 
13874     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13875     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13876     return DAG.getNode(Opcode, dl, TargetVT, BV);
13877   }
13878   return SDValue();
13879 }
13880 
13881 /// Reduce the number of loads when building a vector.
13882 ///
13883 /// Building a vector out of multiple loads can be converted to a load
13884 /// of the vector type if the loads are consecutive. If the loads are
13885 /// consecutive but in descending order, a shuffle is added at the end
13886 /// to reorder the vector.
13887 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13888   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13889          "Should be called with a BUILD_VECTOR node");
13890 
13891   SDLoc dl(N);
13892 
13893   // Return early for non byte-sized type, as they can't be consecutive.
13894   if (!N->getValueType(0).getVectorElementType().isByteSized())
13895     return SDValue();
13896 
13897   bool InputsAreConsecutiveLoads = true;
13898   bool InputsAreReverseConsecutive = true;
13899   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13900   SDValue FirstInput = N->getOperand(0);
13901   bool IsRoundOfExtLoad = false;
13902 
13903   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13904       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13905     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13906     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13907   }
13908   // Not a build vector of (possibly fp_rounded) loads.
13909   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13910       N->getNumOperands() == 1)
13911     return SDValue();
13912 
13913   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13914     // If any inputs are fp_round(extload), they all must be.
13915     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13916       return SDValue();
13917 
13918     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13919       N->getOperand(i);
13920     if (NextInput.getOpcode() != ISD::LOAD)
13921       return SDValue();
13922 
13923     SDValue PreviousInput =
13924       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13925     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13926     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13927 
13928     // If any inputs are fp_round(extload), they all must be.
13929     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13930       return SDValue();
13931 
13932     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13933       InputsAreConsecutiveLoads = false;
13934     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13935       InputsAreReverseConsecutive = false;
13936 
13937     // Exit early if the loads are neither consecutive nor reverse consecutive.
13938     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13939       return SDValue();
13940   }
13941 
13942   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13943          "The loads cannot be both consecutive and reverse consecutive.");
13944 
13945   SDValue FirstLoadOp =
13946     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13947   SDValue LastLoadOp =
13948     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13949                        N->getOperand(N->getNumOperands()-1);
13950 
13951   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13952   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13953   if (InputsAreConsecutiveLoads) {
13954     assert(LD1 && "Input needs to be a LoadSDNode.");
13955     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13956                        LD1->getBasePtr(), LD1->getPointerInfo(),
13957                        LD1->getAlignment());
13958   }
13959   if (InputsAreReverseConsecutive) {
13960     assert(LDL && "Input needs to be a LoadSDNode.");
13961     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13962                                LDL->getBasePtr(), LDL->getPointerInfo(),
13963                                LDL->getAlignment());
13964     SmallVector<int, 16> Ops;
13965     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13966       Ops.push_back(i);
13967 
13968     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13969                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13970   }
13971   return SDValue();
13972 }
13973 
13974 // This function adds the required vector_shuffle needed to get
13975 // the elements of the vector extract in the correct position
13976 // as specified by the CorrectElems encoding.
13977 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13978                                       SDValue Input, uint64_t Elems,
13979                                       uint64_t CorrectElems) {
13980   SDLoc dl(N);
13981 
13982   unsigned NumElems = Input.getValueType().getVectorNumElements();
13983   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13984 
13985   // Knowing the element indices being extracted from the original
13986   // vector and the order in which they're being inserted, just put
13987   // them at element indices required for the instruction.
13988   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13989     if (DAG.getDataLayout().isLittleEndian())
13990       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13991     else
13992       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13993     CorrectElems = CorrectElems >> 8;
13994     Elems = Elems >> 8;
13995   }
13996 
13997   SDValue Shuffle =
13998       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13999                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
14000 
14001   EVT VT = N->getValueType(0);
14002   SDValue Conv = DAG.getBitcast(VT, Shuffle);
14003 
14004   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
14005                                Input.getValueType().getVectorElementType(),
14006                                VT.getVectorNumElements());
14007   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
14008                      DAG.getValueType(ExtVT));
14009 }
14010 
14011 // Look for build vector patterns where input operands come from sign
14012 // extended vector_extract elements of specific indices. If the correct indices
14013 // aren't used, add a vector shuffle to fix up the indices and create
14014 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
14015 // during instruction selection.
14016 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
14017   // This array encodes the indices that the vector sign extend instructions
14018   // extract from when extending from one type to another for both BE and LE.
14019   // The right nibble of each byte corresponds to the LE incides.
14020   // and the left nibble of each byte corresponds to the BE incides.
14021   // For example: 0x3074B8FC  byte->word
14022   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
14023   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
14024   // For example: 0x000070F8  byte->double word
14025   // For LE: the allowed indices are: 0x0,0x8
14026   // For BE: the allowed indices are: 0x7,0xF
14027   uint64_t TargetElems[] = {
14028       0x3074B8FC, // b->w
14029       0x000070F8, // b->d
14030       0x10325476, // h->w
14031       0x00003074, // h->d
14032       0x00001032, // w->d
14033   };
14034 
14035   uint64_t Elems = 0;
14036   int Index;
14037   SDValue Input;
14038 
14039   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
14040     if (!Op)
14041       return false;
14042     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
14043         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
14044       return false;
14045 
14046     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
14047     // of the right width.
14048     SDValue Extract = Op.getOperand(0);
14049     if (Extract.getOpcode() == ISD::ANY_EXTEND)
14050       Extract = Extract.getOperand(0);
14051     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14052       return false;
14053 
14054     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
14055     if (!ExtOp)
14056       return false;
14057 
14058     Index = ExtOp->getZExtValue();
14059     if (Input && Input != Extract.getOperand(0))
14060       return false;
14061 
14062     if (!Input)
14063       Input = Extract.getOperand(0);
14064 
14065     Elems = Elems << 8;
14066     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
14067     Elems |= Index;
14068 
14069     return true;
14070   };
14071 
14072   // If the build vector operands aren't sign extended vector extracts,
14073   // of the same input vector, then return.
14074   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14075     if (!isSExtOfVecExtract(N->getOperand(i))) {
14076       return SDValue();
14077     }
14078   }
14079 
14080   // If the vector extract indicies are not correct, add the appropriate
14081   // vector_shuffle.
14082   int TgtElemArrayIdx;
14083   int InputSize = Input.getValueType().getScalarSizeInBits();
14084   int OutputSize = N->getValueType(0).getScalarSizeInBits();
14085   if (InputSize + OutputSize == 40)
14086     TgtElemArrayIdx = 0;
14087   else if (InputSize + OutputSize == 72)
14088     TgtElemArrayIdx = 1;
14089   else if (InputSize + OutputSize == 48)
14090     TgtElemArrayIdx = 2;
14091   else if (InputSize + OutputSize == 80)
14092     TgtElemArrayIdx = 3;
14093   else if (InputSize + OutputSize == 96)
14094     TgtElemArrayIdx = 4;
14095   else
14096     return SDValue();
14097 
14098   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
14099   CorrectElems = DAG.getDataLayout().isLittleEndian()
14100                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
14101                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
14102   if (Elems != CorrectElems) {
14103     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
14104   }
14105 
14106   // Regular lowering will catch cases where a shuffle is not needed.
14107   return SDValue();
14108 }
14109 
14110 // Look for the pattern of a load from a narrow width to i128, feeding
14111 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
14112 // (LXVRZX). This node represents a zero extending load that will be matched
14113 // to the Load VSX Vector Rightmost instructions.
14114 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
14115   SDLoc DL(N);
14116 
14117   // This combine is only eligible for a BUILD_VECTOR of v1i128.
14118   if (N->getValueType(0) != MVT::v1i128)
14119     return SDValue();
14120 
14121   SDValue Operand = N->getOperand(0);
14122   // Proceed with the transformation if the operand to the BUILD_VECTOR
14123   // is a load instruction.
14124   if (Operand.getOpcode() != ISD::LOAD)
14125     return SDValue();
14126 
14127   LoadSDNode *LD = dyn_cast<LoadSDNode>(Operand);
14128   EVT MemoryType = LD->getMemoryVT();
14129 
14130   // This transformation is only valid if the we are loading either a byte,
14131   // halfword, word, or doubleword.
14132   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
14133                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
14134 
14135   // Ensure that the load from the narrow width is being zero extended to i128.
14136   if (!ValidLDType ||
14137       (LD->getExtensionType() != ISD::ZEXTLOAD &&
14138        LD->getExtensionType() != ISD::EXTLOAD))
14139     return SDValue();
14140 
14141   SDValue LoadOps[] = {
14142       LD->getChain(), LD->getBasePtr(),
14143       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
14144 
14145   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
14146                                  DAG.getVTList(MVT::v1i128, MVT::Other),
14147                                  LoadOps, MemoryType, LD->getMemOperand());
14148 }
14149 
14150 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
14151                                                  DAGCombinerInfo &DCI) const {
14152   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14153          "Should be called with a BUILD_VECTOR node");
14154 
14155   SelectionDAG &DAG = DCI.DAG;
14156   SDLoc dl(N);
14157 
14158   if (!Subtarget.hasVSX())
14159     return SDValue();
14160 
14161   // The target independent DAG combiner will leave a build_vector of
14162   // float-to-int conversions intact. We can generate MUCH better code for
14163   // a float-to-int conversion of a vector of floats.
14164   SDValue FirstInput = N->getOperand(0);
14165   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
14166     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
14167     if (Reduced)
14168       return Reduced;
14169   }
14170 
14171   // If we're building a vector out of consecutive loads, just load that
14172   // vector type.
14173   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
14174   if (Reduced)
14175     return Reduced;
14176 
14177   // If we're building a vector out of extended elements from another vector
14178   // we have P9 vector integer extend instructions. The code assumes legal
14179   // input types (i.e. it can't handle things like v4i16) so do not run before
14180   // legalization.
14181   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
14182     Reduced = combineBVOfVecSExt(N, DAG);
14183     if (Reduced)
14184       return Reduced;
14185   }
14186 
14187   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
14188   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
14189   // is a load from <valid narrow width> to i128.
14190   if (Subtarget.isISA3_1()) {
14191     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
14192     if (BVOfZLoad)
14193       return BVOfZLoad;
14194   }
14195 
14196   if (N->getValueType(0) != MVT::v2f64)
14197     return SDValue();
14198 
14199   // Looking for:
14200   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
14201   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
14202       FirstInput.getOpcode() != ISD::UINT_TO_FP)
14203     return SDValue();
14204   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
14205       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
14206     return SDValue();
14207   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
14208     return SDValue();
14209 
14210   SDValue Ext1 = FirstInput.getOperand(0);
14211   SDValue Ext2 = N->getOperand(1).getOperand(0);
14212   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14213      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14214     return SDValue();
14215 
14216   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
14217   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
14218   if (!Ext1Op || !Ext2Op)
14219     return SDValue();
14220   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
14221       Ext1.getOperand(0) != Ext2.getOperand(0))
14222     return SDValue();
14223 
14224   int FirstElem = Ext1Op->getZExtValue();
14225   int SecondElem = Ext2Op->getZExtValue();
14226   int SubvecIdx;
14227   if (FirstElem == 0 && SecondElem == 1)
14228     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
14229   else if (FirstElem == 2 && SecondElem == 3)
14230     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
14231   else
14232     return SDValue();
14233 
14234   SDValue SrcVec = Ext1.getOperand(0);
14235   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
14236     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
14237   return DAG.getNode(NodeType, dl, MVT::v2f64,
14238                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
14239 }
14240 
14241 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
14242                                               DAGCombinerInfo &DCI) const {
14243   assert((N->getOpcode() == ISD::SINT_TO_FP ||
14244           N->getOpcode() == ISD::UINT_TO_FP) &&
14245          "Need an int -> FP conversion node here");
14246 
14247   if (useSoftFloat() || !Subtarget.has64BitSupport())
14248     return SDValue();
14249 
14250   SelectionDAG &DAG = DCI.DAG;
14251   SDLoc dl(N);
14252   SDValue Op(N, 0);
14253 
14254   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
14255   // from the hardware.
14256   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
14257     return SDValue();
14258   if (!Op.getOperand(0).getValueType().isSimple())
14259     return SDValue();
14260   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
14261       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
14262     return SDValue();
14263 
14264   SDValue FirstOperand(Op.getOperand(0));
14265   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
14266     (FirstOperand.getValueType() == MVT::i8 ||
14267      FirstOperand.getValueType() == MVT::i16);
14268   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
14269     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
14270     bool DstDouble = Op.getValueType() == MVT::f64;
14271     unsigned ConvOp = Signed ?
14272       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
14273       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
14274     SDValue WidthConst =
14275       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
14276                             dl, false);
14277     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
14278     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
14279     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
14280                                          DAG.getVTList(MVT::f64, MVT::Other),
14281                                          Ops, MVT::i8, LDN->getMemOperand());
14282 
14283     // For signed conversion, we need to sign-extend the value in the VSR
14284     if (Signed) {
14285       SDValue ExtOps[] = { Ld, WidthConst };
14286       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
14287       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
14288     } else
14289       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
14290   }
14291 
14292 
14293   // For i32 intermediate values, unfortunately, the conversion functions
14294   // leave the upper 32 bits of the value are undefined. Within the set of
14295   // scalar instructions, we have no method for zero- or sign-extending the
14296   // value. Thus, we cannot handle i32 intermediate values here.
14297   if (Op.getOperand(0).getValueType() == MVT::i32)
14298     return SDValue();
14299 
14300   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
14301          "UINT_TO_FP is supported only with FPCVT");
14302 
14303   // If we have FCFIDS, then use it when converting to single-precision.
14304   // Otherwise, convert to double-precision and then round.
14305   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14306                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
14307                                                             : PPCISD::FCFIDS)
14308                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
14309                                                             : PPCISD::FCFID);
14310   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14311                   ? MVT::f32
14312                   : MVT::f64;
14313 
14314   // If we're converting from a float, to an int, and back to a float again,
14315   // then we don't need the store/load pair at all.
14316   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
14317        Subtarget.hasFPCVT()) ||
14318       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
14319     SDValue Src = Op.getOperand(0).getOperand(0);
14320     if (Src.getValueType() == MVT::f32) {
14321       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
14322       DCI.AddToWorklist(Src.getNode());
14323     } else if (Src.getValueType() != MVT::f64) {
14324       // Make sure that we don't pick up a ppc_fp128 source value.
14325       return SDValue();
14326     }
14327 
14328     unsigned FCTOp =
14329       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
14330                                                         PPCISD::FCTIDUZ;
14331 
14332     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
14333     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
14334 
14335     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
14336       FP = DAG.getNode(ISD::FP_ROUND, dl,
14337                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
14338       DCI.AddToWorklist(FP.getNode());
14339     }
14340 
14341     return FP;
14342   }
14343 
14344   return SDValue();
14345 }
14346 
14347 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
14348 // builtins) into loads with swaps.
14349 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
14350                                               DAGCombinerInfo &DCI) const {
14351   SelectionDAG &DAG = DCI.DAG;
14352   SDLoc dl(N);
14353   SDValue Chain;
14354   SDValue Base;
14355   MachineMemOperand *MMO;
14356 
14357   switch (N->getOpcode()) {
14358   default:
14359     llvm_unreachable("Unexpected opcode for little endian VSX load");
14360   case ISD::LOAD: {
14361     LoadSDNode *LD = cast<LoadSDNode>(N);
14362     Chain = LD->getChain();
14363     Base = LD->getBasePtr();
14364     MMO = LD->getMemOperand();
14365     // If the MMO suggests this isn't a load of a full vector, leave
14366     // things alone.  For a built-in, we have to make the change for
14367     // correctness, so if there is a size problem that will be a bug.
14368     if (MMO->getSize() < 16)
14369       return SDValue();
14370     break;
14371   }
14372   case ISD::INTRINSIC_W_CHAIN: {
14373     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14374     Chain = Intrin->getChain();
14375     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
14376     // us what we want. Get operand 2 instead.
14377     Base = Intrin->getOperand(2);
14378     MMO = Intrin->getMemOperand();
14379     break;
14380   }
14381   }
14382 
14383   MVT VecTy = N->getValueType(0).getSimpleVT();
14384 
14385   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
14386   // aligned and the type is a vector with elements up to 4 bytes
14387   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14388       VecTy.getScalarSizeInBits() <= 32) {
14389     return SDValue();
14390   }
14391 
14392   SDValue LoadOps[] = { Chain, Base };
14393   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14394                                          DAG.getVTList(MVT::v2f64, MVT::Other),
14395                                          LoadOps, MVT::v2f64, MMO);
14396 
14397   DCI.AddToWorklist(Load.getNode());
14398   Chain = Load.getValue(1);
14399   SDValue Swap = DAG.getNode(
14400       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14401   DCI.AddToWorklist(Swap.getNode());
14402 
14403   // Add a bitcast if the resulting load type doesn't match v2f64.
14404   if (VecTy != MVT::v2f64) {
14405     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14406     DCI.AddToWorklist(N.getNode());
14407     // Package {bitcast value, swap's chain} to match Load's shape.
14408     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14409                        N, Swap.getValue(1));
14410   }
14411 
14412   return Swap;
14413 }
14414 
14415 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14416 // builtins) into stores with swaps.
14417 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14418                                                DAGCombinerInfo &DCI) const {
14419   SelectionDAG &DAG = DCI.DAG;
14420   SDLoc dl(N);
14421   SDValue Chain;
14422   SDValue Base;
14423   unsigned SrcOpnd;
14424   MachineMemOperand *MMO;
14425 
14426   switch (N->getOpcode()) {
14427   default:
14428     llvm_unreachable("Unexpected opcode for little endian VSX store");
14429   case ISD::STORE: {
14430     StoreSDNode *ST = cast<StoreSDNode>(N);
14431     Chain = ST->getChain();
14432     Base = ST->getBasePtr();
14433     MMO = ST->getMemOperand();
14434     SrcOpnd = 1;
14435     // If the MMO suggests this isn't a store of a full vector, leave
14436     // things alone.  For a built-in, we have to make the change for
14437     // correctness, so if there is a size problem that will be a bug.
14438     if (MMO->getSize() < 16)
14439       return SDValue();
14440     break;
14441   }
14442   case ISD::INTRINSIC_VOID: {
14443     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14444     Chain = Intrin->getChain();
14445     // Intrin->getBasePtr() oddly does not get what we want.
14446     Base = Intrin->getOperand(3);
14447     MMO = Intrin->getMemOperand();
14448     SrcOpnd = 2;
14449     break;
14450   }
14451   }
14452 
14453   SDValue Src = N->getOperand(SrcOpnd);
14454   MVT VecTy = Src.getValueType().getSimpleVT();
14455 
14456   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14457   // aligned and the type is a vector with elements up to 4 bytes
14458   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14459       VecTy.getScalarSizeInBits() <= 32) {
14460     return SDValue();
14461   }
14462 
14463   // All stores are done as v2f64 and possible bit cast.
14464   if (VecTy != MVT::v2f64) {
14465     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14466     DCI.AddToWorklist(Src.getNode());
14467   }
14468 
14469   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14470                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14471   DCI.AddToWorklist(Swap.getNode());
14472   Chain = Swap.getValue(1);
14473   SDValue StoreOps[] = { Chain, Swap, Base };
14474   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14475                                           DAG.getVTList(MVT::Other),
14476                                           StoreOps, VecTy, MMO);
14477   DCI.AddToWorklist(Store.getNode());
14478   return Store;
14479 }
14480 
14481 // Handle DAG combine for STORE (FP_TO_INT F).
14482 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14483                                                DAGCombinerInfo &DCI) const {
14484 
14485   SelectionDAG &DAG = DCI.DAG;
14486   SDLoc dl(N);
14487   unsigned Opcode = N->getOperand(1).getOpcode();
14488 
14489   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14490          && "Not a FP_TO_INT Instruction!");
14491 
14492   SDValue Val = N->getOperand(1).getOperand(0);
14493   EVT Op1VT = N->getOperand(1).getValueType();
14494   EVT ResVT = Val.getValueType();
14495 
14496   if (!isTypeLegal(ResVT))
14497     return SDValue();
14498 
14499   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14500   bool ValidTypeForStoreFltAsInt =
14501         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14502          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14503 
14504   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14505       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14506     return SDValue();
14507 
14508   // Extend f32 values to f64
14509   if (ResVT.getScalarSizeInBits() == 32) {
14510     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14511     DCI.AddToWorklist(Val.getNode());
14512   }
14513 
14514   // Set signed or unsigned conversion opcode.
14515   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14516                           PPCISD::FP_TO_SINT_IN_VSR :
14517                           PPCISD::FP_TO_UINT_IN_VSR;
14518 
14519   Val = DAG.getNode(ConvOpcode,
14520                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14521   DCI.AddToWorklist(Val.getNode());
14522 
14523   // Set number of bytes being converted.
14524   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14525   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14526                     DAG.getIntPtrConstant(ByteSize, dl, false),
14527                     DAG.getValueType(Op1VT) };
14528 
14529   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14530           DAG.getVTList(MVT::Other), Ops,
14531           cast<StoreSDNode>(N)->getMemoryVT(),
14532           cast<StoreSDNode>(N)->getMemOperand());
14533 
14534   DCI.AddToWorklist(Val.getNode());
14535   return Val;
14536 }
14537 
14538 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14539   // Check that the source of the element keeps flipping
14540   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14541   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14542   for (int i = 1, e = Mask.size(); i < e; i++) {
14543     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14544       return false;
14545     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14546       return false;
14547     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14548   }
14549   return true;
14550 }
14551 
14552 static bool isSplatBV(SDValue Op) {
14553   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14554     return false;
14555   SDValue FirstOp;
14556 
14557   // Find first non-undef input.
14558   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14559     FirstOp = Op.getOperand(i);
14560     if (!FirstOp.isUndef())
14561       break;
14562   }
14563 
14564   // All inputs are undef or the same as the first non-undef input.
14565   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14566     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14567       return false;
14568   return true;
14569 }
14570 
14571 static SDValue isScalarToVec(SDValue Op) {
14572   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14573     return Op;
14574   if (Op.getOpcode() != ISD::BITCAST)
14575     return SDValue();
14576   Op = Op.getOperand(0);
14577   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14578     return Op;
14579   return SDValue();
14580 }
14581 
14582 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14583                                             int LHSMaxIdx, int RHSMinIdx,
14584                                             int RHSMaxIdx, int HalfVec) {
14585   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14586     int Idx = ShuffV[i];
14587     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14588       ShuffV[i] += HalfVec;
14589   }
14590   return;
14591 }
14592 
14593 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14594 // the original is:
14595 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14596 // In such a case, just change the shuffle mask to extract the element
14597 // from the permuted index.
14598 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) {
14599   SDLoc dl(OrigSToV);
14600   EVT VT = OrigSToV.getValueType();
14601   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14602          "Expecting a SCALAR_TO_VECTOR here");
14603   SDValue Input = OrigSToV.getOperand(0);
14604 
14605   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14606     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14607     SDValue OrigVector = Input.getOperand(0);
14608 
14609     // Can't handle non-const element indices or different vector types
14610     // for the input to the extract and the output of the scalar_to_vector.
14611     if (Idx && VT == OrigVector.getValueType()) {
14612       SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1);
14613       NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue();
14614       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14615     }
14616   }
14617   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14618                      OrigSToV.getOperand(0));
14619 }
14620 
14621 // On little endian subtargets, combine shuffles such as:
14622 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14623 // into:
14624 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14625 // because the latter can be matched to a single instruction merge.
14626 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14627 // to put the value into element zero. Adjust the shuffle mask so that the
14628 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14629 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14630                                                 SelectionDAG &DAG) const {
14631   SDValue LHS = SVN->getOperand(0);
14632   SDValue RHS = SVN->getOperand(1);
14633   auto Mask = SVN->getMask();
14634   int NumElts = LHS.getValueType().getVectorNumElements();
14635   SDValue Res(SVN, 0);
14636   SDLoc dl(SVN);
14637 
14638   // None of these combines are useful on big endian systems since the ISA
14639   // already has a big endian bias.
14640   if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14641     return Res;
14642 
14643   // If this is not a shuffle of a shuffle and the first element comes from
14644   // the second vector, canonicalize to the commuted form. This will make it
14645   // more likely to match one of the single instruction patterns.
14646   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14647       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14648     std::swap(LHS, RHS);
14649     Res = DAG.getCommutedVectorShuffle(*SVN);
14650     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14651   }
14652 
14653   // Adjust the shuffle mask if either input vector comes from a
14654   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14655   // form (to prevent the need for a swap).
14656   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14657   SDValue SToVLHS = isScalarToVec(LHS);
14658   SDValue SToVRHS = isScalarToVec(RHS);
14659   if (SToVLHS || SToVRHS) {
14660     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14661                             : SToVRHS.getValueType().getVectorNumElements();
14662     int NumEltsOut = ShuffV.size();
14663 
14664     // Initially assume that neither input is permuted. These will be adjusted
14665     // accordingly if either input is.
14666     int LHSMaxIdx = -1;
14667     int RHSMinIdx = -1;
14668     int RHSMaxIdx = -1;
14669     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14670 
14671     // Get the permuted scalar to vector nodes for the source(s) that come from
14672     // ISD::SCALAR_TO_VECTOR.
14673     if (SToVLHS) {
14674       // Set up the values for the shuffle vector fixup.
14675       LHSMaxIdx = NumEltsOut / NumEltsIn;
14676       SToVLHS = getSToVPermuted(SToVLHS, DAG);
14677       if (SToVLHS.getValueType() != LHS.getValueType())
14678         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14679       LHS = SToVLHS;
14680     }
14681     if (SToVRHS) {
14682       RHSMinIdx = NumEltsOut;
14683       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14684       SToVRHS = getSToVPermuted(SToVRHS, DAG);
14685       if (SToVRHS.getValueType() != RHS.getValueType())
14686         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14687       RHS = SToVRHS;
14688     }
14689 
14690     // Fix up the shuffle mask to reflect where the desired element actually is.
14691     // The minimum and maximum indices that correspond to element zero for both
14692     // the LHS and RHS are computed and will control which shuffle mask entries
14693     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14694     // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by
14695     // HalfVec to refer to the corresponding element in the permuted vector.
14696     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14697                                     HalfVec);
14698     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14699 
14700     // We may have simplified away the shuffle. We won't be able to do anything
14701     // further with it here.
14702     if (!isa<ShuffleVectorSDNode>(Res))
14703       return Res;
14704     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14705   }
14706 
14707   // The common case after we commuted the shuffle is that the RHS is a splat
14708   // and we have elements coming in from the splat at indices that are not
14709   // conducive to using a merge.
14710   // Example:
14711   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14712   if (!isSplatBV(RHS))
14713     return Res;
14714 
14715   // We are looking for a mask such that all even elements are from
14716   // one vector and all odd elements from the other.
14717   if (!isAlternatingShuffMask(Mask, NumElts))
14718     return Res;
14719 
14720   // Adjust the mask so we are pulling in the same index from the splat
14721   // as the index from the interesting vector in consecutive elements.
14722   // Example (even elements from first vector):
14723   // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14724   if (Mask[0] < NumElts)
14725     for (int i = 1, e = Mask.size(); i < e; i += 2)
14726       ShuffV[i] = (ShuffV[i - 1] + NumElts);
14727   // Example (odd elements from first vector):
14728   // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14729   else
14730     for (int i = 0, e = Mask.size(); i < e; i += 2)
14731       ShuffV[i] = (ShuffV[i + 1] + NumElts);
14732 
14733   // If the RHS has undefs, we need to remove them since we may have created
14734   // a shuffle that adds those instead of the splat value.
14735   SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue();
14736   RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal);
14737 
14738   Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14739   return Res;
14740 }
14741 
14742 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14743                                                 LSBaseSDNode *LSBase,
14744                                                 DAGCombinerInfo &DCI) const {
14745   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14746         "Not a reverse memop pattern!");
14747 
14748   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14749     auto Mask = SVN->getMask();
14750     int i = 0;
14751     auto I = Mask.rbegin();
14752     auto E = Mask.rend();
14753 
14754     for (; I != E; ++I) {
14755       if (*I != i)
14756         return false;
14757       i++;
14758     }
14759     return true;
14760   };
14761 
14762   SelectionDAG &DAG = DCI.DAG;
14763   EVT VT = SVN->getValueType(0);
14764 
14765   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14766     return SDValue();
14767 
14768   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14769   // See comment in PPCVSXSwapRemoval.cpp.
14770   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14771   if (!Subtarget.hasP9Vector())
14772     return SDValue();
14773 
14774   if(!IsElementReverse(SVN))
14775     return SDValue();
14776 
14777   if (LSBase->getOpcode() == ISD::LOAD) {
14778     SDLoc dl(SVN);
14779     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14780     return DAG.getMemIntrinsicNode(
14781         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14782         LSBase->getMemoryVT(), LSBase->getMemOperand());
14783   }
14784 
14785   if (LSBase->getOpcode() == ISD::STORE) {
14786     SDLoc dl(LSBase);
14787     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14788                           LSBase->getBasePtr()};
14789     return DAG.getMemIntrinsicNode(
14790         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14791         LSBase->getMemoryVT(), LSBase->getMemOperand());
14792   }
14793 
14794   llvm_unreachable("Expected a load or store node here");
14795 }
14796 
14797 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14798                                              DAGCombinerInfo &DCI) const {
14799   SelectionDAG &DAG = DCI.DAG;
14800   SDLoc dl(N);
14801   switch (N->getOpcode()) {
14802   default: break;
14803   case ISD::ADD:
14804     return combineADD(N, DCI);
14805   case ISD::SHL:
14806     return combineSHL(N, DCI);
14807   case ISD::SRA:
14808     return combineSRA(N, DCI);
14809   case ISD::SRL:
14810     return combineSRL(N, DCI);
14811   case ISD::MUL:
14812     return combineMUL(N, DCI);
14813   case ISD::FMA:
14814   case PPCISD::FNMSUB:
14815     return combineFMALike(N, DCI);
14816   case PPCISD::SHL:
14817     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14818         return N->getOperand(0);
14819     break;
14820   case PPCISD::SRL:
14821     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14822         return N->getOperand(0);
14823     break;
14824   case PPCISD::SRA:
14825     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14826       if (C->isNullValue() ||   //  0 >>s V -> 0.
14827           C->isAllOnesValue())    // -1 >>s V -> -1.
14828         return N->getOperand(0);
14829     }
14830     break;
14831   case ISD::SIGN_EXTEND:
14832   case ISD::ZERO_EXTEND:
14833   case ISD::ANY_EXTEND:
14834     return DAGCombineExtBoolTrunc(N, DCI);
14835   case ISD::TRUNCATE:
14836     return combineTRUNCATE(N, DCI);
14837   case ISD::SETCC:
14838     if (SDValue CSCC = combineSetCC(N, DCI))
14839       return CSCC;
14840     LLVM_FALLTHROUGH;
14841   case ISD::SELECT_CC:
14842     return DAGCombineTruncBoolExt(N, DCI);
14843   case ISD::SINT_TO_FP:
14844   case ISD::UINT_TO_FP:
14845     return combineFPToIntToFP(N, DCI);
14846   case ISD::VECTOR_SHUFFLE:
14847     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14848       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14849       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14850     }
14851     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14852   case ISD::STORE: {
14853 
14854     EVT Op1VT = N->getOperand(1).getValueType();
14855     unsigned Opcode = N->getOperand(1).getOpcode();
14856 
14857     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14858       SDValue Val= combineStoreFPToInt(N, DCI);
14859       if (Val)
14860         return Val;
14861     }
14862 
14863     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14864       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14865       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14866       if (Val)
14867         return Val;
14868     }
14869 
14870     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14871     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14872         N->getOperand(1).getNode()->hasOneUse() &&
14873         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14874          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14875 
14876       // STBRX can only handle simple types and it makes no sense to store less
14877       // two bytes in byte-reversed order.
14878       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14879       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14880         break;
14881 
14882       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14883       // Do an any-extend to 32-bits if this is a half-word input.
14884       if (BSwapOp.getValueType() == MVT::i16)
14885         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14886 
14887       // If the type of BSWAP operand is wider than stored memory width
14888       // it need to be shifted to the right side before STBRX.
14889       if (Op1VT.bitsGT(mVT)) {
14890         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14891         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14892                               DAG.getConstant(Shift, dl, MVT::i32));
14893         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14894         if (Op1VT == MVT::i64)
14895           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14896       }
14897 
14898       SDValue Ops[] = {
14899         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14900       };
14901       return
14902         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14903                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14904                                 cast<StoreSDNode>(N)->getMemOperand());
14905     }
14906 
14907     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14908     // So it can increase the chance of CSE constant construction.
14909     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14910         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14911       // Need to sign-extended to 64-bits to handle negative values.
14912       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14913       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14914                                     MemVT.getSizeInBits());
14915       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14916 
14917       // DAG.getTruncStore() can't be used here because it doesn't accept
14918       // the general (base + offset) addressing mode.
14919       // So we use UpdateNodeOperands and setTruncatingStore instead.
14920       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14921                              N->getOperand(3));
14922       cast<StoreSDNode>(N)->setTruncatingStore(true);
14923       return SDValue(N, 0);
14924     }
14925 
14926     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14927     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14928     if (Op1VT.isSimple()) {
14929       MVT StoreVT = Op1VT.getSimpleVT();
14930       if (Subtarget.needsSwapsForVSXMemOps() &&
14931           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14932            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14933         return expandVSXStoreForLE(N, DCI);
14934     }
14935     break;
14936   }
14937   case ISD::LOAD: {
14938     LoadSDNode *LD = cast<LoadSDNode>(N);
14939     EVT VT = LD->getValueType(0);
14940 
14941     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14942     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14943     if (VT.isSimple()) {
14944       MVT LoadVT = VT.getSimpleVT();
14945       if (Subtarget.needsSwapsForVSXMemOps() &&
14946           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14947            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14948         return expandVSXLoadForLE(N, DCI);
14949     }
14950 
14951     // We sometimes end up with a 64-bit integer load, from which we extract
14952     // two single-precision floating-point numbers. This happens with
14953     // std::complex<float>, and other similar structures, because of the way we
14954     // canonicalize structure copies. However, if we lack direct moves,
14955     // then the final bitcasts from the extracted integer values to the
14956     // floating-point numbers turn into store/load pairs. Even with direct moves,
14957     // just loading the two floating-point numbers is likely better.
14958     auto ReplaceTwoFloatLoad = [&]() {
14959       if (VT != MVT::i64)
14960         return false;
14961 
14962       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14963           LD->isVolatile())
14964         return false;
14965 
14966       //  We're looking for a sequence like this:
14967       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14968       //      t16: i64 = srl t13, Constant:i32<32>
14969       //    t17: i32 = truncate t16
14970       //  t18: f32 = bitcast t17
14971       //    t19: i32 = truncate t13
14972       //  t20: f32 = bitcast t19
14973 
14974       if (!LD->hasNUsesOfValue(2, 0))
14975         return false;
14976 
14977       auto UI = LD->use_begin();
14978       while (UI.getUse().getResNo() != 0) ++UI;
14979       SDNode *Trunc = *UI++;
14980       while (UI.getUse().getResNo() != 0) ++UI;
14981       SDNode *RightShift = *UI;
14982       if (Trunc->getOpcode() != ISD::TRUNCATE)
14983         std::swap(Trunc, RightShift);
14984 
14985       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14986           Trunc->getValueType(0) != MVT::i32 ||
14987           !Trunc->hasOneUse())
14988         return false;
14989       if (RightShift->getOpcode() != ISD::SRL ||
14990           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14991           RightShift->getConstantOperandVal(1) != 32 ||
14992           !RightShift->hasOneUse())
14993         return false;
14994 
14995       SDNode *Trunc2 = *RightShift->use_begin();
14996       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14997           Trunc2->getValueType(0) != MVT::i32 ||
14998           !Trunc2->hasOneUse())
14999         return false;
15000 
15001       SDNode *Bitcast = *Trunc->use_begin();
15002       SDNode *Bitcast2 = *Trunc2->use_begin();
15003 
15004       if (Bitcast->getOpcode() != ISD::BITCAST ||
15005           Bitcast->getValueType(0) != MVT::f32)
15006         return false;
15007       if (Bitcast2->getOpcode() != ISD::BITCAST ||
15008           Bitcast2->getValueType(0) != MVT::f32)
15009         return false;
15010 
15011       if (Subtarget.isLittleEndian())
15012         std::swap(Bitcast, Bitcast2);
15013 
15014       // Bitcast has the second float (in memory-layout order) and Bitcast2
15015       // has the first one.
15016 
15017       SDValue BasePtr = LD->getBasePtr();
15018       if (LD->isIndexed()) {
15019         assert(LD->getAddressingMode() == ISD::PRE_INC &&
15020                "Non-pre-inc AM on PPC?");
15021         BasePtr =
15022           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15023                       LD->getOffset());
15024       }
15025 
15026       auto MMOFlags =
15027           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
15028       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
15029                                       LD->getPointerInfo(), LD->getAlignment(),
15030                                       MMOFlags, LD->getAAInfo());
15031       SDValue AddPtr =
15032         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
15033                     BasePtr, DAG.getIntPtrConstant(4, dl));
15034       SDValue FloatLoad2 = DAG.getLoad(
15035           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
15036           LD->getPointerInfo().getWithOffset(4),
15037           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
15038 
15039       if (LD->isIndexed()) {
15040         // Note that DAGCombine should re-form any pre-increment load(s) from
15041         // what is produced here if that makes sense.
15042         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
15043       }
15044 
15045       DCI.CombineTo(Bitcast2, FloatLoad);
15046       DCI.CombineTo(Bitcast, FloatLoad2);
15047 
15048       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
15049                                     SDValue(FloatLoad2.getNode(), 1));
15050       return true;
15051     };
15052 
15053     if (ReplaceTwoFloatLoad())
15054       return SDValue(N, 0);
15055 
15056     EVT MemVT = LD->getMemoryVT();
15057     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
15058     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
15059     if (LD->isUnindexed() && VT.isVector() &&
15060         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
15061           // P8 and later hardware should just use LOAD.
15062           !Subtarget.hasP8Vector() &&
15063           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
15064            VT == MVT::v4f32))) &&
15065         LD->getAlign() < ABIAlignment) {
15066       // This is a type-legal unaligned Altivec load.
15067       SDValue Chain = LD->getChain();
15068       SDValue Ptr = LD->getBasePtr();
15069       bool isLittleEndian = Subtarget.isLittleEndian();
15070 
15071       // This implements the loading of unaligned vectors as described in
15072       // the venerable Apple Velocity Engine overview. Specifically:
15073       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
15074       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
15075       //
15076       // The general idea is to expand a sequence of one or more unaligned
15077       // loads into an alignment-based permutation-control instruction (lvsl
15078       // or lvsr), a series of regular vector loads (which always truncate
15079       // their input address to an aligned address), and a series of
15080       // permutations.  The results of these permutations are the requested
15081       // loaded values.  The trick is that the last "extra" load is not taken
15082       // from the address you might suspect (sizeof(vector) bytes after the
15083       // last requested load), but rather sizeof(vector) - 1 bytes after the
15084       // last requested vector. The point of this is to avoid a page fault if
15085       // the base address happened to be aligned. This works because if the
15086       // base address is aligned, then adding less than a full vector length
15087       // will cause the last vector in the sequence to be (re)loaded.
15088       // Otherwise, the next vector will be fetched as you might suspect was
15089       // necessary.
15090 
15091       // We might be able to reuse the permutation generation from
15092       // a different base address offset from this one by an aligned amount.
15093       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
15094       // optimization later.
15095       Intrinsic::ID Intr, IntrLD, IntrPerm;
15096       MVT PermCntlTy, PermTy, LDTy;
15097       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15098                             : Intrinsic::ppc_altivec_lvsl;
15099       IntrLD = Intrinsic::ppc_altivec_lvx;
15100       IntrPerm = Intrinsic::ppc_altivec_vperm;
15101       PermCntlTy = MVT::v16i8;
15102       PermTy = MVT::v4i32;
15103       LDTy = MVT::v4i32;
15104 
15105       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
15106 
15107       // Create the new MMO for the new base load. It is like the original MMO,
15108       // but represents an area in memory almost twice the vector size centered
15109       // on the original address. If the address is unaligned, we might start
15110       // reading up to (sizeof(vector)-1) bytes below the address of the
15111       // original unaligned load.
15112       MachineFunction &MF = DAG.getMachineFunction();
15113       MachineMemOperand *BaseMMO =
15114         MF.getMachineMemOperand(LD->getMemOperand(),
15115                                 -(long)MemVT.getStoreSize()+1,
15116                                 2*MemVT.getStoreSize()-1);
15117 
15118       // Create the new base load.
15119       SDValue LDXIntID =
15120           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
15121       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
15122       SDValue BaseLoad =
15123         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15124                                 DAG.getVTList(PermTy, MVT::Other),
15125                                 BaseLoadOps, LDTy, BaseMMO);
15126 
15127       // Note that the value of IncOffset (which is provided to the next
15128       // load's pointer info offset value, and thus used to calculate the
15129       // alignment), and the value of IncValue (which is actually used to
15130       // increment the pointer value) are different! This is because we
15131       // require the next load to appear to be aligned, even though it
15132       // is actually offset from the base pointer by a lesser amount.
15133       int IncOffset = VT.getSizeInBits() / 8;
15134       int IncValue = IncOffset;
15135 
15136       // Walk (both up and down) the chain looking for another load at the real
15137       // (aligned) offset (the alignment of the other load does not matter in
15138       // this case). If found, then do not use the offset reduction trick, as
15139       // that will prevent the loads from being later combined (as they would
15140       // otherwise be duplicates).
15141       if (!findConsecutiveLoad(LD, DAG))
15142         --IncValue;
15143 
15144       SDValue Increment =
15145           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
15146       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15147 
15148       MachineMemOperand *ExtraMMO =
15149         MF.getMachineMemOperand(LD->getMemOperand(),
15150                                 1, 2*MemVT.getStoreSize()-1);
15151       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
15152       SDValue ExtraLoad =
15153         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15154                                 DAG.getVTList(PermTy, MVT::Other),
15155                                 ExtraLoadOps, LDTy, ExtraMMO);
15156 
15157       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15158         BaseLoad.getValue(1), ExtraLoad.getValue(1));
15159 
15160       // Because vperm has a big-endian bias, we must reverse the order
15161       // of the input vectors and complement the permute control vector
15162       // when generating little endian code.  We have already handled the
15163       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
15164       // and ExtraLoad here.
15165       SDValue Perm;
15166       if (isLittleEndian)
15167         Perm = BuildIntrinsicOp(IntrPerm,
15168                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
15169       else
15170         Perm = BuildIntrinsicOp(IntrPerm,
15171                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
15172 
15173       if (VT != PermTy)
15174         Perm = Subtarget.hasAltivec()
15175                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
15176                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
15177                                  DAG.getTargetConstant(1, dl, MVT::i64));
15178                                // second argument is 1 because this rounding
15179                                // is always exact.
15180 
15181       // The output of the permutation is our loaded result, the TokenFactor is
15182       // our new chain.
15183       DCI.CombineTo(N, Perm, TF);
15184       return SDValue(N, 0);
15185     }
15186     }
15187     break;
15188     case ISD::INTRINSIC_WO_CHAIN: {
15189       bool isLittleEndian = Subtarget.isLittleEndian();
15190       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15191       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15192                                            : Intrinsic::ppc_altivec_lvsl);
15193       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
15194         SDValue Add = N->getOperand(1);
15195 
15196         int Bits = 4 /* 16 byte alignment */;
15197 
15198         if (DAG.MaskedValueIsZero(Add->getOperand(1),
15199                                   APInt::getAllOnesValue(Bits /* alignment */)
15200                                       .zext(Add.getScalarValueSizeInBits()))) {
15201           SDNode *BasePtr = Add->getOperand(0).getNode();
15202           for (SDNode::use_iterator UI = BasePtr->use_begin(),
15203                                     UE = BasePtr->use_end();
15204                UI != UE; ++UI) {
15205             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15206                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
15207                     IID) {
15208               // We've found another LVSL/LVSR, and this address is an aligned
15209               // multiple of that one. The results will be the same, so use the
15210               // one we've just found instead.
15211 
15212               return SDValue(*UI, 0);
15213             }
15214           }
15215         }
15216 
15217         if (isa<ConstantSDNode>(Add->getOperand(1))) {
15218           SDNode *BasePtr = Add->getOperand(0).getNode();
15219           for (SDNode::use_iterator UI = BasePtr->use_begin(),
15220                UE = BasePtr->use_end(); UI != UE; ++UI) {
15221             if (UI->getOpcode() == ISD::ADD &&
15222                 isa<ConstantSDNode>(UI->getOperand(1)) &&
15223                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
15224                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
15225                 (1ULL << Bits) == 0) {
15226               SDNode *OtherAdd = *UI;
15227               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
15228                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
15229                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15230                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
15231                   return SDValue(*VI, 0);
15232                 }
15233               }
15234             }
15235           }
15236         }
15237       }
15238 
15239       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
15240       // Expose the vabsduw/h/b opportunity for down stream
15241       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
15242           (IID == Intrinsic::ppc_altivec_vmaxsw ||
15243            IID == Intrinsic::ppc_altivec_vmaxsh ||
15244            IID == Intrinsic::ppc_altivec_vmaxsb)) {
15245         SDValue V1 = N->getOperand(1);
15246         SDValue V2 = N->getOperand(2);
15247         if ((V1.getSimpleValueType() == MVT::v4i32 ||
15248              V1.getSimpleValueType() == MVT::v8i16 ||
15249              V1.getSimpleValueType() == MVT::v16i8) &&
15250             V1.getSimpleValueType() == V2.getSimpleValueType()) {
15251           // (0-a, a)
15252           if (V1.getOpcode() == ISD::SUB &&
15253               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
15254               V1.getOperand(1) == V2) {
15255             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
15256           }
15257           // (a, 0-a)
15258           if (V2.getOpcode() == ISD::SUB &&
15259               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
15260               V2.getOperand(1) == V1) {
15261             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15262           }
15263           // (x-y, y-x)
15264           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
15265               V1.getOperand(0) == V2.getOperand(1) &&
15266               V1.getOperand(1) == V2.getOperand(0)) {
15267             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15268           }
15269         }
15270       }
15271     }
15272 
15273     break;
15274   case ISD::INTRINSIC_W_CHAIN:
15275     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15276     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15277     if (Subtarget.needsSwapsForVSXMemOps()) {
15278       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15279       default:
15280         break;
15281       case Intrinsic::ppc_vsx_lxvw4x:
15282       case Intrinsic::ppc_vsx_lxvd2x:
15283         return expandVSXLoadForLE(N, DCI);
15284       }
15285     }
15286     break;
15287   case ISD::INTRINSIC_VOID:
15288     // For little endian, VSX stores require generating xxswapd/stxvd2x.
15289     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15290     if (Subtarget.needsSwapsForVSXMemOps()) {
15291       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15292       default:
15293         break;
15294       case Intrinsic::ppc_vsx_stxvw4x:
15295       case Intrinsic::ppc_vsx_stxvd2x:
15296         return expandVSXStoreForLE(N, DCI);
15297       }
15298     }
15299     break;
15300   case ISD::BSWAP:
15301     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
15302     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
15303         N->getOperand(0).hasOneUse() &&
15304         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
15305          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
15306           N->getValueType(0) == MVT::i64))) {
15307       SDValue Load = N->getOperand(0);
15308       LoadSDNode *LD = cast<LoadSDNode>(Load);
15309       // Create the byte-swapping load.
15310       SDValue Ops[] = {
15311         LD->getChain(),    // Chain
15312         LD->getBasePtr(),  // Ptr
15313         DAG.getValueType(N->getValueType(0)) // VT
15314       };
15315       SDValue BSLoad =
15316         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
15317                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
15318                                               MVT::i64 : MVT::i32, MVT::Other),
15319                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
15320 
15321       // If this is an i16 load, insert the truncate.
15322       SDValue ResVal = BSLoad;
15323       if (N->getValueType(0) == MVT::i16)
15324         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
15325 
15326       // First, combine the bswap away.  This makes the value produced by the
15327       // load dead.
15328       DCI.CombineTo(N, ResVal);
15329 
15330       // Next, combine the load away, we give it a bogus result value but a real
15331       // chain result.  The result value is dead because the bswap is dead.
15332       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
15333 
15334       // Return N so it doesn't get rechecked!
15335       return SDValue(N, 0);
15336     }
15337     break;
15338   case PPCISD::VCMP:
15339     // If a VCMP_rec node already exists with exactly the same operands as this
15340     // node, use its result instead of this node (VCMP_rec computes both a CR6
15341     // and a normal output).
15342     //
15343     if (!N->getOperand(0).hasOneUse() &&
15344         !N->getOperand(1).hasOneUse() &&
15345         !N->getOperand(2).hasOneUse()) {
15346 
15347       // Scan all of the users of the LHS, looking for VCMP_rec's that match.
15348       SDNode *VCMPrecNode = nullptr;
15349 
15350       SDNode *LHSN = N->getOperand(0).getNode();
15351       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
15352            UI != E; ++UI)
15353         if (UI->getOpcode() == PPCISD::VCMP_rec &&
15354             UI->getOperand(1) == N->getOperand(1) &&
15355             UI->getOperand(2) == N->getOperand(2) &&
15356             UI->getOperand(0) == N->getOperand(0)) {
15357           VCMPrecNode = *UI;
15358           break;
15359         }
15360 
15361       // If there is no VCMP_rec node, or if the flag value has a single use,
15362       // don't transform this.
15363       if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
15364         break;
15365 
15366       // Look at the (necessarily single) use of the flag value.  If it has a
15367       // chain, this transformation is more complex.  Note that multiple things
15368       // could use the value result, which we should ignore.
15369       SDNode *FlagUser = nullptr;
15370       for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
15371            FlagUser == nullptr; ++UI) {
15372         assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
15373         SDNode *User = *UI;
15374         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
15375           if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
15376             FlagUser = User;
15377             break;
15378           }
15379         }
15380       }
15381 
15382       // If the user is a MFOCRF instruction, we know this is safe.
15383       // Otherwise we give up for right now.
15384       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
15385         return SDValue(VCMPrecNode, 0);
15386     }
15387     break;
15388   case ISD::BRCOND: {
15389     SDValue Cond = N->getOperand(1);
15390     SDValue Target = N->getOperand(2);
15391 
15392     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15393         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15394           Intrinsic::loop_decrement) {
15395 
15396       // We now need to make the intrinsic dead (it cannot be instruction
15397       // selected).
15398       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15399       assert(Cond.getNode()->hasOneUse() &&
15400              "Counter decrement has more than one use");
15401 
15402       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15403                          N->getOperand(0), Target);
15404     }
15405   }
15406   break;
15407   case ISD::BR_CC: {
15408     // If this is a branch on an altivec predicate comparison, lower this so
15409     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15410     // lowering is done pre-legalize, because the legalizer lowers the predicate
15411     // compare down to code that is difficult to reassemble.
15412     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15413     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15414 
15415     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15416     // value. If so, pass-through the AND to get to the intrinsic.
15417     if (LHS.getOpcode() == ISD::AND &&
15418         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15419         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15420           Intrinsic::loop_decrement &&
15421         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15422         !isNullConstant(LHS.getOperand(1)))
15423       LHS = LHS.getOperand(0);
15424 
15425     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15426         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15427           Intrinsic::loop_decrement &&
15428         isa<ConstantSDNode>(RHS)) {
15429       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15430              "Counter decrement comparison is not EQ or NE");
15431 
15432       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15433       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15434                     (CC == ISD::SETNE && !Val);
15435 
15436       // We now need to make the intrinsic dead (it cannot be instruction
15437       // selected).
15438       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15439       assert(LHS.getNode()->hasOneUse() &&
15440              "Counter decrement has more than one use");
15441 
15442       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15443                          N->getOperand(0), N->getOperand(4));
15444     }
15445 
15446     int CompareOpc;
15447     bool isDot;
15448 
15449     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15450         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15451         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15452       assert(isDot && "Can't compare against a vector result!");
15453 
15454       // If this is a comparison against something other than 0/1, then we know
15455       // that the condition is never/always true.
15456       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15457       if (Val != 0 && Val != 1) {
15458         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15459           return N->getOperand(0);
15460         // Always !=, turn it into an unconditional branch.
15461         return DAG.getNode(ISD::BR, dl, MVT::Other,
15462                            N->getOperand(0), N->getOperand(4));
15463       }
15464 
15465       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15466 
15467       // Create the PPCISD altivec 'dot' comparison node.
15468       SDValue Ops[] = {
15469         LHS.getOperand(2),  // LHS of compare
15470         LHS.getOperand(3),  // RHS of compare
15471         DAG.getConstant(CompareOpc, dl, MVT::i32)
15472       };
15473       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15474       SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
15475 
15476       // Unpack the result based on how the target uses it.
15477       PPC::Predicate CompOpc;
15478       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15479       default:  // Can't happen, don't crash on invalid number though.
15480       case 0:   // Branch on the value of the EQ bit of CR6.
15481         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15482         break;
15483       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15484         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15485         break;
15486       case 2:   // Branch on the value of the LT bit of CR6.
15487         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15488         break;
15489       case 3:   // Branch on the inverted value of the LT bit of CR6.
15490         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15491         break;
15492       }
15493 
15494       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15495                          DAG.getConstant(CompOpc, dl, MVT::i32),
15496                          DAG.getRegister(PPC::CR6, MVT::i32),
15497                          N->getOperand(4), CompNode.getValue(1));
15498     }
15499     break;
15500   }
15501   case ISD::BUILD_VECTOR:
15502     return DAGCombineBuildVector(N, DCI);
15503   case ISD::ABS:
15504     return combineABS(N, DCI);
15505   case ISD::VSELECT:
15506     return combineVSelect(N, DCI);
15507   }
15508 
15509   return SDValue();
15510 }
15511 
15512 SDValue
15513 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15514                                  SelectionDAG &DAG,
15515                                  SmallVectorImpl<SDNode *> &Created) const {
15516   // fold (sdiv X, pow2)
15517   EVT VT = N->getValueType(0);
15518   if (VT == MVT::i64 && !Subtarget.isPPC64())
15519     return SDValue();
15520   if ((VT != MVT::i32 && VT != MVT::i64) ||
15521       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
15522     return SDValue();
15523 
15524   SDLoc DL(N);
15525   SDValue N0 = N->getOperand(0);
15526 
15527   bool IsNegPow2 = (-Divisor).isPowerOf2();
15528   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15529   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15530 
15531   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15532   Created.push_back(Op.getNode());
15533 
15534   if (IsNegPow2) {
15535     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15536     Created.push_back(Op.getNode());
15537   }
15538 
15539   return Op;
15540 }
15541 
15542 //===----------------------------------------------------------------------===//
15543 // Inline Assembly Support
15544 //===----------------------------------------------------------------------===//
15545 
15546 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15547                                                       KnownBits &Known,
15548                                                       const APInt &DemandedElts,
15549                                                       const SelectionDAG &DAG,
15550                                                       unsigned Depth) const {
15551   Known.resetAll();
15552   switch (Op.getOpcode()) {
15553   default: break;
15554   case PPCISD::LBRX: {
15555     // lhbrx is known to have the top bits cleared out.
15556     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15557       Known.Zero = 0xFFFF0000;
15558     break;
15559   }
15560   case ISD::INTRINSIC_WO_CHAIN: {
15561     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15562     default: break;
15563     case Intrinsic::ppc_altivec_vcmpbfp_p:
15564     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15565     case Intrinsic::ppc_altivec_vcmpequb_p:
15566     case Intrinsic::ppc_altivec_vcmpequh_p:
15567     case Intrinsic::ppc_altivec_vcmpequw_p:
15568     case Intrinsic::ppc_altivec_vcmpequd_p:
15569     case Intrinsic::ppc_altivec_vcmpequq_p:
15570     case Intrinsic::ppc_altivec_vcmpgefp_p:
15571     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15572     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15573     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15574     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15575     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15576     case Intrinsic::ppc_altivec_vcmpgtsq_p:
15577     case Intrinsic::ppc_altivec_vcmpgtub_p:
15578     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15579     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15580     case Intrinsic::ppc_altivec_vcmpgtud_p:
15581     case Intrinsic::ppc_altivec_vcmpgtuq_p:
15582       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15583       break;
15584     }
15585   }
15586   }
15587 }
15588 
15589 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15590   switch (Subtarget.getCPUDirective()) {
15591   default: break;
15592   case PPC::DIR_970:
15593   case PPC::DIR_PWR4:
15594   case PPC::DIR_PWR5:
15595   case PPC::DIR_PWR5X:
15596   case PPC::DIR_PWR6:
15597   case PPC::DIR_PWR6X:
15598   case PPC::DIR_PWR7:
15599   case PPC::DIR_PWR8:
15600   case PPC::DIR_PWR9:
15601   case PPC::DIR_PWR10:
15602   case PPC::DIR_PWR_FUTURE: {
15603     if (!ML)
15604       break;
15605 
15606     if (!DisableInnermostLoopAlign32) {
15607       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15608       // so that we can decrease cache misses and branch-prediction misses.
15609       // Actual alignment of the loop will depend on the hotness check and other
15610       // logic in alignBlocks.
15611       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15612         return Align(32);
15613     }
15614 
15615     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15616 
15617     // For small loops (between 5 and 8 instructions), align to a 32-byte
15618     // boundary so that the entire loop fits in one instruction-cache line.
15619     uint64_t LoopSize = 0;
15620     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15621       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15622         LoopSize += TII->getInstSizeInBytes(*J);
15623         if (LoopSize > 32)
15624           break;
15625       }
15626 
15627     if (LoopSize > 16 && LoopSize <= 32)
15628       return Align(32);
15629 
15630     break;
15631   }
15632   }
15633 
15634   return TargetLowering::getPrefLoopAlignment(ML);
15635 }
15636 
15637 /// getConstraintType - Given a constraint, return the type of
15638 /// constraint it is for this target.
15639 PPCTargetLowering::ConstraintType
15640 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15641   if (Constraint.size() == 1) {
15642     switch (Constraint[0]) {
15643     default: break;
15644     case 'b':
15645     case 'r':
15646     case 'f':
15647     case 'd':
15648     case 'v':
15649     case 'y':
15650       return C_RegisterClass;
15651     case 'Z':
15652       // FIXME: While Z does indicate a memory constraint, it specifically
15653       // indicates an r+r address (used in conjunction with the 'y' modifier
15654       // in the replacement string). Currently, we're forcing the base
15655       // register to be r0 in the asm printer (which is interpreted as zero)
15656       // and forming the complete address in the second register. This is
15657       // suboptimal.
15658       return C_Memory;
15659     }
15660   } else if (Constraint == "wc") { // individual CR bits.
15661     return C_RegisterClass;
15662   } else if (Constraint == "wa" || Constraint == "wd" ||
15663              Constraint == "wf" || Constraint == "ws" ||
15664              Constraint == "wi" || Constraint == "ww") {
15665     return C_RegisterClass; // VSX registers.
15666   }
15667   return TargetLowering::getConstraintType(Constraint);
15668 }
15669 
15670 /// Examine constraint type and operand type and determine a weight value.
15671 /// This object must already have been set up with the operand type
15672 /// and the current alternative constraint selected.
15673 TargetLowering::ConstraintWeight
15674 PPCTargetLowering::getSingleConstraintMatchWeight(
15675     AsmOperandInfo &info, const char *constraint) const {
15676   ConstraintWeight weight = CW_Invalid;
15677   Value *CallOperandVal = info.CallOperandVal;
15678     // If we don't have a value, we can't do a match,
15679     // but allow it at the lowest weight.
15680   if (!CallOperandVal)
15681     return CW_Default;
15682   Type *type = CallOperandVal->getType();
15683 
15684   // Look at the constraint type.
15685   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15686     return CW_Register; // an individual CR bit.
15687   else if ((StringRef(constraint) == "wa" ||
15688             StringRef(constraint) == "wd" ||
15689             StringRef(constraint) == "wf") &&
15690            type->isVectorTy())
15691     return CW_Register;
15692   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15693     return CW_Register; // just hold 64-bit integers data.
15694   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15695     return CW_Register;
15696   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15697     return CW_Register;
15698 
15699   switch (*constraint) {
15700   default:
15701     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15702     break;
15703   case 'b':
15704     if (type->isIntegerTy())
15705       weight = CW_Register;
15706     break;
15707   case 'f':
15708     if (type->isFloatTy())
15709       weight = CW_Register;
15710     break;
15711   case 'd':
15712     if (type->isDoubleTy())
15713       weight = CW_Register;
15714     break;
15715   case 'v':
15716     if (type->isVectorTy())
15717       weight = CW_Register;
15718     break;
15719   case 'y':
15720     weight = CW_Register;
15721     break;
15722   case 'Z':
15723     weight = CW_Memory;
15724     break;
15725   }
15726   return weight;
15727 }
15728 
15729 std::pair<unsigned, const TargetRegisterClass *>
15730 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15731                                                 StringRef Constraint,
15732                                                 MVT VT) const {
15733   if (Constraint.size() == 1) {
15734     // GCC RS6000 Constraint Letters
15735     switch (Constraint[0]) {
15736     case 'b':   // R1-R31
15737       if (VT == MVT::i64 && Subtarget.isPPC64())
15738         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15739       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15740     case 'r':   // R0-R31
15741       if (VT == MVT::i64 && Subtarget.isPPC64())
15742         return std::make_pair(0U, &PPC::G8RCRegClass);
15743       return std::make_pair(0U, &PPC::GPRCRegClass);
15744     // 'd' and 'f' constraints are both defined to be "the floating point
15745     // registers", where one is for 32-bit and the other for 64-bit. We don't
15746     // really care overly much here so just give them all the same reg classes.
15747     case 'd':
15748     case 'f':
15749       if (Subtarget.hasSPE()) {
15750         if (VT == MVT::f32 || VT == MVT::i32)
15751           return std::make_pair(0U, &PPC::GPRCRegClass);
15752         if (VT == MVT::f64 || VT == MVT::i64)
15753           return std::make_pair(0U, &PPC::SPERCRegClass);
15754       } else {
15755         if (VT == MVT::f32 || VT == MVT::i32)
15756           return std::make_pair(0U, &PPC::F4RCRegClass);
15757         if (VT == MVT::f64 || VT == MVT::i64)
15758           return std::make_pair(0U, &PPC::F8RCRegClass);
15759       }
15760       break;
15761     case 'v':
15762       if (Subtarget.hasAltivec())
15763         return std::make_pair(0U, &PPC::VRRCRegClass);
15764       break;
15765     case 'y':   // crrc
15766       return std::make_pair(0U, &PPC::CRRCRegClass);
15767     }
15768   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15769     // An individual CR bit.
15770     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15771   } else if ((Constraint == "wa" || Constraint == "wd" ||
15772              Constraint == "wf" || Constraint == "wi") &&
15773              Subtarget.hasVSX()) {
15774     return std::make_pair(0U, &PPC::VSRCRegClass);
15775   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15776     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15777       return std::make_pair(0U, &PPC::VSSRCRegClass);
15778     else
15779       return std::make_pair(0U, &PPC::VSFRCRegClass);
15780   }
15781 
15782   // If we name a VSX register, we can't defer to the base class because it
15783   // will not recognize the correct register (their names will be VSL{0-31}
15784   // and V{0-31} so they won't match). So we match them here.
15785   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15786     int VSNum = atoi(Constraint.data() + 3);
15787     assert(VSNum >= 0 && VSNum <= 63 &&
15788            "Attempted to access a vsr out of range");
15789     if (VSNum < 32)
15790       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15791     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15792   }
15793   std::pair<unsigned, const TargetRegisterClass *> R =
15794       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15795 
15796   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15797   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15798   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15799   // register.
15800   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15801   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15802   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15803       PPC::GPRCRegClass.contains(R.first))
15804     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15805                             PPC::sub_32, &PPC::G8RCRegClass),
15806                           &PPC::G8RCRegClass);
15807 
15808   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15809   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15810     R.first = PPC::CR0;
15811     R.second = &PPC::CRRCRegClass;
15812   }
15813 
15814   return R;
15815 }
15816 
15817 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15818 /// vector.  If it is invalid, don't add anything to Ops.
15819 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15820                                                      std::string &Constraint,
15821                                                      std::vector<SDValue>&Ops,
15822                                                      SelectionDAG &DAG) const {
15823   SDValue Result;
15824 
15825   // Only support length 1 constraints.
15826   if (Constraint.length() > 1) return;
15827 
15828   char Letter = Constraint[0];
15829   switch (Letter) {
15830   default: break;
15831   case 'I':
15832   case 'J':
15833   case 'K':
15834   case 'L':
15835   case 'M':
15836   case 'N':
15837   case 'O':
15838   case 'P': {
15839     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15840     if (!CST) return; // Must be an immediate to match.
15841     SDLoc dl(Op);
15842     int64_t Value = CST->getSExtValue();
15843     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15844                          // numbers are printed as such.
15845     switch (Letter) {
15846     default: llvm_unreachable("Unknown constraint letter!");
15847     case 'I':  // "I" is a signed 16-bit constant.
15848       if (isInt<16>(Value))
15849         Result = DAG.getTargetConstant(Value, dl, TCVT);
15850       break;
15851     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15852       if (isShiftedUInt<16, 16>(Value))
15853         Result = DAG.getTargetConstant(Value, dl, TCVT);
15854       break;
15855     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15856       if (isShiftedInt<16, 16>(Value))
15857         Result = DAG.getTargetConstant(Value, dl, TCVT);
15858       break;
15859     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15860       if (isUInt<16>(Value))
15861         Result = DAG.getTargetConstant(Value, dl, TCVT);
15862       break;
15863     case 'M':  // "M" is a constant that is greater than 31.
15864       if (Value > 31)
15865         Result = DAG.getTargetConstant(Value, dl, TCVT);
15866       break;
15867     case 'N':  // "N" is a positive constant that is an exact power of two.
15868       if (Value > 0 && isPowerOf2_64(Value))
15869         Result = DAG.getTargetConstant(Value, dl, TCVT);
15870       break;
15871     case 'O':  // "O" is the constant zero.
15872       if (Value == 0)
15873         Result = DAG.getTargetConstant(Value, dl, TCVT);
15874       break;
15875     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15876       if (isInt<16>(-Value))
15877         Result = DAG.getTargetConstant(Value, dl, TCVT);
15878       break;
15879     }
15880     break;
15881   }
15882   }
15883 
15884   if (Result.getNode()) {
15885     Ops.push_back(Result);
15886     return;
15887   }
15888 
15889   // Handle standard constraint letters.
15890   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15891 }
15892 
15893 // isLegalAddressingMode - Return true if the addressing mode represented
15894 // by AM is legal for this target, for a load/store of the specified type.
15895 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15896                                               const AddrMode &AM, Type *Ty,
15897                                               unsigned AS,
15898                                               Instruction *I) const {
15899   // Vector type r+i form is supported since power9 as DQ form. We don't check
15900   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
15901   // imm form is preferred and the offset can be adjusted to use imm form later
15902   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
15903   // max offset to check legal addressing mode, we should be a little aggressive
15904   // to contain other offsets for that LSRUse.
15905   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
15906     return false;
15907 
15908   // PPC allows a sign-extended 16-bit immediate field.
15909   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15910     return false;
15911 
15912   // No global is ever allowed as a base.
15913   if (AM.BaseGV)
15914     return false;
15915 
15916   // PPC only support r+r,
15917   switch (AM.Scale) {
15918   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15919     break;
15920   case 1:
15921     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15922       return false;
15923     // Otherwise we have r+r or r+i.
15924     break;
15925   case 2:
15926     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15927       return false;
15928     // Allow 2*r as r+r.
15929     break;
15930   default:
15931     // No other scales are supported.
15932     return false;
15933   }
15934 
15935   return true;
15936 }
15937 
15938 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15939                                            SelectionDAG &DAG) const {
15940   MachineFunction &MF = DAG.getMachineFunction();
15941   MachineFrameInfo &MFI = MF.getFrameInfo();
15942   MFI.setReturnAddressIsTaken(true);
15943 
15944   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15945     return SDValue();
15946 
15947   SDLoc dl(Op);
15948   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15949 
15950   // Make sure the function does not optimize away the store of the RA to
15951   // the stack.
15952   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15953   FuncInfo->setLRStoreRequired();
15954   bool isPPC64 = Subtarget.isPPC64();
15955   auto PtrVT = getPointerTy(MF.getDataLayout());
15956 
15957   if (Depth > 0) {
15958     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15959     SDValue Offset =
15960         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15961                         isPPC64 ? MVT::i64 : MVT::i32);
15962     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15963                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15964                        MachinePointerInfo());
15965   }
15966 
15967   // Just load the return address off the stack.
15968   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15969   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15970                      MachinePointerInfo());
15971 }
15972 
15973 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15974                                           SelectionDAG &DAG) const {
15975   SDLoc dl(Op);
15976   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15977 
15978   MachineFunction &MF = DAG.getMachineFunction();
15979   MachineFrameInfo &MFI = MF.getFrameInfo();
15980   MFI.setFrameAddressIsTaken(true);
15981 
15982   EVT PtrVT = getPointerTy(MF.getDataLayout());
15983   bool isPPC64 = PtrVT == MVT::i64;
15984 
15985   // Naked functions never have a frame pointer, and so we use r1. For all
15986   // other functions, this decision must be delayed until during PEI.
15987   unsigned FrameReg;
15988   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15989     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15990   else
15991     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15992 
15993   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15994                                          PtrVT);
15995   while (Depth--)
15996     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15997                             FrameAddr, MachinePointerInfo());
15998   return FrameAddr;
15999 }
16000 
16001 // FIXME? Maybe this could be a TableGen attribute on some registers and
16002 // this table could be generated automatically from RegInfo.
16003 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
16004                                               const MachineFunction &MF) const {
16005   bool isPPC64 = Subtarget.isPPC64();
16006 
16007   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
16008   if (!is64Bit && VT != LLT::scalar(32))
16009     report_fatal_error("Invalid register global variable type");
16010 
16011   Register Reg = StringSwitch<Register>(RegName)
16012                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
16013                      .Case("r2", isPPC64 ? Register() : PPC::R2)
16014                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
16015                      .Default(Register());
16016 
16017   if (Reg)
16018     return Reg;
16019   report_fatal_error("Invalid register name global variable");
16020 }
16021 
16022 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
16023   // 32-bit SVR4 ABI access everything as got-indirect.
16024   if (Subtarget.is32BitELFABI())
16025     return true;
16026 
16027   // AIX accesses everything indirectly through the TOC, which is similar to
16028   // the GOT.
16029   if (Subtarget.isAIXABI())
16030     return true;
16031 
16032   CodeModel::Model CModel = getTargetMachine().getCodeModel();
16033   // If it is small or large code model, module locals are accessed
16034   // indirectly by loading their address from .toc/.got.
16035   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
16036     return true;
16037 
16038   // JumpTable and BlockAddress are accessed as got-indirect.
16039   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
16040     return true;
16041 
16042   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
16043     return Subtarget.isGVIndirectSymbol(G->getGlobal());
16044 
16045   return false;
16046 }
16047 
16048 bool
16049 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
16050   // The PowerPC target isn't yet aware of offsets.
16051   return false;
16052 }
16053 
16054 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
16055                                            const CallInst &I,
16056                                            MachineFunction &MF,
16057                                            unsigned Intrinsic) const {
16058   switch (Intrinsic) {
16059   case Intrinsic::ppc_altivec_lvx:
16060   case Intrinsic::ppc_altivec_lvxl:
16061   case Intrinsic::ppc_altivec_lvebx:
16062   case Intrinsic::ppc_altivec_lvehx:
16063   case Intrinsic::ppc_altivec_lvewx:
16064   case Intrinsic::ppc_vsx_lxvd2x:
16065   case Intrinsic::ppc_vsx_lxvw4x:
16066   case Intrinsic::ppc_vsx_lxvd2x_be:
16067   case Intrinsic::ppc_vsx_lxvw4x_be:
16068   case Intrinsic::ppc_vsx_lxvl:
16069   case Intrinsic::ppc_vsx_lxvll: {
16070     EVT VT;
16071     switch (Intrinsic) {
16072     case Intrinsic::ppc_altivec_lvebx:
16073       VT = MVT::i8;
16074       break;
16075     case Intrinsic::ppc_altivec_lvehx:
16076       VT = MVT::i16;
16077       break;
16078     case Intrinsic::ppc_altivec_lvewx:
16079       VT = MVT::i32;
16080       break;
16081     case Intrinsic::ppc_vsx_lxvd2x:
16082     case Intrinsic::ppc_vsx_lxvd2x_be:
16083       VT = MVT::v2f64;
16084       break;
16085     default:
16086       VT = MVT::v4i32;
16087       break;
16088     }
16089 
16090     Info.opc = ISD::INTRINSIC_W_CHAIN;
16091     Info.memVT = VT;
16092     Info.ptrVal = I.getArgOperand(0);
16093     Info.offset = -VT.getStoreSize()+1;
16094     Info.size = 2*VT.getStoreSize()-1;
16095     Info.align = Align(1);
16096     Info.flags = MachineMemOperand::MOLoad;
16097     return true;
16098   }
16099   case Intrinsic::ppc_altivec_stvx:
16100   case Intrinsic::ppc_altivec_stvxl:
16101   case Intrinsic::ppc_altivec_stvebx:
16102   case Intrinsic::ppc_altivec_stvehx:
16103   case Intrinsic::ppc_altivec_stvewx:
16104   case Intrinsic::ppc_vsx_stxvd2x:
16105   case Intrinsic::ppc_vsx_stxvw4x:
16106   case Intrinsic::ppc_vsx_stxvd2x_be:
16107   case Intrinsic::ppc_vsx_stxvw4x_be:
16108   case Intrinsic::ppc_vsx_stxvl:
16109   case Intrinsic::ppc_vsx_stxvll: {
16110     EVT VT;
16111     switch (Intrinsic) {
16112     case Intrinsic::ppc_altivec_stvebx:
16113       VT = MVT::i8;
16114       break;
16115     case Intrinsic::ppc_altivec_stvehx:
16116       VT = MVT::i16;
16117       break;
16118     case Intrinsic::ppc_altivec_stvewx:
16119       VT = MVT::i32;
16120       break;
16121     case Intrinsic::ppc_vsx_stxvd2x:
16122     case Intrinsic::ppc_vsx_stxvd2x_be:
16123       VT = MVT::v2f64;
16124       break;
16125     default:
16126       VT = MVT::v4i32;
16127       break;
16128     }
16129 
16130     Info.opc = ISD::INTRINSIC_VOID;
16131     Info.memVT = VT;
16132     Info.ptrVal = I.getArgOperand(1);
16133     Info.offset = -VT.getStoreSize()+1;
16134     Info.size = 2*VT.getStoreSize()-1;
16135     Info.align = Align(1);
16136     Info.flags = MachineMemOperand::MOStore;
16137     return true;
16138   }
16139   default:
16140     break;
16141   }
16142 
16143   return false;
16144 }
16145 
16146 /// It returns EVT::Other if the type should be determined using generic
16147 /// target-independent logic.
16148 EVT PPCTargetLowering::getOptimalMemOpType(
16149     const MemOp &Op, const AttributeList &FuncAttributes) const {
16150   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
16151     // We should use Altivec/VSX loads and stores when available. For unaligned
16152     // addresses, unaligned VSX loads are only fast starting with the P8.
16153     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
16154         (Op.isAligned(Align(16)) ||
16155          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
16156       return MVT::v4i32;
16157   }
16158 
16159   if (Subtarget.isPPC64()) {
16160     return MVT::i64;
16161   }
16162 
16163   return MVT::i32;
16164 }
16165 
16166 /// Returns true if it is beneficial to convert a load of a constant
16167 /// to just the constant itself.
16168 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16169                                                           Type *Ty) const {
16170   assert(Ty->isIntegerTy());
16171 
16172   unsigned BitSize = Ty->getPrimitiveSizeInBits();
16173   return !(BitSize == 0 || BitSize > 64);
16174 }
16175 
16176 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16177   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16178     return false;
16179   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16180   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16181   return NumBits1 == 64 && NumBits2 == 32;
16182 }
16183 
16184 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16185   if (!VT1.isInteger() || !VT2.isInteger())
16186     return false;
16187   unsigned NumBits1 = VT1.getSizeInBits();
16188   unsigned NumBits2 = VT2.getSizeInBits();
16189   return NumBits1 == 64 && NumBits2 == 32;
16190 }
16191 
16192 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16193   // Generally speaking, zexts are not free, but they are free when they can be
16194   // folded with other operations.
16195   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
16196     EVT MemVT = LD->getMemoryVT();
16197     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
16198          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
16199         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
16200          LD->getExtensionType() == ISD::ZEXTLOAD))
16201       return true;
16202   }
16203 
16204   // FIXME: Add other cases...
16205   //  - 32-bit shifts with a zext to i64
16206   //  - zext after ctlz, bswap, etc.
16207   //  - zext after and by a constant mask
16208 
16209   return TargetLowering::isZExtFree(Val, VT2);
16210 }
16211 
16212 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
16213   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
16214          "invalid fpext types");
16215   // Extending to float128 is not free.
16216   if (DestVT == MVT::f128)
16217     return false;
16218   return true;
16219 }
16220 
16221 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16222   return isInt<16>(Imm) || isUInt<16>(Imm);
16223 }
16224 
16225 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16226   return isInt<16>(Imm) || isUInt<16>(Imm);
16227 }
16228 
16229 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
16230                                                        unsigned,
16231                                                        unsigned,
16232                                                        MachineMemOperand::Flags,
16233                                                        bool *Fast) const {
16234   if (DisablePPCUnaligned)
16235     return false;
16236 
16237   // PowerPC supports unaligned memory access for simple non-vector types.
16238   // Although accessing unaligned addresses is not as efficient as accessing
16239   // aligned addresses, it is generally more efficient than manual expansion,
16240   // and generally only traps for software emulation when crossing page
16241   // boundaries.
16242 
16243   if (!VT.isSimple())
16244     return false;
16245 
16246   if (VT.isFloatingPoint() && !VT.isVector() &&
16247       !Subtarget.allowsUnalignedFPAccess())
16248     return false;
16249 
16250   if (VT.getSimpleVT().isVector()) {
16251     if (Subtarget.hasVSX()) {
16252       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
16253           VT != MVT::v4f32 && VT != MVT::v4i32)
16254         return false;
16255     } else {
16256       return false;
16257     }
16258   }
16259 
16260   if (VT == MVT::ppcf128)
16261     return false;
16262 
16263   if (Fast)
16264     *Fast = true;
16265 
16266   return true;
16267 }
16268 
16269 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
16270                                                SDValue C) const {
16271   // Check integral scalar types.
16272   if (!VT.isScalarInteger())
16273     return false;
16274   if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
16275     if (!ConstNode->getAPIntValue().isSignedIntN(64))
16276       return false;
16277     // This transformation will generate >= 2 operations. But the following
16278     // cases will generate <= 2 instructions during ISEL. So exclude them.
16279     // 1. If the constant multiplier fits 16 bits, it can be handled by one
16280     // HW instruction, ie. MULLI
16281     // 2. If the multiplier after shifted fits 16 bits, an extra shift
16282     // instruction is needed than case 1, ie. MULLI and RLDICR
16283     int64_t Imm = ConstNode->getSExtValue();
16284     unsigned Shift = countTrailingZeros<uint64_t>(Imm);
16285     Imm >>= Shift;
16286     if (isInt<16>(Imm))
16287       return false;
16288     uint64_t UImm = static_cast<uint64_t>(Imm);
16289     if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
16290         isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
16291       return true;
16292   }
16293   return false;
16294 }
16295 
16296 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16297                                                    EVT VT) const {
16298   return isFMAFasterThanFMulAndFAdd(
16299       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
16300 }
16301 
16302 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
16303                                                    Type *Ty) const {
16304   switch (Ty->getScalarType()->getTypeID()) {
16305   case Type::FloatTyID:
16306   case Type::DoubleTyID:
16307     return true;
16308   case Type::FP128TyID:
16309     return Subtarget.hasP9Vector();
16310   default:
16311     return false;
16312   }
16313 }
16314 
16315 // FIXME: add more patterns which are not profitable to hoist.
16316 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
16317   if (!I->hasOneUse())
16318     return true;
16319 
16320   Instruction *User = I->user_back();
16321   assert(User && "A single use instruction with no uses.");
16322 
16323   switch (I->getOpcode()) {
16324   case Instruction::FMul: {
16325     // Don't break FMA, PowerPC prefers FMA.
16326     if (User->getOpcode() != Instruction::FSub &&
16327         User->getOpcode() != Instruction::FAdd)
16328       return true;
16329 
16330     const TargetOptions &Options = getTargetMachine().Options;
16331     const Function *F = I->getFunction();
16332     const DataLayout &DL = F->getParent()->getDataLayout();
16333     Type *Ty = User->getOperand(0)->getType();
16334 
16335     return !(
16336         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
16337         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
16338         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
16339   }
16340   case Instruction::Load: {
16341     // Don't break "store (load float*)" pattern, this pattern will be combined
16342     // to "store (load int32)" in later InstCombine pass. See function
16343     // combineLoadToOperationType. On PowerPC, loading a float point takes more
16344     // cycles than loading a 32 bit integer.
16345     LoadInst *LI = cast<LoadInst>(I);
16346     // For the loads that combineLoadToOperationType does nothing, like
16347     // ordered load, it should be profitable to hoist them.
16348     // For swifterror load, it can only be used for pointer to pointer type, so
16349     // later type check should get rid of this case.
16350     if (!LI->isUnordered())
16351       return true;
16352 
16353     if (User->getOpcode() != Instruction::Store)
16354       return true;
16355 
16356     if (I->getType()->getTypeID() != Type::FloatTyID)
16357       return true;
16358 
16359     return false;
16360   }
16361   default:
16362     return true;
16363   }
16364   return true;
16365 }
16366 
16367 const MCPhysReg *
16368 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
16369   // LR is a callee-save register, but we must treat it as clobbered by any call
16370   // site. Hence we include LR in the scratch registers, which are in turn added
16371   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
16372   // to CTR, which is used by any indirect call.
16373   static const MCPhysReg ScratchRegs[] = {
16374     PPC::X12, PPC::LR8, PPC::CTR8, 0
16375   };
16376 
16377   return ScratchRegs;
16378 }
16379 
16380 Register PPCTargetLowering::getExceptionPointerRegister(
16381     const Constant *PersonalityFn) const {
16382   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
16383 }
16384 
16385 Register PPCTargetLowering::getExceptionSelectorRegister(
16386     const Constant *PersonalityFn) const {
16387   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
16388 }
16389 
16390 bool
16391 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
16392                      EVT VT , unsigned DefinedValues) const {
16393   if (VT == MVT::v2i64)
16394     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
16395 
16396   if (Subtarget.hasVSX())
16397     return true;
16398 
16399   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
16400 }
16401 
16402 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16403   if (DisableILPPref || Subtarget.enableMachineScheduler())
16404     return TargetLowering::getSchedulingPreference(N);
16405 
16406   return Sched::ILP;
16407 }
16408 
16409 // Create a fast isel object.
16410 FastISel *
16411 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16412                                   const TargetLibraryInfo *LibInfo) const {
16413   return PPC::createFastISel(FuncInfo, LibInfo);
16414 }
16415 
16416 // 'Inverted' means the FMA opcode after negating one multiplicand.
16417 // For example, (fma -a b c) = (fnmsub a b c)
16418 static unsigned invertFMAOpcode(unsigned Opc) {
16419   switch (Opc) {
16420   default:
16421     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16422   case ISD::FMA:
16423     return PPCISD::FNMSUB;
16424   case PPCISD::FNMSUB:
16425     return ISD::FMA;
16426   }
16427 }
16428 
16429 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16430                                                 bool LegalOps, bool OptForSize,
16431                                                 NegatibleCost &Cost,
16432                                                 unsigned Depth) const {
16433   if (Depth > SelectionDAG::MaxRecursionDepth)
16434     return SDValue();
16435 
16436   unsigned Opc = Op.getOpcode();
16437   EVT VT = Op.getValueType();
16438   SDNodeFlags Flags = Op.getNode()->getFlags();
16439 
16440   switch (Opc) {
16441   case PPCISD::FNMSUB:
16442     if (!Op.hasOneUse() || !isTypeLegal(VT))
16443       break;
16444 
16445     const TargetOptions &Options = getTargetMachine().Options;
16446     SDValue N0 = Op.getOperand(0);
16447     SDValue N1 = Op.getOperand(1);
16448     SDValue N2 = Op.getOperand(2);
16449     SDLoc Loc(Op);
16450 
16451     NegatibleCost N2Cost = NegatibleCost::Expensive;
16452     SDValue NegN2 =
16453         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16454 
16455     if (!NegN2)
16456       return SDValue();
16457 
16458     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16459     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16460     // These transformations may change sign of zeroes. For example,
16461     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16462     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16463       // Try and choose the cheaper one to negate.
16464       NegatibleCost N0Cost = NegatibleCost::Expensive;
16465       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16466                                            N0Cost, Depth + 1);
16467 
16468       NegatibleCost N1Cost = NegatibleCost::Expensive;
16469       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16470                                            N1Cost, Depth + 1);
16471 
16472       if (NegN0 && N0Cost <= N1Cost) {
16473         Cost = std::min(N0Cost, N2Cost);
16474         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16475       } else if (NegN1) {
16476         Cost = std::min(N1Cost, N2Cost);
16477         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16478       }
16479     }
16480 
16481     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16482     if (isOperationLegal(ISD::FMA, VT)) {
16483       Cost = N2Cost;
16484       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16485     }
16486 
16487     break;
16488   }
16489 
16490   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16491                                               Cost, Depth);
16492 }
16493 
16494 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16495 bool PPCTargetLowering::useLoadStackGuardNode() const {
16496   if (!Subtarget.isTargetLinux())
16497     return TargetLowering::useLoadStackGuardNode();
16498   return true;
16499 }
16500 
16501 // Override to disable global variable loading on Linux.
16502 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16503   if (!Subtarget.isTargetLinux())
16504     return TargetLowering::insertSSPDeclarations(M);
16505 }
16506 
16507 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16508                                      bool ForCodeSize) const {
16509   if (!VT.isSimple() || !Subtarget.hasVSX())
16510     return false;
16511 
16512   switch(VT.getSimpleVT().SimpleTy) {
16513   default:
16514     // For FP types that are currently not supported by PPC backend, return
16515     // false. Examples: f16, f80.
16516     return false;
16517   case MVT::f32:
16518   case MVT::f64:
16519     if (Subtarget.hasPrefixInstrs()) {
16520       // With prefixed instructions, we can materialize anything that can be
16521       // represented with a 32-bit immediate, not just positive zero.
16522       APFloat APFloatOfImm = Imm;
16523       return convertToNonDenormSingle(APFloatOfImm);
16524     }
16525     LLVM_FALLTHROUGH;
16526   case MVT::ppcf128:
16527     return Imm.isPosZero();
16528   }
16529 }
16530 
16531 // For vector shift operation op, fold
16532 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16533 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16534                                   SelectionDAG &DAG) {
16535   SDValue N0 = N->getOperand(0);
16536   SDValue N1 = N->getOperand(1);
16537   EVT VT = N0.getValueType();
16538   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16539   unsigned Opcode = N->getOpcode();
16540   unsigned TargetOpcode;
16541 
16542   switch (Opcode) {
16543   default:
16544     llvm_unreachable("Unexpected shift operation");
16545   case ISD::SHL:
16546     TargetOpcode = PPCISD::SHL;
16547     break;
16548   case ISD::SRL:
16549     TargetOpcode = PPCISD::SRL;
16550     break;
16551   case ISD::SRA:
16552     TargetOpcode = PPCISD::SRA;
16553     break;
16554   }
16555 
16556   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16557       N1->getOpcode() == ISD::AND)
16558     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16559       if (Mask->getZExtValue() == OpSizeInBits - 1)
16560         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16561 
16562   return SDValue();
16563 }
16564 
16565 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16566   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16567     return Value;
16568 
16569   SDValue N0 = N->getOperand(0);
16570   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16571   if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
16572       N0.getOpcode() != ISD::SIGN_EXTEND ||
16573       N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
16574       N->getValueType(0) != MVT::i64)
16575     return SDValue();
16576 
16577   // We can't save an operation here if the value is already extended, and
16578   // the existing shift is easier to combine.
16579   SDValue ExtsSrc = N0.getOperand(0);
16580   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16581       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16582     return SDValue();
16583 
16584   SDLoc DL(N0);
16585   SDValue ShiftBy = SDValue(CN1, 0);
16586   // We want the shift amount to be i32 on the extswli, but the shift could
16587   // have an i64.
16588   if (ShiftBy.getValueType() == MVT::i64)
16589     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16590 
16591   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16592                          ShiftBy);
16593 }
16594 
16595 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16596   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16597     return Value;
16598 
16599   return SDValue();
16600 }
16601 
16602 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16603   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16604     return Value;
16605 
16606   return SDValue();
16607 }
16608 
16609 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16610 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16611 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16612 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16613 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16614                                  const PPCSubtarget &Subtarget) {
16615   if (!Subtarget.isPPC64())
16616     return SDValue();
16617 
16618   SDValue LHS = N->getOperand(0);
16619   SDValue RHS = N->getOperand(1);
16620 
16621   auto isZextOfCompareWithConstant = [](SDValue Op) {
16622     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16623         Op.getValueType() != MVT::i64)
16624       return false;
16625 
16626     SDValue Cmp = Op.getOperand(0);
16627     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16628         Cmp.getOperand(0).getValueType() != MVT::i64)
16629       return false;
16630 
16631     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
16632       int64_t NegConstant = 0 - Constant->getSExtValue();
16633       // Due to the limitations of the addi instruction,
16634       // -C is required to be [-32768, 32767].
16635       return isInt<16>(NegConstant);
16636     }
16637 
16638     return false;
16639   };
16640 
16641   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
16642   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16643 
16644   // If there is a pattern, canonicalize a zext operand to the RHS.
16645   if (LHSHasPattern && !RHSHasPattern)
16646     std::swap(LHS, RHS);
16647   else if (!LHSHasPattern && !RHSHasPattern)
16648     return SDValue();
16649 
16650   SDLoc DL(N);
16651   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16652   SDValue Cmp = RHS.getOperand(0);
16653   SDValue Z = Cmp.getOperand(0);
16654   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
16655 
16656   assert(Constant && "Constant Should not be a null pointer.");
16657   int64_t NegConstant = 0 - Constant->getSExtValue();
16658 
16659   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16660   default: break;
16661   case ISD::SETNE: {
16662     //                                 when C == 0
16663     //                             --> addze X, (addic Z, -1).carry
16664     //                            /
16665     // add X, (zext(setne Z, C))--
16666     //                            \    when -32768 <= -C <= 32767 && C != 0
16667     //                             --> addze X, (addic (addi Z, -C), -1).carry
16668     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16669                               DAG.getConstant(NegConstant, DL, MVT::i64));
16670     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16671     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16672                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16673     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16674                        SDValue(Addc.getNode(), 1));
16675     }
16676   case ISD::SETEQ: {
16677     //                                 when C == 0
16678     //                             --> addze X, (subfic Z, 0).carry
16679     //                            /
16680     // add X, (zext(sete  Z, C))--
16681     //                            \    when -32768 <= -C <= 32767 && C != 0
16682     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16683     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16684                               DAG.getConstant(NegConstant, DL, MVT::i64));
16685     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16686     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16687                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16688     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16689                        SDValue(Subc.getNode(), 1));
16690     }
16691   }
16692 
16693   return SDValue();
16694 }
16695 
16696 // Transform
16697 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16698 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16699 // In this case both C1 and C2 must be known constants.
16700 // C1+C2 must fit into a 34 bit signed integer.
16701 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16702                                           const PPCSubtarget &Subtarget) {
16703   if (!Subtarget.isUsingPCRelativeCalls())
16704     return SDValue();
16705 
16706   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16707   // If we find that node try to cast the Global Address and the Constant.
16708   SDValue LHS = N->getOperand(0);
16709   SDValue RHS = N->getOperand(1);
16710 
16711   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16712     std::swap(LHS, RHS);
16713 
16714   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16715     return SDValue();
16716 
16717   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16718   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16719   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16720 
16721   // Check that both casts succeeded.
16722   if (!GSDN || !ConstNode)
16723     return SDValue();
16724 
16725   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16726   SDLoc DL(GSDN);
16727 
16728   // The signed int offset needs to fit in 34 bits.
16729   if (!isInt<34>(NewOffset))
16730     return SDValue();
16731 
16732   // The new global address is a copy of the old global address except
16733   // that it has the updated Offset.
16734   SDValue GA =
16735       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16736                                  NewOffset, GSDN->getTargetFlags());
16737   SDValue MatPCRel =
16738       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16739   return MatPCRel;
16740 }
16741 
16742 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16743   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16744     return Value;
16745 
16746   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16747     return Value;
16748 
16749   return SDValue();
16750 }
16751 
16752 // Detect TRUNCATE operations on bitcasts of float128 values.
16753 // What we are looking for here is the situtation where we extract a subset
16754 // of bits from a 128 bit float.
16755 // This can be of two forms:
16756 // 1) BITCAST of f128 feeding TRUNCATE
16757 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16758 // The reason this is required is because we do not have a legal i128 type
16759 // and so we want to prevent having to store the f128 and then reload part
16760 // of it.
16761 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16762                                            DAGCombinerInfo &DCI) const {
16763   // If we are using CRBits then try that first.
16764   if (Subtarget.useCRBits()) {
16765     // Check if CRBits did anything and return that if it did.
16766     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16767       return CRTruncValue;
16768   }
16769 
16770   SDLoc dl(N);
16771   SDValue Op0 = N->getOperand(0);
16772 
16773   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
16774   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
16775     EVT VT = N->getValueType(0);
16776     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16777       return SDValue();
16778     SDValue Sub = Op0.getOperand(0);
16779     if (Sub.getOpcode() == ISD::SUB) {
16780       SDValue SubOp0 = Sub.getOperand(0);
16781       SDValue SubOp1 = Sub.getOperand(1);
16782       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16783           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16784         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16785                                SubOp1.getOperand(0),
16786                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16787       }
16788     }
16789   }
16790 
16791   // Looking for a truncate of i128 to i64.
16792   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16793     return SDValue();
16794 
16795   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16796 
16797   // SRL feeding TRUNCATE.
16798   if (Op0.getOpcode() == ISD::SRL) {
16799     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16800     // The right shift has to be by 64 bits.
16801     if (!ConstNode || ConstNode->getZExtValue() != 64)
16802       return SDValue();
16803 
16804     // Switch the element number to extract.
16805     EltToExtract = EltToExtract ? 0 : 1;
16806     // Update Op0 past the SRL.
16807     Op0 = Op0.getOperand(0);
16808   }
16809 
16810   // BITCAST feeding a TRUNCATE possibly via SRL.
16811   if (Op0.getOpcode() == ISD::BITCAST &&
16812       Op0.getValueType() == MVT::i128 &&
16813       Op0.getOperand(0).getValueType() == MVT::f128) {
16814     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16815     return DCI.DAG.getNode(
16816         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16817         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16818   }
16819   return SDValue();
16820 }
16821 
16822 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16823   SelectionDAG &DAG = DCI.DAG;
16824 
16825   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16826   if (!ConstOpOrElement)
16827     return SDValue();
16828 
16829   // An imul is usually smaller than the alternative sequence for legal type.
16830   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16831       isOperationLegal(ISD::MUL, N->getValueType(0)))
16832     return SDValue();
16833 
16834   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16835     switch (this->Subtarget.getCPUDirective()) {
16836     default:
16837       // TODO: enhance the condition for subtarget before pwr8
16838       return false;
16839     case PPC::DIR_PWR8:
16840       //  type        mul     add    shl
16841       // scalar        4       1      1
16842       // vector        7       2      2
16843       return true;
16844     case PPC::DIR_PWR9:
16845     case PPC::DIR_PWR10:
16846     case PPC::DIR_PWR_FUTURE:
16847       //  type        mul     add    shl
16848       // scalar        5       2      2
16849       // vector        7       2      2
16850 
16851       // The cycle RATIO of related operations are showed as a table above.
16852       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16853       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16854       // are 4, it is always profitable; but for 3 instrs patterns
16855       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16856       // So we should only do it for vector type.
16857       return IsAddOne && IsNeg ? VT.isVector() : true;
16858     }
16859   };
16860 
16861   EVT VT = N->getValueType(0);
16862   SDLoc DL(N);
16863 
16864   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16865   bool IsNeg = MulAmt.isNegative();
16866   APInt MulAmtAbs = MulAmt.abs();
16867 
16868   if ((MulAmtAbs - 1).isPowerOf2()) {
16869     // (mul x, 2^N + 1) => (add (shl x, N), x)
16870     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16871 
16872     if (!IsProfitable(IsNeg, true, VT))
16873       return SDValue();
16874 
16875     SDValue Op0 = N->getOperand(0);
16876     SDValue Op1 =
16877         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16878                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16879     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16880 
16881     if (!IsNeg)
16882       return Res;
16883 
16884     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16885   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16886     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16887     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16888 
16889     if (!IsProfitable(IsNeg, false, VT))
16890       return SDValue();
16891 
16892     SDValue Op0 = N->getOperand(0);
16893     SDValue Op1 =
16894         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16895                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16896 
16897     if (!IsNeg)
16898       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16899     else
16900       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16901 
16902   } else {
16903     return SDValue();
16904   }
16905 }
16906 
16907 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16908 // in combiner since we need to check SD flags and other subtarget features.
16909 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16910                                           DAGCombinerInfo &DCI) const {
16911   SDValue N0 = N->getOperand(0);
16912   SDValue N1 = N->getOperand(1);
16913   SDValue N2 = N->getOperand(2);
16914   SDNodeFlags Flags = N->getFlags();
16915   EVT VT = N->getValueType(0);
16916   SelectionDAG &DAG = DCI.DAG;
16917   const TargetOptions &Options = getTargetMachine().Options;
16918   unsigned Opc = N->getOpcode();
16919   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16920   bool LegalOps = !DCI.isBeforeLegalizeOps();
16921   SDLoc Loc(N);
16922 
16923   if (!isOperationLegal(ISD::FMA, VT))
16924     return SDValue();
16925 
16926   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16927   // since (fnmsub a b c)=-0 while c-ab=+0.
16928   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16929     return SDValue();
16930 
16931   // (fma (fneg a) b c) => (fnmsub a b c)
16932   // (fnmsub (fneg a) b c) => (fma a b c)
16933   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16934     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16935 
16936   // (fma a (fneg b) c) => (fnmsub a b c)
16937   // (fnmsub a (fneg b) c) => (fma a b c)
16938   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16939     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16940 
16941   return SDValue();
16942 }
16943 
16944 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16945   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16946   if (!Subtarget.is64BitELFABI())
16947     return false;
16948 
16949   // If not a tail call then no need to proceed.
16950   if (!CI->isTailCall())
16951     return false;
16952 
16953   // If sibling calls have been disabled and tail-calls aren't guaranteed
16954   // there is no reason to duplicate.
16955   auto &TM = getTargetMachine();
16956   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16957     return false;
16958 
16959   // Can't tail call a function called indirectly, or if it has variadic args.
16960   const Function *Callee = CI->getCalledFunction();
16961   if (!Callee || Callee->isVarArg())
16962     return false;
16963 
16964   // Make sure the callee and caller calling conventions are eligible for tco.
16965   const Function *Caller = CI->getParent()->getParent();
16966   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16967                                            CI->getCallingConv()))
16968       return false;
16969 
16970   // If the function is local then we have a good chance at tail-calling it
16971   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16972 }
16973 
16974 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16975   if (!Subtarget.hasVSX())
16976     return false;
16977   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16978     return true;
16979   return VT == MVT::f32 || VT == MVT::f64 ||
16980     VT == MVT::v4f32 || VT == MVT::v2f64;
16981 }
16982 
16983 bool PPCTargetLowering::
16984 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16985   const Value *Mask = AndI.getOperand(1);
16986   // If the mask is suitable for andi. or andis. we should sink the and.
16987   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16988     // Can't handle constants wider than 64-bits.
16989     if (CI->getBitWidth() > 64)
16990       return false;
16991     int64_t ConstVal = CI->getZExtValue();
16992     return isUInt<16>(ConstVal) ||
16993       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16994   }
16995 
16996   // For non-constant masks, we can always use the record-form and.
16997   return true;
16998 }
16999 
17000 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
17001 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
17002 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
17003 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
17004 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
17005 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
17006   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
17007   assert(Subtarget.hasP9Altivec() &&
17008          "Only combine this when P9 altivec supported!");
17009   EVT VT = N->getValueType(0);
17010   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17011     return SDValue();
17012 
17013   SelectionDAG &DAG = DCI.DAG;
17014   SDLoc dl(N);
17015   if (N->getOperand(0).getOpcode() == ISD::SUB) {
17016     // Even for signed integers, if it's known to be positive (as signed
17017     // integer) due to zero-extended inputs.
17018     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
17019     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
17020     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
17021          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
17022         (SubOpcd1 == ISD::ZERO_EXTEND ||
17023          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
17024       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17025                          N->getOperand(0)->getOperand(0),
17026                          N->getOperand(0)->getOperand(1),
17027                          DAG.getTargetConstant(0, dl, MVT::i32));
17028     }
17029 
17030     // For type v4i32, it can be optimized with xvnegsp + vabsduw
17031     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
17032         N->getOperand(0).hasOneUse()) {
17033       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17034                          N->getOperand(0)->getOperand(0),
17035                          N->getOperand(0)->getOperand(1),
17036                          DAG.getTargetConstant(1, dl, MVT::i32));
17037     }
17038   }
17039 
17040   return SDValue();
17041 }
17042 
17043 // For type v4i32/v8ii16/v16i8, transform
17044 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
17045 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
17046 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
17047 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
17048 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
17049                                           DAGCombinerInfo &DCI) const {
17050   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
17051   assert(Subtarget.hasP9Altivec() &&
17052          "Only combine this when P9 altivec supported!");
17053 
17054   SelectionDAG &DAG = DCI.DAG;
17055   SDLoc dl(N);
17056   SDValue Cond = N->getOperand(0);
17057   SDValue TrueOpnd = N->getOperand(1);
17058   SDValue FalseOpnd = N->getOperand(2);
17059   EVT VT = N->getOperand(1).getValueType();
17060 
17061   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
17062       FalseOpnd.getOpcode() != ISD::SUB)
17063     return SDValue();
17064 
17065   // ABSD only available for type v4i32/v8i16/v16i8
17066   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17067     return SDValue();
17068 
17069   // At least to save one more dependent computation
17070   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
17071     return SDValue();
17072 
17073   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17074 
17075   // Can only handle unsigned comparison here
17076   switch (CC) {
17077   default:
17078     return SDValue();
17079   case ISD::SETUGT:
17080   case ISD::SETUGE:
17081     break;
17082   case ISD::SETULT:
17083   case ISD::SETULE:
17084     std::swap(TrueOpnd, FalseOpnd);
17085     break;
17086   }
17087 
17088   SDValue CmpOpnd1 = Cond.getOperand(0);
17089   SDValue CmpOpnd2 = Cond.getOperand(1);
17090 
17091   // SETCC CmpOpnd1 CmpOpnd2 cond
17092   // TrueOpnd = CmpOpnd1 - CmpOpnd2
17093   // FalseOpnd = CmpOpnd2 - CmpOpnd1
17094   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
17095       TrueOpnd.getOperand(1) == CmpOpnd2 &&
17096       FalseOpnd.getOperand(0) == CmpOpnd2 &&
17097       FalseOpnd.getOperand(1) == CmpOpnd1) {
17098     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
17099                        CmpOpnd1, CmpOpnd2,
17100                        DAG.getTargetConstant(0, dl, MVT::i32));
17101   }
17102 
17103   return SDValue();
17104 }
17105