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/MCSymbolXCOFF.h"
78 #include "llvm/Support/AtomicOrdering.h"
79 #include "llvm/Support/BranchProbability.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/CodeGen.h"
82 #include "llvm/Support/CommandLine.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/Debug.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/KnownBits.h"
88 #include "llvm/Support/MachineValueType.h"
89 #include "llvm/Support/MathExtras.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include "llvm/Target/TargetMachine.h"
92 #include "llvm/Target/TargetOptions.h"
93 #include <algorithm>
94 #include <cassert>
95 #include <cstdint>
96 #include <iterator>
97 #include <list>
98 #include <utility>
99 #include <vector>
100 
101 using namespace llvm;
102 
103 #define DEBUG_TYPE "ppc-lowering"
104 
105 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
106 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
107 
108 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
109 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
110 
111 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
112 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
113 
114 static cl::opt<bool> DisableSCO("disable-ppc-sco",
115 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
116 
117 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
118 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
119 
120 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
121 cl::desc("enable quad precision float support on ppc"), cl::Hidden);
122 
123 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
124 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
125 
126 STATISTIC(NumTailCalls, "Number of tail calls");
127 STATISTIC(NumSiblingCalls, "Number of sibling calls");
128 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM");
129 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
130 
131 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
132 
133 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
134 
135 // FIXME: Remove this once the bug has been fixed!
136 extern cl::opt<bool> ANDIGlueBug;
137 
138 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
139                                      const PPCSubtarget &STI)
140     : TargetLowering(TM), Subtarget(STI) {
141   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
142   // arguments are at least 4/8 bytes aligned.
143   bool isPPC64 = Subtarget.isPPC64();
144   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
145 
146   // Set up the register classes.
147   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
148   if (!useSoftFloat()) {
149     if (hasSPE()) {
150       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
151       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
152     } else {
153       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
154       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
155     }
156   }
157 
158   // Match BITREVERSE to customized fast code sequence in the td file.
159   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
160   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
161 
162   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
163   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
164 
165   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
166   for (MVT VT : MVT::integer_valuetypes()) {
167     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
168     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
169   }
170 
171   if (Subtarget.isISA3_0()) {
172     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
173     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
174     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
175     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
176   } else {
177     // No extending loads from f16 or HW conversions back and forth.
178     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
179     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
180     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
181     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
182     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
183     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
184     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
185     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
186   }
187 
188   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
189 
190   // PowerPC has pre-inc load and store's.
191   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
192   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
193   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
194   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
195   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
196   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
197   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
198   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
199   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
200   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
201   if (!Subtarget.hasSPE()) {
202     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
203     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
204     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
205     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
206   }
207 
208   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
209   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
210   for (MVT VT : ScalarIntVTs) {
211     setOperationAction(ISD::ADDC, VT, Legal);
212     setOperationAction(ISD::ADDE, VT, Legal);
213     setOperationAction(ISD::SUBC, VT, Legal);
214     setOperationAction(ISD::SUBE, VT, Legal);
215   }
216 
217   if (Subtarget.useCRBits()) {
218     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
219 
220     if (isPPC64 || Subtarget.hasFPCVT()) {
221       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
222       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
223                          isPPC64 ? MVT::i64 : MVT::i32);
224       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
225       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
226                         isPPC64 ? MVT::i64 : MVT::i32);
227     } else {
228       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
229       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
230     }
231 
232     // PowerPC does not support direct load/store of condition registers.
233     setOperationAction(ISD::LOAD, MVT::i1, Custom);
234     setOperationAction(ISD::STORE, MVT::i1, Custom);
235 
236     // FIXME: Remove this once the ANDI glue bug is fixed:
237     if (ANDIGlueBug)
238       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
239 
240     for (MVT VT : MVT::integer_valuetypes()) {
241       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
242       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
243       setTruncStoreAction(VT, MVT::i1, Expand);
244     }
245 
246     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
247   }
248 
249   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
250   // PPC (the libcall is not available).
251   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
252   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
253 
254   // We do not currently implement these libm ops for PowerPC.
255   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
256   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
257   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
258   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
259   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
260   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
261 
262   // PowerPC has no SREM/UREM instructions unless we are on P9
263   // On P9 we may use a hardware instruction to compute the remainder.
264   // When the result of both the remainder and the division is required it is
265   // more efficient to compute the remainder from the result of the division
266   // rather than use the remainder instruction. The instructions are legalized
267   // directly because the DivRemPairsPass performs the transformation at the IR
268   // level.
269   if (Subtarget.isISA3_0()) {
270     setOperationAction(ISD::SREM, MVT::i32, Legal);
271     setOperationAction(ISD::UREM, MVT::i32, Legal);
272     setOperationAction(ISD::SREM, MVT::i64, Legal);
273     setOperationAction(ISD::UREM, MVT::i64, Legal);
274   } else {
275     setOperationAction(ISD::SREM, MVT::i32, Expand);
276     setOperationAction(ISD::UREM, MVT::i32, Expand);
277     setOperationAction(ISD::SREM, MVT::i64, Expand);
278     setOperationAction(ISD::UREM, MVT::i64, Expand);
279   }
280 
281   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
282   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
283   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
284   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
285   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
286   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
287   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
288   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
289   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
290 
291   // Handle constrained floating-point operations of scalar.
292   // TODO: Handle SPE specific operation.
293   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
294   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
295   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
296   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
297   setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
298   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
299 
300   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
301   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
302   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
303   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
304   setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
305   if (Subtarget.hasVSX())
306     setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f64, Legal);
307 
308   if (Subtarget.hasFSQRT()) {
309     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
310     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
311   }
312 
313   if (Subtarget.hasFPRND()) {
314     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
315     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
316     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
317     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
318 
319     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
320     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
321     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
322     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
323   }
324 
325   // We don't support sin/cos/sqrt/fmod/pow
326   setOperationAction(ISD::FSIN , MVT::f64, Expand);
327   setOperationAction(ISD::FCOS , MVT::f64, Expand);
328   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
329   setOperationAction(ISD::FREM , MVT::f64, Expand);
330   setOperationAction(ISD::FPOW , MVT::f64, Expand);
331   setOperationAction(ISD::FSIN , MVT::f32, Expand);
332   setOperationAction(ISD::FCOS , MVT::f32, Expand);
333   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
334   setOperationAction(ISD::FREM , MVT::f32, Expand);
335   setOperationAction(ISD::FPOW , MVT::f32, Expand);
336   if (Subtarget.hasSPE()) {
337     setOperationAction(ISD::FMA  , MVT::f64, Expand);
338     setOperationAction(ISD::FMA  , MVT::f32, Expand);
339   } else {
340     setOperationAction(ISD::FMA  , MVT::f64, Legal);
341     setOperationAction(ISD::FMA  , MVT::f32, Legal);
342   }
343 
344   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
345 
346   // If we're enabling GP optimizations, use hardware square root
347   if (!Subtarget.hasFSQRT() &&
348       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
349         Subtarget.hasFRE()))
350     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
351 
352   if (!Subtarget.hasFSQRT() &&
353       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
354         Subtarget.hasFRES()))
355     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
356 
357   if (Subtarget.hasFCPSGN()) {
358     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
359     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
360   } else {
361     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
362     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
363   }
364 
365   if (Subtarget.hasFPRND()) {
366     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
367     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
368     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
369     setOperationAction(ISD::FROUND, MVT::f64, Legal);
370 
371     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
372     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
373     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
374     setOperationAction(ISD::FROUND, MVT::f32, Legal);
375   }
376 
377   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
378   // to speed up scalar BSWAP64.
379   // CTPOP or CTTZ were introduced in P8/P9 respectively
380   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
381   if (Subtarget.hasP9Vector())
382     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
383   else
384     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
385   if (Subtarget.isISA3_0()) {
386     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
387     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
388   } else {
389     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
390     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
391   }
392 
393   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
394     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
395     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
396   } else {
397     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
398     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
399   }
400 
401   // PowerPC does not have ROTR
402   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
403   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
404 
405   if (!Subtarget.useCRBits()) {
406     // PowerPC does not have Select
407     setOperationAction(ISD::SELECT, MVT::i32, Expand);
408     setOperationAction(ISD::SELECT, MVT::i64, Expand);
409     setOperationAction(ISD::SELECT, MVT::f32, Expand);
410     setOperationAction(ISD::SELECT, MVT::f64, Expand);
411   }
412 
413   // PowerPC wants to turn select_cc of FP into fsel when possible.
414   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
415   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
416 
417   // PowerPC wants to optimize integer setcc a bit
418   if (!Subtarget.useCRBits())
419     setOperationAction(ISD::SETCC, MVT::i32, Custom);
420 
421   // PowerPC does not have BRCOND which requires SetCC
422   if (!Subtarget.useCRBits())
423     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
424 
425   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
426 
427   if (Subtarget.hasSPE()) {
428     // SPE has built-in conversions
429     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
430     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
431     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
432   } else {
433     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
434     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
435 
436     // PowerPC does not have [U|S]INT_TO_FP
437     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
438     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
439   }
440 
441   if (Subtarget.hasDirectMove() && isPPC64) {
442     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
443     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
444     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
445     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
446     if (TM.Options.UnsafeFPMath) {
447       setOperationAction(ISD::LRINT, MVT::f64, Legal);
448       setOperationAction(ISD::LRINT, MVT::f32, Legal);
449       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
450       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
451       setOperationAction(ISD::LROUND, MVT::f64, Legal);
452       setOperationAction(ISD::LROUND, MVT::f32, Legal);
453       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
454       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
455     }
456   } else {
457     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
458     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
459     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
460     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
461   }
462 
463   // We cannot sextinreg(i1).  Expand to shifts.
464   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
465 
466   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
467   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
468   // support continuation, user-level threading, and etc.. As a result, no
469   // other SjLj exception interfaces are implemented and please don't build
470   // your own exception handling based on them.
471   // LLVM/Clang supports zero-cost DWARF exception handling.
472   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
473   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
474 
475   // We want to legalize GlobalAddress and ConstantPool nodes into the
476   // appropriate instructions to materialize the address.
477   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
478   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
479   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
480   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
481   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
482   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
483   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
484   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
485   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
486   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
487 
488   // TRAP is legal.
489   setOperationAction(ISD::TRAP, MVT::Other, Legal);
490 
491   // TRAMPOLINE is custom lowered.
492   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
493   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
494 
495   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
496   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
497 
498   if (Subtarget.is64BitELFABI()) {
499     // VAARG always uses double-word chunks, so promote anything smaller.
500     setOperationAction(ISD::VAARG, MVT::i1, Promote);
501     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
502     setOperationAction(ISD::VAARG, MVT::i8, Promote);
503     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
504     setOperationAction(ISD::VAARG, MVT::i16, Promote);
505     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
506     setOperationAction(ISD::VAARG, MVT::i32, Promote);
507     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
508     setOperationAction(ISD::VAARG, MVT::Other, Expand);
509   } else if (Subtarget.is32BitELFABI()) {
510     // VAARG is custom lowered with the 32-bit SVR4 ABI.
511     setOperationAction(ISD::VAARG, MVT::Other, Custom);
512     setOperationAction(ISD::VAARG, MVT::i64, Custom);
513   } else
514     setOperationAction(ISD::VAARG, MVT::Other, Expand);
515 
516   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
517   if (Subtarget.is32BitELFABI())
518     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
519   else
520     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
521 
522   // Use the default implementation.
523   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
524   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
525   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
526   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
527   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
528   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
529   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
530   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
531   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
532 
533   // We want to custom lower some of our intrinsics.
534   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
535 
536   // To handle counter-based loop conditions.
537   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
538 
539   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
540   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
541   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
542   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
543 
544   // Comparisons that require checking two conditions.
545   if (Subtarget.hasSPE()) {
546     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
547     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
548     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
549     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
550   }
551   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
552   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
553   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
554   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
555   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
556   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
557   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
558   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
559   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
560   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
561   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
562   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
563 
564   if (Subtarget.has64BitSupport()) {
565     // They also have instructions for converting between i64 and fp.
566     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
567     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
568     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
569     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
570     // This is just the low 32 bits of a (signed) fp->i64 conversion.
571     // We cannot do this with Promote because i64 is not a legal type.
572     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
573 
574     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
575       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
576   } else {
577     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
578     if (Subtarget.hasSPE())
579       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
580     else
581       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
582   }
583 
584   // With the instructions enabled under FPCVT, we can do everything.
585   if (Subtarget.hasFPCVT()) {
586     if (Subtarget.has64BitSupport()) {
587       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
588       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
589       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
590       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
591     }
592 
593     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
594     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
595     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
596     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
597   }
598 
599   if (Subtarget.use64BitRegs()) {
600     // 64-bit PowerPC implementations can support i64 types directly
601     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
602     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
603     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
604     // 64-bit PowerPC wants to expand i128 shifts itself.
605     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
606     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
607     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
608   } else {
609     // 32-bit PowerPC wants to expand i64 shifts itself.
610     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
611     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
612     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
613   }
614 
615   if (Subtarget.hasVSX()) {
616     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
617     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
618     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
619     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
620   }
621 
622   if (Subtarget.hasAltivec()) {
623     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
624       setOperationAction(ISD::SADDSAT, VT, Legal);
625       setOperationAction(ISD::SSUBSAT, VT, Legal);
626       setOperationAction(ISD::UADDSAT, VT, Legal);
627       setOperationAction(ISD::USUBSAT, VT, Legal);
628     }
629     // First set operation action for all vector types to expand. Then we
630     // will selectively turn on ones that can be effectively codegen'd.
631     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
632       // add/sub are legal for all supported vector VT's.
633       setOperationAction(ISD::ADD, VT, Legal);
634       setOperationAction(ISD::SUB, VT, Legal);
635 
636       // For v2i64, these are only valid with P8Vector. This is corrected after
637       // the loop.
638       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
639         setOperationAction(ISD::SMAX, VT, Legal);
640         setOperationAction(ISD::SMIN, VT, Legal);
641         setOperationAction(ISD::UMAX, VT, Legal);
642         setOperationAction(ISD::UMIN, VT, Legal);
643       }
644       else {
645         setOperationAction(ISD::SMAX, VT, Expand);
646         setOperationAction(ISD::SMIN, VT, Expand);
647         setOperationAction(ISD::UMAX, VT, Expand);
648         setOperationAction(ISD::UMIN, VT, Expand);
649       }
650 
651       if (Subtarget.hasVSX()) {
652         setOperationAction(ISD::FMAXNUM, VT, Legal);
653         setOperationAction(ISD::FMINNUM, VT, Legal);
654       }
655 
656       // Vector instructions introduced in P8
657       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
658         setOperationAction(ISD::CTPOP, VT, Legal);
659         setOperationAction(ISD::CTLZ, VT, Legal);
660       }
661       else {
662         setOperationAction(ISD::CTPOP, VT, Expand);
663         setOperationAction(ISD::CTLZ, VT, Expand);
664       }
665 
666       // Vector instructions introduced in P9
667       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
668         setOperationAction(ISD::CTTZ, VT, Legal);
669       else
670         setOperationAction(ISD::CTTZ, VT, Expand);
671 
672       // We promote all shuffles to v16i8.
673       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
674       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
675 
676       // We promote all non-typed operations to v4i32.
677       setOperationAction(ISD::AND   , VT, Promote);
678       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
679       setOperationAction(ISD::OR    , VT, Promote);
680       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
681       setOperationAction(ISD::XOR   , VT, Promote);
682       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
683       setOperationAction(ISD::LOAD  , VT, Promote);
684       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
685       setOperationAction(ISD::SELECT, VT, Promote);
686       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
687       setOperationAction(ISD::VSELECT, VT, Legal);
688       setOperationAction(ISD::SELECT_CC, VT, Promote);
689       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
690       setOperationAction(ISD::STORE, VT, Promote);
691       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
692 
693       // No other operations are legal.
694       setOperationAction(ISD::MUL , VT, Expand);
695       setOperationAction(ISD::SDIV, VT, Expand);
696       setOperationAction(ISD::SREM, VT, Expand);
697       setOperationAction(ISD::UDIV, VT, Expand);
698       setOperationAction(ISD::UREM, VT, Expand);
699       setOperationAction(ISD::FDIV, VT, Expand);
700       setOperationAction(ISD::FREM, VT, Expand);
701       setOperationAction(ISD::FNEG, VT, Expand);
702       setOperationAction(ISD::FSQRT, VT, Expand);
703       setOperationAction(ISD::FLOG, VT, Expand);
704       setOperationAction(ISD::FLOG10, VT, Expand);
705       setOperationAction(ISD::FLOG2, VT, Expand);
706       setOperationAction(ISD::FEXP, VT, Expand);
707       setOperationAction(ISD::FEXP2, VT, Expand);
708       setOperationAction(ISD::FSIN, VT, Expand);
709       setOperationAction(ISD::FCOS, VT, Expand);
710       setOperationAction(ISD::FABS, VT, Expand);
711       setOperationAction(ISD::FFLOOR, VT, Expand);
712       setOperationAction(ISD::FCEIL,  VT, Expand);
713       setOperationAction(ISD::FTRUNC, VT, Expand);
714       setOperationAction(ISD::FRINT,  VT, Expand);
715       setOperationAction(ISD::FNEARBYINT, VT, Expand);
716       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
717       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
718       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
719       setOperationAction(ISD::MULHU, VT, Expand);
720       setOperationAction(ISD::MULHS, VT, Expand);
721       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
722       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
723       setOperationAction(ISD::UDIVREM, VT, Expand);
724       setOperationAction(ISD::SDIVREM, VT, Expand);
725       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
726       setOperationAction(ISD::FPOW, VT, Expand);
727       setOperationAction(ISD::BSWAP, VT, Expand);
728       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
729       setOperationAction(ISD::ROTL, VT, Expand);
730       setOperationAction(ISD::ROTR, VT, Expand);
731 
732       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
733         setTruncStoreAction(VT, InnerVT, Expand);
734         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
735         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
736         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
737       }
738     }
739     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
740     if (!Subtarget.hasP8Vector()) {
741       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
742       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
743       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
744       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
745     }
746 
747     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
748       setOperationAction(ISD::ABS, VT, Custom);
749 
750     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
751     // with merges, splats, etc.
752     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
753 
754     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
755     // are cheap, so handle them before they get expanded to scalar.
756     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
757     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
758     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
759     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
760     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
761 
762     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
763     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
764     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
765     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
766     setOperationAction(ISD::SELECT, MVT::v4i32,
767                        Subtarget.useCRBits() ? Legal : Expand);
768     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
769     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
770     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
771     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
772     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
773     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
774     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
775     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
776     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
777 
778     // Without hasP8Altivec set, v2i64 SMAX isn't available.
779     // But ABS custom lowering requires SMAX support.
780     if (!Subtarget.hasP8Altivec())
781       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
782 
783     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
784     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
785     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
786     if (Subtarget.hasAltivec())
787       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
788         setOperationAction(ISD::ROTL, VT, Legal);
789     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
790     if (Subtarget.hasP8Altivec())
791       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
792 
793     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
794     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
795     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
796     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
797 
798     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
799     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
800 
801     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
802       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
803       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
804     }
805 
806     if (Subtarget.hasP8Altivec())
807       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
808     else
809       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
810 
811     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
812     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
813 
814     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
815     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
816 
817     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
818     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
819     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
820     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
821 
822     // Altivec does not contain unordered floating-point compare instructions
823     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
824     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
825     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
826     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
827 
828     if (Subtarget.hasVSX()) {
829       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
830       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
831       if (Subtarget.hasP8Vector()) {
832         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
833         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
834       }
835       if (Subtarget.hasDirectMove() && isPPC64) {
836         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
837         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
838         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
839         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
840         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
841         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
842         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
843         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
844       }
845       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
846 
847       // The nearbyint variants are not allowed to raise the inexact exception
848       // so we can only code-gen them with unsafe math.
849       if (TM.Options.UnsafeFPMath) {
850         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
851         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
852       }
853 
854       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
855       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
856       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
857       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
858       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
859       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
860       setOperationAction(ISD::FROUND, MVT::f64, Legal);
861       setOperationAction(ISD::FRINT, MVT::f64, Legal);
862 
863       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
864       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
865       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
866       setOperationAction(ISD::FROUND, MVT::f32, Legal);
867       setOperationAction(ISD::FRINT, MVT::f32, Legal);
868 
869       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
870       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
871 
872       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
873       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
874 
875       // Share the Altivec comparison restrictions.
876       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
877       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
878       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
879       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
880 
881       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
882       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
883 
884       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
885 
886       if (Subtarget.hasP8Vector())
887         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
888 
889       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
890 
891       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
892       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
893       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
894 
895       if (Subtarget.hasP8Altivec()) {
896         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
897         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
898         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
899 
900         // 128 bit shifts can be accomplished via 3 instructions for SHL and
901         // SRL, but not for SRA because of the instructions available:
902         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
903         // doing
904         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
905         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
906         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
907 
908         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
909       }
910       else {
911         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
912         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
913         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
914 
915         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
916 
917         // VSX v2i64 only supports non-arithmetic operations.
918         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
919         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
920       }
921 
922       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
923       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
924       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
925       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
926 
927       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
928 
929       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
930       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
931       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
932       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
933 
934       // Custom handling for partial vectors of integers converted to
935       // floating point. We already have optimal handling for v2i32 through
936       // the DAG combine, so those aren't necessary.
937       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
938       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
939       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
940       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
941       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
942       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
943       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
944       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
945 
946       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
947       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
948       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
949       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
950       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
951       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
952 
953       if (Subtarget.hasDirectMove())
954         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
955       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
956 
957       // Handle constrained floating-point operations of vector.
958       // The predictor is `hasVSX` because altivec instruction has
959       // no exception but VSX vector instruction has.
960       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
961       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
962       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
963       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
964       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
965       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
966       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
967       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
968       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal);
969       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
970       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
971       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
972       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
973 
974       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
975       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
976       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
977       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
978       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
979       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
980       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
981       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
982       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal);
983       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
984       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
985       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
986       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
987 
988       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
989     }
990 
991     if (Subtarget.hasP8Altivec()) {
992       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
993       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
994     }
995 
996     if (Subtarget.hasP9Vector()) {
997       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
998       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
999 
1000       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1001       // SRL, but not for SRA because of the instructions available:
1002       // VS{RL} and VS{RL}O.
1003       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1004       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1005       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1006 
1007       if (EnableQuadPrecision) {
1008         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1009         setOperationAction(ISD::FADD, MVT::f128, Legal);
1010         setOperationAction(ISD::FSUB, MVT::f128, Legal);
1011         setOperationAction(ISD::FDIV, MVT::f128, Legal);
1012         setOperationAction(ISD::FMUL, MVT::f128, Legal);
1013         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1014         // No extending loads to f128 on PPC.
1015         for (MVT FPT : MVT::fp_valuetypes())
1016           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1017         setOperationAction(ISD::FMA, MVT::f128, Legal);
1018         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1019         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1020         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1021         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1022         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1023         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1024 
1025         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1026         setOperationAction(ISD::FRINT, MVT::f128, Legal);
1027         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1028         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1029         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1030         setOperationAction(ISD::FROUND, MVT::f128, Legal);
1031 
1032         setOperationAction(ISD::SELECT, MVT::f128, Expand);
1033         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1034         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1035         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1036         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1037         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1038         // No implementation for these ops for PowerPC.
1039         setOperationAction(ISD::FSIN , MVT::f128, Expand);
1040         setOperationAction(ISD::FCOS , MVT::f128, Expand);
1041         setOperationAction(ISD::FPOW, MVT::f128, Expand);
1042         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1043         setOperationAction(ISD::FREM, MVT::f128, Expand);
1044 
1045         // Handle constrained floating-point operations of fp128
1046         setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1047         setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1048         setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1049         setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1050         setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1051         setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1052         setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1053         setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1054         setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1055         setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1056         setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1057         setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1058         setOperationAction(ISD::STRICT_FCEIL,  MVT::f128, Legal);
1059         setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1060         setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1061       }
1062       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1063       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1064       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1065       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1066       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1067     }
1068 
1069     if (Subtarget.hasP9Altivec()) {
1070       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1071       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1072 
1073       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1074       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1075       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1076       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1077       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1078       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1079       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1080     }
1081   }
1082 
1083   if (Subtarget.hasQPX()) {
1084     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1085     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1086     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1087     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
1088 
1089     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
1090     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
1091 
1092     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
1093     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
1094 
1095     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
1096     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
1097 
1098     if (!Subtarget.useCRBits())
1099       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
1100     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1101 
1102     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
1103     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
1104     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
1105     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
1106     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
1107     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
1108     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
1109 
1110     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
1111     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
1112 
1113     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
1114     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
1115 
1116     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
1117     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
1118     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
1119     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
1120     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
1121     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
1122     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
1123     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
1124     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
1125     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
1126 
1127     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
1128     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
1129 
1130     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
1131     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
1132 
1133     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
1134 
1135     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
1136     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
1137     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
1138     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
1139 
1140     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1141     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
1142 
1143     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
1144     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
1145 
1146     if (!Subtarget.useCRBits())
1147       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
1148     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1149 
1150     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
1151     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
1152     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
1153     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
1154     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
1155     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
1156     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
1157 
1158     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
1159     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
1160 
1161     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
1162     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
1163     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
1164     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
1165     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
1166     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
1167     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
1168     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
1169     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
1170     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1171 
1172     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1173     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1174 
1175     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1176     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1177 
1178     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1179 
1180     setOperationAction(ISD::AND , MVT::v4i1, Legal);
1181     setOperationAction(ISD::OR , MVT::v4i1, Legal);
1182     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1183 
1184     if (!Subtarget.useCRBits())
1185       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1186     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1187 
1188     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
1189     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1190 
1191     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1192     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1193     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1194     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1195     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1196     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1197     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1198 
1199     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1200     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1201 
1202     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1203 
1204     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1205     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1206     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1207     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1208 
1209     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1210     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1211     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1212     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1213 
1214     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1215     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1216 
1217     // These need to set FE_INEXACT, and so cannot be vectorized here.
1218     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1219     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1220 
1221     if (TM.Options.UnsafeFPMath) {
1222       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1223       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1224 
1225       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1226       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1227     } else {
1228       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1229       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1230 
1231       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1232       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1233     }
1234 
1235     // TODO: Handle constrained floating-point operations of v4f64
1236   }
1237 
1238   if (Subtarget.has64BitSupport())
1239     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1240 
1241   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1242 
1243   if (!isPPC64) {
1244     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1245     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1246   }
1247 
1248   setBooleanContents(ZeroOrOneBooleanContent);
1249 
1250   if (Subtarget.hasAltivec()) {
1251     // Altivec instructions set fields to all zeros or all ones.
1252     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1253   }
1254 
1255   if (!isPPC64) {
1256     // These libcalls are not available in 32-bit.
1257     setLibcallName(RTLIB::SHL_I128, nullptr);
1258     setLibcallName(RTLIB::SRL_I128, nullptr);
1259     setLibcallName(RTLIB::SRA_I128, nullptr);
1260   }
1261 
1262   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1263 
1264   // We have target-specific dag combine patterns for the following nodes:
1265   setTargetDAGCombine(ISD::ADD);
1266   setTargetDAGCombine(ISD::SHL);
1267   setTargetDAGCombine(ISD::SRA);
1268   setTargetDAGCombine(ISD::SRL);
1269   setTargetDAGCombine(ISD::MUL);
1270   setTargetDAGCombine(ISD::FMA);
1271   setTargetDAGCombine(ISD::SINT_TO_FP);
1272   setTargetDAGCombine(ISD::BUILD_VECTOR);
1273   if (Subtarget.hasFPCVT())
1274     setTargetDAGCombine(ISD::UINT_TO_FP);
1275   setTargetDAGCombine(ISD::LOAD);
1276   setTargetDAGCombine(ISD::STORE);
1277   setTargetDAGCombine(ISD::BR_CC);
1278   if (Subtarget.useCRBits())
1279     setTargetDAGCombine(ISD::BRCOND);
1280   setTargetDAGCombine(ISD::BSWAP);
1281   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1282   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1283   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1284 
1285   setTargetDAGCombine(ISD::SIGN_EXTEND);
1286   setTargetDAGCombine(ISD::ZERO_EXTEND);
1287   setTargetDAGCombine(ISD::ANY_EXTEND);
1288 
1289   setTargetDAGCombine(ISD::TRUNCATE);
1290   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1291 
1292 
1293   if (Subtarget.useCRBits()) {
1294     setTargetDAGCombine(ISD::TRUNCATE);
1295     setTargetDAGCombine(ISD::SETCC);
1296     setTargetDAGCombine(ISD::SELECT_CC);
1297   }
1298 
1299   // Use reciprocal estimates.
1300   if (TM.Options.UnsafeFPMath) {
1301     setTargetDAGCombine(ISD::FDIV);
1302     setTargetDAGCombine(ISD::FSQRT);
1303   }
1304 
1305   if (Subtarget.hasP9Altivec()) {
1306     setTargetDAGCombine(ISD::ABS);
1307     setTargetDAGCombine(ISD::VSELECT);
1308   }
1309 
1310   if (EnableQuadPrecision) {
1311     setLibcallName(RTLIB::LOG_F128, "logf128");
1312     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1313     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1314     setLibcallName(RTLIB::EXP_F128, "expf128");
1315     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1316     setLibcallName(RTLIB::SIN_F128, "sinf128");
1317     setLibcallName(RTLIB::COS_F128, "cosf128");
1318     setLibcallName(RTLIB::POW_F128, "powf128");
1319     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1320     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1321     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1322     setLibcallName(RTLIB::REM_F128, "fmodf128");
1323   }
1324 
1325   // With 32 condition bits, we don't need to sink (and duplicate) compares
1326   // aggressively in CodeGenPrep.
1327   if (Subtarget.useCRBits()) {
1328     setHasMultipleConditionRegisters();
1329     setJumpIsExpensive();
1330   }
1331 
1332   setMinFunctionAlignment(Align(4));
1333 
1334   switch (Subtarget.getCPUDirective()) {
1335   default: break;
1336   case PPC::DIR_970:
1337   case PPC::DIR_A2:
1338   case PPC::DIR_E500:
1339   case PPC::DIR_E500mc:
1340   case PPC::DIR_E5500:
1341   case PPC::DIR_PWR4:
1342   case PPC::DIR_PWR5:
1343   case PPC::DIR_PWR5X:
1344   case PPC::DIR_PWR6:
1345   case PPC::DIR_PWR6X:
1346   case PPC::DIR_PWR7:
1347   case PPC::DIR_PWR8:
1348   case PPC::DIR_PWR9:
1349   case PPC::DIR_PWR10:
1350   case PPC::DIR_PWR_FUTURE:
1351     setPrefLoopAlignment(Align(16));
1352     setPrefFunctionAlignment(Align(16));
1353     break;
1354   }
1355 
1356   if (Subtarget.enableMachineScheduler())
1357     setSchedulingPreference(Sched::Source);
1358   else
1359     setSchedulingPreference(Sched::Hybrid);
1360 
1361   computeRegisterProperties(STI.getRegisterInfo());
1362 
1363   // The Freescale cores do better with aggressive inlining of memcpy and
1364   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1365   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1366       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1367     MaxStoresPerMemset = 32;
1368     MaxStoresPerMemsetOptSize = 16;
1369     MaxStoresPerMemcpy = 32;
1370     MaxStoresPerMemcpyOptSize = 8;
1371     MaxStoresPerMemmove = 32;
1372     MaxStoresPerMemmoveOptSize = 8;
1373   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1374     // The A2 also benefits from (very) aggressive inlining of memcpy and
1375     // friends. The overhead of a the function call, even when warm, can be
1376     // over one hundred cycles.
1377     MaxStoresPerMemset = 128;
1378     MaxStoresPerMemcpy = 128;
1379     MaxStoresPerMemmove = 128;
1380     MaxLoadsPerMemcmp = 128;
1381   } else {
1382     MaxLoadsPerMemcmp = 8;
1383     MaxLoadsPerMemcmpOptSize = 4;
1384   }
1385 
1386   // Let the subtarget (CPU) decide if a predictable select is more expensive
1387   // than the corresponding branch. This information is used in CGP to decide
1388   // when to convert selects into branches.
1389   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1390 }
1391 
1392 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1393 /// the desired ByVal argument alignment.
1394 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1395   if (MaxAlign == MaxMaxAlign)
1396     return;
1397   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1398     if (MaxMaxAlign >= 32 &&
1399         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1400       MaxAlign = Align(32);
1401     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1402              MaxAlign < 16)
1403       MaxAlign = Align(16);
1404   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1405     Align EltAlign;
1406     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1407     if (EltAlign > MaxAlign)
1408       MaxAlign = EltAlign;
1409   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1410     for (auto *EltTy : STy->elements()) {
1411       Align EltAlign;
1412       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1413       if (EltAlign > MaxAlign)
1414         MaxAlign = EltAlign;
1415       if (MaxAlign == MaxMaxAlign)
1416         break;
1417     }
1418   }
1419 }
1420 
1421 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1422 /// function arguments in the caller parameter area.
1423 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1424                                                   const DataLayout &DL) const {
1425   // 16byte and wider vectors are passed on 16byte boundary.
1426   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1427   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1428   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1429     getMaxByValAlign(Ty, Alignment, Subtarget.hasQPX() ? Align(32) : Align(16));
1430   return Alignment.value();
1431 }
1432 
1433 bool PPCTargetLowering::useSoftFloat() const {
1434   return Subtarget.useSoftFloat();
1435 }
1436 
1437 bool PPCTargetLowering::hasSPE() const {
1438   return Subtarget.hasSPE();
1439 }
1440 
1441 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1442   return VT.isScalarInteger();
1443 }
1444 
1445 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific
1446 /// type is cheaper than a multiply followed by a shift.
1447 /// This is true for words and doublewords on 64-bit PowerPC.
1448 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const {
1449   if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) ||
1450                               isOperationLegal(ISD::MULHU, Type)))
1451     return true;
1452   return TargetLowering::isMulhCheaperThanMulShift(Type);
1453 }
1454 
1455 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1456   switch ((PPCISD::NodeType)Opcode) {
1457   case PPCISD::FIRST_NUMBER:    break;
1458   case PPCISD::FSEL:            return "PPCISD::FSEL";
1459   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1460   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1461   case PPCISD::FCFID:           return "PPCISD::FCFID";
1462   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1463   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1464   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1465   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1466   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1467   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1468   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1469   case PPCISD::FP_TO_UINT_IN_VSR:
1470                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1471   case PPCISD::FP_TO_SINT_IN_VSR:
1472                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1473   case PPCISD::FRE:             return "PPCISD::FRE";
1474   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1475   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1476   case PPCISD::VPERM:           return "PPCISD::VPERM";
1477   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1478   case PPCISD::XXSPLTI_SP_TO_DP:
1479     return "PPCISD::XXSPLTI_SP_TO_DP";
1480   case PPCISD::XXSPLTI32DX:
1481     return "PPCISD::XXSPLTI32DX";
1482   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1483   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1484   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1485   case PPCISD::CMPB:            return "PPCISD::CMPB";
1486   case PPCISD::Hi:              return "PPCISD::Hi";
1487   case PPCISD::Lo:              return "PPCISD::Lo";
1488   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1489   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1490   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1491   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1492   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1493   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1494   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1495   case PPCISD::SRL:             return "PPCISD::SRL";
1496   case PPCISD::SRA:             return "PPCISD::SRA";
1497   case PPCISD::SHL:             return "PPCISD::SHL";
1498   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1499   case PPCISD::CALL:            return "PPCISD::CALL";
1500   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1501   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1502   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1503   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1504   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1505   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1506   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1507   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1508   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1509   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1510   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1511   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1512   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1513   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1514   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1515   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1516     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1517   case PPCISD::ANDI_rec_1_EQ_BIT:
1518     return "PPCISD::ANDI_rec_1_EQ_BIT";
1519   case PPCISD::ANDI_rec_1_GT_BIT:
1520     return "PPCISD::ANDI_rec_1_GT_BIT";
1521   case PPCISD::VCMP:            return "PPCISD::VCMP";
1522   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1523   case PPCISD::LBRX:            return "PPCISD::LBRX";
1524   case PPCISD::STBRX:           return "PPCISD::STBRX";
1525   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1526   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1527   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1528   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1529   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1530   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1531   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1532   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1533   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1534   case PPCISD::ST_VSR_SCAL_INT:
1535                                 return "PPCISD::ST_VSR_SCAL_INT";
1536   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1537   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1538   case PPCISD::BDZ:             return "PPCISD::BDZ";
1539   case PPCISD::MFFS:            return "PPCISD::MFFS";
1540   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1541   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1542   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1543   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1544   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1545   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1546   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1547   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1548   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1549   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1550   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1551   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1552   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1553   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1554   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1555   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1556   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1557   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1558   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1559   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1560   case PPCISD::SC:              return "PPCISD::SC";
1561   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1562   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1563   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1564   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1565   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1566   case PPCISD::VABSD:           return "PPCISD::VABSD";
1567   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1568   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1569   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1570   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1571   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1572   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1573   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1574   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1575   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1576   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1577   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1578   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1579   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1580   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1581   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1582   }
1583   return nullptr;
1584 }
1585 
1586 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1587                                           EVT VT) const {
1588   if (!VT.isVector())
1589     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1590 
1591   if (Subtarget.hasQPX())
1592     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1593 
1594   return VT.changeVectorElementTypeToInteger();
1595 }
1596 
1597 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1598   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1599   return true;
1600 }
1601 
1602 //===----------------------------------------------------------------------===//
1603 // Node matching predicates, for use by the tblgen matching code.
1604 //===----------------------------------------------------------------------===//
1605 
1606 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1607 static bool isFloatingPointZero(SDValue Op) {
1608   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1609     return CFP->getValueAPF().isZero();
1610   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1611     // Maybe this has already been legalized into the constant pool?
1612     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1613       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1614         return CFP->getValueAPF().isZero();
1615   }
1616   return false;
1617 }
1618 
1619 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1620 /// true if Op is undef or if it matches the specified value.
1621 static bool isConstantOrUndef(int Op, int Val) {
1622   return Op < 0 || Op == Val;
1623 }
1624 
1625 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1626 /// VPKUHUM instruction.
1627 /// The ShuffleKind distinguishes between big-endian operations with
1628 /// two different inputs (0), either-endian operations with two identical
1629 /// inputs (1), and little-endian operations with two different inputs (2).
1630 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1631 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1632                                SelectionDAG &DAG) {
1633   bool IsLE = DAG.getDataLayout().isLittleEndian();
1634   if (ShuffleKind == 0) {
1635     if (IsLE)
1636       return false;
1637     for (unsigned i = 0; i != 16; ++i)
1638       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1639         return false;
1640   } else if (ShuffleKind == 2) {
1641     if (!IsLE)
1642       return false;
1643     for (unsigned i = 0; i != 16; ++i)
1644       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1645         return false;
1646   } else if (ShuffleKind == 1) {
1647     unsigned j = IsLE ? 0 : 1;
1648     for (unsigned i = 0; i != 8; ++i)
1649       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1650           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1651         return false;
1652   }
1653   return true;
1654 }
1655 
1656 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1657 /// VPKUWUM instruction.
1658 /// The ShuffleKind distinguishes between big-endian operations with
1659 /// two different inputs (0), either-endian operations with two identical
1660 /// inputs (1), and little-endian operations with two different inputs (2).
1661 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1662 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1663                                SelectionDAG &DAG) {
1664   bool IsLE = DAG.getDataLayout().isLittleEndian();
1665   if (ShuffleKind == 0) {
1666     if (IsLE)
1667       return false;
1668     for (unsigned i = 0; i != 16; i += 2)
1669       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1670           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1671         return false;
1672   } else if (ShuffleKind == 2) {
1673     if (!IsLE)
1674       return false;
1675     for (unsigned i = 0; i != 16; i += 2)
1676       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1677           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1678         return false;
1679   } else if (ShuffleKind == 1) {
1680     unsigned j = IsLE ? 0 : 2;
1681     for (unsigned i = 0; i != 8; i += 2)
1682       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1683           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1684           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1685           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1686         return false;
1687   }
1688   return true;
1689 }
1690 
1691 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1692 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1693 /// current subtarget.
1694 ///
1695 /// The ShuffleKind distinguishes between big-endian operations with
1696 /// two different inputs (0), either-endian operations with two identical
1697 /// inputs (1), and little-endian operations with two different inputs (2).
1698 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1699 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1700                                SelectionDAG &DAG) {
1701   const PPCSubtarget& Subtarget =
1702       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1703   if (!Subtarget.hasP8Vector())
1704     return false;
1705 
1706   bool IsLE = DAG.getDataLayout().isLittleEndian();
1707   if (ShuffleKind == 0) {
1708     if (IsLE)
1709       return false;
1710     for (unsigned i = 0; i != 16; i += 4)
1711       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1712           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1713           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1714           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1715         return false;
1716   } else if (ShuffleKind == 2) {
1717     if (!IsLE)
1718       return false;
1719     for (unsigned i = 0; i != 16; i += 4)
1720       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1721           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1722           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1723           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1724         return false;
1725   } else if (ShuffleKind == 1) {
1726     unsigned j = IsLE ? 0 : 4;
1727     for (unsigned i = 0; i != 8; i += 4)
1728       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1729           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1730           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1731           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1732           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1733           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1734           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1735           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1736         return false;
1737   }
1738   return true;
1739 }
1740 
1741 /// isVMerge - Common function, used to match vmrg* shuffles.
1742 ///
1743 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1744                      unsigned LHSStart, unsigned RHSStart) {
1745   if (N->getValueType(0) != MVT::v16i8)
1746     return false;
1747   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1748          "Unsupported merge size!");
1749 
1750   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1751     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1752       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1753                              LHSStart+j+i*UnitSize) ||
1754           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1755                              RHSStart+j+i*UnitSize))
1756         return false;
1757     }
1758   return true;
1759 }
1760 
1761 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1762 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1763 /// The ShuffleKind distinguishes between big-endian merges with two
1764 /// different inputs (0), either-endian merges with two identical inputs (1),
1765 /// and little-endian merges with two different inputs (2).  For the latter,
1766 /// the input operands are swapped (see PPCInstrAltivec.td).
1767 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1768                              unsigned ShuffleKind, SelectionDAG &DAG) {
1769   if (DAG.getDataLayout().isLittleEndian()) {
1770     if (ShuffleKind == 1) // unary
1771       return isVMerge(N, UnitSize, 0, 0);
1772     else if (ShuffleKind == 2) // swapped
1773       return isVMerge(N, UnitSize, 0, 16);
1774     else
1775       return false;
1776   } else {
1777     if (ShuffleKind == 1) // unary
1778       return isVMerge(N, UnitSize, 8, 8);
1779     else if (ShuffleKind == 0) // normal
1780       return isVMerge(N, UnitSize, 8, 24);
1781     else
1782       return false;
1783   }
1784 }
1785 
1786 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1787 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1788 /// The ShuffleKind distinguishes between big-endian merges with two
1789 /// different inputs (0), either-endian merges with two identical inputs (1),
1790 /// and little-endian merges with two different inputs (2).  For the latter,
1791 /// the input operands are swapped (see PPCInstrAltivec.td).
1792 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1793                              unsigned ShuffleKind, SelectionDAG &DAG) {
1794   if (DAG.getDataLayout().isLittleEndian()) {
1795     if (ShuffleKind == 1) // unary
1796       return isVMerge(N, UnitSize, 8, 8);
1797     else if (ShuffleKind == 2) // swapped
1798       return isVMerge(N, UnitSize, 8, 24);
1799     else
1800       return false;
1801   } else {
1802     if (ShuffleKind == 1) // unary
1803       return isVMerge(N, UnitSize, 0, 0);
1804     else if (ShuffleKind == 0) // normal
1805       return isVMerge(N, UnitSize, 0, 16);
1806     else
1807       return false;
1808   }
1809 }
1810 
1811 /**
1812  * Common function used to match vmrgew and vmrgow shuffles
1813  *
1814  * The indexOffset determines whether to look for even or odd words in
1815  * the shuffle mask. This is based on the of the endianness of the target
1816  * machine.
1817  *   - Little Endian:
1818  *     - Use offset of 0 to check for odd elements
1819  *     - Use offset of 4 to check for even elements
1820  *   - Big Endian:
1821  *     - Use offset of 0 to check for even elements
1822  *     - Use offset of 4 to check for odd elements
1823  * A detailed description of the vector element ordering for little endian and
1824  * big endian can be found at
1825  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1826  * Targeting your applications - what little endian and big endian IBM XL C/C++
1827  * compiler differences mean to you
1828  *
1829  * The mask to the shuffle vector instruction specifies the indices of the
1830  * elements from the two input vectors to place in the result. The elements are
1831  * numbered in array-access order, starting with the first vector. These vectors
1832  * are always of type v16i8, thus each vector will contain 16 elements of size
1833  * 8. More info on the shuffle vector can be found in the
1834  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1835  * Language Reference.
1836  *
1837  * The RHSStartValue indicates whether the same input vectors are used (unary)
1838  * or two different input vectors are used, based on the following:
1839  *   - If the instruction uses the same vector for both inputs, the range of the
1840  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1841  *     be 0.
1842  *   - If the instruction has two different vectors then the range of the
1843  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1844  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1845  *     to 31 specify elements in the second vector).
1846  *
1847  * \param[in] N The shuffle vector SD Node to analyze
1848  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1849  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1850  * vector to the shuffle_vector instruction
1851  * \return true iff this shuffle vector represents an even or odd word merge
1852  */
1853 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1854                      unsigned RHSStartValue) {
1855   if (N->getValueType(0) != MVT::v16i8)
1856     return false;
1857 
1858   for (unsigned i = 0; i < 2; ++i)
1859     for (unsigned j = 0; j < 4; ++j)
1860       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1861                              i*RHSStartValue+j+IndexOffset) ||
1862           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1863                              i*RHSStartValue+j+IndexOffset+8))
1864         return false;
1865   return true;
1866 }
1867 
1868 /**
1869  * Determine if the specified shuffle mask is suitable for the vmrgew or
1870  * vmrgow instructions.
1871  *
1872  * \param[in] N The shuffle vector SD Node to analyze
1873  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1874  * \param[in] ShuffleKind Identify the type of merge:
1875  *   - 0 = big-endian merge with two different inputs;
1876  *   - 1 = either-endian merge with two identical inputs;
1877  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1878  *     little-endian merges).
1879  * \param[in] DAG The current SelectionDAG
1880  * \return true iff this shuffle mask
1881  */
1882 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1883                               unsigned ShuffleKind, SelectionDAG &DAG) {
1884   if (DAG.getDataLayout().isLittleEndian()) {
1885     unsigned indexOffset = CheckEven ? 4 : 0;
1886     if (ShuffleKind == 1) // Unary
1887       return isVMerge(N, indexOffset, 0);
1888     else if (ShuffleKind == 2) // swapped
1889       return isVMerge(N, indexOffset, 16);
1890     else
1891       return false;
1892   }
1893   else {
1894     unsigned indexOffset = CheckEven ? 0 : 4;
1895     if (ShuffleKind == 1) // Unary
1896       return isVMerge(N, indexOffset, 0);
1897     else if (ShuffleKind == 0) // Normal
1898       return isVMerge(N, indexOffset, 16);
1899     else
1900       return false;
1901   }
1902   return false;
1903 }
1904 
1905 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1906 /// amount, otherwise return -1.
1907 /// The ShuffleKind distinguishes between big-endian operations with two
1908 /// different inputs (0), either-endian operations with two identical inputs
1909 /// (1), and little-endian operations with two different inputs (2).  For the
1910 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1911 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1912                              SelectionDAG &DAG) {
1913   if (N->getValueType(0) != MVT::v16i8)
1914     return -1;
1915 
1916   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1917 
1918   // Find the first non-undef value in the shuffle mask.
1919   unsigned i;
1920   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1921     /*search*/;
1922 
1923   if (i == 16) return -1;  // all undef.
1924 
1925   // Otherwise, check to see if the rest of the elements are consecutively
1926   // numbered from this value.
1927   unsigned ShiftAmt = SVOp->getMaskElt(i);
1928   if (ShiftAmt < i) return -1;
1929 
1930   ShiftAmt -= i;
1931   bool isLE = DAG.getDataLayout().isLittleEndian();
1932 
1933   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1934     // Check the rest of the elements to see if they are consecutive.
1935     for (++i; i != 16; ++i)
1936       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1937         return -1;
1938   } else if (ShuffleKind == 1) {
1939     // Check the rest of the elements to see if they are consecutive.
1940     for (++i; i != 16; ++i)
1941       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1942         return -1;
1943   } else
1944     return -1;
1945 
1946   if (isLE)
1947     ShiftAmt = 16 - ShiftAmt;
1948 
1949   return ShiftAmt;
1950 }
1951 
1952 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1953 /// specifies a splat of a single element that is suitable for input to
1954 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1955 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1956   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1957          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1958 
1959   // The consecutive indices need to specify an element, not part of two
1960   // different elements.  So abandon ship early if this isn't the case.
1961   if (N->getMaskElt(0) % EltSize != 0)
1962     return false;
1963 
1964   // This is a splat operation if each element of the permute is the same, and
1965   // if the value doesn't reference the second vector.
1966   unsigned ElementBase = N->getMaskElt(0);
1967 
1968   // FIXME: Handle UNDEF elements too!
1969   if (ElementBase >= 16)
1970     return false;
1971 
1972   // Check that the indices are consecutive, in the case of a multi-byte element
1973   // splatted with a v16i8 mask.
1974   for (unsigned i = 1; i != EltSize; ++i)
1975     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1976       return false;
1977 
1978   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1979     if (N->getMaskElt(i) < 0) continue;
1980     for (unsigned j = 0; j != EltSize; ++j)
1981       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1982         return false;
1983   }
1984   return true;
1985 }
1986 
1987 /// Check that the mask is shuffling N byte elements. Within each N byte
1988 /// element of the mask, the indices could be either in increasing or
1989 /// decreasing order as long as they are consecutive.
1990 /// \param[in] N the shuffle vector SD Node to analyze
1991 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1992 /// Word/DoubleWord/QuadWord).
1993 /// \param[in] StepLen the delta indices number among the N byte element, if
1994 /// the mask is in increasing/decreasing order then it is 1/-1.
1995 /// \return true iff the mask is shuffling N byte elements.
1996 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1997                                    int StepLen) {
1998   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1999          "Unexpected element width.");
2000   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2001 
2002   unsigned NumOfElem = 16 / Width;
2003   unsigned MaskVal[16]; //  Width is never greater than 16
2004   for (unsigned i = 0; i < NumOfElem; ++i) {
2005     MaskVal[0] = N->getMaskElt(i * Width);
2006     if ((StepLen == 1) && (MaskVal[0] % Width)) {
2007       return false;
2008     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2009       return false;
2010     }
2011 
2012     for (unsigned int j = 1; j < Width; ++j) {
2013       MaskVal[j] = N->getMaskElt(i * Width + j);
2014       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2015         return false;
2016       }
2017     }
2018   }
2019 
2020   return true;
2021 }
2022 
2023 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2024                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2025   if (!isNByteElemShuffleMask(N, 4, 1))
2026     return false;
2027 
2028   // Now we look at mask elements 0,4,8,12
2029   unsigned M0 = N->getMaskElt(0) / 4;
2030   unsigned M1 = N->getMaskElt(4) / 4;
2031   unsigned M2 = N->getMaskElt(8) / 4;
2032   unsigned M3 = N->getMaskElt(12) / 4;
2033   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2034   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2035 
2036   // Below, let H and L be arbitrary elements of the shuffle mask
2037   // where H is in the range [4,7] and L is in the range [0,3].
2038   // H, 1, 2, 3 or L, 5, 6, 7
2039   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2040       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2041     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2042     InsertAtByte = IsLE ? 12 : 0;
2043     Swap = M0 < 4;
2044     return true;
2045   }
2046   // 0, H, 2, 3 or 4, L, 6, 7
2047   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2048       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2049     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2050     InsertAtByte = IsLE ? 8 : 4;
2051     Swap = M1 < 4;
2052     return true;
2053   }
2054   // 0, 1, H, 3 or 4, 5, L, 7
2055   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2056       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2057     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2058     InsertAtByte = IsLE ? 4 : 8;
2059     Swap = M2 < 4;
2060     return true;
2061   }
2062   // 0, 1, 2, H or 4, 5, 6, L
2063   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2064       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2065     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2066     InsertAtByte = IsLE ? 0 : 12;
2067     Swap = M3 < 4;
2068     return true;
2069   }
2070 
2071   // If both vector operands for the shuffle are the same vector, the mask will
2072   // contain only elements from the first one and the second one will be undef.
2073   if (N->getOperand(1).isUndef()) {
2074     ShiftElts = 0;
2075     Swap = true;
2076     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2077     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2078       InsertAtByte = IsLE ? 12 : 0;
2079       return true;
2080     }
2081     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2082       InsertAtByte = IsLE ? 8 : 4;
2083       return true;
2084     }
2085     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2086       InsertAtByte = IsLE ? 4 : 8;
2087       return true;
2088     }
2089     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2090       InsertAtByte = IsLE ? 0 : 12;
2091       return true;
2092     }
2093   }
2094 
2095   return false;
2096 }
2097 
2098 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2099                                bool &Swap, bool IsLE) {
2100   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2101   // Ensure each byte index of the word is consecutive.
2102   if (!isNByteElemShuffleMask(N, 4, 1))
2103     return false;
2104 
2105   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2106   unsigned M0 = N->getMaskElt(0) / 4;
2107   unsigned M1 = N->getMaskElt(4) / 4;
2108   unsigned M2 = N->getMaskElt(8) / 4;
2109   unsigned M3 = N->getMaskElt(12) / 4;
2110 
2111   // If both vector operands for the shuffle are the same vector, the mask will
2112   // contain only elements from the first one and the second one will be undef.
2113   if (N->getOperand(1).isUndef()) {
2114     assert(M0 < 4 && "Indexing into an undef vector?");
2115     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2116       return false;
2117 
2118     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2119     Swap = false;
2120     return true;
2121   }
2122 
2123   // Ensure each word index of the ShuffleVector Mask is consecutive.
2124   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2125     return false;
2126 
2127   if (IsLE) {
2128     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2129       // Input vectors don't need to be swapped if the leading element
2130       // of the result is one of the 3 left elements of the second vector
2131       // (or if there is no shift to be done at all).
2132       Swap = false;
2133       ShiftElts = (8 - M0) % 8;
2134     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2135       // Input vectors need to be swapped if the leading element
2136       // of the result is one of the 3 left elements of the first vector
2137       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2138       Swap = true;
2139       ShiftElts = (4 - M0) % 4;
2140     }
2141 
2142     return true;
2143   } else {                                          // BE
2144     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2145       // Input vectors don't need to be swapped if the leading element
2146       // of the result is one of the 4 elements of the first vector.
2147       Swap = false;
2148       ShiftElts = M0;
2149     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2150       // Input vectors need to be swapped if the leading element
2151       // of the result is one of the 4 elements of the right vector.
2152       Swap = true;
2153       ShiftElts = M0 - 4;
2154     }
2155 
2156     return true;
2157   }
2158 }
2159 
2160 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2161   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2162 
2163   if (!isNByteElemShuffleMask(N, Width, -1))
2164     return false;
2165 
2166   for (int i = 0; i < 16; i += Width)
2167     if (N->getMaskElt(i) != i + Width - 1)
2168       return false;
2169 
2170   return true;
2171 }
2172 
2173 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2174   return isXXBRShuffleMaskHelper(N, 2);
2175 }
2176 
2177 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2178   return isXXBRShuffleMaskHelper(N, 4);
2179 }
2180 
2181 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2182   return isXXBRShuffleMaskHelper(N, 8);
2183 }
2184 
2185 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2186   return isXXBRShuffleMaskHelper(N, 16);
2187 }
2188 
2189 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2190 /// if the inputs to the instruction should be swapped and set \p DM to the
2191 /// value for the immediate.
2192 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2193 /// AND element 0 of the result comes from the first input (LE) or second input
2194 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2195 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2196 /// mask.
2197 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2198                                bool &Swap, bool IsLE) {
2199   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2200 
2201   // Ensure each byte index of the double word is consecutive.
2202   if (!isNByteElemShuffleMask(N, 8, 1))
2203     return false;
2204 
2205   unsigned M0 = N->getMaskElt(0) / 8;
2206   unsigned M1 = N->getMaskElt(8) / 8;
2207   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2208 
2209   // If both vector operands for the shuffle are the same vector, the mask will
2210   // contain only elements from the first one and the second one will be undef.
2211   if (N->getOperand(1).isUndef()) {
2212     if ((M0 | M1) < 2) {
2213       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2214       Swap = false;
2215       return true;
2216     } else
2217       return false;
2218   }
2219 
2220   if (IsLE) {
2221     if (M0 > 1 && M1 < 2) {
2222       Swap = false;
2223     } else if (M0 < 2 && M1 > 1) {
2224       M0 = (M0 + 2) % 4;
2225       M1 = (M1 + 2) % 4;
2226       Swap = true;
2227     } else
2228       return false;
2229 
2230     // Note: if control flow comes here that means Swap is already set above
2231     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2232     return true;
2233   } else { // BE
2234     if (M0 < 2 && M1 > 1) {
2235       Swap = false;
2236     } else if (M0 > 1 && M1 < 2) {
2237       M0 = (M0 + 2) % 4;
2238       M1 = (M1 + 2) % 4;
2239       Swap = true;
2240     } else
2241       return false;
2242 
2243     // Note: if control flow comes here that means Swap is already set above
2244     DM = (M0 << 1) + (M1 & 1);
2245     return true;
2246   }
2247 }
2248 
2249 
2250 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2251 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2252 /// elements are counted from the left of the vector register).
2253 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2254                                          SelectionDAG &DAG) {
2255   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2256   assert(isSplatShuffleMask(SVOp, EltSize));
2257   if (DAG.getDataLayout().isLittleEndian())
2258     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2259   else
2260     return SVOp->getMaskElt(0) / EltSize;
2261 }
2262 
2263 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2264 /// by using a vspltis[bhw] instruction of the specified element size, return
2265 /// the constant being splatted.  The ByteSize field indicates the number of
2266 /// bytes of each element [124] -> [bhw].
2267 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2268   SDValue OpVal(nullptr, 0);
2269 
2270   // If ByteSize of the splat is bigger than the element size of the
2271   // build_vector, then we have a case where we are checking for a splat where
2272   // multiple elements of the buildvector are folded together into a single
2273   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2274   unsigned EltSize = 16/N->getNumOperands();
2275   if (EltSize < ByteSize) {
2276     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2277     SDValue UniquedVals[4];
2278     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2279 
2280     // See if all of the elements in the buildvector agree across.
2281     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2282       if (N->getOperand(i).isUndef()) continue;
2283       // If the element isn't a constant, bail fully out.
2284       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2285 
2286       if (!UniquedVals[i&(Multiple-1)].getNode())
2287         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2288       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2289         return SDValue();  // no match.
2290     }
2291 
2292     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2293     // either constant or undef values that are identical for each chunk.  See
2294     // if these chunks can form into a larger vspltis*.
2295 
2296     // Check to see if all of the leading entries are either 0 or -1.  If
2297     // neither, then this won't fit into the immediate field.
2298     bool LeadingZero = true;
2299     bool LeadingOnes = true;
2300     for (unsigned i = 0; i != Multiple-1; ++i) {
2301       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2302 
2303       LeadingZero &= isNullConstant(UniquedVals[i]);
2304       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2305     }
2306     // Finally, check the least significant entry.
2307     if (LeadingZero) {
2308       if (!UniquedVals[Multiple-1].getNode())
2309         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2310       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2311       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2312         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2313     }
2314     if (LeadingOnes) {
2315       if (!UniquedVals[Multiple-1].getNode())
2316         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2317       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2318       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2319         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2320     }
2321 
2322     return SDValue();
2323   }
2324 
2325   // Check to see if this buildvec has a single non-undef value in its elements.
2326   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2327     if (N->getOperand(i).isUndef()) continue;
2328     if (!OpVal.getNode())
2329       OpVal = N->getOperand(i);
2330     else if (OpVal != N->getOperand(i))
2331       return SDValue();
2332   }
2333 
2334   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2335 
2336   unsigned ValSizeInBytes = EltSize;
2337   uint64_t Value = 0;
2338   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2339     Value = CN->getZExtValue();
2340   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2341     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2342     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2343   }
2344 
2345   // If the splat value is larger than the element value, then we can never do
2346   // this splat.  The only case that we could fit the replicated bits into our
2347   // immediate field for would be zero, and we prefer to use vxor for it.
2348   if (ValSizeInBytes < ByteSize) return SDValue();
2349 
2350   // If the element value is larger than the splat value, check if it consists
2351   // of a repeated bit pattern of size ByteSize.
2352   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2353     return SDValue();
2354 
2355   // Properly sign extend the value.
2356   int MaskVal = SignExtend32(Value, ByteSize * 8);
2357 
2358   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2359   if (MaskVal == 0) return SDValue();
2360 
2361   // Finally, if this value fits in a 5 bit sext field, return it
2362   if (SignExtend32<5>(MaskVal) == MaskVal)
2363     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2364   return SDValue();
2365 }
2366 
2367 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2368 /// amount, otherwise return -1.
2369 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2370   EVT VT = N->getValueType(0);
2371   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2372     return -1;
2373 
2374   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2375 
2376   // Find the first non-undef value in the shuffle mask.
2377   unsigned i;
2378   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2379     /*search*/;
2380 
2381   if (i == 4) return -1;  // all undef.
2382 
2383   // Otherwise, check to see if the rest of the elements are consecutively
2384   // numbered from this value.
2385   unsigned ShiftAmt = SVOp->getMaskElt(i);
2386   if (ShiftAmt < i) return -1;
2387   ShiftAmt -= i;
2388 
2389   // Check the rest of the elements to see if they are consecutive.
2390   for (++i; i != 4; ++i)
2391     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2392       return -1;
2393 
2394   return ShiftAmt;
2395 }
2396 
2397 //===----------------------------------------------------------------------===//
2398 //  Addressing Mode Selection
2399 //===----------------------------------------------------------------------===//
2400 
2401 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2402 /// or 64-bit immediate, and if the value can be accurately represented as a
2403 /// sign extension from a 16-bit value.  If so, this returns true and the
2404 /// immediate.
2405 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2406   if (!isa<ConstantSDNode>(N))
2407     return false;
2408 
2409   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2410   if (N->getValueType(0) == MVT::i32)
2411     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2412   else
2413     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2414 }
2415 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2416   return isIntS16Immediate(Op.getNode(), Imm);
2417 }
2418 
2419 
2420 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2421 /// be represented as an indexed [r+r] operation.
2422 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2423                                                SDValue &Index,
2424                                                SelectionDAG &DAG) const {
2425   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2426       UI != E; ++UI) {
2427     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2428       if (Memop->getMemoryVT() == MVT::f64) {
2429           Base = N.getOperand(0);
2430           Index = N.getOperand(1);
2431           return true;
2432       }
2433     }
2434   }
2435   return false;
2436 }
2437 
2438 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2439 /// can be represented as an indexed [r+r] operation.  Returns false if it
2440 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2441 /// non-zero and N can be represented by a base register plus a signed 16-bit
2442 /// displacement, make a more precise judgement by checking (displacement % \p
2443 /// EncodingAlignment).
2444 bool PPCTargetLowering::SelectAddressRegReg(
2445     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2446     MaybeAlign EncodingAlignment) const {
2447   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2448   // a [pc+imm].
2449   if (SelectAddressPCRel(N, Base))
2450     return false;
2451 
2452   int16_t Imm = 0;
2453   if (N.getOpcode() == ISD::ADD) {
2454     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2455     // SPE load/store can only handle 8-bit offsets.
2456     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2457         return true;
2458     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2459         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2460       return false; // r+i
2461     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2462       return false;    // r+i
2463 
2464     Base = N.getOperand(0);
2465     Index = N.getOperand(1);
2466     return true;
2467   } else if (N.getOpcode() == ISD::OR) {
2468     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2469         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2470       return false; // r+i can fold it if we can.
2471 
2472     // If this is an or of disjoint bitfields, we can codegen this as an add
2473     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2474     // disjoint.
2475     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2476 
2477     if (LHSKnown.Zero.getBoolValue()) {
2478       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2479       // If all of the bits are known zero on the LHS or RHS, the add won't
2480       // carry.
2481       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2482         Base = N.getOperand(0);
2483         Index = N.getOperand(1);
2484         return true;
2485       }
2486     }
2487   }
2488 
2489   return false;
2490 }
2491 
2492 // If we happen to be doing an i64 load or store into a stack slot that has
2493 // less than a 4-byte alignment, then the frame-index elimination may need to
2494 // use an indexed load or store instruction (because the offset may not be a
2495 // multiple of 4). The extra register needed to hold the offset comes from the
2496 // register scavenger, and it is possible that the scavenger will need to use
2497 // an emergency spill slot. As a result, we need to make sure that a spill slot
2498 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2499 // stack slot.
2500 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2501   // FIXME: This does not handle the LWA case.
2502   if (VT != MVT::i64)
2503     return;
2504 
2505   // NOTE: We'll exclude negative FIs here, which come from argument
2506   // lowering, because there are no known test cases triggering this problem
2507   // using packed structures (or similar). We can remove this exclusion if
2508   // we find such a test case. The reason why this is so test-case driven is
2509   // because this entire 'fixup' is only to prevent crashes (from the
2510   // register scavenger) on not-really-valid inputs. For example, if we have:
2511   //   %a = alloca i1
2512   //   %b = bitcast i1* %a to i64*
2513   //   store i64* a, i64 b
2514   // then the store should really be marked as 'align 1', but is not. If it
2515   // were marked as 'align 1' then the indexed form would have been
2516   // instruction-selected initially, and the problem this 'fixup' is preventing
2517   // won't happen regardless.
2518   if (FrameIdx < 0)
2519     return;
2520 
2521   MachineFunction &MF = DAG.getMachineFunction();
2522   MachineFrameInfo &MFI = MF.getFrameInfo();
2523 
2524   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2525     return;
2526 
2527   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2528   FuncInfo->setHasNonRISpills();
2529 }
2530 
2531 /// Returns true if the address N can be represented by a base register plus
2532 /// a signed 16-bit displacement [r+imm], and if it is not better
2533 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2534 /// displacements that are multiples of that value.
2535 bool PPCTargetLowering::SelectAddressRegImm(
2536     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2537     MaybeAlign EncodingAlignment) const {
2538   // FIXME dl should come from parent load or store, not from address
2539   SDLoc dl(N);
2540 
2541   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2542   // a [pc+imm].
2543   if (SelectAddressPCRel(N, Base))
2544     return false;
2545 
2546   // If this can be more profitably realized as r+r, fail.
2547   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2548     return false;
2549 
2550   if (N.getOpcode() == ISD::ADD) {
2551     int16_t imm = 0;
2552     if (isIntS16Immediate(N.getOperand(1), imm) &&
2553         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2554       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2555       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2556         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2557         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2558       } else {
2559         Base = N.getOperand(0);
2560       }
2561       return true; // [r+i]
2562     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2563       // Match LOAD (ADD (X, Lo(G))).
2564       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2565              && "Cannot handle constant offsets yet!");
2566       Disp = N.getOperand(1).getOperand(0);  // The global address.
2567       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2568              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2569              Disp.getOpcode() == ISD::TargetConstantPool ||
2570              Disp.getOpcode() == ISD::TargetJumpTable);
2571       Base = N.getOperand(0);
2572       return true;  // [&g+r]
2573     }
2574   } else if (N.getOpcode() == ISD::OR) {
2575     int16_t imm = 0;
2576     if (isIntS16Immediate(N.getOperand(1), imm) &&
2577         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2578       // If this is an or of disjoint bitfields, we can codegen this as an add
2579       // (for better address arithmetic) if the LHS and RHS of the OR are
2580       // provably disjoint.
2581       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2582 
2583       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2584         // If all of the bits are known zero on the LHS or RHS, the add won't
2585         // carry.
2586         if (FrameIndexSDNode *FI =
2587               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2588           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2589           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2590         } else {
2591           Base = N.getOperand(0);
2592         }
2593         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2594         return true;
2595       }
2596     }
2597   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2598     // Loading from a constant address.
2599 
2600     // If this address fits entirely in a 16-bit sext immediate field, codegen
2601     // this as "d, 0"
2602     int16_t Imm;
2603     if (isIntS16Immediate(CN, Imm) &&
2604         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2605       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2606       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2607                              CN->getValueType(0));
2608       return true;
2609     }
2610 
2611     // Handle 32-bit sext immediates with LIS + addr mode.
2612     if ((CN->getValueType(0) == MVT::i32 ||
2613          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2614         (!EncodingAlignment ||
2615          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2616       int Addr = (int)CN->getZExtValue();
2617 
2618       // Otherwise, break this down into an LIS + disp.
2619       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2620 
2621       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2622                                    MVT::i32);
2623       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2624       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2625       return true;
2626     }
2627   }
2628 
2629   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2630   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2631     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2632     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2633   } else
2634     Base = N;
2635   return true;      // [r+0]
2636 }
2637 
2638 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2639 /// represented as an indexed [r+r] operation.
2640 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2641                                                 SDValue &Index,
2642                                                 SelectionDAG &DAG) const {
2643   // Check to see if we can easily represent this as an [r+r] address.  This
2644   // will fail if it thinks that the address is more profitably represented as
2645   // reg+imm, e.g. where imm = 0.
2646   if (SelectAddressRegReg(N, Base, Index, DAG))
2647     return true;
2648 
2649   // If the address is the result of an add, we will utilize the fact that the
2650   // address calculation includes an implicit add.  However, we can reduce
2651   // register pressure if we do not materialize a constant just for use as the
2652   // index register.  We only get rid of the add if it is not an add of a
2653   // value and a 16-bit signed constant and both have a single use.
2654   int16_t imm = 0;
2655   if (N.getOpcode() == ISD::ADD &&
2656       (!isIntS16Immediate(N.getOperand(1), imm) ||
2657        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2658     Base = N.getOperand(0);
2659     Index = N.getOperand(1);
2660     return true;
2661   }
2662 
2663   // Otherwise, do it the hard way, using R0 as the base register.
2664   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2665                          N.getValueType());
2666   Index = N;
2667   return true;
2668 }
2669 
2670 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2671   Ty *PCRelCand = dyn_cast<Ty>(N);
2672   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2673 }
2674 
2675 /// Returns true if this address is a PC Relative address.
2676 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2677 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2678 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2679   // This is a materialize PC Relative node. Always select this as PC Relative.
2680   Base = N;
2681   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2682     return true;
2683   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2684       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2685       isValidPCRelNode<JumpTableSDNode>(N) ||
2686       isValidPCRelNode<BlockAddressSDNode>(N))
2687     return true;
2688   return false;
2689 }
2690 
2691 /// Returns true if we should use a direct load into vector instruction
2692 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2693 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2694 
2695   // If there are any other uses other than scalar to vector, then we should
2696   // keep it as a scalar load -> direct move pattern to prevent multiple
2697   // loads.
2698   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2699   if (!LD)
2700     return false;
2701 
2702   EVT MemVT = LD->getMemoryVT();
2703   if (!MemVT.isSimple())
2704     return false;
2705   switch(MemVT.getSimpleVT().SimpleTy) {
2706   case MVT::i64:
2707     break;
2708   case MVT::i32:
2709     if (!ST.hasP8Vector())
2710       return false;
2711     break;
2712   case MVT::i16:
2713   case MVT::i8:
2714     if (!ST.hasP9Vector())
2715       return false;
2716     break;
2717   default:
2718     return false;
2719   }
2720 
2721   SDValue LoadedVal(N, 0);
2722   if (!LoadedVal.hasOneUse())
2723     return false;
2724 
2725   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2726        UI != UE; ++UI)
2727     if (UI.getUse().get().getResNo() == 0 &&
2728         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2729         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2730       return false;
2731 
2732   return true;
2733 }
2734 
2735 /// getPreIndexedAddressParts - returns true by value, base pointer and
2736 /// offset pointer and addressing mode by reference if the node's address
2737 /// can be legally represented as pre-indexed load / store address.
2738 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2739                                                   SDValue &Offset,
2740                                                   ISD::MemIndexedMode &AM,
2741                                                   SelectionDAG &DAG) const {
2742   if (DisablePPCPreinc) return false;
2743 
2744   bool isLoad = true;
2745   SDValue Ptr;
2746   EVT VT;
2747   unsigned Alignment;
2748   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2749     Ptr = LD->getBasePtr();
2750     VT = LD->getMemoryVT();
2751     Alignment = LD->getAlignment();
2752   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2753     Ptr = ST->getBasePtr();
2754     VT  = ST->getMemoryVT();
2755     Alignment = ST->getAlignment();
2756     isLoad = false;
2757   } else
2758     return false;
2759 
2760   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2761   // instructions because we can fold these into a more efficient instruction
2762   // instead, (such as LXSD).
2763   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2764     return false;
2765   }
2766 
2767   // PowerPC doesn't have preinc load/store instructions for vectors (except
2768   // for QPX, which does have preinc r+r forms).
2769   if (VT.isVector()) {
2770     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2771       return false;
2772     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2773       AM = ISD::PRE_INC;
2774       return true;
2775     }
2776   }
2777 
2778   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2779     // Common code will reject creating a pre-inc form if the base pointer
2780     // is a frame index, or if N is a store and the base pointer is either
2781     // the same as or a predecessor of the value being stored.  Check for
2782     // those situations here, and try with swapped Base/Offset instead.
2783     bool Swap = false;
2784 
2785     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2786       Swap = true;
2787     else if (!isLoad) {
2788       SDValue Val = cast<StoreSDNode>(N)->getValue();
2789       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2790         Swap = true;
2791     }
2792 
2793     if (Swap)
2794       std::swap(Base, Offset);
2795 
2796     AM = ISD::PRE_INC;
2797     return true;
2798   }
2799 
2800   // LDU/STU can only handle immediates that are a multiple of 4.
2801   if (VT != MVT::i64) {
2802     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2803       return false;
2804   } else {
2805     // LDU/STU need an address with at least 4-byte alignment.
2806     if (Alignment < 4)
2807       return false;
2808 
2809     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
2810       return false;
2811   }
2812 
2813   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2814     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2815     // sext i32 to i64 when addr mode is r+i.
2816     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2817         LD->getExtensionType() == ISD::SEXTLOAD &&
2818         isa<ConstantSDNode>(Offset))
2819       return false;
2820   }
2821 
2822   AM = ISD::PRE_INC;
2823   return true;
2824 }
2825 
2826 //===----------------------------------------------------------------------===//
2827 //  LowerOperation implementation
2828 //===----------------------------------------------------------------------===//
2829 
2830 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2831 /// and LoOpFlags to the target MO flags.
2832 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2833                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2834                                const GlobalValue *GV = nullptr) {
2835   HiOpFlags = PPCII::MO_HA;
2836   LoOpFlags = PPCII::MO_LO;
2837 
2838   // Don't use the pic base if not in PIC relocation model.
2839   if (IsPIC) {
2840     HiOpFlags |= PPCII::MO_PIC_FLAG;
2841     LoOpFlags |= PPCII::MO_PIC_FLAG;
2842   }
2843 }
2844 
2845 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2846                              SelectionDAG &DAG) {
2847   SDLoc DL(HiPart);
2848   EVT PtrVT = HiPart.getValueType();
2849   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2850 
2851   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2852   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2853 
2854   // With PIC, the first instruction is actually "GR+hi(&G)".
2855   if (isPIC)
2856     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2857                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2858 
2859   // Generate non-pic code that has direct accesses to the constant pool.
2860   // The address of the global is just (hi(&g)+lo(&g)).
2861   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2862 }
2863 
2864 static void setUsesTOCBasePtr(MachineFunction &MF) {
2865   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2866   FuncInfo->setUsesTOCBasePtr();
2867 }
2868 
2869 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2870   setUsesTOCBasePtr(DAG.getMachineFunction());
2871 }
2872 
2873 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2874                                        SDValue GA) const {
2875   const bool Is64Bit = Subtarget.isPPC64();
2876   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2877   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2878                         : Subtarget.isAIXABI()
2879                               ? DAG.getRegister(PPC::R2, VT)
2880                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2881   SDValue Ops[] = { GA, Reg };
2882   return DAG.getMemIntrinsicNode(
2883       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2884       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2885       MachineMemOperand::MOLoad);
2886 }
2887 
2888 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2889                                              SelectionDAG &DAG) const {
2890   EVT PtrVT = Op.getValueType();
2891   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2892   const Constant *C = CP->getConstVal();
2893 
2894   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2895   // The actual address of the GlobalValue is stored in the TOC.
2896   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2897     if (Subtarget.isUsingPCRelativeCalls()) {
2898       SDLoc DL(CP);
2899       EVT Ty = getPointerTy(DAG.getDataLayout());
2900       SDValue ConstPool = DAG.getTargetConstantPool(
2901           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2902       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2903     }
2904     setUsesTOCBasePtr(DAG);
2905     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2906     return getTOCEntry(DAG, SDLoc(CP), GA);
2907   }
2908 
2909   unsigned MOHiFlag, MOLoFlag;
2910   bool IsPIC = isPositionIndependent();
2911   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2912 
2913   if (IsPIC && Subtarget.isSVR4ABI()) {
2914     SDValue GA =
2915         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2916     return getTOCEntry(DAG, SDLoc(CP), GA);
2917   }
2918 
2919   SDValue CPIHi =
2920       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
2921   SDValue CPILo =
2922       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
2923   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2924 }
2925 
2926 // For 64-bit PowerPC, prefer the more compact relative encodings.
2927 // This trades 32 bits per jump table entry for one or two instructions
2928 // on the jump site.
2929 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2930   if (isJumpTableRelative())
2931     return MachineJumpTableInfo::EK_LabelDifference32;
2932 
2933   return TargetLowering::getJumpTableEncoding();
2934 }
2935 
2936 bool PPCTargetLowering::isJumpTableRelative() const {
2937   if (UseAbsoluteJumpTables)
2938     return false;
2939   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2940     return true;
2941   return TargetLowering::isJumpTableRelative();
2942 }
2943 
2944 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2945                                                     SelectionDAG &DAG) const {
2946   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2947     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2948 
2949   switch (getTargetMachine().getCodeModel()) {
2950   case CodeModel::Small:
2951   case CodeModel::Medium:
2952     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2953   default:
2954     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2955                        getPointerTy(DAG.getDataLayout()));
2956   }
2957 }
2958 
2959 const MCExpr *
2960 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2961                                                 unsigned JTI,
2962                                                 MCContext &Ctx) const {
2963   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2964     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2965 
2966   switch (getTargetMachine().getCodeModel()) {
2967   case CodeModel::Small:
2968   case CodeModel::Medium:
2969     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2970   default:
2971     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2972   }
2973 }
2974 
2975 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2976   EVT PtrVT = Op.getValueType();
2977   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2978 
2979   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2980   if (Subtarget.isUsingPCRelativeCalls()) {
2981     SDLoc DL(JT);
2982     EVT Ty = getPointerTy(DAG.getDataLayout());
2983     SDValue GA =
2984         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
2985     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2986     return MatAddr;
2987   }
2988 
2989   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2990   // The actual address of the GlobalValue is stored in the TOC.
2991   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2992     setUsesTOCBasePtr(DAG);
2993     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2994     return getTOCEntry(DAG, SDLoc(JT), GA);
2995   }
2996 
2997   unsigned MOHiFlag, MOLoFlag;
2998   bool IsPIC = isPositionIndependent();
2999   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3000 
3001   if (IsPIC && Subtarget.isSVR4ABI()) {
3002     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3003                                         PPCII::MO_PIC_FLAG);
3004     return getTOCEntry(DAG, SDLoc(GA), GA);
3005   }
3006 
3007   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3008   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3009   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3010 }
3011 
3012 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3013                                              SelectionDAG &DAG) const {
3014   EVT PtrVT = Op.getValueType();
3015   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3016   const BlockAddress *BA = BASDN->getBlockAddress();
3017 
3018   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3019   if (Subtarget.isUsingPCRelativeCalls()) {
3020     SDLoc DL(BASDN);
3021     EVT Ty = getPointerTy(DAG.getDataLayout());
3022     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3023                                            PPCII::MO_PCREL_FLAG);
3024     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3025     return MatAddr;
3026   }
3027 
3028   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3029   // The actual BlockAddress is stored in the TOC.
3030   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3031     setUsesTOCBasePtr(DAG);
3032     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3033     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3034   }
3035 
3036   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3037   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3038     return getTOCEntry(
3039         DAG, SDLoc(BASDN),
3040         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3041 
3042   unsigned MOHiFlag, MOLoFlag;
3043   bool IsPIC = isPositionIndependent();
3044   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3045   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3046   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3047   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3048 }
3049 
3050 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3051                                               SelectionDAG &DAG) const {
3052   // FIXME: TLS addresses currently use medium model code sequences,
3053   // which is the most useful form.  Eventually support for small and
3054   // large models could be added if users need it, at the cost of
3055   // additional complexity.
3056   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3057   if (DAG.getTarget().useEmulatedTLS())
3058     return LowerToTLSEmulatedModel(GA, DAG);
3059 
3060   SDLoc dl(GA);
3061   const GlobalValue *GV = GA->getGlobal();
3062   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3063   bool is64bit = Subtarget.isPPC64();
3064   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3065   PICLevel::Level picLevel = M->getPICLevel();
3066 
3067   const TargetMachine &TM = getTargetMachine();
3068   TLSModel::Model Model = TM.getTLSModel(GV);
3069 
3070   if (Model == TLSModel::LocalExec) {
3071     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3072                                                PPCII::MO_TPREL_HA);
3073     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3074                                                PPCII::MO_TPREL_LO);
3075     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3076                              : DAG.getRegister(PPC::R2, MVT::i32);
3077 
3078     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3079     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3080   }
3081 
3082   if (Model == TLSModel::InitialExec) {
3083     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3084     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3085                                                 PPCII::MO_TLS);
3086     SDValue GOTPtr;
3087     if (is64bit) {
3088       setUsesTOCBasePtr(DAG);
3089       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3090       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
3091                            PtrVT, GOTReg, TGA);
3092     } else {
3093       if (!TM.isPositionIndependent())
3094         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3095       else if (picLevel == PICLevel::SmallPIC)
3096         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3097       else
3098         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3099     }
3100     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
3101                                    PtrVT, TGA, GOTPtr);
3102     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3103   }
3104 
3105   if (Model == TLSModel::GeneralDynamic) {
3106     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3107     SDValue GOTPtr;
3108     if (is64bit) {
3109       setUsesTOCBasePtr(DAG);
3110       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3111       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3112                                    GOTReg, TGA);
3113     } else {
3114       if (picLevel == PICLevel::SmallPIC)
3115         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3116       else
3117         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3118     }
3119     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3120                        GOTPtr, TGA, TGA);
3121   }
3122 
3123   if (Model == TLSModel::LocalDynamic) {
3124     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3125     SDValue GOTPtr;
3126     if (is64bit) {
3127       setUsesTOCBasePtr(DAG);
3128       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3129       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3130                            GOTReg, TGA);
3131     } else {
3132       if (picLevel == PICLevel::SmallPIC)
3133         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3134       else
3135         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3136     }
3137     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3138                                   PtrVT, GOTPtr, TGA, TGA);
3139     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3140                                       PtrVT, TLSAddr, TGA);
3141     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3142   }
3143 
3144   llvm_unreachable("Unknown TLS model!");
3145 }
3146 
3147 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3148                                               SelectionDAG &DAG) const {
3149   EVT PtrVT = Op.getValueType();
3150   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3151   SDLoc DL(GSDN);
3152   const GlobalValue *GV = GSDN->getGlobal();
3153 
3154   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3155   // The actual address of the GlobalValue is stored in the TOC.
3156   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3157     if (Subtarget.isUsingPCRelativeCalls()) {
3158       EVT Ty = getPointerTy(DAG.getDataLayout());
3159       if (isAccessedAsGotIndirect(Op)) {
3160         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3161                                                 PPCII::MO_PCREL_FLAG |
3162                                                     PPCII::MO_GOT_FLAG);
3163         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3164         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3165                                    MachinePointerInfo());
3166         return Load;
3167       } else {
3168         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3169                                                 PPCII::MO_PCREL_FLAG);
3170         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3171       }
3172     }
3173     setUsesTOCBasePtr(DAG);
3174     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3175     return getTOCEntry(DAG, DL, GA);
3176   }
3177 
3178   unsigned MOHiFlag, MOLoFlag;
3179   bool IsPIC = isPositionIndependent();
3180   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3181 
3182   if (IsPIC && Subtarget.isSVR4ABI()) {
3183     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3184                                             GSDN->getOffset(),
3185                                             PPCII::MO_PIC_FLAG);
3186     return getTOCEntry(DAG, DL, GA);
3187   }
3188 
3189   SDValue GAHi =
3190     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3191   SDValue GALo =
3192     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3193 
3194   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3195 }
3196 
3197 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3198   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3199   SDLoc dl(Op);
3200 
3201   if (Op.getValueType() == MVT::v2i64) {
3202     // When the operands themselves are v2i64 values, we need to do something
3203     // special because VSX has no underlying comparison operations for these.
3204     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3205       // Equality can be handled by casting to the legal type for Altivec
3206       // comparisons, everything else needs to be expanded.
3207       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3208         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3209                  DAG.getSetCC(dl, MVT::v4i32,
3210                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3211                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3212                    CC));
3213       }
3214 
3215       return SDValue();
3216     }
3217 
3218     // We handle most of these in the usual way.
3219     return Op;
3220   }
3221 
3222   // If we're comparing for equality to zero, expose the fact that this is
3223   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3224   // fold the new nodes.
3225   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3226     return V;
3227 
3228   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3229     // Leave comparisons against 0 and -1 alone for now, since they're usually
3230     // optimized.  FIXME: revisit this when we can custom lower all setcc
3231     // optimizations.
3232     if (C->isAllOnesValue() || C->isNullValue())
3233       return SDValue();
3234   }
3235 
3236   // If we have an integer seteq/setne, turn it into a compare against zero
3237   // by xor'ing the rhs with the lhs, which is faster than setting a
3238   // condition register, reading it back out, and masking the correct bit.  The
3239   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3240   // the result to other bit-twiddling opportunities.
3241   EVT LHSVT = Op.getOperand(0).getValueType();
3242   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3243     EVT VT = Op.getValueType();
3244     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3245                                 Op.getOperand(1));
3246     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3247   }
3248   return SDValue();
3249 }
3250 
3251 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3252   SDNode *Node = Op.getNode();
3253   EVT VT = Node->getValueType(0);
3254   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3255   SDValue InChain = Node->getOperand(0);
3256   SDValue VAListPtr = Node->getOperand(1);
3257   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3258   SDLoc dl(Node);
3259 
3260   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3261 
3262   // gpr_index
3263   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3264                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3265   InChain = GprIndex.getValue(1);
3266 
3267   if (VT == MVT::i64) {
3268     // Check if GprIndex is even
3269     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3270                                  DAG.getConstant(1, dl, MVT::i32));
3271     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3272                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3273     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3274                                           DAG.getConstant(1, dl, MVT::i32));
3275     // Align GprIndex to be even if it isn't
3276     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3277                            GprIndex);
3278   }
3279 
3280   // fpr index is 1 byte after gpr
3281   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3282                                DAG.getConstant(1, dl, MVT::i32));
3283 
3284   // fpr
3285   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3286                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3287   InChain = FprIndex.getValue(1);
3288 
3289   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3290                                        DAG.getConstant(8, dl, MVT::i32));
3291 
3292   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3293                                         DAG.getConstant(4, dl, MVT::i32));
3294 
3295   // areas
3296   SDValue OverflowArea =
3297       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3298   InChain = OverflowArea.getValue(1);
3299 
3300   SDValue RegSaveArea =
3301       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3302   InChain = RegSaveArea.getValue(1);
3303 
3304   // select overflow_area if index > 8
3305   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3306                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3307 
3308   // adjustment constant gpr_index * 4/8
3309   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3310                                     VT.isInteger() ? GprIndex : FprIndex,
3311                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3312                                                     MVT::i32));
3313 
3314   // OurReg = RegSaveArea + RegConstant
3315   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3316                                RegConstant);
3317 
3318   // Floating types are 32 bytes into RegSaveArea
3319   if (VT.isFloatingPoint())
3320     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3321                          DAG.getConstant(32, dl, MVT::i32));
3322 
3323   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3324   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3325                                    VT.isInteger() ? GprIndex : FprIndex,
3326                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3327                                                    MVT::i32));
3328 
3329   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3330                               VT.isInteger() ? VAListPtr : FprPtr,
3331                               MachinePointerInfo(SV), MVT::i8);
3332 
3333   // determine if we should load from reg_save_area or overflow_area
3334   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3335 
3336   // increase overflow_area by 4/8 if gpr/fpr > 8
3337   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3338                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3339                                           dl, MVT::i32));
3340 
3341   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3342                              OverflowAreaPlusN);
3343 
3344   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3345                               MachinePointerInfo(), MVT::i32);
3346 
3347   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3348 }
3349 
3350 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3351   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3352 
3353   // We have to copy the entire va_list struct:
3354   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3355   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3356                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3357                        false, true, false, MachinePointerInfo(),
3358                        MachinePointerInfo());
3359 }
3360 
3361 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3362                                                   SelectionDAG &DAG) const {
3363   if (Subtarget.isAIXABI())
3364     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3365 
3366   return Op.getOperand(0);
3367 }
3368 
3369 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3370                                                 SelectionDAG &DAG) const {
3371   if (Subtarget.isAIXABI())
3372     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3373 
3374   SDValue Chain = Op.getOperand(0);
3375   SDValue Trmp = Op.getOperand(1); // trampoline
3376   SDValue FPtr = Op.getOperand(2); // nested function
3377   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3378   SDLoc dl(Op);
3379 
3380   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3381   bool isPPC64 = (PtrVT == MVT::i64);
3382   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3383 
3384   TargetLowering::ArgListTy Args;
3385   TargetLowering::ArgListEntry Entry;
3386 
3387   Entry.Ty = IntPtrTy;
3388   Entry.Node = Trmp; Args.push_back(Entry);
3389 
3390   // TrampSize == (isPPC64 ? 48 : 40);
3391   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3392                                isPPC64 ? MVT::i64 : MVT::i32);
3393   Args.push_back(Entry);
3394 
3395   Entry.Node = FPtr; Args.push_back(Entry);
3396   Entry.Node = Nest; Args.push_back(Entry);
3397 
3398   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3399   TargetLowering::CallLoweringInfo CLI(DAG);
3400   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3401       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3402       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3403 
3404   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3405   return CallResult.second;
3406 }
3407 
3408 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3409   MachineFunction &MF = DAG.getMachineFunction();
3410   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3411   EVT PtrVT = getPointerTy(MF.getDataLayout());
3412 
3413   SDLoc dl(Op);
3414 
3415   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3416     // vastart just stores the address of the VarArgsFrameIndex slot into the
3417     // memory location argument.
3418     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3419     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3420     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3421                         MachinePointerInfo(SV));
3422   }
3423 
3424   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3425   // We suppose the given va_list is already allocated.
3426   //
3427   // typedef struct {
3428   //  char gpr;     /* index into the array of 8 GPRs
3429   //                 * stored in the register save area
3430   //                 * gpr=0 corresponds to r3,
3431   //                 * gpr=1 to r4, etc.
3432   //                 */
3433   //  char fpr;     /* index into the array of 8 FPRs
3434   //                 * stored in the register save area
3435   //                 * fpr=0 corresponds to f1,
3436   //                 * fpr=1 to f2, etc.
3437   //                 */
3438   //  char *overflow_arg_area;
3439   //                /* location on stack that holds
3440   //                 * the next overflow argument
3441   //                 */
3442   //  char *reg_save_area;
3443   //               /* where r3:r10 and f1:f8 (if saved)
3444   //                * are stored
3445   //                */
3446   // } va_list[1];
3447 
3448   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3449   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3450   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3451                                             PtrVT);
3452   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3453                                  PtrVT);
3454 
3455   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3456   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3457 
3458   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3459   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3460 
3461   uint64_t FPROffset = 1;
3462   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3463 
3464   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3465 
3466   // Store first byte : number of int regs
3467   SDValue firstStore =
3468       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3469                         MachinePointerInfo(SV), MVT::i8);
3470   uint64_t nextOffset = FPROffset;
3471   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3472                                   ConstFPROffset);
3473 
3474   // Store second byte : number of float regs
3475   SDValue secondStore =
3476       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3477                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3478   nextOffset += StackOffset;
3479   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3480 
3481   // Store second word : arguments given on stack
3482   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3483                                     MachinePointerInfo(SV, nextOffset));
3484   nextOffset += FrameOffset;
3485   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3486 
3487   // Store third word : arguments given in registers
3488   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3489                       MachinePointerInfo(SV, nextOffset));
3490 }
3491 
3492 /// FPR - The set of FP registers that should be allocated for arguments
3493 /// on Darwin and AIX.
3494 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3495                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3496                                 PPC::F11, PPC::F12, PPC::F13};
3497 
3498 /// QFPR - The set of QPX registers that should be allocated for arguments.
3499 static const MCPhysReg QFPR[] = {
3500     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3501     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3502 
3503 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3504 /// the stack.
3505 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3506                                        unsigned PtrByteSize) {
3507   unsigned ArgSize = ArgVT.getStoreSize();
3508   if (Flags.isByVal())
3509     ArgSize = Flags.getByValSize();
3510 
3511   // Round up to multiples of the pointer size, except for array members,
3512   // which are always packed.
3513   if (!Flags.isInConsecutiveRegs())
3514     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3515 
3516   return ArgSize;
3517 }
3518 
3519 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3520 /// on the stack.
3521 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3522                                          ISD::ArgFlagsTy Flags,
3523                                          unsigned PtrByteSize) {
3524   Align Alignment(PtrByteSize);
3525 
3526   // Altivec parameters are padded to a 16 byte boundary.
3527   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3528       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3529       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3530       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3531     Alignment = Align(16);
3532   // QPX vector types stored in double-precision are padded to a 32 byte
3533   // boundary.
3534   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3535     Alignment = Align(32);
3536 
3537   // ByVal parameters are aligned as requested.
3538   if (Flags.isByVal()) {
3539     auto BVAlign = Flags.getNonZeroByValAlign();
3540     if (BVAlign > PtrByteSize) {
3541       if (BVAlign.value() % PtrByteSize != 0)
3542         llvm_unreachable(
3543             "ByVal alignment is not a multiple of the pointer size");
3544 
3545       Alignment = BVAlign;
3546     }
3547   }
3548 
3549   // Array members are always packed to their original alignment.
3550   if (Flags.isInConsecutiveRegs()) {
3551     // If the array member was split into multiple registers, the first
3552     // needs to be aligned to the size of the full type.  (Except for
3553     // ppcf128, which is only aligned as its f64 components.)
3554     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3555       Alignment = Align(OrigVT.getStoreSize());
3556     else
3557       Alignment = Align(ArgVT.getStoreSize());
3558   }
3559 
3560   return Alignment;
3561 }
3562 
3563 /// CalculateStackSlotUsed - Return whether this argument will use its
3564 /// stack slot (instead of being passed in registers).  ArgOffset,
3565 /// AvailableFPRs, and AvailableVRs must hold the current argument
3566 /// position, and will be updated to account for this argument.
3567 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3568                                    ISD::ArgFlagsTy Flags,
3569                                    unsigned PtrByteSize,
3570                                    unsigned LinkageSize,
3571                                    unsigned ParamAreaSize,
3572                                    unsigned &ArgOffset,
3573                                    unsigned &AvailableFPRs,
3574                                    unsigned &AvailableVRs, bool HasQPX) {
3575   bool UseMemory = false;
3576 
3577   // Respect alignment of argument on the stack.
3578   Align Alignment =
3579       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3580   ArgOffset = alignTo(ArgOffset, Alignment);
3581   // If there's no space left in the argument save area, we must
3582   // use memory (this check also catches zero-sized arguments).
3583   if (ArgOffset >= LinkageSize + ParamAreaSize)
3584     UseMemory = true;
3585 
3586   // Allocate argument on the stack.
3587   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3588   if (Flags.isInConsecutiveRegsLast())
3589     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3590   // If we overran the argument save area, we must use memory
3591   // (this check catches arguments passed partially in memory)
3592   if (ArgOffset > LinkageSize + ParamAreaSize)
3593     UseMemory = true;
3594 
3595   // However, if the argument is actually passed in an FPR or a VR,
3596   // we don't use memory after all.
3597   if (!Flags.isByVal()) {
3598     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3599         // QPX registers overlap with the scalar FP registers.
3600         (HasQPX && (ArgVT == MVT::v4f32 ||
3601                     ArgVT == MVT::v4f64 ||
3602                     ArgVT == MVT::v4i1)))
3603       if (AvailableFPRs > 0) {
3604         --AvailableFPRs;
3605         return false;
3606       }
3607     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3608         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3609         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3610         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3611       if (AvailableVRs > 0) {
3612         --AvailableVRs;
3613         return false;
3614       }
3615   }
3616 
3617   return UseMemory;
3618 }
3619 
3620 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3621 /// ensure minimum alignment required for target.
3622 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3623                                      unsigned NumBytes) {
3624   return alignTo(NumBytes, Lowering->getStackAlign());
3625 }
3626 
3627 SDValue PPCTargetLowering::LowerFormalArguments(
3628     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3629     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3630     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3631   if (Subtarget.isAIXABI())
3632     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3633                                     InVals);
3634   if (Subtarget.is64BitELFABI())
3635     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3636                                        InVals);
3637   if (Subtarget.is32BitELFABI())
3638     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3639                                        InVals);
3640 
3641   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3642                                      InVals);
3643 }
3644 
3645 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3646     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3647     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3648     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3649 
3650   // 32-bit SVR4 ABI Stack Frame Layout:
3651   //              +-----------------------------------+
3652   //        +-->  |            Back chain             |
3653   //        |     +-----------------------------------+
3654   //        |     | Floating-point register save area |
3655   //        |     +-----------------------------------+
3656   //        |     |    General register save area     |
3657   //        |     +-----------------------------------+
3658   //        |     |          CR save word             |
3659   //        |     +-----------------------------------+
3660   //        |     |         VRSAVE save word          |
3661   //        |     +-----------------------------------+
3662   //        |     |         Alignment padding         |
3663   //        |     +-----------------------------------+
3664   //        |     |     Vector register save area     |
3665   //        |     +-----------------------------------+
3666   //        |     |       Local variable space        |
3667   //        |     +-----------------------------------+
3668   //        |     |        Parameter list area        |
3669   //        |     +-----------------------------------+
3670   //        |     |           LR save word            |
3671   //        |     +-----------------------------------+
3672   // SP-->  +---  |            Back chain             |
3673   //              +-----------------------------------+
3674   //
3675   // Specifications:
3676   //   System V Application Binary Interface PowerPC Processor Supplement
3677   //   AltiVec Technology Programming Interface Manual
3678 
3679   MachineFunction &MF = DAG.getMachineFunction();
3680   MachineFrameInfo &MFI = MF.getFrameInfo();
3681   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3682 
3683   EVT PtrVT = getPointerTy(MF.getDataLayout());
3684   // Potential tail calls could cause overwriting of argument stack slots.
3685   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3686                        (CallConv == CallingConv::Fast));
3687   const Align PtrAlign(4);
3688 
3689   // Assign locations to all of the incoming arguments.
3690   SmallVector<CCValAssign, 16> ArgLocs;
3691   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3692                  *DAG.getContext());
3693 
3694   // Reserve space for the linkage area on the stack.
3695   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3696   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3697   if (useSoftFloat())
3698     CCInfo.PreAnalyzeFormalArguments(Ins);
3699 
3700   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3701   CCInfo.clearWasPPCF128();
3702 
3703   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3704     CCValAssign &VA = ArgLocs[i];
3705 
3706     // Arguments stored in registers.
3707     if (VA.isRegLoc()) {
3708       const TargetRegisterClass *RC;
3709       EVT ValVT = VA.getValVT();
3710 
3711       switch (ValVT.getSimpleVT().SimpleTy) {
3712         default:
3713           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3714         case MVT::i1:
3715         case MVT::i32:
3716           RC = &PPC::GPRCRegClass;
3717           break;
3718         case MVT::f32:
3719           if (Subtarget.hasP8Vector())
3720             RC = &PPC::VSSRCRegClass;
3721           else if (Subtarget.hasSPE())
3722             RC = &PPC::GPRCRegClass;
3723           else
3724             RC = &PPC::F4RCRegClass;
3725           break;
3726         case MVT::f64:
3727           if (Subtarget.hasVSX())
3728             RC = &PPC::VSFRCRegClass;
3729           else if (Subtarget.hasSPE())
3730             // SPE passes doubles in GPR pairs.
3731             RC = &PPC::GPRCRegClass;
3732           else
3733             RC = &PPC::F8RCRegClass;
3734           break;
3735         case MVT::v16i8:
3736         case MVT::v8i16:
3737         case MVT::v4i32:
3738           RC = &PPC::VRRCRegClass;
3739           break;
3740         case MVT::v4f32:
3741           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3742           break;
3743         case MVT::v2f64:
3744         case MVT::v2i64:
3745           RC = &PPC::VRRCRegClass;
3746           break;
3747         case MVT::v4f64:
3748           RC = &PPC::QFRCRegClass;
3749           break;
3750         case MVT::v4i1:
3751           RC = &PPC::QBRCRegClass;
3752           break;
3753       }
3754 
3755       SDValue ArgValue;
3756       // Transform the arguments stored in physical registers into
3757       // virtual ones.
3758       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3759         assert(i + 1 < e && "No second half of double precision argument");
3760         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3761         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3762         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3763         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3764         if (!Subtarget.isLittleEndian())
3765           std::swap (ArgValueLo, ArgValueHi);
3766         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3767                                ArgValueHi);
3768       } else {
3769         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3770         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3771                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3772         if (ValVT == MVT::i1)
3773           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3774       }
3775 
3776       InVals.push_back(ArgValue);
3777     } else {
3778       // Argument stored in memory.
3779       assert(VA.isMemLoc());
3780 
3781       // Get the extended size of the argument type in stack
3782       unsigned ArgSize = VA.getLocVT().getStoreSize();
3783       // Get the actual size of the argument type
3784       unsigned ObjSize = VA.getValVT().getStoreSize();
3785       unsigned ArgOffset = VA.getLocMemOffset();
3786       // Stack objects in PPC32 are right justified.
3787       ArgOffset += ArgSize - ObjSize;
3788       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3789 
3790       // Create load nodes to retrieve arguments from the stack.
3791       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3792       InVals.push_back(
3793           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3794     }
3795   }
3796 
3797   // Assign locations to all of the incoming aggregate by value arguments.
3798   // Aggregates passed by value are stored in the local variable space of the
3799   // caller's stack frame, right above the parameter list area.
3800   SmallVector<CCValAssign, 16> ByValArgLocs;
3801   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3802                       ByValArgLocs, *DAG.getContext());
3803 
3804   // Reserve stack space for the allocations in CCInfo.
3805   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
3806 
3807   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3808 
3809   // Area that is at least reserved in the caller of this function.
3810   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3811   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3812 
3813   // Set the size that is at least reserved in caller of this function.  Tail
3814   // call optimized function's reserved stack space needs to be aligned so that
3815   // taking the difference between two stack areas will result in an aligned
3816   // stack.
3817   MinReservedArea =
3818       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3819   FuncInfo->setMinReservedArea(MinReservedArea);
3820 
3821   SmallVector<SDValue, 8> MemOps;
3822 
3823   // If the function takes variable number of arguments, make a frame index for
3824   // the start of the first vararg value... for expansion of llvm.va_start.
3825   if (isVarArg) {
3826     static const MCPhysReg GPArgRegs[] = {
3827       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3828       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3829     };
3830     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3831 
3832     static const MCPhysReg FPArgRegs[] = {
3833       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3834       PPC::F8
3835     };
3836     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3837 
3838     if (useSoftFloat() || hasSPE())
3839        NumFPArgRegs = 0;
3840 
3841     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3842     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3843 
3844     // Make room for NumGPArgRegs and NumFPArgRegs.
3845     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3846                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3847 
3848     FuncInfo->setVarArgsStackOffset(
3849       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3850                             CCInfo.getNextStackOffset(), true));
3851 
3852     FuncInfo->setVarArgsFrameIndex(
3853         MFI.CreateStackObject(Depth, Align(8), false));
3854     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3855 
3856     // The fixed integer arguments of a variadic function are stored to the
3857     // VarArgsFrameIndex on the stack so that they may be loaded by
3858     // dereferencing the result of va_next.
3859     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3860       // Get an existing live-in vreg, or add a new one.
3861       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3862       if (!VReg)
3863         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3864 
3865       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3866       SDValue Store =
3867           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3868       MemOps.push_back(Store);
3869       // Increment the address by four for the next argument to store
3870       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3871       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3872     }
3873 
3874     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3875     // is set.
3876     // The double arguments are stored to the VarArgsFrameIndex
3877     // on the stack.
3878     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3879       // Get an existing live-in vreg, or add a new one.
3880       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3881       if (!VReg)
3882         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3883 
3884       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3885       SDValue Store =
3886           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3887       MemOps.push_back(Store);
3888       // Increment the address by eight for the next argument to store
3889       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3890                                          PtrVT);
3891       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3892     }
3893   }
3894 
3895   if (!MemOps.empty())
3896     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3897 
3898   return Chain;
3899 }
3900 
3901 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3902 // value to MVT::i64 and then truncate to the correct register size.
3903 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3904                                              EVT ObjectVT, SelectionDAG &DAG,
3905                                              SDValue ArgVal,
3906                                              const SDLoc &dl) const {
3907   if (Flags.isSExt())
3908     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3909                          DAG.getValueType(ObjectVT));
3910   else if (Flags.isZExt())
3911     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3912                          DAG.getValueType(ObjectVT));
3913 
3914   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3915 }
3916 
3917 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3918     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3919     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3920     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3921   // TODO: add description of PPC stack frame format, or at least some docs.
3922   //
3923   bool isELFv2ABI = Subtarget.isELFv2ABI();
3924   bool isLittleEndian = Subtarget.isLittleEndian();
3925   MachineFunction &MF = DAG.getMachineFunction();
3926   MachineFrameInfo &MFI = MF.getFrameInfo();
3927   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3928 
3929   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3930          "fastcc not supported on varargs functions");
3931 
3932   EVT PtrVT = getPointerTy(MF.getDataLayout());
3933   // Potential tail calls could cause overwriting of argument stack slots.
3934   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3935                        (CallConv == CallingConv::Fast));
3936   unsigned PtrByteSize = 8;
3937   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3938 
3939   static const MCPhysReg GPR[] = {
3940     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3941     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3942   };
3943   static const MCPhysReg VR[] = {
3944     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3945     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3946   };
3947 
3948   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3949   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3950   const unsigned Num_VR_Regs  = array_lengthof(VR);
3951   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3952 
3953   // Do a first pass over the arguments to determine whether the ABI
3954   // guarantees that our caller has allocated the parameter save area
3955   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3956   // in the ELFv2 ABI, it is true if this is a vararg function or if
3957   // any parameter is located in a stack slot.
3958 
3959   bool HasParameterArea = !isELFv2ABI || isVarArg;
3960   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3961   unsigned NumBytes = LinkageSize;
3962   unsigned AvailableFPRs = Num_FPR_Regs;
3963   unsigned AvailableVRs = Num_VR_Regs;
3964   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3965     if (Ins[i].Flags.isNest())
3966       continue;
3967 
3968     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3969                                PtrByteSize, LinkageSize, ParamAreaSize,
3970                                NumBytes, AvailableFPRs, AvailableVRs,
3971                                Subtarget.hasQPX()))
3972       HasParameterArea = true;
3973   }
3974 
3975   // Add DAG nodes to load the arguments or copy them out of registers.  On
3976   // entry to a function on PPC, the arguments start after the linkage area,
3977   // although the first ones are often in registers.
3978 
3979   unsigned ArgOffset = LinkageSize;
3980   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3981   unsigned &QFPR_idx = FPR_idx;
3982   SmallVector<SDValue, 8> MemOps;
3983   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3984   unsigned CurArgIdx = 0;
3985   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3986     SDValue ArgVal;
3987     bool needsLoad = false;
3988     EVT ObjectVT = Ins[ArgNo].VT;
3989     EVT OrigVT = Ins[ArgNo].ArgVT;
3990     unsigned ObjSize = ObjectVT.getStoreSize();
3991     unsigned ArgSize = ObjSize;
3992     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3993     if (Ins[ArgNo].isOrigArg()) {
3994       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3995       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3996     }
3997     // We re-align the argument offset for each argument, except when using the
3998     // fast calling convention, when we need to make sure we do that only when
3999     // we'll actually use a stack slot.
4000     unsigned CurArgOffset;
4001     Align Alignment;
4002     auto ComputeArgOffset = [&]() {
4003       /* Respect alignment of argument on the stack.  */
4004       Alignment =
4005           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4006       ArgOffset = alignTo(ArgOffset, Alignment);
4007       CurArgOffset = ArgOffset;
4008     };
4009 
4010     if (CallConv != CallingConv::Fast) {
4011       ComputeArgOffset();
4012 
4013       /* Compute GPR index associated with argument offset.  */
4014       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4015       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4016     }
4017 
4018     // FIXME the codegen can be much improved in some cases.
4019     // We do not have to keep everything in memory.
4020     if (Flags.isByVal()) {
4021       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4022 
4023       if (CallConv == CallingConv::Fast)
4024         ComputeArgOffset();
4025 
4026       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4027       ObjSize = Flags.getByValSize();
4028       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4029       // Empty aggregate parameters do not take up registers.  Examples:
4030       //   struct { } a;
4031       //   union  { } b;
4032       //   int c[0];
4033       // etc.  However, we have to provide a place-holder in InVals, so
4034       // pretend we have an 8-byte item at the current address for that
4035       // purpose.
4036       if (!ObjSize) {
4037         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4038         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4039         InVals.push_back(FIN);
4040         continue;
4041       }
4042 
4043       // Create a stack object covering all stack doublewords occupied
4044       // by the argument.  If the argument is (fully or partially) on
4045       // the stack, or if the argument is fully in registers but the
4046       // caller has allocated the parameter save anyway, we can refer
4047       // directly to the caller's stack frame.  Otherwise, create a
4048       // local copy in our own frame.
4049       int FI;
4050       if (HasParameterArea ||
4051           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4052         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4053       else
4054         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4055       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4056 
4057       // Handle aggregates smaller than 8 bytes.
4058       if (ObjSize < PtrByteSize) {
4059         // The value of the object is its address, which differs from the
4060         // address of the enclosing doubleword on big-endian systems.
4061         SDValue Arg = FIN;
4062         if (!isLittleEndian) {
4063           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4064           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4065         }
4066         InVals.push_back(Arg);
4067 
4068         if (GPR_idx != Num_GPR_Regs) {
4069           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4070           FuncInfo->addLiveInAttr(VReg, Flags);
4071           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4072           SDValue Store;
4073 
4074           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
4075             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
4076                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
4077             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4078                                       MachinePointerInfo(&*FuncArg), ObjType);
4079           } else {
4080             // For sizes that don't fit a truncating store (3, 5, 6, 7),
4081             // store the whole register as-is to the parameter save area
4082             // slot.
4083             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4084                                  MachinePointerInfo(&*FuncArg));
4085           }
4086 
4087           MemOps.push_back(Store);
4088         }
4089         // Whether we copied from a register or not, advance the offset
4090         // into the parameter save area by a full doubleword.
4091         ArgOffset += PtrByteSize;
4092         continue;
4093       }
4094 
4095       // The value of the object is its address, which is the address of
4096       // its first stack doubleword.
4097       InVals.push_back(FIN);
4098 
4099       // Store whatever pieces of the object are in registers to memory.
4100       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4101         if (GPR_idx == Num_GPR_Regs)
4102           break;
4103 
4104         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4105         FuncInfo->addLiveInAttr(VReg, Flags);
4106         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4107         SDValue Addr = FIN;
4108         if (j) {
4109           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4110           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4111         }
4112         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4113                                      MachinePointerInfo(&*FuncArg, j));
4114         MemOps.push_back(Store);
4115         ++GPR_idx;
4116       }
4117       ArgOffset += ArgSize;
4118       continue;
4119     }
4120 
4121     switch (ObjectVT.getSimpleVT().SimpleTy) {
4122     default: llvm_unreachable("Unhandled argument type!");
4123     case MVT::i1:
4124     case MVT::i32:
4125     case MVT::i64:
4126       if (Flags.isNest()) {
4127         // The 'nest' parameter, if any, is passed in R11.
4128         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4129         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4130 
4131         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4132           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4133 
4134         break;
4135       }
4136 
4137       // These can be scalar arguments or elements of an integer array type
4138       // passed directly.  Clang may use those instead of "byval" aggregate
4139       // types to avoid forcing arguments to memory unnecessarily.
4140       if (GPR_idx != Num_GPR_Regs) {
4141         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4142         FuncInfo->addLiveInAttr(VReg, Flags);
4143         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4144 
4145         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4146           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4147           // value to MVT::i64 and then truncate to the correct register size.
4148           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4149       } else {
4150         if (CallConv == CallingConv::Fast)
4151           ComputeArgOffset();
4152 
4153         needsLoad = true;
4154         ArgSize = PtrByteSize;
4155       }
4156       if (CallConv != CallingConv::Fast || needsLoad)
4157         ArgOffset += 8;
4158       break;
4159 
4160     case MVT::f32:
4161     case MVT::f64:
4162       // These can be scalar arguments or elements of a float array type
4163       // passed directly.  The latter are used to implement ELFv2 homogenous
4164       // float aggregates.
4165       if (FPR_idx != Num_FPR_Regs) {
4166         unsigned VReg;
4167 
4168         if (ObjectVT == MVT::f32)
4169           VReg = MF.addLiveIn(FPR[FPR_idx],
4170                               Subtarget.hasP8Vector()
4171                                   ? &PPC::VSSRCRegClass
4172                                   : &PPC::F4RCRegClass);
4173         else
4174           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4175                                                 ? &PPC::VSFRCRegClass
4176                                                 : &PPC::F8RCRegClass);
4177 
4178         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4179         ++FPR_idx;
4180       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4181         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4182         // once we support fp <-> gpr moves.
4183 
4184         // This can only ever happen in the presence of f32 array types,
4185         // since otherwise we never run out of FPRs before running out
4186         // of GPRs.
4187         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4188         FuncInfo->addLiveInAttr(VReg, Flags);
4189         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4190 
4191         if (ObjectVT == MVT::f32) {
4192           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4193             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4194                                  DAG.getConstant(32, dl, MVT::i32));
4195           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4196         }
4197 
4198         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4199       } else {
4200         if (CallConv == CallingConv::Fast)
4201           ComputeArgOffset();
4202 
4203         needsLoad = true;
4204       }
4205 
4206       // When passing an array of floats, the array occupies consecutive
4207       // space in the argument area; only round up to the next doubleword
4208       // at the end of the array.  Otherwise, each float takes 8 bytes.
4209       if (CallConv != CallingConv::Fast || needsLoad) {
4210         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4211         ArgOffset += ArgSize;
4212         if (Flags.isInConsecutiveRegsLast())
4213           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4214       }
4215       break;
4216     case MVT::v4f32:
4217     case MVT::v4i32:
4218     case MVT::v8i16:
4219     case MVT::v16i8:
4220     case MVT::v2f64:
4221     case MVT::v2i64:
4222     case MVT::v1i128:
4223     case MVT::f128:
4224       if (!Subtarget.hasQPX()) {
4225         // These can be scalar arguments or elements of a vector array type
4226         // passed directly.  The latter are used to implement ELFv2 homogenous
4227         // vector aggregates.
4228         if (VR_idx != Num_VR_Regs) {
4229           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4230           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4231           ++VR_idx;
4232         } else {
4233           if (CallConv == CallingConv::Fast)
4234             ComputeArgOffset();
4235           needsLoad = true;
4236         }
4237         if (CallConv != CallingConv::Fast || needsLoad)
4238           ArgOffset += 16;
4239         break;
4240       } // not QPX
4241 
4242       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
4243              "Invalid QPX parameter type");
4244       LLVM_FALLTHROUGH;
4245 
4246     case MVT::v4f64:
4247     case MVT::v4i1:
4248       // QPX vectors are treated like their scalar floating-point subregisters
4249       // (except that they're larger).
4250       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4251       if (QFPR_idx != Num_QFPR_Regs) {
4252         const TargetRegisterClass *RC;
4253         switch (ObjectVT.getSimpleVT().SimpleTy) {
4254         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4255         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4256         default:         RC = &PPC::QBRCRegClass; break;
4257         }
4258 
4259         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4260         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4261         ++QFPR_idx;
4262       } else {
4263         if (CallConv == CallingConv::Fast)
4264           ComputeArgOffset();
4265         needsLoad = true;
4266       }
4267       if (CallConv != CallingConv::Fast || needsLoad)
4268         ArgOffset += Sz;
4269       break;
4270     }
4271 
4272     // We need to load the argument to a virtual register if we determined
4273     // above that we ran out of physical registers of the appropriate type.
4274     if (needsLoad) {
4275       if (ObjSize < ArgSize && !isLittleEndian)
4276         CurArgOffset += ArgSize - ObjSize;
4277       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4278       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4279       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4280     }
4281 
4282     InVals.push_back(ArgVal);
4283   }
4284 
4285   // Area that is at least reserved in the caller of this function.
4286   unsigned MinReservedArea;
4287   if (HasParameterArea)
4288     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4289   else
4290     MinReservedArea = LinkageSize;
4291 
4292   // Set the size that is at least reserved in caller of this function.  Tail
4293   // call optimized functions' reserved stack space needs to be aligned so that
4294   // taking the difference between two stack areas will result in an aligned
4295   // stack.
4296   MinReservedArea =
4297       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4298   FuncInfo->setMinReservedArea(MinReservedArea);
4299 
4300   // If the function takes variable number of arguments, make a frame index for
4301   // the start of the first vararg value... for expansion of llvm.va_start.
4302   if (isVarArg) {
4303     int Depth = ArgOffset;
4304 
4305     FuncInfo->setVarArgsFrameIndex(
4306       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4307     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4308 
4309     // If this function is vararg, store any remaining integer argument regs
4310     // to their spots on the stack so that they may be loaded by dereferencing
4311     // the result of va_next.
4312     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4313          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4314       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4315       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4316       SDValue Store =
4317           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4318       MemOps.push_back(Store);
4319       // Increment the address by four for the next argument to store
4320       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4321       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4322     }
4323   }
4324 
4325   if (!MemOps.empty())
4326     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4327 
4328   return Chain;
4329 }
4330 
4331 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4332     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4333     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4334     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4335   // TODO: add description of PPC stack frame format, or at least some docs.
4336   //
4337   MachineFunction &MF = DAG.getMachineFunction();
4338   MachineFrameInfo &MFI = MF.getFrameInfo();
4339   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4340 
4341   EVT PtrVT = getPointerTy(MF.getDataLayout());
4342   bool isPPC64 = PtrVT == MVT::i64;
4343   // Potential tail calls could cause overwriting of argument stack slots.
4344   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4345                        (CallConv == CallingConv::Fast));
4346   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4347   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4348   unsigned ArgOffset = LinkageSize;
4349   // Area that is at least reserved in caller of this function.
4350   unsigned MinReservedArea = ArgOffset;
4351 
4352   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4353     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4354     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4355   };
4356   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4357     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4358     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4359   };
4360   static const MCPhysReg VR[] = {
4361     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4362     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4363   };
4364 
4365   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4366   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4367   const unsigned Num_VR_Regs  = array_lengthof( VR);
4368 
4369   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4370 
4371   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4372 
4373   // In 32-bit non-varargs functions, the stack space for vectors is after the
4374   // stack space for non-vectors.  We do not use this space unless we have
4375   // too many vectors to fit in registers, something that only occurs in
4376   // constructed examples:), but we have to walk the arglist to figure
4377   // that out...for the pathological case, compute VecArgOffset as the
4378   // start of the vector parameter area.  Computing VecArgOffset is the
4379   // entire point of the following loop.
4380   unsigned VecArgOffset = ArgOffset;
4381   if (!isVarArg && !isPPC64) {
4382     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4383          ++ArgNo) {
4384       EVT ObjectVT = Ins[ArgNo].VT;
4385       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4386 
4387       if (Flags.isByVal()) {
4388         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4389         unsigned ObjSize = Flags.getByValSize();
4390         unsigned ArgSize =
4391                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4392         VecArgOffset += ArgSize;
4393         continue;
4394       }
4395 
4396       switch(ObjectVT.getSimpleVT().SimpleTy) {
4397       default: llvm_unreachable("Unhandled argument type!");
4398       case MVT::i1:
4399       case MVT::i32:
4400       case MVT::f32:
4401         VecArgOffset += 4;
4402         break;
4403       case MVT::i64:  // PPC64
4404       case MVT::f64:
4405         // FIXME: We are guaranteed to be !isPPC64 at this point.
4406         // Does MVT::i64 apply?
4407         VecArgOffset += 8;
4408         break;
4409       case MVT::v4f32:
4410       case MVT::v4i32:
4411       case MVT::v8i16:
4412       case MVT::v16i8:
4413         // Nothing to do, we're only looking at Nonvector args here.
4414         break;
4415       }
4416     }
4417   }
4418   // We've found where the vector parameter area in memory is.  Skip the
4419   // first 12 parameters; these don't use that memory.
4420   VecArgOffset = ((VecArgOffset+15)/16)*16;
4421   VecArgOffset += 12*16;
4422 
4423   // Add DAG nodes to load the arguments or copy them out of registers.  On
4424   // entry to a function on PPC, the arguments start after the linkage area,
4425   // although the first ones are often in registers.
4426 
4427   SmallVector<SDValue, 8> MemOps;
4428   unsigned nAltivecParamsAtEnd = 0;
4429   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4430   unsigned CurArgIdx = 0;
4431   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4432     SDValue ArgVal;
4433     bool needsLoad = false;
4434     EVT ObjectVT = Ins[ArgNo].VT;
4435     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4436     unsigned ArgSize = ObjSize;
4437     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4438     if (Ins[ArgNo].isOrigArg()) {
4439       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4440       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4441     }
4442     unsigned CurArgOffset = ArgOffset;
4443 
4444     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4445     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4446         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4447       if (isVarArg || isPPC64) {
4448         MinReservedArea = ((MinReservedArea+15)/16)*16;
4449         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4450                                                   Flags,
4451                                                   PtrByteSize);
4452       } else  nAltivecParamsAtEnd++;
4453     } else
4454       // Calculate min reserved area.
4455       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4456                                                 Flags,
4457                                                 PtrByteSize);
4458 
4459     // FIXME the codegen can be much improved in some cases.
4460     // We do not have to keep everything in memory.
4461     if (Flags.isByVal()) {
4462       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4463 
4464       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4465       ObjSize = Flags.getByValSize();
4466       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4467       // Objects of size 1 and 2 are right justified, everything else is
4468       // left justified.  This means the memory address is adjusted forwards.
4469       if (ObjSize==1 || ObjSize==2) {
4470         CurArgOffset = CurArgOffset + (4 - ObjSize);
4471       }
4472       // The value of the object is its address.
4473       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4474       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4475       InVals.push_back(FIN);
4476       if (ObjSize==1 || ObjSize==2) {
4477         if (GPR_idx != Num_GPR_Regs) {
4478           unsigned VReg;
4479           if (isPPC64)
4480             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4481           else
4482             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4483           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4484           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4485           SDValue Store =
4486               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4487                                 MachinePointerInfo(&*FuncArg), ObjType);
4488           MemOps.push_back(Store);
4489           ++GPR_idx;
4490         }
4491 
4492         ArgOffset += PtrByteSize;
4493 
4494         continue;
4495       }
4496       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4497         // Store whatever pieces of the object are in registers
4498         // to memory.  ArgOffset will be the address of the beginning
4499         // of the object.
4500         if (GPR_idx != Num_GPR_Regs) {
4501           unsigned VReg;
4502           if (isPPC64)
4503             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4504           else
4505             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4506           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4507           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4508           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4509           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4510                                        MachinePointerInfo(&*FuncArg, j));
4511           MemOps.push_back(Store);
4512           ++GPR_idx;
4513           ArgOffset += PtrByteSize;
4514         } else {
4515           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4516           break;
4517         }
4518       }
4519       continue;
4520     }
4521 
4522     switch (ObjectVT.getSimpleVT().SimpleTy) {
4523     default: llvm_unreachable("Unhandled argument type!");
4524     case MVT::i1:
4525     case MVT::i32:
4526       if (!isPPC64) {
4527         if (GPR_idx != Num_GPR_Regs) {
4528           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4529           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4530 
4531           if (ObjectVT == MVT::i1)
4532             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4533 
4534           ++GPR_idx;
4535         } else {
4536           needsLoad = true;
4537           ArgSize = PtrByteSize;
4538         }
4539         // All int arguments reserve stack space in the Darwin ABI.
4540         ArgOffset += PtrByteSize;
4541         break;
4542       }
4543       LLVM_FALLTHROUGH;
4544     case MVT::i64:  // PPC64
4545       if (GPR_idx != Num_GPR_Regs) {
4546         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4547         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4548 
4549         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4550           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4551           // value to MVT::i64 and then truncate to the correct register size.
4552           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4553 
4554         ++GPR_idx;
4555       } else {
4556         needsLoad = true;
4557         ArgSize = PtrByteSize;
4558       }
4559       // All int arguments reserve stack space in the Darwin ABI.
4560       ArgOffset += 8;
4561       break;
4562 
4563     case MVT::f32:
4564     case MVT::f64:
4565       // Every 4 bytes of argument space consumes one of the GPRs available for
4566       // argument passing.
4567       if (GPR_idx != Num_GPR_Regs) {
4568         ++GPR_idx;
4569         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4570           ++GPR_idx;
4571       }
4572       if (FPR_idx != Num_FPR_Regs) {
4573         unsigned VReg;
4574 
4575         if (ObjectVT == MVT::f32)
4576           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4577         else
4578           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4579 
4580         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4581         ++FPR_idx;
4582       } else {
4583         needsLoad = true;
4584       }
4585 
4586       // All FP arguments reserve stack space in the Darwin ABI.
4587       ArgOffset += isPPC64 ? 8 : ObjSize;
4588       break;
4589     case MVT::v4f32:
4590     case MVT::v4i32:
4591     case MVT::v8i16:
4592     case MVT::v16i8:
4593       // Note that vector arguments in registers don't reserve stack space,
4594       // except in varargs functions.
4595       if (VR_idx != Num_VR_Regs) {
4596         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4597         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4598         if (isVarArg) {
4599           while ((ArgOffset % 16) != 0) {
4600             ArgOffset += PtrByteSize;
4601             if (GPR_idx != Num_GPR_Regs)
4602               GPR_idx++;
4603           }
4604           ArgOffset += 16;
4605           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4606         }
4607         ++VR_idx;
4608       } else {
4609         if (!isVarArg && !isPPC64) {
4610           // Vectors go after all the nonvectors.
4611           CurArgOffset = VecArgOffset;
4612           VecArgOffset += 16;
4613         } else {
4614           // Vectors are aligned.
4615           ArgOffset = ((ArgOffset+15)/16)*16;
4616           CurArgOffset = ArgOffset;
4617           ArgOffset += 16;
4618         }
4619         needsLoad = true;
4620       }
4621       break;
4622     }
4623 
4624     // We need to load the argument to a virtual register if we determined above
4625     // that we ran out of physical registers of the appropriate type.
4626     if (needsLoad) {
4627       int FI = MFI.CreateFixedObject(ObjSize,
4628                                      CurArgOffset + (ArgSize - ObjSize),
4629                                      isImmutable);
4630       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4631       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4632     }
4633 
4634     InVals.push_back(ArgVal);
4635   }
4636 
4637   // Allow for Altivec parameters at the end, if needed.
4638   if (nAltivecParamsAtEnd) {
4639     MinReservedArea = ((MinReservedArea+15)/16)*16;
4640     MinReservedArea += 16*nAltivecParamsAtEnd;
4641   }
4642 
4643   // Area that is at least reserved in the caller of this function.
4644   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4645 
4646   // Set the size that is at least reserved in caller of this function.  Tail
4647   // call optimized functions' reserved stack space needs to be aligned so that
4648   // taking the difference between two stack areas will result in an aligned
4649   // stack.
4650   MinReservedArea =
4651       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4652   FuncInfo->setMinReservedArea(MinReservedArea);
4653 
4654   // If the function takes variable number of arguments, make a frame index for
4655   // the start of the first vararg value... for expansion of llvm.va_start.
4656   if (isVarArg) {
4657     int Depth = ArgOffset;
4658 
4659     FuncInfo->setVarArgsFrameIndex(
4660       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4661                             Depth, true));
4662     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4663 
4664     // If this function is vararg, store any remaining integer argument regs
4665     // to their spots on the stack so that they may be loaded by dereferencing
4666     // the result of va_next.
4667     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4668       unsigned VReg;
4669 
4670       if (isPPC64)
4671         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4672       else
4673         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4674 
4675       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4676       SDValue Store =
4677           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4678       MemOps.push_back(Store);
4679       // Increment the address by four for the next argument to store
4680       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4681       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4682     }
4683   }
4684 
4685   if (!MemOps.empty())
4686     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4687 
4688   return Chain;
4689 }
4690 
4691 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4692 /// adjusted to accommodate the arguments for the tailcall.
4693 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4694                                    unsigned ParamSize) {
4695 
4696   if (!isTailCall) return 0;
4697 
4698   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4699   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4700   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4701   // Remember only if the new adjustment is bigger.
4702   if (SPDiff < FI->getTailCallSPDelta())
4703     FI->setTailCallSPDelta(SPDiff);
4704 
4705   return SPDiff;
4706 }
4707 
4708 static bool isFunctionGlobalAddress(SDValue Callee);
4709 
4710 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4711                               const TargetMachine &TM) {
4712   // It does not make sense to call callsShareTOCBase() with a caller that
4713   // is PC Relative since PC Relative callers do not have a TOC.
4714 #ifndef NDEBUG
4715   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4716   assert(!STICaller->isUsingPCRelativeCalls() &&
4717          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4718 #endif
4719 
4720   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4721   // don't have enough information to determine if the caller and callee share
4722   // the same  TOC base, so we have to pessimistically assume they don't for
4723   // correctness.
4724   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4725   if (!G)
4726     return false;
4727 
4728   const GlobalValue *GV = G->getGlobal();
4729 
4730   // If the callee is preemptable, then the static linker will use a plt-stub
4731   // which saves the toc to the stack, and needs a nop after the call
4732   // instruction to convert to a toc-restore.
4733   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4734     return false;
4735 
4736   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4737   // We may need a TOC restore in the situation where the caller requires a
4738   // valid TOC but the callee is PC Relative and does not.
4739   const Function *F = dyn_cast<Function>(GV);
4740   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4741 
4742   // If we have an Alias we can try to get the function from there.
4743   if (Alias) {
4744     const GlobalObject *GlobalObj = Alias->getBaseObject();
4745     F = dyn_cast<Function>(GlobalObj);
4746   }
4747 
4748   // If we still have no valid function pointer we do not have enough
4749   // information to determine if the callee uses PC Relative calls so we must
4750   // assume that it does.
4751   if (!F)
4752     return false;
4753 
4754   // If the callee uses PC Relative we cannot guarantee that the callee won't
4755   // clobber the TOC of the caller and so we must assume that the two
4756   // functions do not share a TOC base.
4757   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4758   if (STICallee->isUsingPCRelativeCalls())
4759     return false;
4760 
4761   // The medium and large code models are expected to provide a sufficiently
4762   // large TOC to provide all data addressing needs of a module with a
4763   // single TOC.
4764   if (CodeModel::Medium == TM.getCodeModel() ||
4765       CodeModel::Large == TM.getCodeModel())
4766     return true;
4767 
4768   // Otherwise we need to ensure callee and caller are in the same section,
4769   // since the linker may allocate multiple TOCs, and we don't know which
4770   // sections will belong to the same TOC base.
4771   if (!GV->isStrongDefinitionForLinker())
4772     return false;
4773 
4774   // Any explicitly-specified sections and section prefixes must also match.
4775   // Also, if we're using -ffunction-sections, then each function is always in
4776   // a different section (the same is true for COMDAT functions).
4777   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4778       GV->getSection() != Caller->getSection())
4779     return false;
4780   if (const auto *F = dyn_cast<Function>(GV)) {
4781     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4782       return false;
4783   }
4784 
4785   return true;
4786 }
4787 
4788 static bool
4789 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4790                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4791   assert(Subtarget.is64BitELFABI());
4792 
4793   const unsigned PtrByteSize = 8;
4794   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4795 
4796   static const MCPhysReg GPR[] = {
4797     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4798     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4799   };
4800   static const MCPhysReg VR[] = {
4801     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4802     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4803   };
4804 
4805   const unsigned NumGPRs = array_lengthof(GPR);
4806   const unsigned NumFPRs = 13;
4807   const unsigned NumVRs = array_lengthof(VR);
4808   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4809 
4810   unsigned NumBytes = LinkageSize;
4811   unsigned AvailableFPRs = NumFPRs;
4812   unsigned AvailableVRs = NumVRs;
4813 
4814   for (const ISD::OutputArg& Param : Outs) {
4815     if (Param.Flags.isNest()) continue;
4816 
4817     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4818                                PtrByteSize, LinkageSize, ParamAreaSize,
4819                                NumBytes, AvailableFPRs, AvailableVRs,
4820                                Subtarget.hasQPX()))
4821       return true;
4822   }
4823   return false;
4824 }
4825 
4826 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4827   if (CB.arg_size() != CallerFn->arg_size())
4828     return false;
4829 
4830   auto CalleeArgIter = CB.arg_begin();
4831   auto CalleeArgEnd = CB.arg_end();
4832   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4833 
4834   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4835     const Value* CalleeArg = *CalleeArgIter;
4836     const Value* CallerArg = &(*CallerArgIter);
4837     if (CalleeArg == CallerArg)
4838       continue;
4839 
4840     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4841     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4842     //      }
4843     // 1st argument of callee is undef and has the same type as caller.
4844     if (CalleeArg->getType() == CallerArg->getType() &&
4845         isa<UndefValue>(CalleeArg))
4846       continue;
4847 
4848     return false;
4849   }
4850 
4851   return true;
4852 }
4853 
4854 // Returns true if TCO is possible between the callers and callees
4855 // calling conventions.
4856 static bool
4857 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4858                                     CallingConv::ID CalleeCC) {
4859   // Tail calls are possible with fastcc and ccc.
4860   auto isTailCallableCC  = [] (CallingConv::ID CC){
4861       return  CC == CallingConv::C || CC == CallingConv::Fast;
4862   };
4863   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4864     return false;
4865 
4866   // We can safely tail call both fastcc and ccc callees from a c calling
4867   // convention caller. If the caller is fastcc, we may have less stack space
4868   // than a non-fastcc caller with the same signature so disable tail-calls in
4869   // that case.
4870   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4871 }
4872 
4873 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4874     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4875     const SmallVectorImpl<ISD::OutputArg> &Outs,
4876     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4877   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4878 
4879   if (DisableSCO && !TailCallOpt) return false;
4880 
4881   // Variadic argument functions are not supported.
4882   if (isVarArg) return false;
4883 
4884   auto &Caller = DAG.getMachineFunction().getFunction();
4885   // Check that the calling conventions are compatible for tco.
4886   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4887     return false;
4888 
4889   // Caller contains any byval parameter is not supported.
4890   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4891     return false;
4892 
4893   // Callee contains any byval parameter is not supported, too.
4894   // Note: This is a quick work around, because in some cases, e.g.
4895   // caller's stack size > callee's stack size, we are still able to apply
4896   // sibling call optimization. For example, gcc is able to do SCO for caller1
4897   // in the following example, but not for caller2.
4898   //   struct test {
4899   //     long int a;
4900   //     char ary[56];
4901   //   } gTest;
4902   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4903   //     b->a = v.a;
4904   //     return 0;
4905   //   }
4906   //   void caller1(struct test a, struct test c, struct test *b) {
4907   //     callee(gTest, b); }
4908   //   void caller2(struct test *b) { callee(gTest, b); }
4909   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4910     return false;
4911 
4912   // If callee and caller use different calling conventions, we cannot pass
4913   // parameters on stack since offsets for the parameter area may be different.
4914   if (Caller.getCallingConv() != CalleeCC &&
4915       needStackSlotPassParameters(Subtarget, Outs))
4916     return false;
4917 
4918   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4919   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4920   // callee potentially have different TOC bases then we cannot tail call since
4921   // we need to restore the TOC pointer after the call.
4922   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4923   // We cannot guarantee this for indirect calls or calls to external functions.
4924   // When PC-Relative addressing is used, the concept of the TOC is no longer
4925   // applicable so this check is not required.
4926   // Check first for indirect calls.
4927   if (!Subtarget.isUsingPCRelativeCalls() &&
4928       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4929     return false;
4930 
4931   // Check if we share the TOC base.
4932   if (!Subtarget.isUsingPCRelativeCalls() &&
4933       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4934     return false;
4935 
4936   // TCO allows altering callee ABI, so we don't have to check further.
4937   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4938     return true;
4939 
4940   if (DisableSCO) return false;
4941 
4942   // If callee use the same argument list that caller is using, then we can
4943   // apply SCO on this case. If it is not, then we need to check if callee needs
4944   // stack for passing arguments.
4945   // PC Relative tail calls may not have a CallBase.
4946   // If there is no CallBase we cannot verify if we have the same argument
4947   // list so assume that we don't have the same argument list.
4948   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4949       needStackSlotPassParameters(Subtarget, Outs))
4950     return false;
4951   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4952     return false;
4953 
4954   return true;
4955 }
4956 
4957 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4958 /// for tail call optimization. Targets which want to do tail call
4959 /// optimization should implement this function.
4960 bool
4961 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4962                                                      CallingConv::ID CalleeCC,
4963                                                      bool isVarArg,
4964                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4965                                                      SelectionDAG& DAG) const {
4966   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4967     return false;
4968 
4969   // Variable argument functions are not supported.
4970   if (isVarArg)
4971     return false;
4972 
4973   MachineFunction &MF = DAG.getMachineFunction();
4974   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4975   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4976     // Functions containing by val parameters are not supported.
4977     for (unsigned i = 0; i != Ins.size(); i++) {
4978        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4979        if (Flags.isByVal()) return false;
4980     }
4981 
4982     // Non-PIC/GOT tail calls are supported.
4983     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4984       return true;
4985 
4986     // At the moment we can only do local tail calls (in same module, hidden
4987     // or protected) if we are generating PIC.
4988     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4989       return G->getGlobal()->hasHiddenVisibility()
4990           || G->getGlobal()->hasProtectedVisibility();
4991   }
4992 
4993   return false;
4994 }
4995 
4996 /// isCallCompatibleAddress - Return the immediate to use if the specified
4997 /// 32-bit value is representable in the immediate field of a BxA instruction.
4998 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4999   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5000   if (!C) return nullptr;
5001 
5002   int Addr = C->getZExtValue();
5003   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
5004       SignExtend32<26>(Addr) != Addr)
5005     return nullptr;  // Top 6 bits have to be sext of immediate.
5006 
5007   return DAG
5008       .getConstant(
5009           (int)C->getZExtValue() >> 2, SDLoc(Op),
5010           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
5011       .getNode();
5012 }
5013 
5014 namespace {
5015 
5016 struct TailCallArgumentInfo {
5017   SDValue Arg;
5018   SDValue FrameIdxOp;
5019   int FrameIdx = 0;
5020 
5021   TailCallArgumentInfo() = default;
5022 };
5023 
5024 } // end anonymous namespace
5025 
5026 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
5027 static void StoreTailCallArgumentsToStackSlot(
5028     SelectionDAG &DAG, SDValue Chain,
5029     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
5030     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
5031   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
5032     SDValue Arg = TailCallArgs[i].Arg;
5033     SDValue FIN = TailCallArgs[i].FrameIdxOp;
5034     int FI = TailCallArgs[i].FrameIdx;
5035     // Store relative to framepointer.
5036     MemOpChains.push_back(DAG.getStore(
5037         Chain, dl, Arg, FIN,
5038         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
5039   }
5040 }
5041 
5042 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
5043 /// the appropriate stack slot for the tail call optimized function call.
5044 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
5045                                              SDValue OldRetAddr, SDValue OldFP,
5046                                              int SPDiff, const SDLoc &dl) {
5047   if (SPDiff) {
5048     // Calculate the new stack slot for the return address.
5049     MachineFunction &MF = DAG.getMachineFunction();
5050     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
5051     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
5052     bool isPPC64 = Subtarget.isPPC64();
5053     int SlotSize = isPPC64 ? 8 : 4;
5054     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
5055     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
5056                                                          NewRetAddrLoc, true);
5057     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5058     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
5059     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
5060                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
5061   }
5062   return Chain;
5063 }
5064 
5065 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5066 /// the position of the argument.
5067 static void
5068 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
5069                          SDValue Arg, int SPDiff, unsigned ArgOffset,
5070                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
5071   int Offset = ArgOffset + SPDiff;
5072   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5073   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5074   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5075   SDValue FIN = DAG.getFrameIndex(FI, VT);
5076   TailCallArgumentInfo Info;
5077   Info.Arg = Arg;
5078   Info.FrameIdxOp = FIN;
5079   Info.FrameIdx = FI;
5080   TailCallArguments.push_back(Info);
5081 }
5082 
5083 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5084 /// stack slot. Returns the chain as result and the loaded frame pointers in
5085 /// LROpOut/FPOpout. Used when tail calling.
5086 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5087     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5088     SDValue &FPOpOut, const SDLoc &dl) const {
5089   if (SPDiff) {
5090     // Load the LR and FP stack slot for later adjusting.
5091     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5092     LROpOut = getReturnAddrFrameIndex(DAG);
5093     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5094     Chain = SDValue(LROpOut.getNode(), 1);
5095   }
5096   return Chain;
5097 }
5098 
5099 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5100 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5101 /// specified by the specific parameter attribute. The copy will be passed as
5102 /// a byval function parameter.
5103 /// Sometimes what we are copying is the end of a larger object, the part that
5104 /// does not fit in registers.
5105 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5106                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5107                                          SelectionDAG &DAG, const SDLoc &dl) {
5108   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5109   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5110                        Flags.getNonZeroByValAlign(), false, false, false,
5111                        MachinePointerInfo(), MachinePointerInfo());
5112 }
5113 
5114 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5115 /// tail calls.
5116 static void LowerMemOpCallTo(
5117     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5118     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5119     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5120     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5121   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5122   if (!isTailCall) {
5123     if (isVector) {
5124       SDValue StackPtr;
5125       if (isPPC64)
5126         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5127       else
5128         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5129       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5130                            DAG.getConstant(ArgOffset, dl, PtrVT));
5131     }
5132     MemOpChains.push_back(
5133         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5134     // Calculate and remember argument location.
5135   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5136                                   TailCallArguments);
5137 }
5138 
5139 static void
5140 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5141                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5142                 SDValue FPOp,
5143                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5144   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5145   // might overwrite each other in case of tail call optimization.
5146   SmallVector<SDValue, 8> MemOpChains2;
5147   // Do not flag preceding copytoreg stuff together with the following stuff.
5148   InFlag = SDValue();
5149   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5150                                     MemOpChains2, dl);
5151   if (!MemOpChains2.empty())
5152     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5153 
5154   // Store the return address to the appropriate stack slot.
5155   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5156 
5157   // Emit callseq_end just before tailcall node.
5158   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5159                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5160   InFlag = Chain.getValue(1);
5161 }
5162 
5163 // Is this global address that of a function that can be called by name? (as
5164 // opposed to something that must hold a descriptor for an indirect call).
5165 static bool isFunctionGlobalAddress(SDValue Callee) {
5166   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5167     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5168         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5169       return false;
5170 
5171     return G->getGlobal()->getValueType()->isFunctionTy();
5172   }
5173 
5174   return false;
5175 }
5176 
5177 SDValue PPCTargetLowering::LowerCallResult(
5178     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5179     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5180     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5181   SmallVector<CCValAssign, 16> RVLocs;
5182   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5183                     *DAG.getContext());
5184 
5185   CCRetInfo.AnalyzeCallResult(
5186       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5187                ? RetCC_PPC_Cold
5188                : RetCC_PPC);
5189 
5190   // Copy all of the result registers out of their specified physreg.
5191   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5192     CCValAssign &VA = RVLocs[i];
5193     assert(VA.isRegLoc() && "Can only return in registers!");
5194 
5195     SDValue Val;
5196 
5197     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5198       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5199                                       InFlag);
5200       Chain = Lo.getValue(1);
5201       InFlag = Lo.getValue(2);
5202       VA = RVLocs[++i]; // skip ahead to next loc
5203       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5204                                       InFlag);
5205       Chain = Hi.getValue(1);
5206       InFlag = Hi.getValue(2);
5207       if (!Subtarget.isLittleEndian())
5208         std::swap (Lo, Hi);
5209       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5210     } else {
5211       Val = DAG.getCopyFromReg(Chain, dl,
5212                                VA.getLocReg(), VA.getLocVT(), InFlag);
5213       Chain = Val.getValue(1);
5214       InFlag = Val.getValue(2);
5215     }
5216 
5217     switch (VA.getLocInfo()) {
5218     default: llvm_unreachable("Unknown loc info!");
5219     case CCValAssign::Full: break;
5220     case CCValAssign::AExt:
5221       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5222       break;
5223     case CCValAssign::ZExt:
5224       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5225                         DAG.getValueType(VA.getValVT()));
5226       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5227       break;
5228     case CCValAssign::SExt:
5229       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5230                         DAG.getValueType(VA.getValVT()));
5231       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5232       break;
5233     }
5234 
5235     InVals.push_back(Val);
5236   }
5237 
5238   return Chain;
5239 }
5240 
5241 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5242                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5243   // PatchPoint calls are not indirect.
5244   if (isPatchPoint)
5245     return false;
5246 
5247   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5248     return false;
5249 
5250   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5251   // becuase the immediate function pointer points to a descriptor instead of
5252   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5253   // pointer immediate points to the global entry point, while the BLA would
5254   // need to jump to the local entry point (see rL211174).
5255   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5256       isBLACompatibleAddress(Callee, DAG))
5257     return false;
5258 
5259   return true;
5260 }
5261 
5262 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5263 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5264   return Subtarget.isAIXABI() ||
5265          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5266 }
5267 
5268 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5269                               const Function &Caller,
5270                               const SDValue &Callee,
5271                               const PPCSubtarget &Subtarget,
5272                               const TargetMachine &TM) {
5273   if (CFlags.IsTailCall)
5274     return PPCISD::TC_RETURN;
5275 
5276   // This is a call through a function pointer.
5277   if (CFlags.IsIndirect) {
5278     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5279     // indirect calls. The save of the caller's TOC pointer to the stack will be
5280     // inserted into the DAG as part of call lowering. The restore of the TOC
5281     // pointer is modeled by using a pseudo instruction for the call opcode that
5282     // represents the 2 instruction sequence of an indirect branch and link,
5283     // immediately followed by a load of the TOC pointer from the the stack save
5284     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5285     // as it is not saved or used.
5286     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5287                                                : PPCISD::BCTRL;
5288   }
5289 
5290   if (Subtarget.isUsingPCRelativeCalls()) {
5291     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5292     return PPCISD::CALL_NOTOC;
5293   }
5294 
5295   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5296   // immediately following the call instruction if the caller and callee may
5297   // have different TOC bases. At link time if the linker determines the calls
5298   // may not share a TOC base, the call is redirected to a trampoline inserted
5299   // by the linker. The trampoline will (among other things) save the callers
5300   // TOC pointer at an ABI designated offset in the linkage area and the linker
5301   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5302   // into gpr2.
5303   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5304     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5305                                                   : PPCISD::CALL_NOP;
5306 
5307   return PPCISD::CALL;
5308 }
5309 
5310 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5311                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5312   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5313     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5314       return SDValue(Dest, 0);
5315 
5316   // Returns true if the callee is local, and false otherwise.
5317   auto isLocalCallee = [&]() {
5318     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5319     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5320     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5321 
5322     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5323            !dyn_cast_or_null<GlobalIFunc>(GV);
5324   };
5325 
5326   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5327   // a static relocation model causes some versions of GNU LD (2.17.50, at
5328   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5329   // built with secure-PLT.
5330   bool UsePlt =
5331       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5332       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5333 
5334   // On AIX, direct function calls reference the symbol for the function's
5335   // entry point, which is named by prepending a "." before the function's
5336   // C-linkage name.
5337   const auto getAIXFuncEntryPointSymbolSDNode =
5338       [&](StringRef FuncName, bool IsDeclaration,
5339           const XCOFF::StorageClass &SC) {
5340         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5341 
5342         MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5343             Context.getOrCreateSymbol(Twine(".") + Twine(FuncName)));
5344 
5345         if (IsDeclaration && !S->hasRepresentedCsectSet()) {
5346           // On AIX, an undefined symbol needs to be associated with a
5347           // MCSectionXCOFF to get the correct storage mapping class.
5348           // In this case, XCOFF::XMC_PR.
5349           MCSectionXCOFF *Sec = Context.getXCOFFSection(
5350               S->getSymbolTableName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC,
5351               SectionKind::getMetadata());
5352           S->setRepresentedCsect(Sec);
5353         }
5354 
5355         MVT PtrVT =
5356             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5357         return DAG.getMCSymbol(S, PtrVT);
5358       };
5359 
5360   if (isFunctionGlobalAddress(Callee)) {
5361     const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5362     const GlobalValue *GV = G->getGlobal();
5363 
5364     if (!Subtarget.isAIXABI())
5365       return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5366                                         UsePlt ? PPCII::MO_PLT : 0);
5367 
5368     assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5369     const GlobalObject *GO = cast<GlobalObject>(GV);
5370     const XCOFF::StorageClass SC =
5371         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5372     return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(),
5373                                             SC);
5374   }
5375 
5376   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5377     const char *SymName = S->getSymbol();
5378     if (!Subtarget.isAIXABI())
5379       return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5380                                          UsePlt ? PPCII::MO_PLT : 0);
5381 
5382     // If there exists a user-declared function whose name is the same as the
5383     // ExternalSymbol's, then we pick up the user-declared version.
5384     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5385     if (const Function *F =
5386             dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) {
5387       const XCOFF::StorageClass SC =
5388           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F);
5389       return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(),
5390                                               SC);
5391     }
5392 
5393     return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT);
5394   }
5395 
5396   // No transformation needed.
5397   assert(Callee.getNode() && "What no callee?");
5398   return Callee;
5399 }
5400 
5401 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5402   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5403          "Expected a CALLSEQ_STARTSDNode.");
5404 
5405   // The last operand is the chain, except when the node has glue. If the node
5406   // has glue, then the last operand is the glue, and the chain is the second
5407   // last operand.
5408   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5409   if (LastValue.getValueType() != MVT::Glue)
5410     return LastValue;
5411 
5412   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5413 }
5414 
5415 // Creates the node that moves a functions address into the count register
5416 // to prepare for an indirect call instruction.
5417 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5418                                 SDValue &Glue, SDValue &Chain,
5419                                 const SDLoc &dl) {
5420   SDValue MTCTROps[] = {Chain, Callee, Glue};
5421   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5422   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5423                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5424   // The glue is the second value produced.
5425   Glue = Chain.getValue(1);
5426 }
5427 
5428 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5429                                           SDValue &Glue, SDValue &Chain,
5430                                           SDValue CallSeqStart,
5431                                           const CallBase *CB, const SDLoc &dl,
5432                                           bool hasNest,
5433                                           const PPCSubtarget &Subtarget) {
5434   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5435   // entry point, but to the function descriptor (the function entry point
5436   // address is part of the function descriptor though).
5437   // The function descriptor is a three doubleword structure with the
5438   // following fields: function entry point, TOC base address and
5439   // environment pointer.
5440   // Thus for a call through a function pointer, the following actions need
5441   // to be performed:
5442   //   1. Save the TOC of the caller in the TOC save area of its stack
5443   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5444   //   2. Load the address of the function entry point from the function
5445   //      descriptor.
5446   //   3. Load the TOC of the callee from the function descriptor into r2.
5447   //   4. Load the environment pointer from the function descriptor into
5448   //      r11.
5449   //   5. Branch to the function entry point address.
5450   //   6. On return of the callee, the TOC of the caller needs to be
5451   //      restored (this is done in FinishCall()).
5452   //
5453   // The loads are scheduled at the beginning of the call sequence, and the
5454   // register copies are flagged together to ensure that no other
5455   // operations can be scheduled in between. E.g. without flagging the
5456   // copies together, a TOC access in the caller could be scheduled between
5457   // the assignment of the callee TOC and the branch to the callee, which leads
5458   // to incorrect code.
5459 
5460   // Start by loading the function address from the descriptor.
5461   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5462   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5463                       ? (MachineMemOperand::MODereferenceable |
5464                          MachineMemOperand::MOInvariant)
5465                       : MachineMemOperand::MONone;
5466 
5467   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5468 
5469   // Registers used in building the DAG.
5470   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5471   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5472 
5473   // Offsets of descriptor members.
5474   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5475   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5476 
5477   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5478   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5479 
5480   // One load for the functions entry point address.
5481   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5482                                     Alignment, MMOFlags);
5483 
5484   // One for loading the TOC anchor for the module that contains the called
5485   // function.
5486   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5487   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5488   SDValue TOCPtr =
5489       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5490                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5491 
5492   // One for loading the environment pointer.
5493   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5494   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5495   SDValue LoadEnvPtr =
5496       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5497                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5498 
5499 
5500   // Then copy the newly loaded TOC anchor to the TOC pointer.
5501   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5502   Chain = TOCVal.getValue(0);
5503   Glue = TOCVal.getValue(1);
5504 
5505   // If the function call has an explicit 'nest' parameter, it takes the
5506   // place of the environment pointer.
5507   assert((!hasNest || !Subtarget.isAIXABI()) &&
5508          "Nest parameter is not supported on AIX.");
5509   if (!hasNest) {
5510     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5511     Chain = EnvVal.getValue(0);
5512     Glue = EnvVal.getValue(1);
5513   }
5514 
5515   // The rest of the indirect call sequence is the same as the non-descriptor
5516   // DAG.
5517   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5518 }
5519 
5520 static void
5521 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5522                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5523                   SelectionDAG &DAG,
5524                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5525                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5526                   const PPCSubtarget &Subtarget) {
5527   const bool IsPPC64 = Subtarget.isPPC64();
5528   // MVT for a general purpose register.
5529   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5530 
5531   // First operand is always the chain.
5532   Ops.push_back(Chain);
5533 
5534   // If it's a direct call pass the callee as the second operand.
5535   if (!CFlags.IsIndirect)
5536     Ops.push_back(Callee);
5537   else {
5538     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5539 
5540     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5541     // on the stack (this would have been done in `LowerCall_64SVR4` or
5542     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5543     // represents both the indirect branch and a load that restores the TOC
5544     // pointer from the linkage area. The operand for the TOC restore is an add
5545     // of the TOC save offset to the stack pointer. This must be the second
5546     // operand: after the chain input but before any other variadic arguments.
5547     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5548     // saved or used.
5549     if (isTOCSaveRestoreRequired(Subtarget)) {
5550       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5551 
5552       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5553       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5554       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5555       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5556       Ops.push_back(AddTOC);
5557     }
5558 
5559     // Add the register used for the environment pointer.
5560     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5561       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5562                                     RegVT));
5563 
5564 
5565     // Add CTR register as callee so a bctr can be emitted later.
5566     if (CFlags.IsTailCall)
5567       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5568   }
5569 
5570   // If this is a tail call add stack pointer delta.
5571   if (CFlags.IsTailCall)
5572     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5573 
5574   // Add argument registers to the end of the list so that they are known live
5575   // into the call.
5576   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5577     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5578                                   RegsToPass[i].second.getValueType()));
5579 
5580   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5581   // no way to mark dependencies as implicit here.
5582   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5583   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5584        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5585     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5586 
5587   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5588   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5589     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5590 
5591   // Add a register mask operand representing the call-preserved registers.
5592   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5593   const uint32_t *Mask =
5594       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5595   assert(Mask && "Missing call preserved mask for calling convention");
5596   Ops.push_back(DAG.getRegisterMask(Mask));
5597 
5598   // If the glue is valid, it is the last operand.
5599   if (Glue.getNode())
5600     Ops.push_back(Glue);
5601 }
5602 
5603 SDValue PPCTargetLowering::FinishCall(
5604     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5605     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5606     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5607     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5608     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5609 
5610   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5611       Subtarget.isAIXABI())
5612     setUsesTOCBasePtr(DAG);
5613 
5614   unsigned CallOpc =
5615       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5616                     Subtarget, DAG.getTarget());
5617 
5618   if (!CFlags.IsIndirect)
5619     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5620   else if (Subtarget.usesFunctionDescriptors())
5621     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5622                                   dl, CFlags.HasNest, Subtarget);
5623   else
5624     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5625 
5626   // Build the operand list for the call instruction.
5627   SmallVector<SDValue, 8> Ops;
5628   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5629                     SPDiff, Subtarget);
5630 
5631   // Emit tail call.
5632   if (CFlags.IsTailCall) {
5633     // Indirect tail call when using PC Relative calls do not have the same
5634     // constraints.
5635     assert(((Callee.getOpcode() == ISD::Register &&
5636              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5637             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5638             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5639             isa<ConstantSDNode>(Callee) ||
5640             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5641            "Expecting a global address, external symbol, absolute value, "
5642            "register or an indirect tail call when PC Relative calls are "
5643            "used.");
5644     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5645     assert(CallOpc == PPCISD::TC_RETURN &&
5646            "Unexpected call opcode for a tail call.");
5647     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5648     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5649   }
5650 
5651   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5652   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5653   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5654   Glue = Chain.getValue(1);
5655 
5656   // When performing tail call optimization the callee pops its arguments off
5657   // the stack. Account for this here so these bytes can be pushed back on in
5658   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5659   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5660                          getTargetMachine().Options.GuaranteedTailCallOpt)
5661                             ? NumBytes
5662                             : 0;
5663 
5664   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5665                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5666                              Glue, dl);
5667   Glue = Chain.getValue(1);
5668 
5669   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5670                          DAG, InVals);
5671 }
5672 
5673 SDValue
5674 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5675                              SmallVectorImpl<SDValue> &InVals) const {
5676   SelectionDAG &DAG                     = CLI.DAG;
5677   SDLoc &dl                             = CLI.DL;
5678   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5679   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5680   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5681   SDValue Chain                         = CLI.Chain;
5682   SDValue Callee                        = CLI.Callee;
5683   bool &isTailCall                      = CLI.IsTailCall;
5684   CallingConv::ID CallConv              = CLI.CallConv;
5685   bool isVarArg                         = CLI.IsVarArg;
5686   bool isPatchPoint                     = CLI.IsPatchPoint;
5687   const CallBase *CB                    = CLI.CB;
5688 
5689   if (isTailCall) {
5690     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5691       isTailCall = false;
5692     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5693       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5694           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5695     else
5696       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5697                                                      Ins, DAG);
5698     if (isTailCall) {
5699       ++NumTailCalls;
5700       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5701         ++NumSiblingCalls;
5702 
5703       // PC Relative calls no longer guarantee that the callee is a Global
5704       // Address Node. The callee could be an indirect tail call in which
5705       // case the SDValue for the callee could be a load (to load the address
5706       // of a function pointer) or it may be a register copy (to move the
5707       // address of the callee from a function parameter into a virtual
5708       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5709       assert((Subtarget.isUsingPCRelativeCalls() ||
5710               isa<GlobalAddressSDNode>(Callee)) &&
5711              "Callee should be an llvm::Function object.");
5712 
5713       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5714                         << "\nTCO callee: ");
5715       LLVM_DEBUG(Callee.dump());
5716     }
5717   }
5718 
5719   if (!isTailCall && CB && CB->isMustTailCall())
5720     report_fatal_error("failed to perform tail call elimination on a call "
5721                        "site marked musttail");
5722 
5723   // When long calls (i.e. indirect calls) are always used, calls are always
5724   // made via function pointer. If we have a function name, first translate it
5725   // into a pointer.
5726   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5727       !isTailCall)
5728     Callee = LowerGlobalAddress(Callee, DAG);
5729 
5730   CallFlags CFlags(
5731       CallConv, isTailCall, isVarArg, isPatchPoint,
5732       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5733       // hasNest
5734       Subtarget.is64BitELFABI() &&
5735           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5736       CLI.NoMerge);
5737 
5738   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5739     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5740                             InVals, CB);
5741 
5742   if (Subtarget.isSVR4ABI())
5743     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5744                             InVals, CB);
5745 
5746   if (Subtarget.isAIXABI())
5747     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5748                          InVals, CB);
5749 
5750   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5751                           InVals, CB);
5752 }
5753 
5754 SDValue PPCTargetLowering::LowerCall_32SVR4(
5755     SDValue Chain, SDValue Callee, CallFlags CFlags,
5756     const SmallVectorImpl<ISD::OutputArg> &Outs,
5757     const SmallVectorImpl<SDValue> &OutVals,
5758     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5759     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5760     const CallBase *CB) const {
5761   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5762   // of the 32-bit SVR4 ABI stack frame layout.
5763 
5764   const CallingConv::ID CallConv = CFlags.CallConv;
5765   const bool IsVarArg = CFlags.IsVarArg;
5766   const bool IsTailCall = CFlags.IsTailCall;
5767 
5768   assert((CallConv == CallingConv::C ||
5769           CallConv == CallingConv::Cold ||
5770           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5771 
5772   const Align PtrAlign(4);
5773 
5774   MachineFunction &MF = DAG.getMachineFunction();
5775 
5776   // Mark this function as potentially containing a function that contains a
5777   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5778   // and restoring the callers stack pointer in this functions epilog. This is
5779   // done because by tail calling the called function might overwrite the value
5780   // in this function's (MF) stack pointer stack slot 0(SP).
5781   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5782       CallConv == CallingConv::Fast)
5783     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5784 
5785   // Count how many bytes are to be pushed on the stack, including the linkage
5786   // area, parameter list area and the part of the local variable space which
5787   // contains copies of aggregates which are passed by value.
5788 
5789   // Assign locations to all of the outgoing arguments.
5790   SmallVector<CCValAssign, 16> ArgLocs;
5791   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5792 
5793   // Reserve space for the linkage area on the stack.
5794   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5795                        PtrAlign);
5796   if (useSoftFloat())
5797     CCInfo.PreAnalyzeCallOperands(Outs);
5798 
5799   if (IsVarArg) {
5800     // Handle fixed and variable vector arguments differently.
5801     // Fixed vector arguments go into registers as long as registers are
5802     // available. Variable vector arguments always go into memory.
5803     unsigned NumArgs = Outs.size();
5804 
5805     for (unsigned i = 0; i != NumArgs; ++i) {
5806       MVT ArgVT = Outs[i].VT;
5807       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5808       bool Result;
5809 
5810       if (Outs[i].IsFixed) {
5811         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5812                                CCInfo);
5813       } else {
5814         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5815                                       ArgFlags, CCInfo);
5816       }
5817 
5818       if (Result) {
5819 #ifndef NDEBUG
5820         errs() << "Call operand #" << i << " has unhandled type "
5821              << EVT(ArgVT).getEVTString() << "\n";
5822 #endif
5823         llvm_unreachable(nullptr);
5824       }
5825     }
5826   } else {
5827     // All arguments are treated the same.
5828     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5829   }
5830   CCInfo.clearWasPPCF128();
5831 
5832   // Assign locations to all of the outgoing aggregate by value arguments.
5833   SmallVector<CCValAssign, 16> ByValArgLocs;
5834   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5835 
5836   // Reserve stack space for the allocations in CCInfo.
5837   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5838 
5839   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5840 
5841   // Size of the linkage area, parameter list area and the part of the local
5842   // space variable where copies of aggregates which are passed by value are
5843   // stored.
5844   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5845 
5846   // Calculate by how many bytes the stack has to be adjusted in case of tail
5847   // call optimization.
5848   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5849 
5850   // Adjust the stack pointer for the new arguments...
5851   // These operations are automatically eliminated by the prolog/epilog pass
5852   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5853   SDValue CallSeqStart = Chain;
5854 
5855   // Load the return address and frame pointer so it can be moved somewhere else
5856   // later.
5857   SDValue LROp, FPOp;
5858   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5859 
5860   // Set up a copy of the stack pointer for use loading and storing any
5861   // arguments that may not fit in the registers available for argument
5862   // passing.
5863   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5864 
5865   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5866   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5867   SmallVector<SDValue, 8> MemOpChains;
5868 
5869   bool seenFloatArg = false;
5870   // Walk the register/memloc assignments, inserting copies/loads.
5871   // i - Tracks the index into the list of registers allocated for the call
5872   // RealArgIdx - Tracks the index into the list of actual function arguments
5873   // j - Tracks the index into the list of byval arguments
5874   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5875        i != e;
5876        ++i, ++RealArgIdx) {
5877     CCValAssign &VA = ArgLocs[i];
5878     SDValue Arg = OutVals[RealArgIdx];
5879     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5880 
5881     if (Flags.isByVal()) {
5882       // Argument is an aggregate which is passed by value, thus we need to
5883       // create a copy of it in the local variable space of the current stack
5884       // frame (which is the stack frame of the caller) and pass the address of
5885       // this copy to the callee.
5886       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5887       CCValAssign &ByValVA = ByValArgLocs[j++];
5888       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5889 
5890       // Memory reserved in the local variable space of the callers stack frame.
5891       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5892 
5893       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5894       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5895                            StackPtr, PtrOff);
5896 
5897       // Create a copy of the argument in the local area of the current
5898       // stack frame.
5899       SDValue MemcpyCall =
5900         CreateCopyOfByValArgument(Arg, PtrOff,
5901                                   CallSeqStart.getNode()->getOperand(0),
5902                                   Flags, DAG, dl);
5903 
5904       // This must go outside the CALLSEQ_START..END.
5905       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5906                                                      SDLoc(MemcpyCall));
5907       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5908                              NewCallSeqStart.getNode());
5909       Chain = CallSeqStart = NewCallSeqStart;
5910 
5911       // Pass the address of the aggregate copy on the stack either in a
5912       // physical register or in the parameter list area of the current stack
5913       // frame to the callee.
5914       Arg = PtrOff;
5915     }
5916 
5917     // When useCRBits() is true, there can be i1 arguments.
5918     // It is because getRegisterType(MVT::i1) => MVT::i1,
5919     // and for other integer types getRegisterType() => MVT::i32.
5920     // Extend i1 and ensure callee will get i32.
5921     if (Arg.getValueType() == MVT::i1)
5922       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5923                         dl, MVT::i32, Arg);
5924 
5925     if (VA.isRegLoc()) {
5926       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5927       // Put argument in a physical register.
5928       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5929         bool IsLE = Subtarget.isLittleEndian();
5930         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5931                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5932         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5933         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5934                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5935         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5936                              SVal.getValue(0)));
5937       } else
5938         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5939     } else {
5940       // Put argument in the parameter list area of the current stack frame.
5941       assert(VA.isMemLoc());
5942       unsigned LocMemOffset = VA.getLocMemOffset();
5943 
5944       if (!IsTailCall) {
5945         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5946         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5947                              StackPtr, PtrOff);
5948 
5949         MemOpChains.push_back(
5950             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5951       } else {
5952         // Calculate and remember argument location.
5953         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5954                                  TailCallArguments);
5955       }
5956     }
5957   }
5958 
5959   if (!MemOpChains.empty())
5960     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5961 
5962   // Build a sequence of copy-to-reg nodes chained together with token chain
5963   // and flag operands which copy the outgoing args into the appropriate regs.
5964   SDValue InFlag;
5965   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5966     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5967                              RegsToPass[i].second, InFlag);
5968     InFlag = Chain.getValue(1);
5969   }
5970 
5971   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5972   // registers.
5973   if (IsVarArg) {
5974     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5975     SDValue Ops[] = { Chain, InFlag };
5976 
5977     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5978                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5979 
5980     InFlag = Chain.getValue(1);
5981   }
5982 
5983   if (IsTailCall)
5984     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5985                     TailCallArguments);
5986 
5987   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5988                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5989 }
5990 
5991 // Copy an argument into memory, being careful to do this outside the
5992 // call sequence for the call to which the argument belongs.
5993 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5994     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5995     SelectionDAG &DAG, const SDLoc &dl) const {
5996   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5997                         CallSeqStart.getNode()->getOperand(0),
5998                         Flags, DAG, dl);
5999   // The MEMCPY must go outside the CALLSEQ_START..END.
6000   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
6001   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
6002                                                  SDLoc(MemcpyCall));
6003   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
6004                          NewCallSeqStart.getNode());
6005   return NewCallSeqStart;
6006 }
6007 
6008 SDValue PPCTargetLowering::LowerCall_64SVR4(
6009     SDValue Chain, SDValue Callee, CallFlags CFlags,
6010     const SmallVectorImpl<ISD::OutputArg> &Outs,
6011     const SmallVectorImpl<SDValue> &OutVals,
6012     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6013     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6014     const CallBase *CB) const {
6015   bool isELFv2ABI = Subtarget.isELFv2ABI();
6016   bool isLittleEndian = Subtarget.isLittleEndian();
6017   unsigned NumOps = Outs.size();
6018   bool IsSibCall = false;
6019   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
6020 
6021   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6022   unsigned PtrByteSize = 8;
6023 
6024   MachineFunction &MF = DAG.getMachineFunction();
6025 
6026   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
6027     IsSibCall = true;
6028 
6029   // Mark this function as potentially containing a function that contains a
6030   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6031   // and restoring the callers stack pointer in this functions epilog. This is
6032   // done because by tail calling the called function might overwrite the value
6033   // in this function's (MF) stack pointer stack slot 0(SP).
6034   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6035     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6036 
6037   assert(!(IsFastCall && CFlags.IsVarArg) &&
6038          "fastcc not supported on varargs functions");
6039 
6040   // Count how many bytes are to be pushed on the stack, including the linkage
6041   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
6042   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
6043   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
6044   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6045   unsigned NumBytes = LinkageSize;
6046   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6047   unsigned &QFPR_idx = FPR_idx;
6048 
6049   static const MCPhysReg GPR[] = {
6050     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6051     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6052   };
6053   static const MCPhysReg VR[] = {
6054     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6055     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6056   };
6057 
6058   const unsigned NumGPRs = array_lengthof(GPR);
6059   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
6060   const unsigned NumVRs  = array_lengthof(VR);
6061   const unsigned NumQFPRs = NumFPRs;
6062 
6063   // On ELFv2, we can avoid allocating the parameter area if all the arguments
6064   // can be passed to the callee in registers.
6065   // For the fast calling convention, there is another check below.
6066   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6067   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6068   if (!HasParameterArea) {
6069     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6070     unsigned AvailableFPRs = NumFPRs;
6071     unsigned AvailableVRs = NumVRs;
6072     unsigned NumBytesTmp = NumBytes;
6073     for (unsigned i = 0; i != NumOps; ++i) {
6074       if (Outs[i].Flags.isNest()) continue;
6075       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6076                                 PtrByteSize, LinkageSize, ParamAreaSize,
6077                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
6078                                 Subtarget.hasQPX()))
6079         HasParameterArea = true;
6080     }
6081   }
6082 
6083   // When using the fast calling convention, we don't provide backing for
6084   // arguments that will be in registers.
6085   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6086 
6087   // Avoid allocating parameter area for fastcc functions if all the arguments
6088   // can be passed in the registers.
6089   if (IsFastCall)
6090     HasParameterArea = false;
6091 
6092   // Add up all the space actually used.
6093   for (unsigned i = 0; i != NumOps; ++i) {
6094     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6095     EVT ArgVT = Outs[i].VT;
6096     EVT OrigVT = Outs[i].ArgVT;
6097 
6098     if (Flags.isNest())
6099       continue;
6100 
6101     if (IsFastCall) {
6102       if (Flags.isByVal()) {
6103         NumGPRsUsed += (Flags.getByValSize()+7)/8;
6104         if (NumGPRsUsed > NumGPRs)
6105           HasParameterArea = true;
6106       } else {
6107         switch (ArgVT.getSimpleVT().SimpleTy) {
6108         default: llvm_unreachable("Unexpected ValueType for argument!");
6109         case MVT::i1:
6110         case MVT::i32:
6111         case MVT::i64:
6112           if (++NumGPRsUsed <= NumGPRs)
6113             continue;
6114           break;
6115         case MVT::v4i32:
6116         case MVT::v8i16:
6117         case MVT::v16i8:
6118         case MVT::v2f64:
6119         case MVT::v2i64:
6120         case MVT::v1i128:
6121         case MVT::f128:
6122           if (++NumVRsUsed <= NumVRs)
6123             continue;
6124           break;
6125         case MVT::v4f32:
6126           // When using QPX, this is handled like a FP register, otherwise, it
6127           // is an Altivec register.
6128           if (Subtarget.hasQPX()) {
6129             if (++NumFPRsUsed <= NumFPRs)
6130               continue;
6131           } else {
6132             if (++NumVRsUsed <= NumVRs)
6133               continue;
6134           }
6135           break;
6136         case MVT::f32:
6137         case MVT::f64:
6138         case MVT::v4f64: // QPX
6139         case MVT::v4i1:  // QPX
6140           if (++NumFPRsUsed <= NumFPRs)
6141             continue;
6142           break;
6143         }
6144         HasParameterArea = true;
6145       }
6146     }
6147 
6148     /* Respect alignment of argument on the stack.  */
6149     auto Alignement =
6150         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6151     NumBytes = alignTo(NumBytes, Alignement);
6152 
6153     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6154     if (Flags.isInConsecutiveRegsLast())
6155       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6156   }
6157 
6158   unsigned NumBytesActuallyUsed = NumBytes;
6159 
6160   // In the old ELFv1 ABI,
6161   // the prolog code of the callee may store up to 8 GPR argument registers to
6162   // the stack, allowing va_start to index over them in memory if its varargs.
6163   // Because we cannot tell if this is needed on the caller side, we have to
6164   // conservatively assume that it is needed.  As such, make sure we have at
6165   // least enough stack space for the caller to store the 8 GPRs.
6166   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6167   // really requires memory operands, e.g. a vararg function.
6168   if (HasParameterArea)
6169     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6170   else
6171     NumBytes = LinkageSize;
6172 
6173   // Tail call needs the stack to be aligned.
6174   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6175     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6176 
6177   int SPDiff = 0;
6178 
6179   // Calculate by how many bytes the stack has to be adjusted in case of tail
6180   // call optimization.
6181   if (!IsSibCall)
6182     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6183 
6184   // To protect arguments on the stack from being clobbered in a tail call,
6185   // force all the loads to happen before doing any other lowering.
6186   if (CFlags.IsTailCall)
6187     Chain = DAG.getStackArgumentTokenFactor(Chain);
6188 
6189   // Adjust the stack pointer for the new arguments...
6190   // These operations are automatically eliminated by the prolog/epilog pass
6191   if (!IsSibCall)
6192     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6193   SDValue CallSeqStart = Chain;
6194 
6195   // Load the return address and frame pointer so it can be move somewhere else
6196   // later.
6197   SDValue LROp, FPOp;
6198   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6199 
6200   // Set up a copy of the stack pointer for use loading and storing any
6201   // arguments that may not fit in the registers available for argument
6202   // passing.
6203   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6204 
6205   // Figure out which arguments are going to go in registers, and which in
6206   // memory.  Also, if this is a vararg function, floating point operations
6207   // must be stored to our stack, and loaded into integer regs as well, if
6208   // any integer regs are available for argument passing.
6209   unsigned ArgOffset = LinkageSize;
6210 
6211   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6212   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6213 
6214   SmallVector<SDValue, 8> MemOpChains;
6215   for (unsigned i = 0; i != NumOps; ++i) {
6216     SDValue Arg = OutVals[i];
6217     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6218     EVT ArgVT = Outs[i].VT;
6219     EVT OrigVT = Outs[i].ArgVT;
6220 
6221     // PtrOff will be used to store the current argument to the stack if a
6222     // register cannot be found for it.
6223     SDValue PtrOff;
6224 
6225     // We re-align the argument offset for each argument, except when using the
6226     // fast calling convention, when we need to make sure we do that only when
6227     // we'll actually use a stack slot.
6228     auto ComputePtrOff = [&]() {
6229       /* Respect alignment of argument on the stack.  */
6230       auto Alignment =
6231           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6232       ArgOffset = alignTo(ArgOffset, Alignment);
6233 
6234       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6235 
6236       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6237     };
6238 
6239     if (!IsFastCall) {
6240       ComputePtrOff();
6241 
6242       /* Compute GPR index associated with argument offset.  */
6243       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6244       GPR_idx = std::min(GPR_idx, NumGPRs);
6245     }
6246 
6247     // Promote integers to 64-bit values.
6248     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6249       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6250       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6251       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6252     }
6253 
6254     // FIXME memcpy is used way more than necessary.  Correctness first.
6255     // Note: "by value" is code for passing a structure by value, not
6256     // basic types.
6257     if (Flags.isByVal()) {
6258       // Note: Size includes alignment padding, so
6259       //   struct x { short a; char b; }
6260       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6261       // These are the proper values we need for right-justifying the
6262       // aggregate in a parameter register.
6263       unsigned Size = Flags.getByValSize();
6264 
6265       // An empty aggregate parameter takes up no storage and no
6266       // registers.
6267       if (Size == 0)
6268         continue;
6269 
6270       if (IsFastCall)
6271         ComputePtrOff();
6272 
6273       // All aggregates smaller than 8 bytes must be passed right-justified.
6274       if (Size==1 || Size==2 || Size==4) {
6275         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6276         if (GPR_idx != NumGPRs) {
6277           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6278                                         MachinePointerInfo(), VT);
6279           MemOpChains.push_back(Load.getValue(1));
6280           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6281 
6282           ArgOffset += PtrByteSize;
6283           continue;
6284         }
6285       }
6286 
6287       if (GPR_idx == NumGPRs && Size < 8) {
6288         SDValue AddPtr = PtrOff;
6289         if (!isLittleEndian) {
6290           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6291                                           PtrOff.getValueType());
6292           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6293         }
6294         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6295                                                           CallSeqStart,
6296                                                           Flags, DAG, dl);
6297         ArgOffset += PtrByteSize;
6298         continue;
6299       }
6300       // Copy entire object into memory.  There are cases where gcc-generated
6301       // code assumes it is there, even if it could be put entirely into
6302       // registers.  (This is not what the doc says.)
6303 
6304       // FIXME: The above statement is likely due to a misunderstanding of the
6305       // documents.  All arguments must be copied into the parameter area BY
6306       // THE CALLEE in the event that the callee takes the address of any
6307       // formal argument.  That has not yet been implemented.  However, it is
6308       // reasonable to use the stack area as a staging area for the register
6309       // load.
6310 
6311       // Skip this for small aggregates, as we will use the same slot for a
6312       // right-justified copy, below.
6313       if (Size >= 8)
6314         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6315                                                           CallSeqStart,
6316                                                           Flags, DAG, dl);
6317 
6318       // When a register is available, pass a small aggregate right-justified.
6319       if (Size < 8 && GPR_idx != NumGPRs) {
6320         // The easiest way to get this right-justified in a register
6321         // is to copy the structure into the rightmost portion of a
6322         // local variable slot, then load the whole slot into the
6323         // register.
6324         // FIXME: The memcpy seems to produce pretty awful code for
6325         // small aggregates, particularly for packed ones.
6326         // FIXME: It would be preferable to use the slot in the
6327         // parameter save area instead of a new local variable.
6328         SDValue AddPtr = PtrOff;
6329         if (!isLittleEndian) {
6330           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6331           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6332         }
6333         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6334                                                           CallSeqStart,
6335                                                           Flags, DAG, dl);
6336 
6337         // Load the slot into the register.
6338         SDValue Load =
6339             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6340         MemOpChains.push_back(Load.getValue(1));
6341         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6342 
6343         // Done with this argument.
6344         ArgOffset += PtrByteSize;
6345         continue;
6346       }
6347 
6348       // For aggregates larger than PtrByteSize, copy the pieces of the
6349       // object that fit into registers from the parameter save area.
6350       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6351         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6352         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6353         if (GPR_idx != NumGPRs) {
6354           SDValue Load =
6355               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6356           MemOpChains.push_back(Load.getValue(1));
6357           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6358           ArgOffset += PtrByteSize;
6359         } else {
6360           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6361           break;
6362         }
6363       }
6364       continue;
6365     }
6366 
6367     switch (Arg.getSimpleValueType().SimpleTy) {
6368     default: llvm_unreachable("Unexpected ValueType for argument!");
6369     case MVT::i1:
6370     case MVT::i32:
6371     case MVT::i64:
6372       if (Flags.isNest()) {
6373         // The 'nest' parameter, if any, is passed in R11.
6374         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6375         break;
6376       }
6377 
6378       // These can be scalar arguments or elements of an integer array type
6379       // passed directly.  Clang may use those instead of "byval" aggregate
6380       // types to avoid forcing arguments to memory unnecessarily.
6381       if (GPR_idx != NumGPRs) {
6382         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6383       } else {
6384         if (IsFastCall)
6385           ComputePtrOff();
6386 
6387         assert(HasParameterArea &&
6388                "Parameter area must exist to pass an argument in memory.");
6389         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6390                          true, CFlags.IsTailCall, false, MemOpChains,
6391                          TailCallArguments, dl);
6392         if (IsFastCall)
6393           ArgOffset += PtrByteSize;
6394       }
6395       if (!IsFastCall)
6396         ArgOffset += PtrByteSize;
6397       break;
6398     case MVT::f32:
6399     case MVT::f64: {
6400       // These can be scalar arguments or elements of a float array type
6401       // passed directly.  The latter are used to implement ELFv2 homogenous
6402       // float aggregates.
6403 
6404       // Named arguments go into FPRs first, and once they overflow, the
6405       // remaining arguments go into GPRs and then the parameter save area.
6406       // Unnamed arguments for vararg functions always go to GPRs and
6407       // then the parameter save area.  For now, put all arguments to vararg
6408       // routines always in both locations (FPR *and* GPR or stack slot).
6409       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6410       bool NeededLoad = false;
6411 
6412       // First load the argument into the next available FPR.
6413       if (FPR_idx != NumFPRs)
6414         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6415 
6416       // Next, load the argument into GPR or stack slot if needed.
6417       if (!NeedGPROrStack)
6418         ;
6419       else if (GPR_idx != NumGPRs && !IsFastCall) {
6420         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6421         // once we support fp <-> gpr moves.
6422 
6423         // In the non-vararg case, this can only ever happen in the
6424         // presence of f32 array types, since otherwise we never run
6425         // out of FPRs before running out of GPRs.
6426         SDValue ArgVal;
6427 
6428         // Double values are always passed in a single GPR.
6429         if (Arg.getValueType() != MVT::f32) {
6430           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6431 
6432         // Non-array float values are extended and passed in a GPR.
6433         } else if (!Flags.isInConsecutiveRegs()) {
6434           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6435           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6436 
6437         // If we have an array of floats, we collect every odd element
6438         // together with its predecessor into one GPR.
6439         } else if (ArgOffset % PtrByteSize != 0) {
6440           SDValue Lo, Hi;
6441           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6442           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6443           if (!isLittleEndian)
6444             std::swap(Lo, Hi);
6445           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6446 
6447         // The final element, if even, goes into the first half of a GPR.
6448         } else if (Flags.isInConsecutiveRegsLast()) {
6449           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6450           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6451           if (!isLittleEndian)
6452             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6453                                  DAG.getConstant(32, dl, MVT::i32));
6454 
6455         // Non-final even elements are skipped; they will be handled
6456         // together the with subsequent argument on the next go-around.
6457         } else
6458           ArgVal = SDValue();
6459 
6460         if (ArgVal.getNode())
6461           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6462       } else {
6463         if (IsFastCall)
6464           ComputePtrOff();
6465 
6466         // Single-precision floating-point values are mapped to the
6467         // second (rightmost) word of the stack doubleword.
6468         if (Arg.getValueType() == MVT::f32 &&
6469             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6470           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6471           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6472         }
6473 
6474         assert(HasParameterArea &&
6475                "Parameter area must exist to pass an argument in memory.");
6476         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6477                          true, CFlags.IsTailCall, false, MemOpChains,
6478                          TailCallArguments, dl);
6479 
6480         NeededLoad = true;
6481       }
6482       // When passing an array of floats, the array occupies consecutive
6483       // space in the argument area; only round up to the next doubleword
6484       // at the end of the array.  Otherwise, each float takes 8 bytes.
6485       if (!IsFastCall || NeededLoad) {
6486         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6487                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6488         if (Flags.isInConsecutiveRegsLast())
6489           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6490       }
6491       break;
6492     }
6493     case MVT::v4f32:
6494     case MVT::v4i32:
6495     case MVT::v8i16:
6496     case MVT::v16i8:
6497     case MVT::v2f64:
6498     case MVT::v2i64:
6499     case MVT::v1i128:
6500     case MVT::f128:
6501       if (!Subtarget.hasQPX()) {
6502       // These can be scalar arguments or elements of a vector array type
6503       // passed directly.  The latter are used to implement ELFv2 homogenous
6504       // vector aggregates.
6505 
6506       // For a varargs call, named arguments go into VRs or on the stack as
6507       // usual; unnamed arguments always go to the stack or the corresponding
6508       // GPRs when within range.  For now, we always put the value in both
6509       // locations (or even all three).
6510       if (CFlags.IsVarArg) {
6511         assert(HasParameterArea &&
6512                "Parameter area must exist if we have a varargs call.");
6513         // We could elide this store in the case where the object fits
6514         // entirely in R registers.  Maybe later.
6515         SDValue Store =
6516             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6517         MemOpChains.push_back(Store);
6518         if (VR_idx != NumVRs) {
6519           SDValue Load =
6520               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6521           MemOpChains.push_back(Load.getValue(1));
6522           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6523         }
6524         ArgOffset += 16;
6525         for (unsigned i=0; i<16; i+=PtrByteSize) {
6526           if (GPR_idx == NumGPRs)
6527             break;
6528           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6529                                    DAG.getConstant(i, dl, PtrVT));
6530           SDValue Load =
6531               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6532           MemOpChains.push_back(Load.getValue(1));
6533           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6534         }
6535         break;
6536       }
6537 
6538       // Non-varargs Altivec params go into VRs or on the stack.
6539       if (VR_idx != NumVRs) {
6540         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6541       } else {
6542         if (IsFastCall)
6543           ComputePtrOff();
6544 
6545         assert(HasParameterArea &&
6546                "Parameter area must exist to pass an argument in memory.");
6547         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6548                          true, CFlags.IsTailCall, true, MemOpChains,
6549                          TailCallArguments, dl);
6550         if (IsFastCall)
6551           ArgOffset += 16;
6552       }
6553 
6554       if (!IsFastCall)
6555         ArgOffset += 16;
6556       break;
6557       } // not QPX
6558 
6559       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6560              "Invalid QPX parameter type");
6561 
6562       LLVM_FALLTHROUGH;
6563     case MVT::v4f64:
6564     case MVT::v4i1: {
6565       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6566       if (CFlags.IsVarArg) {
6567         assert(HasParameterArea &&
6568                "Parameter area must exist if we have a varargs call.");
6569         // We could elide this store in the case where the object fits
6570         // entirely in R registers.  Maybe later.
6571         SDValue Store =
6572             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6573         MemOpChains.push_back(Store);
6574         if (QFPR_idx != NumQFPRs) {
6575           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6576                                      PtrOff, MachinePointerInfo());
6577           MemOpChains.push_back(Load.getValue(1));
6578           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6579         }
6580         ArgOffset += (IsF32 ? 16 : 32);
6581         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6582           if (GPR_idx == NumGPRs)
6583             break;
6584           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6585                                    DAG.getConstant(i, dl, PtrVT));
6586           SDValue Load =
6587               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6588           MemOpChains.push_back(Load.getValue(1));
6589           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6590         }
6591         break;
6592       }
6593 
6594       // Non-varargs QPX params go into registers or on the stack.
6595       if (QFPR_idx != NumQFPRs) {
6596         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6597       } else {
6598         if (IsFastCall)
6599           ComputePtrOff();
6600 
6601         assert(HasParameterArea &&
6602                "Parameter area must exist to pass an argument in memory.");
6603         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6604                          true, CFlags.IsTailCall, true, MemOpChains,
6605                          TailCallArguments, dl);
6606         if (IsFastCall)
6607           ArgOffset += (IsF32 ? 16 : 32);
6608       }
6609 
6610       if (!IsFastCall)
6611         ArgOffset += (IsF32 ? 16 : 32);
6612       break;
6613       }
6614     }
6615   }
6616 
6617   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6618          "mismatch in size of parameter area");
6619   (void)NumBytesActuallyUsed;
6620 
6621   if (!MemOpChains.empty())
6622     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6623 
6624   // Check if this is an indirect call (MTCTR/BCTRL).
6625   // See prepareDescriptorIndirectCall and buildCallOperands for more
6626   // information about calls through function pointers in the 64-bit SVR4 ABI.
6627   if (CFlags.IsIndirect) {
6628     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6629     // caller in the TOC save area.
6630     if (isTOCSaveRestoreRequired(Subtarget)) {
6631       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6632       // Load r2 into a virtual register and store it to the TOC save area.
6633       setUsesTOCBasePtr(DAG);
6634       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6635       // TOC save area offset.
6636       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6637       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6638       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6639       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6640                            MachinePointerInfo::getStack(
6641                                DAG.getMachineFunction(), TOCSaveOffset));
6642     }
6643     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6644     // This does not mean the MTCTR instruction must use R12; it's easier
6645     // to model this as an extra parameter, so do that.
6646     if (isELFv2ABI && !CFlags.IsPatchPoint)
6647       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6648   }
6649 
6650   // Build a sequence of copy-to-reg nodes chained together with token chain
6651   // and flag operands which copy the outgoing args into the appropriate regs.
6652   SDValue InFlag;
6653   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6654     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6655                              RegsToPass[i].second, InFlag);
6656     InFlag = Chain.getValue(1);
6657   }
6658 
6659   if (CFlags.IsTailCall && !IsSibCall)
6660     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6661                     TailCallArguments);
6662 
6663   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6664                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6665 }
6666 
6667 SDValue PPCTargetLowering::LowerCall_Darwin(
6668     SDValue Chain, SDValue Callee, CallFlags CFlags,
6669     const SmallVectorImpl<ISD::OutputArg> &Outs,
6670     const SmallVectorImpl<SDValue> &OutVals,
6671     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6672     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6673     const CallBase *CB) const {
6674   unsigned NumOps = Outs.size();
6675 
6676   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6677   bool isPPC64 = PtrVT == MVT::i64;
6678   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6679 
6680   MachineFunction &MF = DAG.getMachineFunction();
6681 
6682   // Mark this function as potentially containing a function that contains a
6683   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6684   // and restoring the callers stack pointer in this functions epilog. This is
6685   // done because by tail calling the called function might overwrite the value
6686   // in this function's (MF) stack pointer stack slot 0(SP).
6687   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6688       CFlags.CallConv == CallingConv::Fast)
6689     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6690 
6691   // Count how many bytes are to be pushed on the stack, including the linkage
6692   // area, and parameter passing area.  We start with 24/48 bytes, which is
6693   // prereserved space for [SP][CR][LR][3 x unused].
6694   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6695   unsigned NumBytes = LinkageSize;
6696 
6697   // Add up all the space actually used.
6698   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6699   // they all go in registers, but we must reserve stack space for them for
6700   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6701   // assigned stack space in order, with padding so Altivec parameters are
6702   // 16-byte aligned.
6703   unsigned nAltivecParamsAtEnd = 0;
6704   for (unsigned i = 0; i != NumOps; ++i) {
6705     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6706     EVT ArgVT = Outs[i].VT;
6707     // Varargs Altivec parameters are padded to a 16 byte boundary.
6708     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6709         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6710         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6711       if (!CFlags.IsVarArg && !isPPC64) {
6712         // Non-varargs Altivec parameters go after all the non-Altivec
6713         // parameters; handle those later so we know how much padding we need.
6714         nAltivecParamsAtEnd++;
6715         continue;
6716       }
6717       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6718       NumBytes = ((NumBytes+15)/16)*16;
6719     }
6720     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6721   }
6722 
6723   // Allow for Altivec parameters at the end, if needed.
6724   if (nAltivecParamsAtEnd) {
6725     NumBytes = ((NumBytes+15)/16)*16;
6726     NumBytes += 16*nAltivecParamsAtEnd;
6727   }
6728 
6729   // The prolog code of the callee may store up to 8 GPR argument registers to
6730   // the stack, allowing va_start to index over them in memory if its varargs.
6731   // Because we cannot tell if this is needed on the caller side, we have to
6732   // conservatively assume that it is needed.  As such, make sure we have at
6733   // least enough stack space for the caller to store the 8 GPRs.
6734   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6735 
6736   // Tail call needs the stack to be aligned.
6737   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6738       CFlags.CallConv == CallingConv::Fast)
6739     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6740 
6741   // Calculate by how many bytes the stack has to be adjusted in case of tail
6742   // call optimization.
6743   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6744 
6745   // To protect arguments on the stack from being clobbered in a tail call,
6746   // force all the loads to happen before doing any other lowering.
6747   if (CFlags.IsTailCall)
6748     Chain = DAG.getStackArgumentTokenFactor(Chain);
6749 
6750   // Adjust the stack pointer for the new arguments...
6751   // These operations are automatically eliminated by the prolog/epilog pass
6752   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6753   SDValue CallSeqStart = Chain;
6754 
6755   // Load the return address and frame pointer so it can be move somewhere else
6756   // later.
6757   SDValue LROp, FPOp;
6758   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6759 
6760   // Set up a copy of the stack pointer for use loading and storing any
6761   // arguments that may not fit in the registers available for argument
6762   // passing.
6763   SDValue StackPtr;
6764   if (isPPC64)
6765     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6766   else
6767     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6768 
6769   // Figure out which arguments are going to go in registers, and which in
6770   // memory.  Also, if this is a vararg function, floating point operations
6771   // must be stored to our stack, and loaded into integer regs as well, if
6772   // any integer regs are available for argument passing.
6773   unsigned ArgOffset = LinkageSize;
6774   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6775 
6776   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6777     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6778     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6779   };
6780   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6781     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6782     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6783   };
6784   static const MCPhysReg VR[] = {
6785     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6786     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6787   };
6788   const unsigned NumGPRs = array_lengthof(GPR_32);
6789   const unsigned NumFPRs = 13;
6790   const unsigned NumVRs  = array_lengthof(VR);
6791 
6792   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6793 
6794   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6795   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6796 
6797   SmallVector<SDValue, 8> MemOpChains;
6798   for (unsigned i = 0; i != NumOps; ++i) {
6799     SDValue Arg = OutVals[i];
6800     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6801 
6802     // PtrOff will be used to store the current argument to the stack if a
6803     // register cannot be found for it.
6804     SDValue PtrOff;
6805 
6806     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6807 
6808     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6809 
6810     // On PPC64, promote integers to 64-bit values.
6811     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6812       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6813       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6814       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6815     }
6816 
6817     // FIXME memcpy is used way more than necessary.  Correctness first.
6818     // Note: "by value" is code for passing a structure by value, not
6819     // basic types.
6820     if (Flags.isByVal()) {
6821       unsigned Size = Flags.getByValSize();
6822       // Very small objects are passed right-justified.  Everything else is
6823       // passed left-justified.
6824       if (Size==1 || Size==2) {
6825         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6826         if (GPR_idx != NumGPRs) {
6827           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6828                                         MachinePointerInfo(), VT);
6829           MemOpChains.push_back(Load.getValue(1));
6830           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6831 
6832           ArgOffset += PtrByteSize;
6833         } else {
6834           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6835                                           PtrOff.getValueType());
6836           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6837           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6838                                                             CallSeqStart,
6839                                                             Flags, DAG, dl);
6840           ArgOffset += PtrByteSize;
6841         }
6842         continue;
6843       }
6844       // Copy entire object into memory.  There are cases where gcc-generated
6845       // code assumes it is there, even if it could be put entirely into
6846       // registers.  (This is not what the doc says.)
6847       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6848                                                         CallSeqStart,
6849                                                         Flags, DAG, dl);
6850 
6851       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6852       // copy the pieces of the object that fit into registers from the
6853       // parameter save area.
6854       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6855         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6856         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6857         if (GPR_idx != NumGPRs) {
6858           SDValue Load =
6859               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6860           MemOpChains.push_back(Load.getValue(1));
6861           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6862           ArgOffset += PtrByteSize;
6863         } else {
6864           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6865           break;
6866         }
6867       }
6868       continue;
6869     }
6870 
6871     switch (Arg.getSimpleValueType().SimpleTy) {
6872     default: llvm_unreachable("Unexpected ValueType for argument!");
6873     case MVT::i1:
6874     case MVT::i32:
6875     case MVT::i64:
6876       if (GPR_idx != NumGPRs) {
6877         if (Arg.getValueType() == MVT::i1)
6878           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6879 
6880         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6881       } else {
6882         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6883                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6884                          TailCallArguments, dl);
6885       }
6886       ArgOffset += PtrByteSize;
6887       break;
6888     case MVT::f32:
6889     case MVT::f64:
6890       if (FPR_idx != NumFPRs) {
6891         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6892 
6893         if (CFlags.IsVarArg) {
6894           SDValue Store =
6895               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6896           MemOpChains.push_back(Store);
6897 
6898           // Float varargs are always shadowed in available integer registers
6899           if (GPR_idx != NumGPRs) {
6900             SDValue Load =
6901                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6902             MemOpChains.push_back(Load.getValue(1));
6903             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6904           }
6905           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6906             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6907             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6908             SDValue Load =
6909                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6910             MemOpChains.push_back(Load.getValue(1));
6911             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6912           }
6913         } else {
6914           // If we have any FPRs remaining, we may also have GPRs remaining.
6915           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6916           // GPRs.
6917           if (GPR_idx != NumGPRs)
6918             ++GPR_idx;
6919           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6920               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6921             ++GPR_idx;
6922         }
6923       } else
6924         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6925                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6926                          TailCallArguments, dl);
6927       if (isPPC64)
6928         ArgOffset += 8;
6929       else
6930         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6931       break;
6932     case MVT::v4f32:
6933     case MVT::v4i32:
6934     case MVT::v8i16:
6935     case MVT::v16i8:
6936       if (CFlags.IsVarArg) {
6937         // These go aligned on the stack, or in the corresponding R registers
6938         // when within range.  The Darwin PPC ABI doc claims they also go in
6939         // V registers; in fact gcc does this only for arguments that are
6940         // prototyped, not for those that match the ...  We do it for all
6941         // arguments, seems to work.
6942         while (ArgOffset % 16 !=0) {
6943           ArgOffset += PtrByteSize;
6944           if (GPR_idx != NumGPRs)
6945             GPR_idx++;
6946         }
6947         // We could elide this store in the case where the object fits
6948         // entirely in R registers.  Maybe later.
6949         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6950                              DAG.getConstant(ArgOffset, dl, PtrVT));
6951         SDValue Store =
6952             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6953         MemOpChains.push_back(Store);
6954         if (VR_idx != NumVRs) {
6955           SDValue Load =
6956               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6957           MemOpChains.push_back(Load.getValue(1));
6958           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6959         }
6960         ArgOffset += 16;
6961         for (unsigned i=0; i<16; i+=PtrByteSize) {
6962           if (GPR_idx == NumGPRs)
6963             break;
6964           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6965                                    DAG.getConstant(i, dl, PtrVT));
6966           SDValue Load =
6967               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6968           MemOpChains.push_back(Load.getValue(1));
6969           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6970         }
6971         break;
6972       }
6973 
6974       // Non-varargs Altivec params generally go in registers, but have
6975       // stack space allocated at the end.
6976       if (VR_idx != NumVRs) {
6977         // Doesn't have GPR space allocated.
6978         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6979       } else if (nAltivecParamsAtEnd==0) {
6980         // We are emitting Altivec params in order.
6981         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6982                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6983                          TailCallArguments, dl);
6984         ArgOffset += 16;
6985       }
6986       break;
6987     }
6988   }
6989   // If all Altivec parameters fit in registers, as they usually do,
6990   // they get stack space following the non-Altivec parameters.  We
6991   // don't track this here because nobody below needs it.
6992   // If there are more Altivec parameters than fit in registers emit
6993   // the stores here.
6994   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6995     unsigned j = 0;
6996     // Offset is aligned; skip 1st 12 params which go in V registers.
6997     ArgOffset = ((ArgOffset+15)/16)*16;
6998     ArgOffset += 12*16;
6999     for (unsigned i = 0; i != NumOps; ++i) {
7000       SDValue Arg = OutVals[i];
7001       EVT ArgType = Outs[i].VT;
7002       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
7003           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
7004         if (++j > NumVRs) {
7005           SDValue PtrOff;
7006           // We are emitting Altivec params in order.
7007           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
7008                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
7009                            TailCallArguments, dl);
7010           ArgOffset += 16;
7011         }
7012       }
7013     }
7014   }
7015 
7016   if (!MemOpChains.empty())
7017     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7018 
7019   // On Darwin, R12 must contain the address of an indirect callee.  This does
7020   // not mean the MTCTR instruction must use R12; it's easier to model this as
7021   // an extra parameter, so do that.
7022   if (CFlags.IsIndirect) {
7023     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7024     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
7025                                                    PPC::R12), Callee));
7026   }
7027 
7028   // Build a sequence of copy-to-reg nodes chained together with token chain
7029   // and flag operands which copy the outgoing args into the appropriate regs.
7030   SDValue InFlag;
7031   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
7032     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
7033                              RegsToPass[i].second, InFlag);
7034     InFlag = Chain.getValue(1);
7035   }
7036 
7037   if (CFlags.IsTailCall)
7038     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
7039                     TailCallArguments);
7040 
7041   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7042                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7043 }
7044 
7045 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
7046                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
7047                    CCState &State) {
7048 
7049   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
7050       State.getMachineFunction().getSubtarget());
7051   const bool IsPPC64 = Subtarget.isPPC64();
7052   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
7053   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
7054 
7055   assert((!ValVT.isInteger() ||
7056           (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) &&
7057          "Integer argument exceeds register size: should have been legalized");
7058 
7059   if (ValVT == MVT::f128)
7060     report_fatal_error("f128 is unimplemented on AIX.");
7061 
7062   if (ArgFlags.isNest())
7063     report_fatal_error("Nest arguments are unimplemented.");
7064 
7065   if (ValVT.isVector() || LocVT.isVector())
7066     report_fatal_error("Vector arguments are unimplemented on AIX.");
7067 
7068   static const MCPhysReg GPR_32[] = {// 32-bit registers.
7069                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7070                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7071   static const MCPhysReg GPR_64[] = {// 64-bit registers.
7072                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7073                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7074 
7075   if (ArgFlags.isByVal()) {
7076     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
7077       report_fatal_error("Pass-by-value arguments with alignment greater than "
7078                          "register width are not supported.");
7079 
7080     const unsigned ByValSize = ArgFlags.getByValSize();
7081 
7082     // An empty aggregate parameter takes up no storage and no registers,
7083     // but needs a MemLoc for a stack slot for the formal arguments side.
7084     if (ByValSize == 0) {
7085       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
7086                                        State.getNextStackOffset(), RegVT,
7087                                        LocInfo));
7088       return false;
7089     }
7090 
7091     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
7092     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
7093     for (const unsigned E = Offset + StackSize; Offset < E;
7094          Offset += PtrAlign.value()) {
7095       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
7096         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7097       else {
7098         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
7099                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
7100                                          LocInfo));
7101         break;
7102       }
7103     }
7104     return false;
7105   }
7106 
7107   // Arguments always reserve parameter save area.
7108   switch (ValVT.SimpleTy) {
7109   default:
7110     report_fatal_error("Unhandled value type for argument.");
7111   case MVT::i64:
7112     // i64 arguments should have been split to i32 for PPC32.
7113     assert(IsPPC64 && "PPC32 should have split i64 values.");
7114     LLVM_FALLTHROUGH;
7115   case MVT::i1:
7116   case MVT::i32: {
7117     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
7118     // AIX integer arguments are always passed in register width.
7119     if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
7120       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
7121                                   : CCValAssign::LocInfo::ZExt;
7122     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
7123       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7124     else
7125       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
7126 
7127     return false;
7128   }
7129   case MVT::f32:
7130   case MVT::f64: {
7131     // Parameter save area (PSA) is reserved even if the float passes in fpr.
7132     const unsigned StoreSize = LocVT.getStoreSize();
7133     // Floats are always 4-byte aligned in the PSA on AIX.
7134     // This includes f64 in 64-bit mode for ABI compatibility.
7135     const unsigned Offset =
7136         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
7137     unsigned FReg = State.AllocateReg(FPR);
7138     if (FReg)
7139       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
7140 
7141     // Reserve and initialize GPRs or initialize the PSA as required.
7142     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
7143       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
7144         assert(FReg && "An FPR should be available when a GPR is reserved.");
7145         if (State.isVarArg()) {
7146           // Successfully reserved GPRs are only initialized for vararg calls.
7147           // Custom handling is required for:
7148           //   f64 in PPC32 needs to be split into 2 GPRs.
7149           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
7150           State.addLoc(
7151               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7152         }
7153       } else {
7154         // If there are insufficient GPRs, the PSA needs to be initialized.
7155         // Initialization occurs even if an FPR was initialized for
7156         // compatibility with the AIX XL compiler. The full memory for the
7157         // argument will be initialized even if a prior word is saved in GPR.
7158         // A custom memLoc is used when the argument also passes in FPR so
7159         // that the callee handling can skip over it easily.
7160         State.addLoc(
7161             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
7162                                              LocInfo)
7163                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7164         break;
7165       }
7166     }
7167 
7168     return false;
7169   }
7170   }
7171   return true;
7172 }
7173 
7174 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
7175                                                     bool IsPPC64) {
7176   assert((IsPPC64 || SVT != MVT::i64) &&
7177          "i64 should have been split for 32-bit codegen.");
7178 
7179   switch (SVT) {
7180   default:
7181     report_fatal_error("Unexpected value type for formal argument");
7182   case MVT::i1:
7183   case MVT::i32:
7184   case MVT::i64:
7185     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7186   case MVT::f32:
7187     return &PPC::F4RCRegClass;
7188   case MVT::f64:
7189     return &PPC::F8RCRegClass;
7190   }
7191 }
7192 
7193 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
7194                                         SelectionDAG &DAG, SDValue ArgValue,
7195                                         MVT LocVT, const SDLoc &dl) {
7196   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7197   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
7198 
7199   if (Flags.isSExt())
7200     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7201                            DAG.getValueType(ValVT));
7202   else if (Flags.isZExt())
7203     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7204                            DAG.getValueType(ValVT));
7205 
7206   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7207 }
7208 
7209 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7210   const unsigned LASize = FL->getLinkageSize();
7211 
7212   if (PPC::GPRCRegClass.contains(Reg)) {
7213     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7214            "Reg must be a valid argument register!");
7215     return LASize + 4 * (Reg - PPC::R3);
7216   }
7217 
7218   if (PPC::G8RCRegClass.contains(Reg)) {
7219     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7220            "Reg must be a valid argument register!");
7221     return LASize + 8 * (Reg - PPC::X3);
7222   }
7223 
7224   llvm_unreachable("Only general purpose registers expected.");
7225 }
7226 
7227 //   AIX ABI Stack Frame Layout:
7228 //
7229 //   Low Memory +--------------------------------------------+
7230 //   SP   +---> | Back chain                                 | ---+
7231 //        |     +--------------------------------------------+    |
7232 //        |     | Saved Condition Register                   |    |
7233 //        |     +--------------------------------------------+    |
7234 //        |     | Saved Linkage Register                     |    |
7235 //        |     +--------------------------------------------+    | Linkage Area
7236 //        |     | Reserved for compilers                     |    |
7237 //        |     +--------------------------------------------+    |
7238 //        |     | Reserved for binders                       |    |
7239 //        |     +--------------------------------------------+    |
7240 //        |     | Saved TOC pointer                          | ---+
7241 //        |     +--------------------------------------------+
7242 //        |     | Parameter save area                        |
7243 //        |     +--------------------------------------------+
7244 //        |     | Alloca space                               |
7245 //        |     +--------------------------------------------+
7246 //        |     | Local variable space                       |
7247 //        |     +--------------------------------------------+
7248 //        |     | Float/int conversion temporary             |
7249 //        |     +--------------------------------------------+
7250 //        |     | Save area for AltiVec registers            |
7251 //        |     +--------------------------------------------+
7252 //        |     | AltiVec alignment padding                  |
7253 //        |     +--------------------------------------------+
7254 //        |     | Save area for VRSAVE register              |
7255 //        |     +--------------------------------------------+
7256 //        |     | Save area for General Purpose registers    |
7257 //        |     +--------------------------------------------+
7258 //        |     | Save area for Floating Point registers     |
7259 //        |     +--------------------------------------------+
7260 //        +---- | Back chain                                 |
7261 // High Memory  +--------------------------------------------+
7262 //
7263 //  Specifications:
7264 //  AIX 7.2 Assembler Language Reference
7265 //  Subroutine linkage convention
7266 
7267 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7268     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7269     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7270     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7271 
7272   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7273           CallConv == CallingConv::Fast) &&
7274          "Unexpected calling convention!");
7275 
7276   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7277     report_fatal_error("Tail call support is unimplemented on AIX.");
7278 
7279   if (useSoftFloat())
7280     report_fatal_error("Soft float support is unimplemented on AIX.");
7281 
7282   const PPCSubtarget &Subtarget =
7283       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7284   if (Subtarget.hasQPX())
7285     report_fatal_error("QPX support is not supported on AIX.");
7286 
7287   const bool IsPPC64 = Subtarget.isPPC64();
7288   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7289 
7290   // Assign locations to all of the incoming arguments.
7291   SmallVector<CCValAssign, 16> ArgLocs;
7292   MachineFunction &MF = DAG.getMachineFunction();
7293   MachineFrameInfo &MFI = MF.getFrameInfo();
7294   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7295 
7296   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7297   // Reserve space for the linkage area on the stack.
7298   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7299   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7300   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7301 
7302   SmallVector<SDValue, 8> MemOps;
7303 
7304   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7305     CCValAssign &VA = ArgLocs[I++];
7306     MVT LocVT = VA.getLocVT();
7307     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7308 
7309     // For compatibility with the AIX XL compiler, the float args in the
7310     // parameter save area are initialized even if the argument is available
7311     // in register.  The caller is required to initialize both the register
7312     // and memory, however, the callee can choose to expect it in either.
7313     // The memloc is dismissed here because the argument is retrieved from
7314     // the register.
7315     if (VA.isMemLoc() && VA.needsCustom())
7316       continue;
7317 
7318     if (Flags.isByVal() && VA.isMemLoc()) {
7319       const unsigned Size =
7320           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7321                   PtrByteSize);
7322       const int FI = MF.getFrameInfo().CreateFixedObject(
7323           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7324           /* IsAliased */ true);
7325       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7326       InVals.push_back(FIN);
7327 
7328       continue;
7329     }
7330 
7331     if (Flags.isByVal()) {
7332       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7333 
7334       const MCPhysReg ArgReg = VA.getLocReg();
7335       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7336 
7337       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7338         report_fatal_error("Over aligned byvals not supported yet.");
7339 
7340       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7341       const int FI = MF.getFrameInfo().CreateFixedObject(
7342           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7343           /* IsAliased */ true);
7344       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7345       InVals.push_back(FIN);
7346 
7347       // Add live ins for all the RegLocs for the same ByVal.
7348       const TargetRegisterClass *RegClass =
7349           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7350 
7351       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7352                                                unsigned Offset) {
7353         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7354         // Since the callers side has left justified the aggregate in the
7355         // register, we can simply store the entire register into the stack
7356         // slot.
7357         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7358         // The store to the fixedstack object is needed becuase accessing a
7359         // field of the ByVal will use a gep and load. Ideally we will optimize
7360         // to extracting the value from the register directly, and elide the
7361         // stores when the arguments address is not taken, but that will need to
7362         // be future work.
7363         SDValue Store =
7364             DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom,
7365                          DAG.getObjectPtrOffset(dl, FIN, Offset),
7366                          MachinePointerInfo::getFixedStack(MF, FI, Offset));
7367 
7368         MemOps.push_back(Store);
7369       };
7370 
7371       unsigned Offset = 0;
7372       HandleRegLoc(VA.getLocReg(), Offset);
7373       Offset += PtrByteSize;
7374       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7375            Offset += PtrByteSize) {
7376         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7377                "RegLocs should be for ByVal argument.");
7378 
7379         const CCValAssign RL = ArgLocs[I++];
7380         HandleRegLoc(RL.getLocReg(), Offset);
7381       }
7382 
7383       if (Offset != StackSize) {
7384         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7385                "Expected MemLoc for remaining bytes.");
7386         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7387         // Consume the MemLoc.The InVal has already been emitted, so nothing
7388         // more needs to be done.
7389         ++I;
7390       }
7391 
7392       continue;
7393     }
7394 
7395     EVT ValVT = VA.getValVT();
7396     if (VA.isRegLoc() && !VA.needsCustom()) {
7397       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7398       unsigned VReg =
7399           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7400       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7401       if (ValVT.isScalarInteger() &&
7402           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7403         ArgValue =
7404             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7405       }
7406       InVals.push_back(ArgValue);
7407       continue;
7408     }
7409     if (VA.isMemLoc()) {
7410       const unsigned LocSize = LocVT.getStoreSize();
7411       const unsigned ValSize = ValVT.getStoreSize();
7412       assert((ValSize <= LocSize) &&
7413              "Object size is larger than size of MemLoc");
7414       int CurArgOffset = VA.getLocMemOffset();
7415       // Objects are right-justified because AIX is big-endian.
7416       if (LocSize > ValSize)
7417         CurArgOffset += LocSize - ValSize;
7418       // Potential tail calls could cause overwriting of argument stack slots.
7419       const bool IsImmutable =
7420           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7421             (CallConv == CallingConv::Fast));
7422       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7423       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7424       SDValue ArgValue =
7425           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7426       InVals.push_back(ArgValue);
7427       continue;
7428     }
7429   }
7430 
7431   // On AIX a minimum of 8 words is saved to the parameter save area.
7432   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7433   // Area that is at least reserved in the caller of this function.
7434   unsigned CallerReservedArea =
7435       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7436 
7437   // Set the size that is at least reserved in caller of this function. Tail
7438   // call optimized function's reserved stack space needs to be aligned so
7439   // that taking the difference between two stack areas will result in an
7440   // aligned stack.
7441   CallerReservedArea =
7442       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7443   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7444   FuncInfo->setMinReservedArea(CallerReservedArea);
7445 
7446   if (isVarArg) {
7447     FuncInfo->setVarArgsFrameIndex(
7448         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7449     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7450 
7451     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7452                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7453 
7454     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7455                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7456     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7457 
7458     // The fixed integer arguments of a variadic function are stored to the
7459     // VarArgsFrameIndex on the stack so that they may be loaded by
7460     // dereferencing the result of va_next.
7461     for (unsigned GPRIndex =
7462              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7463          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7464 
7465       const unsigned VReg =
7466           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7467                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7468 
7469       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7470       SDValue Store =
7471           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7472       MemOps.push_back(Store);
7473       // Increment the address for the next argument to store.
7474       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7475       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7476     }
7477   }
7478 
7479   if (!MemOps.empty())
7480     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7481 
7482   return Chain;
7483 }
7484 
7485 SDValue PPCTargetLowering::LowerCall_AIX(
7486     SDValue Chain, SDValue Callee, CallFlags CFlags,
7487     const SmallVectorImpl<ISD::OutputArg> &Outs,
7488     const SmallVectorImpl<SDValue> &OutVals,
7489     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7490     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7491     const CallBase *CB) const {
7492   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7493   // AIX ABI stack frame layout.
7494 
7495   assert((CFlags.CallConv == CallingConv::C ||
7496           CFlags.CallConv == CallingConv::Cold ||
7497           CFlags.CallConv == CallingConv::Fast) &&
7498          "Unexpected calling convention!");
7499 
7500   if (CFlags.IsPatchPoint)
7501     report_fatal_error("This call type is unimplemented on AIX.");
7502 
7503   const PPCSubtarget& Subtarget =
7504       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7505   if (Subtarget.hasQPX())
7506     report_fatal_error("QPX is not supported on AIX.");
7507   if (Subtarget.hasAltivec())
7508     report_fatal_error("Altivec support is unimplemented on AIX.");
7509 
7510   MachineFunction &MF = DAG.getMachineFunction();
7511   SmallVector<CCValAssign, 16> ArgLocs;
7512   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7513                  *DAG.getContext());
7514 
7515   // Reserve space for the linkage save area (LSA) on the stack.
7516   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7517   //   [SP][CR][LR][2 x reserved][TOC].
7518   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7519   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7520   const bool IsPPC64 = Subtarget.isPPC64();
7521   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7522   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7523   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7524   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7525 
7526   // The prolog code of the callee may store up to 8 GPR argument registers to
7527   // the stack, allowing va_start to index over them in memory if the callee
7528   // is variadic.
7529   // Because we cannot tell if this is needed on the caller side, we have to
7530   // conservatively assume that it is needed.  As such, make sure we have at
7531   // least enough stack space for the caller to store the 8 GPRs.
7532   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7533   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7534                                      CCInfo.getNextStackOffset());
7535 
7536   // Adjust the stack pointer for the new arguments...
7537   // These operations are automatically eliminated by the prolog/epilog pass.
7538   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7539   SDValue CallSeqStart = Chain;
7540 
7541   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7542   SmallVector<SDValue, 8> MemOpChains;
7543 
7544   // Set up a copy of the stack pointer for loading and storing any
7545   // arguments that may not fit in the registers available for argument
7546   // passing.
7547   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7548                                    : DAG.getRegister(PPC::R1, MVT::i32);
7549 
7550   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7551     const unsigned ValNo = ArgLocs[I].getValNo();
7552     SDValue Arg = OutVals[ValNo];
7553     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7554 
7555     if (Flags.isByVal()) {
7556       const unsigned ByValSize = Flags.getByValSize();
7557 
7558       // Nothing to do for zero-sized ByVals on the caller side.
7559       if (!ByValSize) {
7560         ++I;
7561         continue;
7562       }
7563 
7564       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7565         return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain,
7566                               (LoadOffset != 0)
7567                                   ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7568                                   : Arg,
7569                               MachinePointerInfo(), VT);
7570       };
7571 
7572       unsigned LoadOffset = 0;
7573 
7574       // Initialize registers, which are fully occupied by the by-val argument.
7575       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7576         SDValue Load = GetLoad(PtrVT, LoadOffset);
7577         MemOpChains.push_back(Load.getValue(1));
7578         LoadOffset += PtrByteSize;
7579         const CCValAssign &ByValVA = ArgLocs[I++];
7580         assert(ByValVA.getValNo() == ValNo &&
7581                "Unexpected location for pass-by-value argument.");
7582         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7583       }
7584 
7585       if (LoadOffset == ByValSize)
7586         continue;
7587 
7588       // There must be one more loc to handle the remainder.
7589       assert(ArgLocs[I].getValNo() == ValNo &&
7590              "Expected additional location for by-value argument.");
7591 
7592       if (ArgLocs[I].isMemLoc()) {
7593         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7594         const CCValAssign &ByValVA = ArgLocs[I++];
7595         ISD::ArgFlagsTy MemcpyFlags = Flags;
7596         // Only memcpy the bytes that don't pass in register.
7597         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7598         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7599             (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7600                               : Arg,
7601             DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()),
7602             CallSeqStart, MemcpyFlags, DAG, dl);
7603         continue;
7604       }
7605 
7606       // Initialize the final register residue.
7607       // Any residue that occupies the final by-val arg register must be
7608       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7609       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7610       // 2 and 1 byte loads.
7611       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7612       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7613              "Unexpected register residue for by-value argument.");
7614       SDValue ResidueVal;
7615       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7616         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7617         const MVT VT =
7618             N == 1 ? MVT::i8
7619                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7620         SDValue Load = GetLoad(VT, LoadOffset);
7621         MemOpChains.push_back(Load.getValue(1));
7622         LoadOffset += N;
7623         Bytes += N;
7624 
7625         // By-val arguments are passed left-justfied in register.
7626         // Every load here needs to be shifted, otherwise a full register load
7627         // should have been used.
7628         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7629                "Unexpected load emitted during handling of pass-by-value "
7630                "argument.");
7631         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7632         EVT ShiftAmountTy =
7633             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7634         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7635         SDValue ShiftedLoad =
7636             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7637         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7638                                               ShiftedLoad)
7639                                 : ShiftedLoad;
7640       }
7641 
7642       const CCValAssign &ByValVA = ArgLocs[I++];
7643       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7644       continue;
7645     }
7646 
7647     CCValAssign &VA = ArgLocs[I++];
7648     const MVT LocVT = VA.getLocVT();
7649     const MVT ValVT = VA.getValVT();
7650 
7651     switch (VA.getLocInfo()) {
7652     default:
7653       report_fatal_error("Unexpected argument extension type.");
7654     case CCValAssign::Full:
7655       break;
7656     case CCValAssign::ZExt:
7657       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7658       break;
7659     case CCValAssign::SExt:
7660       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7661       break;
7662     }
7663 
7664     if (VA.isRegLoc() && !VA.needsCustom()) {
7665       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7666       continue;
7667     }
7668 
7669     if (VA.isMemLoc()) {
7670       SDValue PtrOff =
7671           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7672       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7673       MemOpChains.push_back(
7674           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7675 
7676       continue;
7677     }
7678 
7679     // Custom handling is used for GPR initializations for vararg float
7680     // arguments.
7681     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7682            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7683            "Unexpected register handling for calling convention.");
7684 
7685     SDValue ArgAsInt =
7686         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7687 
7688     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7689       // f32 in 32-bit GPR
7690       // f64 in 64-bit GPR
7691       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7692     else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits())
7693       // f32 in 64-bit GPR.
7694       RegsToPass.push_back(std::make_pair(
7695           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7696     else {
7697       // f64 in two 32-bit GPRs
7698       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7699       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7700              "Unexpected custom register for argument!");
7701       CCValAssign &GPR1 = VA;
7702       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7703                                      DAG.getConstant(32, dl, MVT::i8));
7704       RegsToPass.push_back(std::make_pair(
7705           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7706 
7707       if (I != E) {
7708         // If only 1 GPR was available, there will only be one custom GPR and
7709         // the argument will also pass in memory.
7710         CCValAssign &PeekArg = ArgLocs[I];
7711         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7712           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7713           CCValAssign &GPR2 = ArgLocs[I++];
7714           RegsToPass.push_back(std::make_pair(
7715               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7716         }
7717       }
7718     }
7719   }
7720 
7721   if (!MemOpChains.empty())
7722     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7723 
7724   // For indirect calls, we need to save the TOC base to the stack for
7725   // restoration after the call.
7726   if (CFlags.IsIndirect) {
7727     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7728     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7729     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7730     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7731     const unsigned TOCSaveOffset =
7732         Subtarget.getFrameLowering()->getTOCSaveOffset();
7733 
7734     setUsesTOCBasePtr(DAG);
7735     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7736     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7737     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7738     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7739     Chain = DAG.getStore(
7740         Val.getValue(1), dl, Val, AddPtr,
7741         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7742   }
7743 
7744   // Build a sequence of copy-to-reg nodes chained together with token chain
7745   // and flag operands which copy the outgoing args into the appropriate regs.
7746   SDValue InFlag;
7747   for (auto Reg : RegsToPass) {
7748     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7749     InFlag = Chain.getValue(1);
7750   }
7751 
7752   const int SPDiff = 0;
7753   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7754                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7755 }
7756 
7757 bool
7758 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7759                                   MachineFunction &MF, bool isVarArg,
7760                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7761                                   LLVMContext &Context) const {
7762   SmallVector<CCValAssign, 16> RVLocs;
7763   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7764   return CCInfo.CheckReturn(
7765       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7766                 ? RetCC_PPC_Cold
7767                 : RetCC_PPC);
7768 }
7769 
7770 SDValue
7771 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7772                                bool isVarArg,
7773                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7774                                const SmallVectorImpl<SDValue> &OutVals,
7775                                const SDLoc &dl, SelectionDAG &DAG) const {
7776   SmallVector<CCValAssign, 16> RVLocs;
7777   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7778                  *DAG.getContext());
7779   CCInfo.AnalyzeReturn(Outs,
7780                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7781                            ? RetCC_PPC_Cold
7782                            : RetCC_PPC);
7783 
7784   SDValue Flag;
7785   SmallVector<SDValue, 4> RetOps(1, Chain);
7786 
7787   // Copy the result values into the output registers.
7788   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7789     CCValAssign &VA = RVLocs[i];
7790     assert(VA.isRegLoc() && "Can only return in registers!");
7791 
7792     SDValue Arg = OutVals[RealResIdx];
7793 
7794     switch (VA.getLocInfo()) {
7795     default: llvm_unreachable("Unknown loc info!");
7796     case CCValAssign::Full: break;
7797     case CCValAssign::AExt:
7798       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7799       break;
7800     case CCValAssign::ZExt:
7801       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7802       break;
7803     case CCValAssign::SExt:
7804       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7805       break;
7806     }
7807     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7808       bool isLittleEndian = Subtarget.isLittleEndian();
7809       // Legalize ret f64 -> ret 2 x i32.
7810       SDValue SVal =
7811           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7812                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7813       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7814       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7815       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7816                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7817       Flag = Chain.getValue(1);
7818       VA = RVLocs[++i]; // skip ahead to next loc
7819       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7820     } else
7821       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7822     Flag = Chain.getValue(1);
7823     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7824   }
7825 
7826   RetOps[0] = Chain;  // Update chain.
7827 
7828   // Add the flag if we have it.
7829   if (Flag.getNode())
7830     RetOps.push_back(Flag);
7831 
7832   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7833 }
7834 
7835 SDValue
7836 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7837                                                 SelectionDAG &DAG) const {
7838   SDLoc dl(Op);
7839 
7840   // Get the correct type for integers.
7841   EVT IntVT = Op.getValueType();
7842 
7843   // Get the inputs.
7844   SDValue Chain = Op.getOperand(0);
7845   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7846   // Build a DYNAREAOFFSET node.
7847   SDValue Ops[2] = {Chain, FPSIdx};
7848   SDVTList VTs = DAG.getVTList(IntVT);
7849   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7850 }
7851 
7852 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7853                                              SelectionDAG &DAG) const {
7854   // When we pop the dynamic allocation we need to restore the SP link.
7855   SDLoc dl(Op);
7856 
7857   // Get the correct type for pointers.
7858   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7859 
7860   // Construct the stack pointer operand.
7861   bool isPPC64 = Subtarget.isPPC64();
7862   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7863   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7864 
7865   // Get the operands for the STACKRESTORE.
7866   SDValue Chain = Op.getOperand(0);
7867   SDValue SaveSP = Op.getOperand(1);
7868 
7869   // Load the old link SP.
7870   SDValue LoadLinkSP =
7871       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7872 
7873   // Restore the stack pointer.
7874   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7875 
7876   // Store the old link SP.
7877   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7878 }
7879 
7880 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7881   MachineFunction &MF = DAG.getMachineFunction();
7882   bool isPPC64 = Subtarget.isPPC64();
7883   EVT PtrVT = getPointerTy(MF.getDataLayout());
7884 
7885   // Get current frame pointer save index.  The users of this index will be
7886   // primarily DYNALLOC instructions.
7887   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7888   int RASI = FI->getReturnAddrSaveIndex();
7889 
7890   // If the frame pointer save index hasn't been defined yet.
7891   if (!RASI) {
7892     // Find out what the fix offset of the frame pointer save area.
7893     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7894     // Allocate the frame index for frame pointer save area.
7895     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7896     // Save the result.
7897     FI->setReturnAddrSaveIndex(RASI);
7898   }
7899   return DAG.getFrameIndex(RASI, PtrVT);
7900 }
7901 
7902 SDValue
7903 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7904   MachineFunction &MF = DAG.getMachineFunction();
7905   bool isPPC64 = Subtarget.isPPC64();
7906   EVT PtrVT = getPointerTy(MF.getDataLayout());
7907 
7908   // Get current frame pointer save index.  The users of this index will be
7909   // primarily DYNALLOC instructions.
7910   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7911   int FPSI = FI->getFramePointerSaveIndex();
7912 
7913   // If the frame pointer save index hasn't been defined yet.
7914   if (!FPSI) {
7915     // Find out what the fix offset of the frame pointer save area.
7916     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7917     // Allocate the frame index for frame pointer save area.
7918     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7919     // Save the result.
7920     FI->setFramePointerSaveIndex(FPSI);
7921   }
7922   return DAG.getFrameIndex(FPSI, PtrVT);
7923 }
7924 
7925 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7926                                                    SelectionDAG &DAG) const {
7927   MachineFunction &MF = DAG.getMachineFunction();
7928   // Get the inputs.
7929   SDValue Chain = Op.getOperand(0);
7930   SDValue Size  = Op.getOperand(1);
7931   SDLoc dl(Op);
7932 
7933   // Get the correct type for pointers.
7934   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7935   // Negate the size.
7936   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7937                                 DAG.getConstant(0, dl, PtrVT), Size);
7938   // Construct a node for the frame pointer save index.
7939   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7940   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7941   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7942   if (hasInlineStackProbe(MF))
7943     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7944   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7945 }
7946 
7947 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7948                                                      SelectionDAG &DAG) const {
7949   MachineFunction &MF = DAG.getMachineFunction();
7950 
7951   bool isPPC64 = Subtarget.isPPC64();
7952   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7953 
7954   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7955   return DAG.getFrameIndex(FI, PtrVT);
7956 }
7957 
7958 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7959                                                SelectionDAG &DAG) const {
7960   SDLoc DL(Op);
7961   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7962                      DAG.getVTList(MVT::i32, MVT::Other),
7963                      Op.getOperand(0), Op.getOperand(1));
7964 }
7965 
7966 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7967                                                 SelectionDAG &DAG) const {
7968   SDLoc DL(Op);
7969   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7970                      Op.getOperand(0), Op.getOperand(1));
7971 }
7972 
7973 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7974   if (Op.getValueType().isVector())
7975     return LowerVectorLoad(Op, DAG);
7976 
7977   assert(Op.getValueType() == MVT::i1 &&
7978          "Custom lowering only for i1 loads");
7979 
7980   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7981 
7982   SDLoc dl(Op);
7983   LoadSDNode *LD = cast<LoadSDNode>(Op);
7984 
7985   SDValue Chain = LD->getChain();
7986   SDValue BasePtr = LD->getBasePtr();
7987   MachineMemOperand *MMO = LD->getMemOperand();
7988 
7989   SDValue NewLD =
7990       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7991                      BasePtr, MVT::i8, MMO);
7992   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7993 
7994   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7995   return DAG.getMergeValues(Ops, dl);
7996 }
7997 
7998 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7999   if (Op.getOperand(1).getValueType().isVector())
8000     return LowerVectorStore(Op, DAG);
8001 
8002   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
8003          "Custom lowering only for i1 stores");
8004 
8005   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
8006 
8007   SDLoc dl(Op);
8008   StoreSDNode *ST = cast<StoreSDNode>(Op);
8009 
8010   SDValue Chain = ST->getChain();
8011   SDValue BasePtr = ST->getBasePtr();
8012   SDValue Value = ST->getValue();
8013   MachineMemOperand *MMO = ST->getMemOperand();
8014 
8015   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
8016                       Value);
8017   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
8018 }
8019 
8020 // FIXME: Remove this once the ANDI glue bug is fixed:
8021 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8022   assert(Op.getValueType() == MVT::i1 &&
8023          "Custom lowering only for i1 results");
8024 
8025   SDLoc DL(Op);
8026   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
8027 }
8028 
8029 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
8030                                                SelectionDAG &DAG) const {
8031 
8032   // Implements a vector truncate that fits in a vector register as a shuffle.
8033   // We want to legalize vector truncates down to where the source fits in
8034   // a vector register (and target is therefore smaller than vector register
8035   // size).  At that point legalization will try to custom lower the sub-legal
8036   // result and get here - where we can contain the truncate as a single target
8037   // operation.
8038 
8039   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
8040   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
8041   //
8042   // We will implement it for big-endian ordering as this (where x denotes
8043   // undefined):
8044   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
8045   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
8046   //
8047   // The same operation in little-endian ordering will be:
8048   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
8049   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
8050 
8051   assert(Op.getValueType().isVector() && "Vector type expected.");
8052 
8053   SDLoc DL(Op);
8054   SDValue N1 = Op.getOperand(0);
8055   unsigned SrcSize = N1.getValueType().getSizeInBits();
8056   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
8057   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
8058 
8059   EVT TrgVT = Op.getValueType();
8060   unsigned TrgNumElts = TrgVT.getVectorNumElements();
8061   EVT EltVT = TrgVT.getVectorElementType();
8062   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8063   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8064 
8065   // First list the elements we want to keep.
8066   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
8067   SmallVector<int, 16> ShuffV;
8068   if (Subtarget.isLittleEndian())
8069     for (unsigned i = 0; i < TrgNumElts; ++i)
8070       ShuffV.push_back(i * SizeMult);
8071   else
8072     for (unsigned i = 1; i <= TrgNumElts; ++i)
8073       ShuffV.push_back(i * SizeMult - 1);
8074 
8075   // Populate the remaining elements with undefs.
8076   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
8077     // ShuffV.push_back(i + WideNumElts);
8078     ShuffV.push_back(WideNumElts + 1);
8079 
8080   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
8081   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
8082 }
8083 
8084 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
8085 /// possible.
8086 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
8087   // Not FP? Not a fsel.
8088   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
8089       !Op.getOperand(2).getValueType().isFloatingPoint())
8090     return Op;
8091 
8092   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
8093 
8094   EVT ResVT = Op.getValueType();
8095   EVT CmpVT = Op.getOperand(0).getValueType();
8096   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8097   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
8098   SDLoc dl(Op);
8099   SDNodeFlags Flags = Op.getNode()->getFlags();
8100 
8101   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
8102   // presence of infinities.
8103   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
8104     switch (CC) {
8105     default:
8106       break;
8107     case ISD::SETOGT:
8108     case ISD::SETGT:
8109       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
8110     case ISD::SETOLT:
8111     case ISD::SETLT:
8112       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
8113     }
8114   }
8115 
8116   // We might be able to do better than this under some circumstances, but in
8117   // general, fsel-based lowering of select is a finite-math-only optimization.
8118   // For more information, see section F.3 of the 2.06 ISA specification.
8119   // With ISA 3.0
8120   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
8121       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
8122     return Op;
8123 
8124   // If the RHS of the comparison is a 0.0, we don't need to do the
8125   // subtraction at all.
8126   SDValue Sel1;
8127   if (isFloatingPointZero(RHS))
8128     switch (CC) {
8129     default: break;       // SETUO etc aren't handled by fsel.
8130     case ISD::SETNE:
8131       std::swap(TV, FV);
8132       LLVM_FALLTHROUGH;
8133     case ISD::SETEQ:
8134       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8135         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8136       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8137       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8138         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8139       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8140                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
8141     case ISD::SETULT:
8142     case ISD::SETLT:
8143       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8144       LLVM_FALLTHROUGH;
8145     case ISD::SETOGE:
8146     case ISD::SETGE:
8147       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8148         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8149       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8150     case ISD::SETUGT:
8151     case ISD::SETGT:
8152       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8153       LLVM_FALLTHROUGH;
8154     case ISD::SETOLE:
8155     case ISD::SETLE:
8156       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8157         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8158       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8159                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
8160     }
8161 
8162   SDValue Cmp;
8163   switch (CC) {
8164   default: break;       // SETUO etc aren't handled by fsel.
8165   case ISD::SETNE:
8166     std::swap(TV, FV);
8167     LLVM_FALLTHROUGH;
8168   case ISD::SETEQ:
8169     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8170     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8171       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8172     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8173     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8174       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8175     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8176                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8177   case ISD::SETULT:
8178   case ISD::SETLT:
8179     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8180     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8181       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8182     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8183   case ISD::SETOGE:
8184   case ISD::SETGE:
8185     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8186     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8187       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8188     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8189   case ISD::SETUGT:
8190   case ISD::SETGT:
8191     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8192     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8193       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8194     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8195   case ISD::SETOLE:
8196   case ISD::SETLE:
8197     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8198     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8199       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8200     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8201   }
8202   return Op;
8203 }
8204 
8205 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8206                                                SelectionDAG &DAG,
8207                                                const SDLoc &dl) const {
8208   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8209   SDValue Src = Op.getOperand(0);
8210   if (Src.getValueType() == MVT::f32)
8211     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8212 
8213   SDValue Tmp;
8214   switch (Op.getSimpleValueType().SimpleTy) {
8215   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8216   case MVT::i32:
8217     Tmp = DAG.getNode(
8218         Op.getOpcode() == ISD::FP_TO_SINT
8219             ? PPCISD::FCTIWZ
8220             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8221         dl, MVT::f64, Src);
8222     break;
8223   case MVT::i64:
8224     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8225            "i64 FP_TO_UINT is supported only with FPCVT");
8226     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8227                                                         PPCISD::FCTIDUZ,
8228                       dl, MVT::f64, Src);
8229     break;
8230   }
8231 
8232   // Convert the FP value to an int value through memory.
8233   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8234     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
8235   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8236   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8237   MachinePointerInfo MPI =
8238       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8239 
8240   // Emit a store to the stack slot.
8241   SDValue Chain;
8242   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8243   if (i32Stack) {
8244     MachineFunction &MF = DAG.getMachineFunction();
8245     Alignment = Align(4);
8246     MachineMemOperand *MMO =
8247         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8248     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
8249     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8250               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8251   } else
8252     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment);
8253 
8254   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8255   // add in a bias on big endian.
8256   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8257     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8258                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8259     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8260   }
8261 
8262   RLI.Chain = Chain;
8263   RLI.Ptr = FIPtr;
8264   RLI.MPI = MPI;
8265   RLI.Alignment = Alignment;
8266 }
8267 
8268 /// Custom lowers floating point to integer conversions to use
8269 /// the direct move instructions available in ISA 2.07 to avoid the
8270 /// need for load/store combinations.
8271 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8272                                                     SelectionDAG &DAG,
8273                                                     const SDLoc &dl) const {
8274   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8275   SDValue Src = Op.getOperand(0);
8276 
8277   if (Src.getValueType() == MVT::f32)
8278     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8279 
8280   SDValue Tmp;
8281   switch (Op.getSimpleValueType().SimpleTy) {
8282   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8283   case MVT::i32:
8284     Tmp = DAG.getNode(
8285         Op.getOpcode() == ISD::FP_TO_SINT
8286             ? PPCISD::FCTIWZ
8287             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8288         dl, MVT::f64, Src);
8289     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
8290     break;
8291   case MVT::i64:
8292     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8293            "i64 FP_TO_UINT is supported only with FPCVT");
8294     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8295                                                         PPCISD::FCTIDUZ,
8296                       dl, MVT::f64, Src);
8297     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
8298     break;
8299   }
8300   return Tmp;
8301 }
8302 
8303 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8304                                           const SDLoc &dl) const {
8305 
8306   // FP to INT conversions are legal for f128.
8307   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
8308     return Op;
8309 
8310   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8311   // PPC (the libcall is not available).
8312   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
8313     if (Op.getValueType() == MVT::i32) {
8314       if (Op.getOpcode() == ISD::FP_TO_SINT) {
8315         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8316                                  MVT::f64, Op.getOperand(0),
8317                                  DAG.getIntPtrConstant(0, dl));
8318         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8319                                  MVT::f64, Op.getOperand(0),
8320                                  DAG.getIntPtrConstant(1, dl));
8321 
8322         // Add the two halves of the long double in round-to-zero mode.
8323         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8324 
8325         // Now use a smaller FP_TO_SINT.
8326         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8327       }
8328       if (Op.getOpcode() == ISD::FP_TO_UINT) {
8329         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8330         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8331         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
8332         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8333         // FIXME: generated code sucks.
8334         // TODO: Are there fast-math-flags to propagate to this FSUB?
8335         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
8336                                    Op.getOperand(0), Tmp);
8337         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8338         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
8339                            DAG.getConstant(0x80000000, dl, MVT::i32));
8340         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
8341                                     Op.getOperand(0));
8342         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
8343                                ISD::SETGE);
8344       }
8345     }
8346 
8347     return SDValue();
8348   }
8349 
8350   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8351     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8352 
8353   ReuseLoadInfo RLI;
8354   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8355 
8356   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8357                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8358 }
8359 
8360 // We're trying to insert a regular store, S, and then a load, L. If the
8361 // incoming value, O, is a load, we might just be able to have our load use the
8362 // address used by O. However, we don't know if anything else will store to
8363 // that address before we can load from it. To prevent this situation, we need
8364 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8365 // the same chain operand as O, we create a token factor from the chain results
8366 // of O and L, and we replace all uses of O's chain result with that token
8367 // factor (see spliceIntoChain below for this last part).
8368 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8369                                             ReuseLoadInfo &RLI,
8370                                             SelectionDAG &DAG,
8371                                             ISD::LoadExtType ET) const {
8372   SDLoc dl(Op);
8373   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8374                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8375   if (ET == ISD::NON_EXTLOAD &&
8376       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8377       isOperationLegalOrCustom(Op.getOpcode(),
8378                                Op.getOperand(0).getValueType())) {
8379 
8380     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8381     return true;
8382   }
8383 
8384   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8385   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8386       LD->isNonTemporal())
8387     return false;
8388   if (LD->getMemoryVT() != MemVT)
8389     return false;
8390 
8391   RLI.Ptr = LD->getBasePtr();
8392   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8393     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8394            "Non-pre-inc AM on PPC?");
8395     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8396                           LD->getOffset());
8397   }
8398 
8399   RLI.Chain = LD->getChain();
8400   RLI.MPI = LD->getPointerInfo();
8401   RLI.IsDereferenceable = LD->isDereferenceable();
8402   RLI.IsInvariant = LD->isInvariant();
8403   RLI.Alignment = LD->getAlign();
8404   RLI.AAInfo = LD->getAAInfo();
8405   RLI.Ranges = LD->getRanges();
8406 
8407   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8408   return true;
8409 }
8410 
8411 // Given the head of the old chain, ResChain, insert a token factor containing
8412 // it and NewResChain, and make users of ResChain now be users of that token
8413 // factor.
8414 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8415 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8416                                         SDValue NewResChain,
8417                                         SelectionDAG &DAG) const {
8418   if (!ResChain)
8419     return;
8420 
8421   SDLoc dl(NewResChain);
8422 
8423   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8424                            NewResChain, DAG.getUNDEF(MVT::Other));
8425   assert(TF.getNode() != NewResChain.getNode() &&
8426          "A new TF really is required here");
8427 
8428   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8429   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8430 }
8431 
8432 /// Analyze profitability of direct move
8433 /// prefer float load to int load plus direct move
8434 /// when there is no integer use of int load
8435 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8436   SDNode *Origin = Op.getOperand(0).getNode();
8437   if (Origin->getOpcode() != ISD::LOAD)
8438     return true;
8439 
8440   // If there is no LXSIBZX/LXSIHZX, like Power8,
8441   // prefer direct move if the memory size is 1 or 2 bytes.
8442   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8443   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8444     return true;
8445 
8446   for (SDNode::use_iterator UI = Origin->use_begin(),
8447                             UE = Origin->use_end();
8448        UI != UE; ++UI) {
8449 
8450     // Only look at the users of the loaded value.
8451     if (UI.getUse().get().getResNo() != 0)
8452       continue;
8453 
8454     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8455         UI->getOpcode() != ISD::UINT_TO_FP)
8456       return true;
8457   }
8458 
8459   return false;
8460 }
8461 
8462 /// Custom lowers integer to floating point conversions to use
8463 /// the direct move instructions available in ISA 2.07 to avoid the
8464 /// need for load/store combinations.
8465 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8466                                                     SelectionDAG &DAG,
8467                                                     const SDLoc &dl) const {
8468   assert((Op.getValueType() == MVT::f32 ||
8469           Op.getValueType() == MVT::f64) &&
8470          "Invalid floating point type as target of conversion");
8471   assert(Subtarget.hasFPCVT() &&
8472          "Int to FP conversions with direct moves require FPCVT");
8473   SDValue FP;
8474   SDValue Src = Op.getOperand(0);
8475   bool SinglePrec = Op.getValueType() == MVT::f32;
8476   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8477   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
8478   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
8479                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
8480 
8481   if (WordInt) {
8482     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
8483                      dl, MVT::f64, Src);
8484     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8485   }
8486   else {
8487     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
8488     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8489   }
8490 
8491   return FP;
8492 }
8493 
8494 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8495 
8496   EVT VecVT = Vec.getValueType();
8497   assert(VecVT.isVector() && "Expected a vector type.");
8498   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8499 
8500   EVT EltVT = VecVT.getVectorElementType();
8501   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8502   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8503 
8504   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8505   SmallVector<SDValue, 16> Ops(NumConcat);
8506   Ops[0] = Vec;
8507   SDValue UndefVec = DAG.getUNDEF(VecVT);
8508   for (unsigned i = 1; i < NumConcat; ++i)
8509     Ops[i] = UndefVec;
8510 
8511   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8512 }
8513 
8514 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8515                                                 const SDLoc &dl) const {
8516 
8517   unsigned Opc = Op.getOpcode();
8518   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
8519          "Unexpected conversion type");
8520   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8521          "Supports conversions to v2f64/v4f32 only.");
8522 
8523   bool SignedConv = Opc == ISD::SINT_TO_FP;
8524   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8525 
8526   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
8527   EVT WideVT = Wide.getValueType();
8528   unsigned WideNumElts = WideVT.getVectorNumElements();
8529   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8530 
8531   SmallVector<int, 16> ShuffV;
8532   for (unsigned i = 0; i < WideNumElts; ++i)
8533     ShuffV.push_back(i + WideNumElts);
8534 
8535   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8536   int SaveElts = FourEltRes ? 4 : 2;
8537   if (Subtarget.isLittleEndian())
8538     for (int i = 0; i < SaveElts; i++)
8539       ShuffV[i * Stride] = i;
8540   else
8541     for (int i = 1; i <= SaveElts; i++)
8542       ShuffV[i * Stride - 1] = i - 1;
8543 
8544   SDValue ShuffleSrc2 =
8545       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8546   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8547 
8548   SDValue Extend;
8549   if (SignedConv) {
8550     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8551     EVT ExtVT = Op.getOperand(0).getValueType();
8552     if (Subtarget.hasP9Altivec())
8553       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8554                                IntermediateVT.getVectorNumElements());
8555 
8556     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8557                          DAG.getValueType(ExtVT));
8558   } else
8559     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8560 
8561   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8562 }
8563 
8564 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8565                                           SelectionDAG &DAG) const {
8566   SDLoc dl(Op);
8567 
8568   EVT InVT = Op.getOperand(0).getValueType();
8569   EVT OutVT = Op.getValueType();
8570   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8571       isOperationCustom(Op.getOpcode(), InVT))
8572     return LowerINT_TO_FPVector(Op, DAG, dl);
8573 
8574   // Conversions to f128 are legal.
8575   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
8576     return Op;
8577 
8578   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
8579     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
8580       return SDValue();
8581 
8582     SDValue Value = Op.getOperand(0);
8583     // The values are now known to be -1 (false) or 1 (true). To convert this
8584     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8585     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8586     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8587 
8588     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8589 
8590     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8591 
8592     if (Op.getValueType() != MVT::v4f64)
8593       Value = DAG.getNode(ISD::FP_ROUND, dl,
8594                           Op.getValueType(), Value,
8595                           DAG.getIntPtrConstant(1, dl));
8596     return Value;
8597   }
8598 
8599   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8600   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8601     return SDValue();
8602 
8603   if (Op.getOperand(0).getValueType() == MVT::i1)
8604     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
8605                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8606                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8607 
8608   // If we have direct moves, we can do all the conversion, skip the store/load
8609   // however, without FPCVT we can't do most conversions.
8610   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8611       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8612     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8613 
8614   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8615          "UINT_TO_FP is supported only with FPCVT");
8616 
8617   // If we have FCFIDS, then use it when converting to single-precision.
8618   // Otherwise, convert to double-precision and then round.
8619   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8620                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8621                                                             : PPCISD::FCFIDS)
8622                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8623                                                             : PPCISD::FCFID);
8624   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8625                   ? MVT::f32
8626                   : MVT::f64;
8627 
8628   if (Op.getOperand(0).getValueType() == MVT::i64) {
8629     SDValue SINT = Op.getOperand(0);
8630     // When converting to single-precision, we actually need to convert
8631     // to double-precision first and then round to single-precision.
8632     // To avoid double-rounding effects during that operation, we have
8633     // to prepare the input operand.  Bits that might be truncated when
8634     // converting to double-precision are replaced by a bit that won't
8635     // be lost at this stage, but is below the single-precision rounding
8636     // position.
8637     //
8638     // However, if -enable-unsafe-fp-math is in effect, accept double
8639     // rounding to avoid the extra overhead.
8640     if (Op.getValueType() == MVT::f32 &&
8641         !Subtarget.hasFPCVT() &&
8642         !DAG.getTarget().Options.UnsafeFPMath) {
8643 
8644       // Twiddle input to make sure the low 11 bits are zero.  (If this
8645       // is the case, we are guaranteed the value will fit into the 53 bit
8646       // mantissa of an IEEE double-precision value without rounding.)
8647       // If any of those low 11 bits were not zero originally, make sure
8648       // bit 12 (value 2048) is set instead, so that the final rounding
8649       // to single-precision gets the correct result.
8650       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8651                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8652       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8653                           Round, DAG.getConstant(2047, dl, MVT::i64));
8654       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8655       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8656                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8657 
8658       // However, we cannot use that value unconditionally: if the magnitude
8659       // of the input value is small, the bit-twiddling we did above might
8660       // end up visibly changing the output.  Fortunately, in that case, we
8661       // don't need to twiddle bits since the original input will convert
8662       // exactly to double-precision floating-point already.  Therefore,
8663       // construct a conditional to use the original value if the top 11
8664       // bits are all sign-bit copies, and use the rounded value computed
8665       // above otherwise.
8666       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8667                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8668       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8669                          Cond, DAG.getConstant(1, dl, MVT::i64));
8670       Cond = DAG.getSetCC(
8671           dl,
8672           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8673           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8674 
8675       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8676     }
8677 
8678     ReuseLoadInfo RLI;
8679     SDValue Bits;
8680 
8681     MachineFunction &MF = DAG.getMachineFunction();
8682     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8683       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8684                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8685       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8686     } else if (Subtarget.hasLFIWAX() &&
8687                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8688       MachineMemOperand *MMO =
8689         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8690                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8691       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8692       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8693                                      DAG.getVTList(MVT::f64, MVT::Other),
8694                                      Ops, MVT::i32, MMO);
8695       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8696     } else if (Subtarget.hasFPCVT() &&
8697                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8698       MachineMemOperand *MMO =
8699         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8700                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8701       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8702       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8703                                      DAG.getVTList(MVT::f64, MVT::Other),
8704                                      Ops, MVT::i32, MMO);
8705       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8706     } else if (((Subtarget.hasLFIWAX() &&
8707                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8708                 (Subtarget.hasFPCVT() &&
8709                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8710                SINT.getOperand(0).getValueType() == MVT::i32) {
8711       MachineFrameInfo &MFI = MF.getFrameInfo();
8712       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8713 
8714       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8715       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8716 
8717       SDValue Store =
8718           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8719                        MachinePointerInfo::getFixedStack(
8720                            DAG.getMachineFunction(), FrameIdx));
8721 
8722       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8723              "Expected an i32 store");
8724 
8725       RLI.Ptr = FIdx;
8726       RLI.Chain = Store;
8727       RLI.MPI =
8728           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8729       RLI.Alignment = Align(4);
8730 
8731       MachineMemOperand *MMO =
8732         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8733                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8734       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8735       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8736                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8737                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8738                                      Ops, MVT::i32, MMO);
8739     } else
8740       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8741 
8742     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
8743 
8744     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8745       FP = DAG.getNode(ISD::FP_ROUND, dl,
8746                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8747     return FP;
8748   }
8749 
8750   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
8751          "Unhandled INT_TO_FP type in custom expander!");
8752   // Since we only generate this in 64-bit mode, we can take advantage of
8753   // 64-bit registers.  In particular, sign extend the input value into the
8754   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8755   // then lfd it and fcfid it.
8756   MachineFunction &MF = DAG.getMachineFunction();
8757   MachineFrameInfo &MFI = MF.getFrameInfo();
8758   EVT PtrVT = getPointerTy(MF.getDataLayout());
8759 
8760   SDValue Ld;
8761   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8762     ReuseLoadInfo RLI;
8763     bool ReusingLoad;
8764     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
8765                                             DAG))) {
8766       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8767       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8768 
8769       SDValue Store =
8770           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8771                        MachinePointerInfo::getFixedStack(
8772                            DAG.getMachineFunction(), FrameIdx));
8773 
8774       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8775              "Expected an i32 store");
8776 
8777       RLI.Ptr = FIdx;
8778       RLI.Chain = Store;
8779       RLI.MPI =
8780           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8781       RLI.Alignment = Align(4);
8782     }
8783 
8784     MachineMemOperand *MMO =
8785       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8786                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8787     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8788     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
8789                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
8790                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
8791                                  Ops, MVT::i32, MMO);
8792     if (ReusingLoad)
8793       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8794   } else {
8795     assert(Subtarget.isPPC64() &&
8796            "i32->FP without LFIWAX supported only on PPC64");
8797 
8798     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8799     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8800 
8801     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
8802                                 Op.getOperand(0));
8803 
8804     // STD the extended value into the stack slot.
8805     SDValue Store = DAG.getStore(
8806         DAG.getEntryNode(), dl, Ext64, FIdx,
8807         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8808 
8809     // Load the value as a double.
8810     Ld = DAG.getLoad(
8811         MVT::f64, dl, Store, FIdx,
8812         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8813   }
8814 
8815   // FCFID it and return it.
8816   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
8817   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8818     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8819                      DAG.getIntPtrConstant(0, dl));
8820   return FP;
8821 }
8822 
8823 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8824                                             SelectionDAG &DAG) const {
8825   SDLoc dl(Op);
8826   /*
8827    The rounding mode is in bits 30:31 of FPSR, and has the following
8828    settings:
8829      00 Round to nearest
8830      01 Round to 0
8831      10 Round to +inf
8832      11 Round to -inf
8833 
8834   FLT_ROUNDS, on the other hand, expects the following:
8835     -1 Undefined
8836      0 Round to 0
8837      1 Round to nearest
8838      2 Round to +inf
8839      3 Round to -inf
8840 
8841   To perform the conversion, we do:
8842     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8843   */
8844 
8845   MachineFunction &MF = DAG.getMachineFunction();
8846   EVT VT = Op.getValueType();
8847   EVT PtrVT = getPointerTy(MF.getDataLayout());
8848 
8849   // Save FP Control Word to register
8850   SDValue Chain = Op.getOperand(0);
8851   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8852   Chain = MFFS.getValue(1);
8853 
8854   // Save FP register to stack slot
8855   int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8856   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8857   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8858 
8859   // Load FP Control Word from low 32 bits of stack slot.
8860   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8861   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8862   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8863   Chain = CWD.getValue(1);
8864 
8865   // Transform as necessary
8866   SDValue CWD1 =
8867     DAG.getNode(ISD::AND, dl, MVT::i32,
8868                 CWD, DAG.getConstant(3, dl, MVT::i32));
8869   SDValue CWD2 =
8870     DAG.getNode(ISD::SRL, dl, MVT::i32,
8871                 DAG.getNode(ISD::AND, dl, MVT::i32,
8872                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8873                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8874                             DAG.getConstant(3, dl, MVT::i32)),
8875                 DAG.getConstant(1, dl, MVT::i32));
8876 
8877   SDValue RetVal =
8878     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8879 
8880   RetVal =
8881       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8882                   dl, VT, RetVal);
8883 
8884   return DAG.getMergeValues({RetVal, Chain}, dl);
8885 }
8886 
8887 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8888   EVT VT = Op.getValueType();
8889   unsigned BitWidth = VT.getSizeInBits();
8890   SDLoc dl(Op);
8891   assert(Op.getNumOperands() == 3 &&
8892          VT == Op.getOperand(1).getValueType() &&
8893          "Unexpected SHL!");
8894 
8895   // Expand into a bunch of logical ops.  Note that these ops
8896   // depend on the PPC behavior for oversized shift amounts.
8897   SDValue Lo = Op.getOperand(0);
8898   SDValue Hi = Op.getOperand(1);
8899   SDValue Amt = Op.getOperand(2);
8900   EVT AmtVT = Amt.getValueType();
8901 
8902   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8903                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8904   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8905   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8906   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8907   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8908                              DAG.getConstant(-BitWidth, dl, AmtVT));
8909   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8910   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8911   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8912   SDValue OutOps[] = { OutLo, OutHi };
8913   return DAG.getMergeValues(OutOps, dl);
8914 }
8915 
8916 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8917   EVT VT = Op.getValueType();
8918   SDLoc dl(Op);
8919   unsigned BitWidth = VT.getSizeInBits();
8920   assert(Op.getNumOperands() == 3 &&
8921          VT == Op.getOperand(1).getValueType() &&
8922          "Unexpected SRL!");
8923 
8924   // Expand into a bunch of logical ops.  Note that these ops
8925   // depend on the PPC behavior for oversized shift amounts.
8926   SDValue Lo = Op.getOperand(0);
8927   SDValue Hi = Op.getOperand(1);
8928   SDValue Amt = Op.getOperand(2);
8929   EVT AmtVT = Amt.getValueType();
8930 
8931   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8932                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8933   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8934   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8935   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8936   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8937                              DAG.getConstant(-BitWidth, dl, AmtVT));
8938   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8939   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8940   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8941   SDValue OutOps[] = { OutLo, OutHi };
8942   return DAG.getMergeValues(OutOps, dl);
8943 }
8944 
8945 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8946   SDLoc dl(Op);
8947   EVT VT = Op.getValueType();
8948   unsigned BitWidth = VT.getSizeInBits();
8949   assert(Op.getNumOperands() == 3 &&
8950          VT == Op.getOperand(1).getValueType() &&
8951          "Unexpected SRA!");
8952 
8953   // Expand into a bunch of logical ops, followed by a select_cc.
8954   SDValue Lo = Op.getOperand(0);
8955   SDValue Hi = Op.getOperand(1);
8956   SDValue Amt = Op.getOperand(2);
8957   EVT AmtVT = Amt.getValueType();
8958 
8959   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8960                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8961   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8962   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8963   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8964   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8965                              DAG.getConstant(-BitWidth, dl, AmtVT));
8966   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8967   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8968   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8969                                   Tmp4, Tmp6, ISD::SETLE);
8970   SDValue OutOps[] = { OutLo, OutHi };
8971   return DAG.getMergeValues(OutOps, dl);
8972 }
8973 
8974 //===----------------------------------------------------------------------===//
8975 // Vector related lowering.
8976 //
8977 
8978 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8979 /// element size of SplatSize. Cast the result to VT.
8980 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8981                                       SelectionDAG &DAG, const SDLoc &dl) {
8982   static const MVT VTys[] = { // canonical VT to use for each size.
8983     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8984   };
8985 
8986   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8987 
8988   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8989   if (Val == ((1LU << (SplatSize * 8)) - 1)) {
8990     SplatSize = 1;
8991     Val = 0xFF;
8992   }
8993 
8994   EVT CanonicalVT = VTys[SplatSize-1];
8995 
8996   // Build a canonical splat for this value.
8997   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8998 }
8999 
9000 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
9001 /// specified intrinsic ID.
9002 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
9003                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
9004   if (DestVT == MVT::Other) DestVT = Op.getValueType();
9005   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9006                      DAG.getConstant(IID, dl, MVT::i32), Op);
9007 }
9008 
9009 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
9010 /// specified intrinsic ID.
9011 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
9012                                 SelectionDAG &DAG, const SDLoc &dl,
9013                                 EVT DestVT = MVT::Other) {
9014   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
9015   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9016                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
9017 }
9018 
9019 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
9020 /// specified intrinsic ID.
9021 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
9022                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
9023                                 EVT DestVT = MVT::Other) {
9024   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
9025   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9026                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
9027 }
9028 
9029 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
9030 /// amount.  The result has the specified value type.
9031 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
9032                            SelectionDAG &DAG, const SDLoc &dl) {
9033   // Force LHS/RHS to be the right type.
9034   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
9035   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
9036 
9037   int Ops[16];
9038   for (unsigned i = 0; i != 16; ++i)
9039     Ops[i] = i + Amt;
9040   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
9041   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9042 }
9043 
9044 /// Do we have an efficient pattern in a .td file for this node?
9045 ///
9046 /// \param V - pointer to the BuildVectorSDNode being matched
9047 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
9048 ///
9049 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
9050 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
9051 /// the opposite is true (expansion is beneficial) are:
9052 /// - The node builds a vector out of integers that are not 32 or 64-bits
9053 /// - The node builds a vector out of constants
9054 /// - The node is a "load-and-splat"
9055 /// In all other cases, we will choose to keep the BUILD_VECTOR.
9056 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
9057                                             bool HasDirectMove,
9058                                             bool HasP8Vector) {
9059   EVT VecVT = V->getValueType(0);
9060   bool RightType = VecVT == MVT::v2f64 ||
9061     (HasP8Vector && VecVT == MVT::v4f32) ||
9062     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
9063   if (!RightType)
9064     return false;
9065 
9066   bool IsSplat = true;
9067   bool IsLoad = false;
9068   SDValue Op0 = V->getOperand(0);
9069 
9070   // This function is called in a block that confirms the node is not a constant
9071   // splat. So a constant BUILD_VECTOR here means the vector is built out of
9072   // different constants.
9073   if (V->isConstant())
9074     return false;
9075   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9076     if (V->getOperand(i).isUndef())
9077       return false;
9078     // We want to expand nodes that represent load-and-splat even if the
9079     // loaded value is a floating point truncation or conversion to int.
9080     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9081         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9082          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9083         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9084          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9085         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9086          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9087       IsLoad = true;
9088     // If the operands are different or the input is not a load and has more
9089     // uses than just this BV node, then it isn't a splat.
9090     if (V->getOperand(i) != Op0 ||
9091         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9092       IsSplat = false;
9093   }
9094   return !(IsSplat && IsLoad);
9095 }
9096 
9097 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9098 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9099 
9100   SDLoc dl(Op);
9101   SDValue Op0 = Op->getOperand(0);
9102 
9103   if (!EnableQuadPrecision ||
9104       (Op.getValueType() != MVT::f128 ) ||
9105       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9106       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
9107       (Op0.getOperand(1).getValueType() != MVT::i64))
9108     return SDValue();
9109 
9110   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9111                      Op0.getOperand(1));
9112 }
9113 
9114 static const SDValue *getNormalLoadInput(const SDValue &Op) {
9115   const SDValue *InputLoad = &Op;
9116   if (InputLoad->getOpcode() == ISD::BITCAST)
9117     InputLoad = &InputLoad->getOperand(0);
9118   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9119       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED)
9120     InputLoad = &InputLoad->getOperand(0);
9121   if (InputLoad->getOpcode() != ISD::LOAD)
9122     return nullptr;
9123   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9124   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9125 }
9126 
9127 // Convert the argument APFloat to a single precision APFloat if there is no
9128 // loss in information during the conversion to single precision APFloat and the
9129 // resulting number is not a denormal number. Return true if successful.
9130 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9131   APFloat APFloatToConvert = ArgAPFloat;
9132   bool LosesInfo = true;
9133   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9134                            &LosesInfo);
9135   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9136   if (Success)
9137     ArgAPFloat = APFloatToConvert;
9138   return Success;
9139 }
9140 
9141 // Bitcast the argument APInt to a double and convert it to a single precision
9142 // APFloat, bitcast the APFloat to an APInt and assign it to the original
9143 // argument if there is no loss in information during the conversion from
9144 // double to single precision APFloat and the resulting number is not a denormal
9145 // number. Return true if successful.
9146 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9147   double DpValue = ArgAPInt.bitsToDouble();
9148   APFloat APFloatDp(DpValue);
9149   bool Success = convertToNonDenormSingle(APFloatDp);
9150   if (Success)
9151     ArgAPInt = APFloatDp.bitcastToAPInt();
9152   return Success;
9153 }
9154 
9155 // If this is a case we can't handle, return null and let the default
9156 // expansion code take care of it.  If we CAN select this case, and if it
9157 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9158 // this case more efficiently than a constant pool load, lower it to the
9159 // sequence of ops that should be used.
9160 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9161                                              SelectionDAG &DAG) const {
9162   SDLoc dl(Op);
9163   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9164   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9165 
9166   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
9167     // We first build an i32 vector, load it into a QPX register,
9168     // then convert it to a floating-point vector and compare it
9169     // to a zero vector to get the boolean result.
9170     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9171     int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
9172     MachinePointerInfo PtrInfo =
9173         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9174     EVT PtrVT = getPointerTy(DAG.getDataLayout());
9175     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9176 
9177     assert(BVN->getNumOperands() == 4 &&
9178       "BUILD_VECTOR for v4i1 does not have 4 operands");
9179 
9180     bool IsConst = true;
9181     for (unsigned i = 0; i < 4; ++i) {
9182       if (BVN->getOperand(i).isUndef()) continue;
9183       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
9184         IsConst = false;
9185         break;
9186       }
9187     }
9188 
9189     if (IsConst) {
9190       Constant *One =
9191         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
9192       Constant *NegOne =
9193         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
9194 
9195       Constant *CV[4];
9196       for (unsigned i = 0; i < 4; ++i) {
9197         if (BVN->getOperand(i).isUndef())
9198           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
9199         else if (isNullConstant(BVN->getOperand(i)))
9200           CV[i] = NegOne;
9201         else
9202           CV[i] = One;
9203       }
9204 
9205       Constant *CP = ConstantVector::get(CV);
9206       SDValue CPIdx =
9207           DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), Align(16));
9208 
9209       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
9210       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
9211       return DAG.getMemIntrinsicNode(
9212           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
9213           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
9214     }
9215 
9216     SmallVector<SDValue, 4> Stores;
9217     for (unsigned i = 0; i < 4; ++i) {
9218       if (BVN->getOperand(i).isUndef()) continue;
9219 
9220       unsigned Offset = 4*i;
9221       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9222       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9223 
9224       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
9225       if (StoreSize > 4) {
9226         Stores.push_back(
9227             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
9228                               PtrInfo.getWithOffset(Offset), MVT::i32));
9229       } else {
9230         SDValue StoreValue = BVN->getOperand(i);
9231         if (StoreSize < 4)
9232           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
9233 
9234         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
9235                                       PtrInfo.getWithOffset(Offset)));
9236       }
9237     }
9238 
9239     SDValue StoreChain;
9240     if (!Stores.empty())
9241       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9242     else
9243       StoreChain = DAG.getEntryNode();
9244 
9245     // Now load from v4i32 into the QPX register; this will extend it to
9246     // v4i64 but not yet convert it to a floating point. Nevertheless, this
9247     // is typed as v4f64 because the QPX register integer states are not
9248     // explicitly represented.
9249 
9250     SDValue Ops[] = {StoreChain,
9251                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
9252                      FIdx};
9253     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
9254 
9255     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
9256       dl, VTs, Ops, MVT::v4i32, PtrInfo);
9257     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9258       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
9259       LoadedVect);
9260 
9261     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
9262 
9263     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
9264   }
9265 
9266   // All other QPX vectors are handled by generic code.
9267   if (Subtarget.hasQPX())
9268     return SDValue();
9269 
9270   // Check if this is a splat of a constant value.
9271   APInt APSplatBits, APSplatUndef;
9272   unsigned SplatBitSize;
9273   bool HasAnyUndefs;
9274   bool BVNIsConstantSplat =
9275       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9276                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9277 
9278   // If it is a splat of a double, check if we can shrink it to a 32 bit
9279   // non-denormal float which when converted back to double gives us the same
9280   // double. This is to exploit the XXSPLTIDP instruction.
9281   if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() &&
9282       (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) &&
9283       convertToNonDenormSingle(APSplatBits)) {
9284     SDValue SplatNode = DAG.getNode(
9285         PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9286         DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9287     return DAG.getBitcast(Op.getValueType(), SplatNode);
9288   }
9289 
9290   if (!BVNIsConstantSplat || SplatBitSize > 32) {
9291 
9292     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
9293     // Handle load-and-splat patterns as we have instructions that will do this
9294     // in one go.
9295     if (InputLoad && DAG.isSplatValue(Op, true)) {
9296       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9297 
9298       // We have handling for 4 and 8 byte elements.
9299       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9300 
9301       // Checking for a single use of this load, we have to check for vector
9302       // width (128 bits) / ElementSize uses (since each operand of the
9303       // BUILD_VECTOR is a separate use of the value.
9304       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
9305           ((Subtarget.hasVSX() && ElementSize == 64) ||
9306            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9307         SDValue Ops[] = {
9308           LD->getChain(),    // Chain
9309           LD->getBasePtr(),  // Ptr
9310           DAG.getValueType(Op.getValueType()) // VT
9311         };
9312         return
9313           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
9314                                   DAG.getVTList(Op.getValueType(), MVT::Other),
9315                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
9316       }
9317     }
9318 
9319     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
9320     // lowered to VSX instructions under certain conditions.
9321     // Without VSX, there is no pattern more efficient than expanding the node.
9322     if (Subtarget.hasVSX() &&
9323         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9324                                         Subtarget.hasP8Vector()))
9325       return Op;
9326     return SDValue();
9327   }
9328 
9329   uint64_t SplatBits = APSplatBits.getZExtValue();
9330   uint64_t SplatUndef = APSplatUndef.getZExtValue();
9331   unsigned SplatSize = SplatBitSize / 8;
9332 
9333   // First, handle single instruction cases.
9334 
9335   // All zeros?
9336   if (SplatBits == 0) {
9337     // Canonicalize all zero vectors to be v4i32.
9338     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9339       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9340       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9341     }
9342     return Op;
9343   }
9344 
9345   // We have XXSPLTIW for constant splats four bytes wide.
9346   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9347   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9348   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9349   // turned into a 4-byte splat of 0xABABABAB.
9350   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9351     return getCanonicalConstSplat((SplatBits |= SplatBits << 16), SplatSize * 2,
9352                                   Op.getValueType(), DAG, dl);
9353 
9354   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9355     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9356                                   dl);
9357 
9358   // We have XXSPLTIB for constant splats one byte wide.
9359   if (Subtarget.hasP9Vector() && SplatSize == 1)
9360     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9361                                   dl);
9362 
9363   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9364   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9365                     (32-SplatBitSize));
9366   if (SextVal >= -16 && SextVal <= 15)
9367     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9368                                   dl);
9369 
9370   // Two instruction sequences.
9371 
9372   // If this value is in the range [-32,30] and is even, use:
9373   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9374   // If this value is in the range [17,31] and is odd, use:
9375   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9376   // If this value is in the range [-31,-17] and is odd, use:
9377   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9378   // Note the last two are three-instruction sequences.
9379   if (SextVal >= -32 && SextVal <= 31) {
9380     // To avoid having these optimizations undone by constant folding,
9381     // we convert to a pseudo that will be expanded later into one of
9382     // the above forms.
9383     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9384     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9385               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9386     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9387     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9388     if (VT == Op.getValueType())
9389       return RetVal;
9390     else
9391       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9392   }
9393 
9394   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9395   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9396   // for fneg/fabs.
9397   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9398     // Make -1 and vspltisw -1:
9399     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9400 
9401     // Make the VSLW intrinsic, computing 0x8000_0000.
9402     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9403                                    OnesV, DAG, dl);
9404 
9405     // xor by OnesV to invert it.
9406     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9407     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9408   }
9409 
9410   // Check to see if this is a wide variety of vsplti*, binop self cases.
9411   static const signed char SplatCsts[] = {
9412     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9413     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9414   };
9415 
9416   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9417     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9418     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9419     int i = SplatCsts[idx];
9420 
9421     // Figure out what shift amount will be used by altivec if shifted by i in
9422     // this splat size.
9423     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9424 
9425     // vsplti + shl self.
9426     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9427       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9428       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9429         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9430         Intrinsic::ppc_altivec_vslw
9431       };
9432       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9433       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9434     }
9435 
9436     // vsplti + srl self.
9437     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9438       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9439       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9440         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9441         Intrinsic::ppc_altivec_vsrw
9442       };
9443       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9444       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9445     }
9446 
9447     // vsplti + sra self.
9448     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9449       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9450       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9451         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9452         Intrinsic::ppc_altivec_vsraw
9453       };
9454       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9455       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9456     }
9457 
9458     // vsplti + rol self.
9459     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9460                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9461       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9462       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9463         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9464         Intrinsic::ppc_altivec_vrlw
9465       };
9466       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9467       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9468     }
9469 
9470     // t = vsplti c, result = vsldoi t, t, 1
9471     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9472       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9473       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9474       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9475     }
9476     // t = vsplti c, result = vsldoi t, t, 2
9477     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9478       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9479       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9480       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9481     }
9482     // t = vsplti c, result = vsldoi t, t, 3
9483     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9484       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9485       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9486       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9487     }
9488   }
9489 
9490   return SDValue();
9491 }
9492 
9493 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9494 /// the specified operations to build the shuffle.
9495 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9496                                       SDValue RHS, SelectionDAG &DAG,
9497                                       const SDLoc &dl) {
9498   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9499   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9500   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9501 
9502   enum {
9503     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9504     OP_VMRGHW,
9505     OP_VMRGLW,
9506     OP_VSPLTISW0,
9507     OP_VSPLTISW1,
9508     OP_VSPLTISW2,
9509     OP_VSPLTISW3,
9510     OP_VSLDOI4,
9511     OP_VSLDOI8,
9512     OP_VSLDOI12
9513   };
9514 
9515   if (OpNum == OP_COPY) {
9516     if (LHSID == (1*9+2)*9+3) return LHS;
9517     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9518     return RHS;
9519   }
9520 
9521   SDValue OpLHS, OpRHS;
9522   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9523   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9524 
9525   int ShufIdxs[16];
9526   switch (OpNum) {
9527   default: llvm_unreachable("Unknown i32 permute!");
9528   case OP_VMRGHW:
9529     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9530     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9531     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9532     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9533     break;
9534   case OP_VMRGLW:
9535     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9536     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9537     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9538     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9539     break;
9540   case OP_VSPLTISW0:
9541     for (unsigned i = 0; i != 16; ++i)
9542       ShufIdxs[i] = (i&3)+0;
9543     break;
9544   case OP_VSPLTISW1:
9545     for (unsigned i = 0; i != 16; ++i)
9546       ShufIdxs[i] = (i&3)+4;
9547     break;
9548   case OP_VSPLTISW2:
9549     for (unsigned i = 0; i != 16; ++i)
9550       ShufIdxs[i] = (i&3)+8;
9551     break;
9552   case OP_VSPLTISW3:
9553     for (unsigned i = 0; i != 16; ++i)
9554       ShufIdxs[i] = (i&3)+12;
9555     break;
9556   case OP_VSLDOI4:
9557     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9558   case OP_VSLDOI8:
9559     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9560   case OP_VSLDOI12:
9561     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9562   }
9563   EVT VT = OpLHS.getValueType();
9564   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9565   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9566   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9567   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9568 }
9569 
9570 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9571 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9572 /// SDValue.
9573 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9574                                            SelectionDAG &DAG) const {
9575   const unsigned BytesInVector = 16;
9576   bool IsLE = Subtarget.isLittleEndian();
9577   SDLoc dl(N);
9578   SDValue V1 = N->getOperand(0);
9579   SDValue V2 = N->getOperand(1);
9580   unsigned ShiftElts = 0, InsertAtByte = 0;
9581   bool Swap = false;
9582 
9583   // Shifts required to get the byte we want at element 7.
9584   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9585                                    0, 15, 14, 13, 12, 11, 10, 9};
9586   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9587                                 1, 2,  3,  4,  5,  6,  7,  8};
9588 
9589   ArrayRef<int> Mask = N->getMask();
9590   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9591 
9592   // For each mask element, find out if we're just inserting something
9593   // from V2 into V1 or vice versa.
9594   // Possible permutations inserting an element from V2 into V1:
9595   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9596   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9597   //   ...
9598   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9599   // Inserting from V1 into V2 will be similar, except mask range will be
9600   // [16,31].
9601 
9602   bool FoundCandidate = false;
9603   // If both vector operands for the shuffle are the same vector, the mask
9604   // will contain only elements from the first one and the second one will be
9605   // undef.
9606   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9607   // Go through the mask of half-words to find an element that's being moved
9608   // from one vector to the other.
9609   for (unsigned i = 0; i < BytesInVector; ++i) {
9610     unsigned CurrentElement = Mask[i];
9611     // If 2nd operand is undefined, we should only look for element 7 in the
9612     // Mask.
9613     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9614       continue;
9615 
9616     bool OtherElementsInOrder = true;
9617     // Examine the other elements in the Mask to see if they're in original
9618     // order.
9619     for (unsigned j = 0; j < BytesInVector; ++j) {
9620       if (j == i)
9621         continue;
9622       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9623       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9624       // in which we always assume we're always picking from the 1st operand.
9625       int MaskOffset =
9626           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9627       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9628         OtherElementsInOrder = false;
9629         break;
9630       }
9631     }
9632     // If other elements are in original order, we record the number of shifts
9633     // we need to get the element we want into element 7. Also record which byte
9634     // in the vector we should insert into.
9635     if (OtherElementsInOrder) {
9636       // If 2nd operand is undefined, we assume no shifts and no swapping.
9637       if (V2.isUndef()) {
9638         ShiftElts = 0;
9639         Swap = false;
9640       } else {
9641         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9642         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9643                          : BigEndianShifts[CurrentElement & 0xF];
9644         Swap = CurrentElement < BytesInVector;
9645       }
9646       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9647       FoundCandidate = true;
9648       break;
9649     }
9650   }
9651 
9652   if (!FoundCandidate)
9653     return SDValue();
9654 
9655   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9656   // optionally with VECSHL if shift is required.
9657   if (Swap)
9658     std::swap(V1, V2);
9659   if (V2.isUndef())
9660     V2 = V1;
9661   if (ShiftElts) {
9662     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9663                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9664     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9665                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9666   }
9667   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9668                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9669 }
9670 
9671 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9672 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9673 /// SDValue.
9674 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9675                                            SelectionDAG &DAG) const {
9676   const unsigned NumHalfWords = 8;
9677   const unsigned BytesInVector = NumHalfWords * 2;
9678   // Check that the shuffle is on half-words.
9679   if (!isNByteElemShuffleMask(N, 2, 1))
9680     return SDValue();
9681 
9682   bool IsLE = Subtarget.isLittleEndian();
9683   SDLoc dl(N);
9684   SDValue V1 = N->getOperand(0);
9685   SDValue V2 = N->getOperand(1);
9686   unsigned ShiftElts = 0, InsertAtByte = 0;
9687   bool Swap = false;
9688 
9689   // Shifts required to get the half-word we want at element 3.
9690   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9691   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9692 
9693   uint32_t Mask = 0;
9694   uint32_t OriginalOrderLow = 0x1234567;
9695   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9696   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9697   // 32-bit space, only need 4-bit nibbles per element.
9698   for (unsigned i = 0; i < NumHalfWords; ++i) {
9699     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9700     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9701   }
9702 
9703   // For each mask element, find out if we're just inserting something
9704   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9705   // from V2 into V1:
9706   //   X, 1, 2, 3, 4, 5, 6, 7
9707   //   0, X, 2, 3, 4, 5, 6, 7
9708   //   0, 1, X, 3, 4, 5, 6, 7
9709   //   0, 1, 2, X, 4, 5, 6, 7
9710   //   0, 1, 2, 3, X, 5, 6, 7
9711   //   0, 1, 2, 3, 4, X, 6, 7
9712   //   0, 1, 2, 3, 4, 5, X, 7
9713   //   0, 1, 2, 3, 4, 5, 6, X
9714   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9715 
9716   bool FoundCandidate = false;
9717   // Go through the mask of half-words to find an element that's being moved
9718   // from one vector to the other.
9719   for (unsigned i = 0; i < NumHalfWords; ++i) {
9720     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9721     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9722     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9723     uint32_t TargetOrder = 0x0;
9724 
9725     // If both vector operands for the shuffle are the same vector, the mask
9726     // will contain only elements from the first one and the second one will be
9727     // undef.
9728     if (V2.isUndef()) {
9729       ShiftElts = 0;
9730       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9731       TargetOrder = OriginalOrderLow;
9732       Swap = false;
9733       // Skip if not the correct element or mask of other elements don't equal
9734       // to our expected order.
9735       if (MaskOneElt == VINSERTHSrcElem &&
9736           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9737         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9738         FoundCandidate = true;
9739         break;
9740       }
9741     } else { // If both operands are defined.
9742       // Target order is [8,15] if the current mask is between [0,7].
9743       TargetOrder =
9744           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9745       // Skip if mask of other elements don't equal our expected order.
9746       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9747         // We only need the last 3 bits for the number of shifts.
9748         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9749                          : BigEndianShifts[MaskOneElt & 0x7];
9750         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9751         Swap = MaskOneElt < NumHalfWords;
9752         FoundCandidate = true;
9753         break;
9754       }
9755     }
9756   }
9757 
9758   if (!FoundCandidate)
9759     return SDValue();
9760 
9761   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9762   // optionally with VECSHL if shift is required.
9763   if (Swap)
9764     std::swap(V1, V2);
9765   if (V2.isUndef())
9766     V2 = V1;
9767   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9768   if (ShiftElts) {
9769     // Double ShiftElts because we're left shifting on v16i8 type.
9770     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9771                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9772     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9773     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9774                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9775     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9776   }
9777   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9778   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9779                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9780   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9781 }
9782 
9783 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9784 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9785 /// return the default SDValue.
9786 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9787                                               SelectionDAG &DAG) const {
9788   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9789   // to v16i8. Peek through the bitcasts to get the actual operands.
9790   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9791   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9792 
9793   auto ShuffleMask = SVN->getMask();
9794   SDValue VecShuffle(SVN, 0);
9795   SDLoc DL(SVN);
9796 
9797   // Check that we have a four byte shuffle.
9798   if (!isNByteElemShuffleMask(SVN, 4, 1))
9799     return SDValue();
9800 
9801   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9802   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9803     std::swap(LHS, RHS);
9804     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9805     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9806   }
9807 
9808   // Ensure that the RHS is a vector of constants.
9809   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9810   if (!BVN)
9811     return SDValue();
9812 
9813   // Check if RHS is a splat of 4-bytes (or smaller).
9814   APInt APSplatValue, APSplatUndef;
9815   unsigned SplatBitSize;
9816   bool HasAnyUndefs;
9817   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9818                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9819       SplatBitSize > 32)
9820     return SDValue();
9821 
9822   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9823   // The instruction splats a constant C into two words of the source vector
9824   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9825   // Thus we check that the shuffle mask is the equivalent  of
9826   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9827   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9828   // within each word are consecutive, so we only need to check the first byte.
9829   SDValue Index;
9830   bool IsLE = Subtarget.isLittleEndian();
9831   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9832       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9833        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9834     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9835   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9836            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9837             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9838     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9839   else
9840     return SDValue();
9841 
9842   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9843   // for XXSPLTI32DX.
9844   unsigned SplatVal = APSplatValue.getZExtValue();
9845   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9846     SplatVal |= (SplatVal << SplatBitSize);
9847 
9848   SDValue SplatNode = DAG.getNode(
9849       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9850       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9851   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9852 }
9853 
9854 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9855 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9856 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9857 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9858 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9859   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9860   assert(Op.getValueType() == MVT::v1i128 &&
9861          "Only set v1i128 as custom, other type shouldn't reach here!");
9862   SDLoc dl(Op);
9863   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9864   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9865   unsigned SHLAmt = N1.getConstantOperandVal(0);
9866   if (SHLAmt % 8 == 0) {
9867     SmallVector<int, 16> Mask(16, 0);
9868     std::iota(Mask.begin(), Mask.end(), 0);
9869     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9870     if (SDValue Shuffle =
9871             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9872                                  DAG.getUNDEF(MVT::v16i8), Mask))
9873       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9874   }
9875   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9876   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9877                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9878   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9879                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9880   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9881   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9882 }
9883 
9884 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9885 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9886 /// return the code it can be lowered into.  Worst case, it can always be
9887 /// lowered into a vperm.
9888 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9889                                                SelectionDAG &DAG) const {
9890   SDLoc dl(Op);
9891   SDValue V1 = Op.getOperand(0);
9892   SDValue V2 = Op.getOperand(1);
9893   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9894 
9895   // Any nodes that were combined in the target-independent combiner prior
9896   // to vector legalization will not be sent to the target combine. Try to
9897   // combine it here.
9898   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9899     Op = NewShuffle;
9900     SVOp = cast<ShuffleVectorSDNode>(Op);
9901     V1 = Op.getOperand(0);
9902     V2 = Op.getOperand(1);
9903   }
9904   EVT VT = Op.getValueType();
9905   bool isLittleEndian = Subtarget.isLittleEndian();
9906 
9907   unsigned ShiftElts, InsertAtByte;
9908   bool Swap = false;
9909 
9910   // If this is a load-and-splat, we can do that with a single instruction
9911   // in some cases. However if the load has multiple uses, we don't want to
9912   // combine it because that will just produce multiple loads.
9913   const SDValue *InputLoad = getNormalLoadInput(V1);
9914   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9915       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9916       InputLoad->hasOneUse()) {
9917     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9918     int SplatIdx =
9919       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9920 
9921     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9922     // For 4-byte load-and-splat, we need Power9.
9923     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9924       uint64_t Offset = 0;
9925       if (IsFourByte)
9926         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9927       else
9928         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9929 
9930       // If we are loading a partial vector, it does not make sense to adjust
9931       // the base pointer. This happens with (splat (s_to_v_permuted (ld))).
9932       if (LD->getMemoryVT().getSizeInBits() == (IsFourByte ? 32 : 64))
9933         Offset = 0;
9934       SDValue BasePtr = LD->getBasePtr();
9935       if (Offset != 0)
9936         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9937                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9938       SDValue Ops[] = {
9939         LD->getChain(),    // Chain
9940         BasePtr,           // BasePtr
9941         DAG.getValueType(Op.getValueType()) // VT
9942       };
9943       SDVTList VTL =
9944         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9945       SDValue LdSplt =
9946         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9947                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9948       if (LdSplt.getValueType() != SVOp->getValueType(0))
9949         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9950       return LdSplt;
9951     }
9952   }
9953   if (Subtarget.hasP9Vector() &&
9954       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9955                            isLittleEndian)) {
9956     if (Swap)
9957       std::swap(V1, V2);
9958     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9959     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9960     if (ShiftElts) {
9961       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9962                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9963       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9964                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9965       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9966     }
9967     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9968                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9969     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9970   }
9971 
9972   if (Subtarget.hasPrefixInstrs()) {
9973     SDValue SplatInsertNode;
9974     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9975       return SplatInsertNode;
9976   }
9977 
9978   if (Subtarget.hasP9Altivec()) {
9979     SDValue NewISDNode;
9980     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9981       return NewISDNode;
9982 
9983     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9984       return NewISDNode;
9985   }
9986 
9987   if (Subtarget.hasVSX() &&
9988       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9989     if (Swap)
9990       std::swap(V1, V2);
9991     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9992     SDValue Conv2 =
9993         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9994 
9995     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9996                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9997     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9998   }
9999 
10000   if (Subtarget.hasVSX() &&
10001     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
10002     if (Swap)
10003       std::swap(V1, V2);
10004     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10005     SDValue Conv2 =
10006         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
10007 
10008     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
10009                               DAG.getConstant(ShiftElts, dl, MVT::i32));
10010     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
10011   }
10012 
10013   if (Subtarget.hasP9Vector()) {
10014      if (PPC::isXXBRHShuffleMask(SVOp)) {
10015       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10016       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
10017       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
10018     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
10019       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10020       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
10021       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
10022     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
10023       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10024       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
10025       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
10026     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
10027       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
10028       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
10029       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
10030     }
10031   }
10032 
10033   if (Subtarget.hasVSX()) {
10034     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
10035       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
10036 
10037       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10038       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
10039                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
10040       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
10041     }
10042 
10043     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
10044     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
10045       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
10046       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
10047       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
10048     }
10049   }
10050 
10051   if (Subtarget.hasQPX()) {
10052     if (VT.getVectorNumElements() != 4)
10053       return SDValue();
10054 
10055     if (V2.isUndef()) V2 = V1;
10056 
10057     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
10058     if (AlignIdx != -1) {
10059       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
10060                          DAG.getConstant(AlignIdx, dl, MVT::i32));
10061     } else if (SVOp->isSplat()) {
10062       int SplatIdx = SVOp->getSplatIndex();
10063       if (SplatIdx >= 4) {
10064         std::swap(V1, V2);
10065         SplatIdx -= 4;
10066       }
10067 
10068       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
10069                          DAG.getConstant(SplatIdx, dl, MVT::i32));
10070     }
10071 
10072     // Lower this into a qvgpci/qvfperm pair.
10073 
10074     // Compute the qvgpci literal
10075     unsigned idx = 0;
10076     for (unsigned i = 0; i < 4; ++i) {
10077       int m = SVOp->getMaskElt(i);
10078       unsigned mm = m >= 0 ? (unsigned) m : i;
10079       idx |= mm << (3-i)*3;
10080     }
10081 
10082     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
10083                              DAG.getConstant(idx, dl, MVT::i32));
10084     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
10085   }
10086 
10087   // Cases that are handled by instructions that take permute immediates
10088   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
10089   // selected by the instruction selector.
10090   if (V2.isUndef()) {
10091     if (PPC::isSplatShuffleMask(SVOp, 1) ||
10092         PPC::isSplatShuffleMask(SVOp, 2) ||
10093         PPC::isSplatShuffleMask(SVOp, 4) ||
10094         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
10095         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
10096         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
10097         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
10098         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
10099         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
10100         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
10101         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
10102         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
10103         (Subtarget.hasP8Altivec() && (
10104          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
10105          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
10106          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
10107       return Op;
10108     }
10109   }
10110 
10111   // Altivec has a variety of "shuffle immediates" that take two vector inputs
10112   // and produce a fixed permutation.  If any of these match, do not lower to
10113   // VPERM.
10114   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
10115   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10116       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10117       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
10118       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10119       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10120       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10121       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10122       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10123       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10124       (Subtarget.hasP8Altivec() && (
10125        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10126        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
10127        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
10128     return Op;
10129 
10130   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
10131   // perfect shuffle table to emit an optimal matching sequence.
10132   ArrayRef<int> PermMask = SVOp->getMask();
10133 
10134   unsigned PFIndexes[4];
10135   bool isFourElementShuffle = true;
10136   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
10137     unsigned EltNo = 8;   // Start out undef.
10138     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
10139       if (PermMask[i*4+j] < 0)
10140         continue;   // Undef, ignore it.
10141 
10142       unsigned ByteSource = PermMask[i*4+j];
10143       if ((ByteSource & 3) != j) {
10144         isFourElementShuffle = false;
10145         break;
10146       }
10147 
10148       if (EltNo == 8) {
10149         EltNo = ByteSource/4;
10150       } else if (EltNo != ByteSource/4) {
10151         isFourElementShuffle = false;
10152         break;
10153       }
10154     }
10155     PFIndexes[i] = EltNo;
10156   }
10157 
10158   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
10159   // perfect shuffle vector to determine if it is cost effective to do this as
10160   // discrete instructions, or whether we should use a vperm.
10161   // For now, we skip this for little endian until such time as we have a
10162   // little-endian perfect shuffle table.
10163   if (isFourElementShuffle && !isLittleEndian) {
10164     // Compute the index in the perfect shuffle table.
10165     unsigned PFTableIndex =
10166       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
10167 
10168     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10169     unsigned Cost  = (PFEntry >> 30);
10170 
10171     // Determining when to avoid vperm is tricky.  Many things affect the cost
10172     // of vperm, particularly how many times the perm mask needs to be computed.
10173     // For example, if the perm mask can be hoisted out of a loop or is already
10174     // used (perhaps because there are multiple permutes with the same shuffle
10175     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
10176     // the loop requires an extra register.
10177     //
10178     // As a compromise, we only emit discrete instructions if the shuffle can be
10179     // generated in 3 or fewer operations.  When we have loop information
10180     // available, if this block is within a loop, we should avoid using vperm
10181     // for 3-operation perms and use a constant pool load instead.
10182     if (Cost < 3)
10183       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10184   }
10185 
10186   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10187   // vector that will get spilled to the constant pool.
10188   if (V2.isUndef()) V2 = V1;
10189 
10190   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10191   // that it is in input element units, not in bytes.  Convert now.
10192 
10193   // For little endian, the order of the input vectors is reversed, and
10194   // the permutation mask is complemented with respect to 31.  This is
10195   // necessary to produce proper semantics with the big-endian-biased vperm
10196   // instruction.
10197   EVT EltVT = V1.getValueType().getVectorElementType();
10198   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
10199 
10200   SmallVector<SDValue, 16> ResultMask;
10201   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10202     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10203 
10204     for (unsigned j = 0; j != BytesPerElement; ++j)
10205       if (isLittleEndian)
10206         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
10207                                              dl, MVT::i32));
10208       else
10209         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
10210                                              MVT::i32));
10211   }
10212 
10213   ShufflesHandledWithVPERM++;
10214   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10215   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
10216   LLVM_DEBUG(SVOp->dump());
10217   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
10218   LLVM_DEBUG(VPermMask.dump());
10219 
10220   if (isLittleEndian)
10221     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10222                        V2, V1, VPermMask);
10223   else
10224     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10225                        V1, V2, VPermMask);
10226 }
10227 
10228 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10229 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10230 /// information about the intrinsic.
10231 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10232                                  bool &isDot, const PPCSubtarget &Subtarget) {
10233   unsigned IntrinsicID =
10234       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10235   CompareOpc = -1;
10236   isDot = false;
10237   switch (IntrinsicID) {
10238   default:
10239     return false;
10240   // Comparison predicates.
10241   case Intrinsic::ppc_altivec_vcmpbfp_p:
10242     CompareOpc = 966;
10243     isDot = true;
10244     break;
10245   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10246     CompareOpc = 198;
10247     isDot = true;
10248     break;
10249   case Intrinsic::ppc_altivec_vcmpequb_p:
10250     CompareOpc = 6;
10251     isDot = true;
10252     break;
10253   case Intrinsic::ppc_altivec_vcmpequh_p:
10254     CompareOpc = 70;
10255     isDot = true;
10256     break;
10257   case Intrinsic::ppc_altivec_vcmpequw_p:
10258     CompareOpc = 134;
10259     isDot = true;
10260     break;
10261   case Intrinsic::ppc_altivec_vcmpequd_p:
10262     if (Subtarget.hasP8Altivec()) {
10263       CompareOpc = 199;
10264       isDot = true;
10265     } else
10266       return false;
10267     break;
10268   case Intrinsic::ppc_altivec_vcmpneb_p:
10269   case Intrinsic::ppc_altivec_vcmpneh_p:
10270   case Intrinsic::ppc_altivec_vcmpnew_p:
10271   case Intrinsic::ppc_altivec_vcmpnezb_p:
10272   case Intrinsic::ppc_altivec_vcmpnezh_p:
10273   case Intrinsic::ppc_altivec_vcmpnezw_p:
10274     if (Subtarget.hasP9Altivec()) {
10275       switch (IntrinsicID) {
10276       default:
10277         llvm_unreachable("Unknown comparison intrinsic.");
10278       case Intrinsic::ppc_altivec_vcmpneb_p:
10279         CompareOpc = 7;
10280         break;
10281       case Intrinsic::ppc_altivec_vcmpneh_p:
10282         CompareOpc = 71;
10283         break;
10284       case Intrinsic::ppc_altivec_vcmpnew_p:
10285         CompareOpc = 135;
10286         break;
10287       case Intrinsic::ppc_altivec_vcmpnezb_p:
10288         CompareOpc = 263;
10289         break;
10290       case Intrinsic::ppc_altivec_vcmpnezh_p:
10291         CompareOpc = 327;
10292         break;
10293       case Intrinsic::ppc_altivec_vcmpnezw_p:
10294         CompareOpc = 391;
10295         break;
10296       }
10297       isDot = true;
10298     } else
10299       return false;
10300     break;
10301   case Intrinsic::ppc_altivec_vcmpgefp_p:
10302     CompareOpc = 454;
10303     isDot = true;
10304     break;
10305   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10306     CompareOpc = 710;
10307     isDot = true;
10308     break;
10309   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10310     CompareOpc = 774;
10311     isDot = true;
10312     break;
10313   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10314     CompareOpc = 838;
10315     isDot = true;
10316     break;
10317   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10318     CompareOpc = 902;
10319     isDot = true;
10320     break;
10321   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10322     if (Subtarget.hasP8Altivec()) {
10323       CompareOpc = 967;
10324       isDot = true;
10325     } else
10326       return false;
10327     break;
10328   case Intrinsic::ppc_altivec_vcmpgtub_p:
10329     CompareOpc = 518;
10330     isDot = true;
10331     break;
10332   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10333     CompareOpc = 582;
10334     isDot = true;
10335     break;
10336   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10337     CompareOpc = 646;
10338     isDot = true;
10339     break;
10340   case Intrinsic::ppc_altivec_vcmpgtud_p:
10341     if (Subtarget.hasP8Altivec()) {
10342       CompareOpc = 711;
10343       isDot = true;
10344     } else
10345       return false;
10346     break;
10347 
10348   // VSX predicate comparisons use the same infrastructure
10349   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10350   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10351   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10352   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10353   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10354   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10355     if (Subtarget.hasVSX()) {
10356       switch (IntrinsicID) {
10357       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10358         CompareOpc = 99;
10359         break;
10360       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10361         CompareOpc = 115;
10362         break;
10363       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10364         CompareOpc = 107;
10365         break;
10366       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10367         CompareOpc = 67;
10368         break;
10369       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10370         CompareOpc = 83;
10371         break;
10372       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10373         CompareOpc = 75;
10374         break;
10375       }
10376       isDot = true;
10377     } else
10378       return false;
10379     break;
10380 
10381   // Normal Comparisons.
10382   case Intrinsic::ppc_altivec_vcmpbfp:
10383     CompareOpc = 966;
10384     break;
10385   case Intrinsic::ppc_altivec_vcmpeqfp:
10386     CompareOpc = 198;
10387     break;
10388   case Intrinsic::ppc_altivec_vcmpequb:
10389     CompareOpc = 6;
10390     break;
10391   case Intrinsic::ppc_altivec_vcmpequh:
10392     CompareOpc = 70;
10393     break;
10394   case Intrinsic::ppc_altivec_vcmpequw:
10395     CompareOpc = 134;
10396     break;
10397   case Intrinsic::ppc_altivec_vcmpequd:
10398     if (Subtarget.hasP8Altivec())
10399       CompareOpc = 199;
10400     else
10401       return false;
10402     break;
10403   case Intrinsic::ppc_altivec_vcmpneb:
10404   case Intrinsic::ppc_altivec_vcmpneh:
10405   case Intrinsic::ppc_altivec_vcmpnew:
10406   case Intrinsic::ppc_altivec_vcmpnezb:
10407   case Intrinsic::ppc_altivec_vcmpnezh:
10408   case Intrinsic::ppc_altivec_vcmpnezw:
10409     if (Subtarget.hasP9Altivec())
10410       switch (IntrinsicID) {
10411       default:
10412         llvm_unreachable("Unknown comparison intrinsic.");
10413       case Intrinsic::ppc_altivec_vcmpneb:
10414         CompareOpc = 7;
10415         break;
10416       case Intrinsic::ppc_altivec_vcmpneh:
10417         CompareOpc = 71;
10418         break;
10419       case Intrinsic::ppc_altivec_vcmpnew:
10420         CompareOpc = 135;
10421         break;
10422       case Intrinsic::ppc_altivec_vcmpnezb:
10423         CompareOpc = 263;
10424         break;
10425       case Intrinsic::ppc_altivec_vcmpnezh:
10426         CompareOpc = 327;
10427         break;
10428       case Intrinsic::ppc_altivec_vcmpnezw:
10429         CompareOpc = 391;
10430         break;
10431       }
10432     else
10433       return false;
10434     break;
10435   case Intrinsic::ppc_altivec_vcmpgefp:
10436     CompareOpc = 454;
10437     break;
10438   case Intrinsic::ppc_altivec_vcmpgtfp:
10439     CompareOpc = 710;
10440     break;
10441   case Intrinsic::ppc_altivec_vcmpgtsb:
10442     CompareOpc = 774;
10443     break;
10444   case Intrinsic::ppc_altivec_vcmpgtsh:
10445     CompareOpc = 838;
10446     break;
10447   case Intrinsic::ppc_altivec_vcmpgtsw:
10448     CompareOpc = 902;
10449     break;
10450   case Intrinsic::ppc_altivec_vcmpgtsd:
10451     if (Subtarget.hasP8Altivec())
10452       CompareOpc = 967;
10453     else
10454       return false;
10455     break;
10456   case Intrinsic::ppc_altivec_vcmpgtub:
10457     CompareOpc = 518;
10458     break;
10459   case Intrinsic::ppc_altivec_vcmpgtuh:
10460     CompareOpc = 582;
10461     break;
10462   case Intrinsic::ppc_altivec_vcmpgtuw:
10463     CompareOpc = 646;
10464     break;
10465   case Intrinsic::ppc_altivec_vcmpgtud:
10466     if (Subtarget.hasP8Altivec())
10467       CompareOpc = 711;
10468     else
10469       return false;
10470     break;
10471   }
10472   return true;
10473 }
10474 
10475 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10476 /// lower, do it, otherwise return null.
10477 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10478                                                    SelectionDAG &DAG) const {
10479   unsigned IntrinsicID =
10480     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10481 
10482   SDLoc dl(Op);
10483 
10484   if (IntrinsicID == Intrinsic::thread_pointer) {
10485     // Reads the thread pointer register, used for __builtin_thread_pointer.
10486     if (Subtarget.isPPC64())
10487       return DAG.getRegister(PPC::X13, MVT::i64);
10488     return DAG.getRegister(PPC::R2, MVT::i32);
10489   }
10490 
10491   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10492   // opcode number of the comparison.
10493   int CompareOpc;
10494   bool isDot;
10495   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10496     return SDValue();    // Don't custom lower most intrinsics.
10497 
10498   // If this is a non-dot comparison, make the VCMP node and we are done.
10499   if (!isDot) {
10500     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10501                               Op.getOperand(1), Op.getOperand(2),
10502                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10503     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10504   }
10505 
10506   // Create the PPCISD altivec 'dot' comparison node.
10507   SDValue Ops[] = {
10508     Op.getOperand(2),  // LHS
10509     Op.getOperand(3),  // RHS
10510     DAG.getConstant(CompareOpc, dl, MVT::i32)
10511   };
10512   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10513   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10514 
10515   // Now that we have the comparison, emit a copy from the CR to a GPR.
10516   // This is flagged to the above dot comparison.
10517   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10518                                 DAG.getRegister(PPC::CR6, MVT::i32),
10519                                 CompNode.getValue(1));
10520 
10521   // Unpack the result based on how the target uses it.
10522   unsigned BitNo;   // Bit # of CR6.
10523   bool InvertBit;   // Invert result?
10524   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10525   default:  // Can't happen, don't crash on invalid number though.
10526   case 0:   // Return the value of the EQ bit of CR6.
10527     BitNo = 0; InvertBit = false;
10528     break;
10529   case 1:   // Return the inverted value of the EQ bit of CR6.
10530     BitNo = 0; InvertBit = true;
10531     break;
10532   case 2:   // Return the value of the LT bit of CR6.
10533     BitNo = 2; InvertBit = false;
10534     break;
10535   case 3:   // Return the inverted value of the LT bit of CR6.
10536     BitNo = 2; InvertBit = true;
10537     break;
10538   }
10539 
10540   // Shift the bit into the low position.
10541   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10542                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10543   // Isolate the bit.
10544   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10545                       DAG.getConstant(1, dl, MVT::i32));
10546 
10547   // If we are supposed to, toggle the bit.
10548   if (InvertBit)
10549     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10550                         DAG.getConstant(1, dl, MVT::i32));
10551   return Flags;
10552 }
10553 
10554 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10555                                                SelectionDAG &DAG) const {
10556   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10557   // the beginning of the argument list.
10558   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10559   SDLoc DL(Op);
10560   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10561   case Intrinsic::ppc_cfence: {
10562     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10563     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10564     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10565                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10566                                                   Op.getOperand(ArgStart + 1)),
10567                                       Op.getOperand(0)),
10568                    0);
10569   }
10570   default:
10571     break;
10572   }
10573   return SDValue();
10574 }
10575 
10576 // Lower scalar BSWAP64 to xxbrd.
10577 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10578   SDLoc dl(Op);
10579   // MTVSRDD
10580   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10581                    Op.getOperand(0));
10582   // XXBRD
10583   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10584   // MFVSRD
10585   int VectorIndex = 0;
10586   if (Subtarget.isLittleEndian())
10587     VectorIndex = 1;
10588   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10589                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10590   return Op;
10591 }
10592 
10593 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10594 // compared to a value that is atomically loaded (atomic loads zero-extend).
10595 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10596                                                 SelectionDAG &DAG) const {
10597   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10598          "Expecting an atomic compare-and-swap here.");
10599   SDLoc dl(Op);
10600   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10601   EVT MemVT = AtomicNode->getMemoryVT();
10602   if (MemVT.getSizeInBits() >= 32)
10603     return Op;
10604 
10605   SDValue CmpOp = Op.getOperand(2);
10606   // If this is already correctly zero-extended, leave it alone.
10607   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10608   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10609     return Op;
10610 
10611   // Clear the high bits of the compare operand.
10612   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10613   SDValue NewCmpOp =
10614     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10615                 DAG.getConstant(MaskVal, dl, MVT::i32));
10616 
10617   // Replace the existing compare operand with the properly zero-extended one.
10618   SmallVector<SDValue, 4> Ops;
10619   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10620     Ops.push_back(AtomicNode->getOperand(i));
10621   Ops[2] = NewCmpOp;
10622   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10623   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10624   auto NodeTy =
10625     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10626   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10627 }
10628 
10629 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10630                                                  SelectionDAG &DAG) const {
10631   SDLoc dl(Op);
10632   // Create a stack slot that is 16-byte aligned.
10633   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10634   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10635   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10636   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10637 
10638   // Store the input value into Value#0 of the stack slot.
10639   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10640                                MachinePointerInfo());
10641   // Load it out.
10642   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10643 }
10644 
10645 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10646                                                   SelectionDAG &DAG) const {
10647   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10648          "Should only be called for ISD::INSERT_VECTOR_ELT");
10649 
10650   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10651   // We have legal lowering for constant indices but not for variable ones.
10652   if (!C)
10653     return SDValue();
10654 
10655   EVT VT = Op.getValueType();
10656   SDLoc dl(Op);
10657   SDValue V1 = Op.getOperand(0);
10658   SDValue V2 = Op.getOperand(1);
10659   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10660   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10661     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10662     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10663     unsigned InsertAtElement = C->getZExtValue();
10664     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10665     if (Subtarget.isLittleEndian()) {
10666       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10667     }
10668     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10669                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10670   }
10671   return Op;
10672 }
10673 
10674 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10675                                                    SelectionDAG &DAG) const {
10676   SDLoc dl(Op);
10677   SDNode *N = Op.getNode();
10678 
10679   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
10680          "Unknown extract_vector_elt type");
10681 
10682   SDValue Value = N->getOperand(0);
10683 
10684   // The first part of this is like the store lowering except that we don't
10685   // need to track the chain.
10686 
10687   // The values are now known to be -1 (false) or 1 (true). To convert this
10688   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10689   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10690   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10691 
10692   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10693   // understand how to form the extending load.
10694   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10695 
10696   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10697 
10698   // Now convert to an integer and store.
10699   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10700     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10701     Value);
10702 
10703   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10704   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10705   MachinePointerInfo PtrInfo =
10706       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10707   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10708   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10709 
10710   SDValue StoreChain = DAG.getEntryNode();
10711   SDValue Ops[] = {StoreChain,
10712                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10713                    Value, FIdx};
10714   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10715 
10716   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10717     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10718 
10719   // Extract the value requested.
10720   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10721   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10722   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10723 
10724   SDValue IntVal =
10725       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
10726 
10727   if (!Subtarget.useCRBits())
10728     return IntVal;
10729 
10730   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
10731 }
10732 
10733 /// Lowering for QPX v4i1 loads
10734 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10735                                            SelectionDAG &DAG) const {
10736   SDLoc dl(Op);
10737   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10738   SDValue LoadChain = LN->getChain();
10739   SDValue BasePtr = LN->getBasePtr();
10740 
10741   if (Op.getValueType() == MVT::v4f64 ||
10742       Op.getValueType() == MVT::v4f32) {
10743     EVT MemVT = LN->getMemoryVT();
10744     unsigned Alignment = LN->getAlignment();
10745 
10746     // If this load is properly aligned, then it is legal.
10747     if (Alignment >= MemVT.getStoreSize())
10748       return Op;
10749 
10750     EVT ScalarVT = Op.getValueType().getScalarType(),
10751         ScalarMemVT = MemVT.getScalarType();
10752     unsigned Stride = ScalarMemVT.getStoreSize();
10753 
10754     SDValue Vals[4], LoadChains[4];
10755     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10756       SDValue Load;
10757       if (ScalarVT != ScalarMemVT)
10758         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
10759                               BasePtr,
10760                               LN->getPointerInfo().getWithOffset(Idx * Stride),
10761                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10762                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
10763       else
10764         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
10765                            LN->getPointerInfo().getWithOffset(Idx * Stride),
10766                            MinAlign(Alignment, Idx * Stride),
10767                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
10768 
10769       if (Idx == 0 && LN->isIndexed()) {
10770         assert(LN->getAddressingMode() == ISD::PRE_INC &&
10771                "Unknown addressing mode on vector load");
10772         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
10773                                   LN->getAddressingMode());
10774       }
10775 
10776       Vals[Idx] = Load;
10777       LoadChains[Idx] = Load.getValue(1);
10778 
10779       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10780                             DAG.getConstant(Stride, dl,
10781                                             BasePtr.getValueType()));
10782     }
10783 
10784     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10785     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
10786 
10787     if (LN->isIndexed()) {
10788       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
10789       return DAG.getMergeValues(RetOps, dl);
10790     }
10791 
10792     SDValue RetOps[] = { Value, TF };
10793     return DAG.getMergeValues(RetOps, dl);
10794   }
10795 
10796   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
10797   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
10798 
10799   // To lower v4i1 from a byte array, we load the byte elements of the
10800   // vector and then reuse the BUILD_VECTOR logic.
10801 
10802   SDValue VectElmts[4], VectElmtChains[4];
10803   for (unsigned i = 0; i < 4; ++i) {
10804     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10805     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10806 
10807     VectElmts[i] = DAG.getExtLoad(
10808         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
10809         LN->getPointerInfo().getWithOffset(i), MVT::i8,
10810         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
10811     VectElmtChains[i] = VectElmts[i].getValue(1);
10812   }
10813 
10814   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
10815   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
10816 
10817   SDValue RVals[] = { Value, LoadChain };
10818   return DAG.getMergeValues(RVals, dl);
10819 }
10820 
10821 /// Lowering for QPX v4i1 stores
10822 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10823                                             SelectionDAG &DAG) const {
10824   SDLoc dl(Op);
10825   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10826   SDValue StoreChain = SN->getChain();
10827   SDValue BasePtr = SN->getBasePtr();
10828   SDValue Value = SN->getValue();
10829 
10830   if (Value.getValueType() == MVT::v4f64 ||
10831       Value.getValueType() == MVT::v4f32) {
10832     EVT MemVT = SN->getMemoryVT();
10833     unsigned Alignment = SN->getAlignment();
10834 
10835     // If this store is properly aligned, then it is legal.
10836     if (Alignment >= MemVT.getStoreSize())
10837       return Op;
10838 
10839     EVT ScalarVT = Value.getValueType().getScalarType(),
10840         ScalarMemVT = MemVT.getScalarType();
10841     unsigned Stride = ScalarMemVT.getStoreSize();
10842 
10843     SDValue Stores[4];
10844     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10845       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
10846                                DAG.getVectorIdxConstant(Idx, dl));
10847       SDValue Store;
10848       if (ScalarVT != ScalarMemVT)
10849         Store =
10850             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
10851                               SN->getPointerInfo().getWithOffset(Idx * Stride),
10852                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10853                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
10854       else
10855         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
10856                              SN->getPointerInfo().getWithOffset(Idx * Stride),
10857                              MinAlign(Alignment, Idx * Stride),
10858                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
10859 
10860       if (Idx == 0 && SN->isIndexed()) {
10861         assert(SN->getAddressingMode() == ISD::PRE_INC &&
10862                "Unknown addressing mode on vector store");
10863         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
10864                                     SN->getAddressingMode());
10865       }
10866 
10867       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10868                             DAG.getConstant(Stride, dl,
10869                                             BasePtr.getValueType()));
10870       Stores[Idx] = Store;
10871     }
10872 
10873     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10874 
10875     if (SN->isIndexed()) {
10876       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
10877       return DAG.getMergeValues(RetOps, dl);
10878     }
10879 
10880     return TF;
10881   }
10882 
10883   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
10884   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
10885 
10886   // The values are now known to be -1 (false) or 1 (true). To convert this
10887   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10888   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10889   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10890 
10891   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10892   // understand how to form the extending load.
10893   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10894 
10895   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10896 
10897   // Now convert to an integer and store.
10898   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10899     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10900     Value);
10901 
10902   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10903   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10904   MachinePointerInfo PtrInfo =
10905       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10906   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10907   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10908 
10909   SDValue Ops[] = {StoreChain,
10910                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10911                    Value, FIdx};
10912   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10913 
10914   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10915     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10916 
10917   // Move data into the byte array.
10918   SDValue Loads[4], LoadChains[4];
10919   for (unsigned i = 0; i < 4; ++i) {
10920     unsigned Offset = 4*i;
10921     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10922     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10923 
10924     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
10925                            PtrInfo.getWithOffset(Offset));
10926     LoadChains[i] = Loads[i].getValue(1);
10927   }
10928 
10929   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10930 
10931   SDValue Stores[4];
10932   for (unsigned i = 0; i < 4; ++i) {
10933     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10934     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10935 
10936     Stores[i] = DAG.getTruncStore(
10937         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
10938         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
10939         SN->getAAInfo());
10940   }
10941 
10942   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10943 
10944   return StoreChain;
10945 }
10946 
10947 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10948   SDLoc dl(Op);
10949   if (Op.getValueType() == MVT::v4i32) {
10950     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10951 
10952     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10953     // +16 as shift amt.
10954     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10955     SDValue RHSSwap =   // = vrlw RHS, 16
10956       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10957 
10958     // Shrinkify inputs to v8i16.
10959     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10960     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10961     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10962 
10963     // Low parts multiplied together, generating 32-bit results (we ignore the
10964     // top parts).
10965     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10966                                         LHS, RHS, DAG, dl, MVT::v4i32);
10967 
10968     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10969                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10970     // Shift the high parts up 16 bits.
10971     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10972                               Neg16, DAG, dl);
10973     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10974   } else if (Op.getValueType() == MVT::v16i8) {
10975     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10976     bool isLittleEndian = Subtarget.isLittleEndian();
10977 
10978     // Multiply the even 8-bit parts, producing 16-bit sums.
10979     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10980                                            LHS, RHS, DAG, dl, MVT::v8i16);
10981     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10982 
10983     // Multiply the odd 8-bit parts, producing 16-bit sums.
10984     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10985                                           LHS, RHS, DAG, dl, MVT::v8i16);
10986     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10987 
10988     // Merge the results together.  Because vmuleub and vmuloub are
10989     // instructions with a big-endian bias, we must reverse the
10990     // element numbering and reverse the meaning of "odd" and "even"
10991     // when generating little endian code.
10992     int Ops[16];
10993     for (unsigned i = 0; i != 8; ++i) {
10994       if (isLittleEndian) {
10995         Ops[i*2  ] = 2*i;
10996         Ops[i*2+1] = 2*i+16;
10997       } else {
10998         Ops[i*2  ] = 2*i+1;
10999         Ops[i*2+1] = 2*i+1+16;
11000       }
11001     }
11002     if (isLittleEndian)
11003       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
11004     else
11005       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
11006   } else {
11007     llvm_unreachable("Unknown mul to lower!");
11008   }
11009 }
11010 
11011 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
11012 
11013   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
11014 
11015   EVT VT = Op.getValueType();
11016   assert(VT.isVector() &&
11017          "Only set vector abs as custom, scalar abs shouldn't reach here!");
11018   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11019           VT == MVT::v16i8) &&
11020          "Unexpected vector element type!");
11021   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
11022          "Current subtarget doesn't support smax v2i64!");
11023 
11024   // For vector abs, it can be lowered to:
11025   // abs x
11026   // ==>
11027   // y = -x
11028   // smax(x, y)
11029 
11030   SDLoc dl(Op);
11031   SDValue X = Op.getOperand(0);
11032   SDValue Zero = DAG.getConstant(0, dl, VT);
11033   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
11034 
11035   // SMAX patch https://reviews.llvm.org/D47332
11036   // hasn't landed yet, so use intrinsic first here.
11037   // TODO: Should use SMAX directly once SMAX patch landed
11038   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
11039   if (VT == MVT::v2i64)
11040     BifID = Intrinsic::ppc_altivec_vmaxsd;
11041   else if (VT == MVT::v8i16)
11042     BifID = Intrinsic::ppc_altivec_vmaxsh;
11043   else if (VT == MVT::v16i8)
11044     BifID = Intrinsic::ppc_altivec_vmaxsb;
11045 
11046   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
11047 }
11048 
11049 // Custom lowering for fpext vf32 to v2f64
11050 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11051 
11052   assert(Op.getOpcode() == ISD::FP_EXTEND &&
11053          "Should only be called for ISD::FP_EXTEND");
11054 
11055   // FIXME: handle extends from half precision float vectors on P9.
11056   // We only want to custom lower an extend from v2f32 to v2f64.
11057   if (Op.getValueType() != MVT::v2f64 ||
11058       Op.getOperand(0).getValueType() != MVT::v2f32)
11059     return SDValue();
11060 
11061   SDLoc dl(Op);
11062   SDValue Op0 = Op.getOperand(0);
11063 
11064   switch (Op0.getOpcode()) {
11065   default:
11066     return SDValue();
11067   case ISD::EXTRACT_SUBVECTOR: {
11068     assert(Op0.getNumOperands() == 2 &&
11069            isa<ConstantSDNode>(Op0->getOperand(1)) &&
11070            "Node should have 2 operands with second one being a constant!");
11071 
11072     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
11073       return SDValue();
11074 
11075     // Custom lower is only done for high or low doubleword.
11076     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
11077     if (Idx % 2 != 0)
11078       return SDValue();
11079 
11080     // Since input is v4f32, at this point Idx is either 0 or 2.
11081     // Shift to get the doubleword position we want.
11082     int DWord = Idx >> 1;
11083 
11084     // High and low word positions are different on little endian.
11085     if (Subtarget.isLittleEndian())
11086       DWord ^= 0x1;
11087 
11088     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
11089                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
11090   }
11091   case ISD::FADD:
11092   case ISD::FMUL:
11093   case ISD::FSUB: {
11094     SDValue NewLoad[2];
11095     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
11096       // Ensure both input are loads.
11097       SDValue LdOp = Op0.getOperand(i);
11098       if (LdOp.getOpcode() != ISD::LOAD)
11099         return SDValue();
11100       // Generate new load node.
11101       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
11102       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11103       NewLoad[i] = DAG.getMemIntrinsicNode(
11104           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11105           LD->getMemoryVT(), LD->getMemOperand());
11106     }
11107     SDValue NewOp =
11108         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
11109                     NewLoad[1], Op0.getNode()->getFlags());
11110     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
11111                        DAG.getConstant(0, dl, MVT::i32));
11112   }
11113   case ISD::LOAD: {
11114     LoadSDNode *LD = cast<LoadSDNode>(Op0);
11115     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11116     SDValue NewLd = DAG.getMemIntrinsicNode(
11117         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11118         LD->getMemoryVT(), LD->getMemOperand());
11119     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
11120                        DAG.getConstant(0, dl, MVT::i32));
11121   }
11122   }
11123   llvm_unreachable("ERROR:Should return for all cases within swtich.");
11124 }
11125 
11126 /// LowerOperation - Provide custom lowering hooks for some operations.
11127 ///
11128 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11129   switch (Op.getOpcode()) {
11130   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
11131   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11132   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11133   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11134   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11135   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11136   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11137   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11138   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11139 
11140   // Variable argument lowering.
11141   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11142   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11143   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11144 
11145   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
11146   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11147   case ISD::GET_DYNAMIC_AREA_OFFSET:
11148     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
11149 
11150   // Exception handling lowering.
11151   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
11152   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11153   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11154 
11155   case ISD::LOAD:               return LowerLOAD(Op, DAG);
11156   case ISD::STORE:              return LowerSTORE(Op, DAG);
11157   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
11158   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
11159   case ISD::FP_TO_UINT:
11160   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
11161   case ISD::UINT_TO_FP:
11162   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
11163   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11164 
11165   // Lower 64-bit shifts.
11166   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
11167   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
11168   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
11169 
11170   // Vector-related lowering.
11171   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11172   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11173   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11174   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11175   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11176   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11177   case ISD::MUL:                return LowerMUL(Op, DAG);
11178   case ISD::ABS:                return LowerABS(Op, DAG);
11179   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
11180   case ISD::ROTL:               return LowerROTL(Op, DAG);
11181 
11182   // For counter-based loop handling.
11183   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
11184 
11185   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11186 
11187   // Frame & Return address.
11188   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11189   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11190 
11191   case ISD::INTRINSIC_VOID:
11192     return LowerINTRINSIC_VOID(Op, DAG);
11193   case ISD::BSWAP:
11194     return LowerBSWAP(Op, DAG);
11195   case ISD::ATOMIC_CMP_SWAP:
11196     return LowerATOMIC_CMP_SWAP(Op, DAG);
11197   }
11198 }
11199 
11200 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
11201                                            SmallVectorImpl<SDValue>&Results,
11202                                            SelectionDAG &DAG) const {
11203   SDLoc dl(N);
11204   switch (N->getOpcode()) {
11205   default:
11206     llvm_unreachable("Do not know how to custom type legalize this operation!");
11207   case ISD::READCYCLECOUNTER: {
11208     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11209     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
11210 
11211     Results.push_back(
11212         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
11213     Results.push_back(RTB.getValue(2));
11214     break;
11215   }
11216   case ISD::INTRINSIC_W_CHAIN: {
11217     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
11218         Intrinsic::loop_decrement)
11219       break;
11220 
11221     assert(N->getValueType(0) == MVT::i1 &&
11222            "Unexpected result type for CTR decrement intrinsic");
11223     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11224                                  N->getValueType(0));
11225     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
11226     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
11227                                  N->getOperand(1));
11228 
11229     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
11230     Results.push_back(NewInt.getValue(1));
11231     break;
11232   }
11233   case ISD::VAARG: {
11234     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
11235       return;
11236 
11237     EVT VT = N->getValueType(0);
11238 
11239     if (VT == MVT::i64) {
11240       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
11241 
11242       Results.push_back(NewNode);
11243       Results.push_back(NewNode.getValue(1));
11244     }
11245     return;
11246   }
11247   case ISD::FP_TO_SINT:
11248   case ISD::FP_TO_UINT:
11249     // LowerFP_TO_INT() can only handle f32 and f64.
11250     if (N->getOperand(0).getValueType() == MVT::ppcf128)
11251       return;
11252     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
11253     return;
11254   case ISD::TRUNCATE: {
11255     EVT TrgVT = N->getValueType(0);
11256     EVT OpVT = N->getOperand(0).getValueType();
11257     if (TrgVT.isVector() &&
11258         isOperationCustom(N->getOpcode(), TrgVT) &&
11259         OpVT.getSizeInBits() <= 128 &&
11260         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
11261       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
11262     return;
11263   }
11264   case ISD::BITCAST:
11265     // Don't handle bitcast here.
11266     return;
11267   case ISD::FP_EXTEND:
11268     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
11269     if (Lowered)
11270       Results.push_back(Lowered);
11271     return;
11272   }
11273 }
11274 
11275 //===----------------------------------------------------------------------===//
11276 //  Other Lowering Code
11277 //===----------------------------------------------------------------------===//
11278 
11279 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
11280   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11281   Function *Func = Intrinsic::getDeclaration(M, Id);
11282   return Builder.CreateCall(Func, {});
11283 }
11284 
11285 // The mappings for emitLeading/TrailingFence is taken from
11286 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11287 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11288                                                  Instruction *Inst,
11289                                                  AtomicOrdering Ord) const {
11290   if (Ord == AtomicOrdering::SequentiallyConsistent)
11291     return callIntrinsic(Builder, Intrinsic::ppc_sync);
11292   if (isReleaseOrStronger(Ord))
11293     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11294   return nullptr;
11295 }
11296 
11297 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11298                                                   Instruction *Inst,
11299                                                   AtomicOrdering Ord) const {
11300   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11301     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11302     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11303     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11304     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11305       return Builder.CreateCall(
11306           Intrinsic::getDeclaration(
11307               Builder.GetInsertBlock()->getParent()->getParent(),
11308               Intrinsic::ppc_cfence, {Inst->getType()}),
11309           {Inst});
11310     // FIXME: Can use isync for rmw operation.
11311     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11312   }
11313   return nullptr;
11314 }
11315 
11316 MachineBasicBlock *
11317 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11318                                     unsigned AtomicSize,
11319                                     unsigned BinOpcode,
11320                                     unsigned CmpOpcode,
11321                                     unsigned CmpPred) const {
11322   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11323   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11324 
11325   auto LoadMnemonic = PPC::LDARX;
11326   auto StoreMnemonic = PPC::STDCX;
11327   switch (AtomicSize) {
11328   default:
11329     llvm_unreachable("Unexpected size of atomic entity");
11330   case 1:
11331     LoadMnemonic = PPC::LBARX;
11332     StoreMnemonic = PPC::STBCX;
11333     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11334     break;
11335   case 2:
11336     LoadMnemonic = PPC::LHARX;
11337     StoreMnemonic = PPC::STHCX;
11338     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11339     break;
11340   case 4:
11341     LoadMnemonic = PPC::LWARX;
11342     StoreMnemonic = PPC::STWCX;
11343     break;
11344   case 8:
11345     LoadMnemonic = PPC::LDARX;
11346     StoreMnemonic = PPC::STDCX;
11347     break;
11348   }
11349 
11350   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11351   MachineFunction *F = BB->getParent();
11352   MachineFunction::iterator It = ++BB->getIterator();
11353 
11354   Register dest = MI.getOperand(0).getReg();
11355   Register ptrA = MI.getOperand(1).getReg();
11356   Register ptrB = MI.getOperand(2).getReg();
11357   Register incr = MI.getOperand(3).getReg();
11358   DebugLoc dl = MI.getDebugLoc();
11359 
11360   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11361   MachineBasicBlock *loop2MBB =
11362     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11363   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11364   F->insert(It, loopMBB);
11365   if (CmpOpcode)
11366     F->insert(It, loop2MBB);
11367   F->insert(It, exitMBB);
11368   exitMBB->splice(exitMBB->begin(), BB,
11369                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11370   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11371 
11372   MachineRegisterInfo &RegInfo = F->getRegInfo();
11373   Register TmpReg = (!BinOpcode) ? incr :
11374     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11375                                            : &PPC::GPRCRegClass);
11376 
11377   //  thisMBB:
11378   //   ...
11379   //   fallthrough --> loopMBB
11380   BB->addSuccessor(loopMBB);
11381 
11382   //  loopMBB:
11383   //   l[wd]arx dest, ptr
11384   //   add r0, dest, incr
11385   //   st[wd]cx. r0, ptr
11386   //   bne- loopMBB
11387   //   fallthrough --> exitMBB
11388 
11389   // For max/min...
11390   //  loopMBB:
11391   //   l[wd]arx dest, ptr
11392   //   cmpl?[wd] incr, dest
11393   //   bgt exitMBB
11394   //  loop2MBB:
11395   //   st[wd]cx. dest, ptr
11396   //   bne- loopMBB
11397   //   fallthrough --> exitMBB
11398 
11399   BB = loopMBB;
11400   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11401     .addReg(ptrA).addReg(ptrB);
11402   if (BinOpcode)
11403     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11404   if (CmpOpcode) {
11405     // Signed comparisons of byte or halfword values must be sign-extended.
11406     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11407       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11408       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11409               ExtReg).addReg(dest);
11410       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11411         .addReg(incr).addReg(ExtReg);
11412     } else
11413       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11414         .addReg(incr).addReg(dest);
11415 
11416     BuildMI(BB, dl, TII->get(PPC::BCC))
11417       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11418     BB->addSuccessor(loop2MBB);
11419     BB->addSuccessor(exitMBB);
11420     BB = loop2MBB;
11421   }
11422   BuildMI(BB, dl, TII->get(StoreMnemonic))
11423     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11424   BuildMI(BB, dl, TII->get(PPC::BCC))
11425     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11426   BB->addSuccessor(loopMBB);
11427   BB->addSuccessor(exitMBB);
11428 
11429   //  exitMBB:
11430   //   ...
11431   BB = exitMBB;
11432   return BB;
11433 }
11434 
11435 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11436     MachineInstr &MI, MachineBasicBlock *BB,
11437     bool is8bit, // operation
11438     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11439   // If we support part-word atomic mnemonics, just use them
11440   if (Subtarget.hasPartwordAtomics())
11441     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11442                             CmpPred);
11443 
11444   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11445   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11446   // In 64 bit mode we have to use 64 bits for addresses, even though the
11447   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11448   // registers without caring whether they're 32 or 64, but here we're
11449   // doing actual arithmetic on the addresses.
11450   bool is64bit = Subtarget.isPPC64();
11451   bool isLittleEndian = Subtarget.isLittleEndian();
11452   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11453 
11454   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11455   MachineFunction *F = BB->getParent();
11456   MachineFunction::iterator It = ++BB->getIterator();
11457 
11458   Register dest = MI.getOperand(0).getReg();
11459   Register ptrA = MI.getOperand(1).getReg();
11460   Register ptrB = MI.getOperand(2).getReg();
11461   Register incr = MI.getOperand(3).getReg();
11462   DebugLoc dl = MI.getDebugLoc();
11463 
11464   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11465   MachineBasicBlock *loop2MBB =
11466       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11467   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11468   F->insert(It, loopMBB);
11469   if (CmpOpcode)
11470     F->insert(It, loop2MBB);
11471   F->insert(It, exitMBB);
11472   exitMBB->splice(exitMBB->begin(), BB,
11473                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11474   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11475 
11476   MachineRegisterInfo &RegInfo = F->getRegInfo();
11477   const TargetRegisterClass *RC =
11478       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11479   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11480 
11481   Register PtrReg = RegInfo.createVirtualRegister(RC);
11482   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11483   Register ShiftReg =
11484       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11485   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11486   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11487   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11488   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11489   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11490   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11491   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11492   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11493   Register Ptr1Reg;
11494   Register TmpReg =
11495       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11496 
11497   //  thisMBB:
11498   //   ...
11499   //   fallthrough --> loopMBB
11500   BB->addSuccessor(loopMBB);
11501 
11502   // The 4-byte load must be aligned, while a char or short may be
11503   // anywhere in the word.  Hence all this nasty bookkeeping code.
11504   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11505   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11506   //   xori shift, shift1, 24 [16]
11507   //   rlwinm ptr, ptr1, 0, 0, 29
11508   //   slw incr2, incr, shift
11509   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11510   //   slw mask, mask2, shift
11511   //  loopMBB:
11512   //   lwarx tmpDest, ptr
11513   //   add tmp, tmpDest, incr2
11514   //   andc tmp2, tmpDest, mask
11515   //   and tmp3, tmp, mask
11516   //   or tmp4, tmp3, tmp2
11517   //   stwcx. tmp4, ptr
11518   //   bne- loopMBB
11519   //   fallthrough --> exitMBB
11520   //   srw dest, tmpDest, shift
11521   if (ptrA != ZeroReg) {
11522     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11523     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11524         .addReg(ptrA)
11525         .addReg(ptrB);
11526   } else {
11527     Ptr1Reg = ptrB;
11528   }
11529   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11530   // mode.
11531   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11532       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11533       .addImm(3)
11534       .addImm(27)
11535       .addImm(is8bit ? 28 : 27);
11536   if (!isLittleEndian)
11537     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11538         .addReg(Shift1Reg)
11539         .addImm(is8bit ? 24 : 16);
11540   if (is64bit)
11541     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11542         .addReg(Ptr1Reg)
11543         .addImm(0)
11544         .addImm(61);
11545   else
11546     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11547         .addReg(Ptr1Reg)
11548         .addImm(0)
11549         .addImm(0)
11550         .addImm(29);
11551   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11552   if (is8bit)
11553     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11554   else {
11555     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11556     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11557         .addReg(Mask3Reg)
11558         .addImm(65535);
11559   }
11560   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11561       .addReg(Mask2Reg)
11562       .addReg(ShiftReg);
11563 
11564   BB = loopMBB;
11565   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11566       .addReg(ZeroReg)
11567       .addReg(PtrReg);
11568   if (BinOpcode)
11569     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11570         .addReg(Incr2Reg)
11571         .addReg(TmpDestReg);
11572   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11573       .addReg(TmpDestReg)
11574       .addReg(MaskReg);
11575   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11576   if (CmpOpcode) {
11577     // For unsigned comparisons, we can directly compare the shifted values.
11578     // For signed comparisons we shift and sign extend.
11579     Register SReg = RegInfo.createVirtualRegister(GPRC);
11580     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11581         .addReg(TmpDestReg)
11582         .addReg(MaskReg);
11583     unsigned ValueReg = SReg;
11584     unsigned CmpReg = Incr2Reg;
11585     if (CmpOpcode == PPC::CMPW) {
11586       ValueReg = RegInfo.createVirtualRegister(GPRC);
11587       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11588           .addReg(SReg)
11589           .addReg(ShiftReg);
11590       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11591       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11592           .addReg(ValueReg);
11593       ValueReg = ValueSReg;
11594       CmpReg = incr;
11595     }
11596     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11597         .addReg(CmpReg)
11598         .addReg(ValueReg);
11599     BuildMI(BB, dl, TII->get(PPC::BCC))
11600         .addImm(CmpPred)
11601         .addReg(PPC::CR0)
11602         .addMBB(exitMBB);
11603     BB->addSuccessor(loop2MBB);
11604     BB->addSuccessor(exitMBB);
11605     BB = loop2MBB;
11606   }
11607   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11608   BuildMI(BB, dl, TII->get(PPC::STWCX))
11609       .addReg(Tmp4Reg)
11610       .addReg(ZeroReg)
11611       .addReg(PtrReg);
11612   BuildMI(BB, dl, TII->get(PPC::BCC))
11613       .addImm(PPC::PRED_NE)
11614       .addReg(PPC::CR0)
11615       .addMBB(loopMBB);
11616   BB->addSuccessor(loopMBB);
11617   BB->addSuccessor(exitMBB);
11618 
11619   //  exitMBB:
11620   //   ...
11621   BB = exitMBB;
11622   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11623       .addReg(TmpDestReg)
11624       .addReg(ShiftReg);
11625   return BB;
11626 }
11627 
11628 llvm::MachineBasicBlock *
11629 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11630                                     MachineBasicBlock *MBB) const {
11631   DebugLoc DL = MI.getDebugLoc();
11632   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11633   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11634 
11635   MachineFunction *MF = MBB->getParent();
11636   MachineRegisterInfo &MRI = MF->getRegInfo();
11637 
11638   const BasicBlock *BB = MBB->getBasicBlock();
11639   MachineFunction::iterator I = ++MBB->getIterator();
11640 
11641   Register DstReg = MI.getOperand(0).getReg();
11642   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11643   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11644   Register mainDstReg = MRI.createVirtualRegister(RC);
11645   Register restoreDstReg = MRI.createVirtualRegister(RC);
11646 
11647   MVT PVT = getPointerTy(MF->getDataLayout());
11648   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11649          "Invalid Pointer Size!");
11650   // For v = setjmp(buf), we generate
11651   //
11652   // thisMBB:
11653   //  SjLjSetup mainMBB
11654   //  bl mainMBB
11655   //  v_restore = 1
11656   //  b sinkMBB
11657   //
11658   // mainMBB:
11659   //  buf[LabelOffset] = LR
11660   //  v_main = 0
11661   //
11662   // sinkMBB:
11663   //  v = phi(main, restore)
11664   //
11665 
11666   MachineBasicBlock *thisMBB = MBB;
11667   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11668   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11669   MF->insert(I, mainMBB);
11670   MF->insert(I, sinkMBB);
11671 
11672   MachineInstrBuilder MIB;
11673 
11674   // Transfer the remainder of BB and its successor edges to sinkMBB.
11675   sinkMBB->splice(sinkMBB->begin(), MBB,
11676                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11677   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11678 
11679   // Note that the structure of the jmp_buf used here is not compatible
11680   // with that used by libc, and is not designed to be. Specifically, it
11681   // stores only those 'reserved' registers that LLVM does not otherwise
11682   // understand how to spill. Also, by convention, by the time this
11683   // intrinsic is called, Clang has already stored the frame address in the
11684   // first slot of the buffer and stack address in the third. Following the
11685   // X86 target code, we'll store the jump address in the second slot. We also
11686   // need to save the TOC pointer (R2) to handle jumps between shared
11687   // libraries, and that will be stored in the fourth slot. The thread
11688   // identifier (R13) is not affected.
11689 
11690   // thisMBB:
11691   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11692   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11693   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11694 
11695   // Prepare IP either in reg.
11696   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11697   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11698   Register BufReg = MI.getOperand(1).getReg();
11699 
11700   if (Subtarget.is64BitELFABI()) {
11701     setUsesTOCBasePtr(*MBB->getParent());
11702     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11703               .addReg(PPC::X2)
11704               .addImm(TOCOffset)
11705               .addReg(BufReg)
11706               .cloneMemRefs(MI);
11707   }
11708 
11709   // Naked functions never have a base pointer, and so we use r1. For all
11710   // other functions, this decision must be delayed until during PEI.
11711   unsigned BaseReg;
11712   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11713     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11714   else
11715     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11716 
11717   MIB = BuildMI(*thisMBB, MI, DL,
11718                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11719             .addReg(BaseReg)
11720             .addImm(BPOffset)
11721             .addReg(BufReg)
11722             .cloneMemRefs(MI);
11723 
11724   // Setup
11725   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11726   MIB.addRegMask(TRI->getNoPreservedMask());
11727 
11728   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11729 
11730   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11731           .addMBB(mainMBB);
11732   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11733 
11734   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11735   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11736 
11737   // mainMBB:
11738   //  mainDstReg = 0
11739   MIB =
11740       BuildMI(mainMBB, DL,
11741               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11742 
11743   // Store IP
11744   if (Subtarget.isPPC64()) {
11745     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11746             .addReg(LabelReg)
11747             .addImm(LabelOffset)
11748             .addReg(BufReg);
11749   } else {
11750     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11751             .addReg(LabelReg)
11752             .addImm(LabelOffset)
11753             .addReg(BufReg);
11754   }
11755   MIB.cloneMemRefs(MI);
11756 
11757   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11758   mainMBB->addSuccessor(sinkMBB);
11759 
11760   // sinkMBB:
11761   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11762           TII->get(PPC::PHI), DstReg)
11763     .addReg(mainDstReg).addMBB(mainMBB)
11764     .addReg(restoreDstReg).addMBB(thisMBB);
11765 
11766   MI.eraseFromParent();
11767   return sinkMBB;
11768 }
11769 
11770 MachineBasicBlock *
11771 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11772                                      MachineBasicBlock *MBB) const {
11773   DebugLoc DL = MI.getDebugLoc();
11774   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11775 
11776   MachineFunction *MF = MBB->getParent();
11777   MachineRegisterInfo &MRI = MF->getRegInfo();
11778 
11779   MVT PVT = getPointerTy(MF->getDataLayout());
11780   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11781          "Invalid Pointer Size!");
11782 
11783   const TargetRegisterClass *RC =
11784     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11785   Register Tmp = MRI.createVirtualRegister(RC);
11786   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11787   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11788   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11789   unsigned BP =
11790       (PVT == MVT::i64)
11791           ? PPC::X30
11792           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11793                                                               : PPC::R30);
11794 
11795   MachineInstrBuilder MIB;
11796 
11797   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11798   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11799   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11800   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11801 
11802   Register BufReg = MI.getOperand(0).getReg();
11803 
11804   // Reload FP (the jumped-to function may not have had a
11805   // frame pointer, and if so, then its r31 will be restored
11806   // as necessary).
11807   if (PVT == MVT::i64) {
11808     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11809             .addImm(0)
11810             .addReg(BufReg);
11811   } else {
11812     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11813             .addImm(0)
11814             .addReg(BufReg);
11815   }
11816   MIB.cloneMemRefs(MI);
11817 
11818   // Reload IP
11819   if (PVT == MVT::i64) {
11820     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11821             .addImm(LabelOffset)
11822             .addReg(BufReg);
11823   } else {
11824     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11825             .addImm(LabelOffset)
11826             .addReg(BufReg);
11827   }
11828   MIB.cloneMemRefs(MI);
11829 
11830   // Reload SP
11831   if (PVT == MVT::i64) {
11832     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11833             .addImm(SPOffset)
11834             .addReg(BufReg);
11835   } else {
11836     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11837             .addImm(SPOffset)
11838             .addReg(BufReg);
11839   }
11840   MIB.cloneMemRefs(MI);
11841 
11842   // Reload BP
11843   if (PVT == MVT::i64) {
11844     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11845             .addImm(BPOffset)
11846             .addReg(BufReg);
11847   } else {
11848     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11849             .addImm(BPOffset)
11850             .addReg(BufReg);
11851   }
11852   MIB.cloneMemRefs(MI);
11853 
11854   // Reload TOC
11855   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11856     setUsesTOCBasePtr(*MBB->getParent());
11857     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11858               .addImm(TOCOffset)
11859               .addReg(BufReg)
11860               .cloneMemRefs(MI);
11861   }
11862 
11863   // Jump
11864   BuildMI(*MBB, MI, DL,
11865           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11866   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11867 
11868   MI.eraseFromParent();
11869   return MBB;
11870 }
11871 
11872 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11873   // If the function specifically requests inline stack probes, emit them.
11874   if (MF.getFunction().hasFnAttribute("probe-stack"))
11875     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11876            "inline-asm";
11877   return false;
11878 }
11879 
11880 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11881   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11882   unsigned StackAlign = TFI->getStackAlignment();
11883   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11884          "Unexpected stack alignment");
11885   // The default stack probe size is 4096 if the function has no
11886   // stack-probe-size attribute.
11887   unsigned StackProbeSize = 4096;
11888   const Function &Fn = MF.getFunction();
11889   if (Fn.hasFnAttribute("stack-probe-size"))
11890     Fn.getFnAttribute("stack-probe-size")
11891         .getValueAsString()
11892         .getAsInteger(0, StackProbeSize);
11893   // Round down to the stack alignment.
11894   StackProbeSize &= ~(StackAlign - 1);
11895   return StackProbeSize ? StackProbeSize : StackAlign;
11896 }
11897 
11898 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11899 // into three phases. In the first phase, it uses pseudo instruction
11900 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11901 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11902 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11903 // MaxCallFrameSize so that it can calculate correct data area pointer.
11904 MachineBasicBlock *
11905 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11906                                     MachineBasicBlock *MBB) const {
11907   const bool isPPC64 = Subtarget.isPPC64();
11908   MachineFunction *MF = MBB->getParent();
11909   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11910   DebugLoc DL = MI.getDebugLoc();
11911   const unsigned ProbeSize = getStackProbeSize(*MF);
11912   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11913   MachineRegisterInfo &MRI = MF->getRegInfo();
11914   // The CFG of probing stack looks as
11915   //         +-----+
11916   //         | MBB |
11917   //         +--+--+
11918   //            |
11919   //       +----v----+
11920   //  +--->+ TestMBB +---+
11921   //  |    +----+----+   |
11922   //  |         |        |
11923   //  |   +-----v----+   |
11924   //  +---+ BlockMBB |   |
11925   //      +----------+   |
11926   //                     |
11927   //       +---------+   |
11928   //       | TailMBB +<--+
11929   //       +---------+
11930   // In MBB, calculate previous frame pointer and final stack pointer.
11931   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11932   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11933   // TailMBB is spliced via \p MI.
11934   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11935   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11936   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11937 
11938   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11939   MF->insert(MBBIter, TestMBB);
11940   MF->insert(MBBIter, BlockMBB);
11941   MF->insert(MBBIter, TailMBB);
11942 
11943   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11944   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11945 
11946   Register DstReg = MI.getOperand(0).getReg();
11947   Register NegSizeReg = MI.getOperand(1).getReg();
11948   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11949   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11950   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11951 
11952   // Get the canonical FinalStackPtr like what
11953   // PPCRegisterInfo::lowerDynamicAlloc does.
11954   BuildMI(*MBB, {MI}, DL,
11955           TII->get(isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64
11956                            : PPC::PREPARE_PROBED_ALLOCA_32),
11957           FramePointer)
11958       .addDef(FinalStackPtr)
11959       .addReg(NegSizeReg)
11960       .add(MI.getOperand(2))
11961       .add(MI.getOperand(3));
11962 
11963   // Materialize a scratch register for update.
11964   int64_t NegProbeSize = -(int64_t)ProbeSize;
11965   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
11966   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11967   if (!isInt<16>(NegProbeSize)) {
11968     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11969     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
11970         .addImm(NegProbeSize >> 16);
11971     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
11972             ScratchReg)
11973         .addReg(TempReg)
11974         .addImm(NegProbeSize & 0xFFFF);
11975   } else
11976     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
11977         .addImm(NegProbeSize);
11978 
11979   {
11980     // Probing leading residual part.
11981     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11982     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
11983         .addReg(NegSizeReg)
11984         .addReg(ScratchReg);
11985     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11986     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
11987         .addReg(Div)
11988         .addReg(ScratchReg);
11989     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11990     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
11991         .addReg(Mul)
11992         .addReg(NegSizeReg);
11993     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11994         .addReg(FramePointer)
11995         .addReg(SPReg)
11996         .addReg(NegMod);
11997   }
11998 
11999   {
12000     // Remaining part should be multiple of ProbeSize.
12001     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
12002     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
12003         .addReg(SPReg)
12004         .addReg(FinalStackPtr);
12005     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
12006         .addImm(PPC::PRED_EQ)
12007         .addReg(CmpResult)
12008         .addMBB(TailMBB);
12009     TestMBB->addSuccessor(BlockMBB);
12010     TestMBB->addSuccessor(TailMBB);
12011   }
12012 
12013   {
12014     // Touch the block.
12015     // |P...|P...|P...
12016     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
12017         .addReg(FramePointer)
12018         .addReg(SPReg)
12019         .addReg(ScratchReg);
12020     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
12021     BlockMBB->addSuccessor(TestMBB);
12022   }
12023 
12024   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
12025   // DYNAREAOFFSET pseudo instruction to get the future result.
12026   Register MaxCallFrameSizeReg =
12027       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12028   BuildMI(TailMBB, DL,
12029           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
12030           MaxCallFrameSizeReg)
12031       .add(MI.getOperand(2))
12032       .add(MI.getOperand(3));
12033   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
12034       .addReg(SPReg)
12035       .addReg(MaxCallFrameSizeReg);
12036 
12037   // Splice instructions after MI to TailMBB.
12038   TailMBB->splice(TailMBB->end(), MBB,
12039                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
12040   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
12041   MBB->addSuccessor(TestMBB);
12042 
12043   // Delete the pseudo instruction.
12044   MI.eraseFromParent();
12045 
12046   ++NumDynamicAllocaProbed;
12047   return TailMBB;
12048 }
12049 
12050 MachineBasicBlock *
12051 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
12052                                                MachineBasicBlock *BB) const {
12053   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
12054       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
12055     if (Subtarget.is64BitELFABI() &&
12056         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
12057         !Subtarget.isUsingPCRelativeCalls()) {
12058       // Call lowering should have added an r2 operand to indicate a dependence
12059       // on the TOC base pointer value. It can't however, because there is no
12060       // way to mark the dependence as implicit there, and so the stackmap code
12061       // will confuse it with a regular operand. Instead, add the dependence
12062       // here.
12063       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
12064     }
12065 
12066     return emitPatchPoint(MI, BB);
12067   }
12068 
12069   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
12070       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
12071     return emitEHSjLjSetJmp(MI, BB);
12072   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
12073              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
12074     return emitEHSjLjLongJmp(MI, BB);
12075   }
12076 
12077   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12078 
12079   // To "insert" these instructions we actually have to insert their
12080   // control-flow patterns.
12081   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12082   MachineFunction::iterator It = ++BB->getIterator();
12083 
12084   MachineFunction *F = BB->getParent();
12085 
12086   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12087       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
12088       MI.getOpcode() == PPC::SELECT_I8) {
12089     SmallVector<MachineOperand, 2> Cond;
12090     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12091         MI.getOpcode() == PPC::SELECT_CC_I8)
12092       Cond.push_back(MI.getOperand(4));
12093     else
12094       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
12095     Cond.push_back(MI.getOperand(1));
12096 
12097     DebugLoc dl = MI.getDebugLoc();
12098     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
12099                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
12100   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
12101              MI.getOpcode() == PPC::SELECT_CC_F8 ||
12102              MI.getOpcode() == PPC::SELECT_CC_F16 ||
12103              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
12104              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
12105              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
12106              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
12107              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
12108              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
12109              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
12110              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
12111              MI.getOpcode() == PPC::SELECT_CC_SPE ||
12112              MI.getOpcode() == PPC::SELECT_F4 ||
12113              MI.getOpcode() == PPC::SELECT_F8 ||
12114              MI.getOpcode() == PPC::SELECT_F16 ||
12115              MI.getOpcode() == PPC::SELECT_QFRC ||
12116              MI.getOpcode() == PPC::SELECT_QSRC ||
12117              MI.getOpcode() == PPC::SELECT_QBRC ||
12118              MI.getOpcode() == PPC::SELECT_SPE ||
12119              MI.getOpcode() == PPC::SELECT_SPE4 ||
12120              MI.getOpcode() == PPC::SELECT_VRRC ||
12121              MI.getOpcode() == PPC::SELECT_VSFRC ||
12122              MI.getOpcode() == PPC::SELECT_VSSRC ||
12123              MI.getOpcode() == PPC::SELECT_VSRC) {
12124     // The incoming instruction knows the destination vreg to set, the
12125     // condition code register to branch on, the true/false values to
12126     // select between, and a branch opcode to use.
12127 
12128     //  thisMBB:
12129     //  ...
12130     //   TrueVal = ...
12131     //   cmpTY ccX, r1, r2
12132     //   bCC copy1MBB
12133     //   fallthrough --> copy0MBB
12134     MachineBasicBlock *thisMBB = BB;
12135     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12136     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12137     DebugLoc dl = MI.getDebugLoc();
12138     F->insert(It, copy0MBB);
12139     F->insert(It, sinkMBB);
12140 
12141     // Transfer the remainder of BB and its successor edges to sinkMBB.
12142     sinkMBB->splice(sinkMBB->begin(), BB,
12143                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12144     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12145 
12146     // Next, add the true and fallthrough blocks as its successors.
12147     BB->addSuccessor(copy0MBB);
12148     BB->addSuccessor(sinkMBB);
12149 
12150     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
12151         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
12152         MI.getOpcode() == PPC::SELECT_F16 ||
12153         MI.getOpcode() == PPC::SELECT_SPE4 ||
12154         MI.getOpcode() == PPC::SELECT_SPE ||
12155         MI.getOpcode() == PPC::SELECT_QFRC ||
12156         MI.getOpcode() == PPC::SELECT_QSRC ||
12157         MI.getOpcode() == PPC::SELECT_QBRC ||
12158         MI.getOpcode() == PPC::SELECT_VRRC ||
12159         MI.getOpcode() == PPC::SELECT_VSFRC ||
12160         MI.getOpcode() == PPC::SELECT_VSSRC ||
12161         MI.getOpcode() == PPC::SELECT_VSRC) {
12162       BuildMI(BB, dl, TII->get(PPC::BC))
12163           .addReg(MI.getOperand(1).getReg())
12164           .addMBB(sinkMBB);
12165     } else {
12166       unsigned SelectPred = MI.getOperand(4).getImm();
12167       BuildMI(BB, dl, TII->get(PPC::BCC))
12168           .addImm(SelectPred)
12169           .addReg(MI.getOperand(1).getReg())
12170           .addMBB(sinkMBB);
12171     }
12172 
12173     //  copy0MBB:
12174     //   %FalseValue = ...
12175     //   # fallthrough to sinkMBB
12176     BB = copy0MBB;
12177 
12178     // Update machine-CFG edges
12179     BB->addSuccessor(sinkMBB);
12180 
12181     //  sinkMBB:
12182     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12183     //  ...
12184     BB = sinkMBB;
12185     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
12186         .addReg(MI.getOperand(3).getReg())
12187         .addMBB(copy0MBB)
12188         .addReg(MI.getOperand(2).getReg())
12189         .addMBB(thisMBB);
12190   } else if (MI.getOpcode() == PPC::ReadTB) {
12191     // To read the 64-bit time-base register on a 32-bit target, we read the
12192     // two halves. Should the counter have wrapped while it was being read, we
12193     // need to try again.
12194     // ...
12195     // readLoop:
12196     // mfspr Rx,TBU # load from TBU
12197     // mfspr Ry,TB  # load from TB
12198     // mfspr Rz,TBU # load from TBU
12199     // cmpw crX,Rx,Rz # check if 'old'='new'
12200     // bne readLoop   # branch if they're not equal
12201     // ...
12202 
12203     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
12204     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12205     DebugLoc dl = MI.getDebugLoc();
12206     F->insert(It, readMBB);
12207     F->insert(It, sinkMBB);
12208 
12209     // Transfer the remainder of BB and its successor edges to sinkMBB.
12210     sinkMBB->splice(sinkMBB->begin(), BB,
12211                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12212     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12213 
12214     BB->addSuccessor(readMBB);
12215     BB = readMBB;
12216 
12217     MachineRegisterInfo &RegInfo = F->getRegInfo();
12218     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
12219     Register LoReg = MI.getOperand(0).getReg();
12220     Register HiReg = MI.getOperand(1).getReg();
12221 
12222     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
12223     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
12224     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
12225 
12226     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12227 
12228     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
12229         .addReg(HiReg)
12230         .addReg(ReadAgainReg);
12231     BuildMI(BB, dl, TII->get(PPC::BCC))
12232         .addImm(PPC::PRED_NE)
12233         .addReg(CmpReg)
12234         .addMBB(readMBB);
12235 
12236     BB->addSuccessor(readMBB);
12237     BB->addSuccessor(sinkMBB);
12238   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
12239     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
12240   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
12241     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
12242   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
12243     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
12244   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
12245     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
12246 
12247   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
12248     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
12249   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
12250     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
12251   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
12252     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
12253   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
12254     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
12255 
12256   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
12257     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
12258   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
12259     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
12260   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
12261     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
12262   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
12263     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
12264 
12265   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
12266     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
12267   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
12268     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
12269   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
12270     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
12271   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
12272     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
12273 
12274   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
12275     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
12276   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
12277     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
12278   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
12279     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
12280   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
12281     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
12282 
12283   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
12284     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
12285   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
12286     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
12287   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
12288     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
12289   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
12290     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
12291 
12292   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
12293     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
12294   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
12295     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
12296   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
12297     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
12298   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
12299     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
12300 
12301   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
12302     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
12303   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
12304     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
12305   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
12306     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
12307   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
12308     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
12309 
12310   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
12311     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
12312   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
12313     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
12314   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
12315     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
12316   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
12317     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
12318 
12319   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
12320     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
12321   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
12322     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
12323   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
12324     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
12325   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
12326     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
12327 
12328   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
12329     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
12330   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
12331     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
12332   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
12333     BB = EmitAtomicBinary(MI, BB, 4, 0);
12334   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
12335     BB = EmitAtomicBinary(MI, BB, 8, 0);
12336   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
12337            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
12338            (Subtarget.hasPartwordAtomics() &&
12339             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
12340            (Subtarget.hasPartwordAtomics() &&
12341             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
12342     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
12343 
12344     auto LoadMnemonic = PPC::LDARX;
12345     auto StoreMnemonic = PPC::STDCX;
12346     switch (MI.getOpcode()) {
12347     default:
12348       llvm_unreachable("Compare and swap of unknown size");
12349     case PPC::ATOMIC_CMP_SWAP_I8:
12350       LoadMnemonic = PPC::LBARX;
12351       StoreMnemonic = PPC::STBCX;
12352       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12353       break;
12354     case PPC::ATOMIC_CMP_SWAP_I16:
12355       LoadMnemonic = PPC::LHARX;
12356       StoreMnemonic = PPC::STHCX;
12357       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12358       break;
12359     case PPC::ATOMIC_CMP_SWAP_I32:
12360       LoadMnemonic = PPC::LWARX;
12361       StoreMnemonic = PPC::STWCX;
12362       break;
12363     case PPC::ATOMIC_CMP_SWAP_I64:
12364       LoadMnemonic = PPC::LDARX;
12365       StoreMnemonic = PPC::STDCX;
12366       break;
12367     }
12368     Register dest = MI.getOperand(0).getReg();
12369     Register ptrA = MI.getOperand(1).getReg();
12370     Register ptrB = MI.getOperand(2).getReg();
12371     Register oldval = MI.getOperand(3).getReg();
12372     Register newval = MI.getOperand(4).getReg();
12373     DebugLoc dl = MI.getDebugLoc();
12374 
12375     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12376     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12377     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12378     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12379     F->insert(It, loop1MBB);
12380     F->insert(It, loop2MBB);
12381     F->insert(It, midMBB);
12382     F->insert(It, exitMBB);
12383     exitMBB->splice(exitMBB->begin(), BB,
12384                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12385     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12386 
12387     //  thisMBB:
12388     //   ...
12389     //   fallthrough --> loopMBB
12390     BB->addSuccessor(loop1MBB);
12391 
12392     // loop1MBB:
12393     //   l[bhwd]arx dest, ptr
12394     //   cmp[wd] dest, oldval
12395     //   bne- midMBB
12396     // loop2MBB:
12397     //   st[bhwd]cx. newval, ptr
12398     //   bne- loopMBB
12399     //   b exitBB
12400     // midMBB:
12401     //   st[bhwd]cx. dest, ptr
12402     // exitBB:
12403     BB = loop1MBB;
12404     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12405     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12406         .addReg(oldval)
12407         .addReg(dest);
12408     BuildMI(BB, dl, TII->get(PPC::BCC))
12409         .addImm(PPC::PRED_NE)
12410         .addReg(PPC::CR0)
12411         .addMBB(midMBB);
12412     BB->addSuccessor(loop2MBB);
12413     BB->addSuccessor(midMBB);
12414 
12415     BB = loop2MBB;
12416     BuildMI(BB, dl, TII->get(StoreMnemonic))
12417         .addReg(newval)
12418         .addReg(ptrA)
12419         .addReg(ptrB);
12420     BuildMI(BB, dl, TII->get(PPC::BCC))
12421         .addImm(PPC::PRED_NE)
12422         .addReg(PPC::CR0)
12423         .addMBB(loop1MBB);
12424     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12425     BB->addSuccessor(loop1MBB);
12426     BB->addSuccessor(exitMBB);
12427 
12428     BB = midMBB;
12429     BuildMI(BB, dl, TII->get(StoreMnemonic))
12430         .addReg(dest)
12431         .addReg(ptrA)
12432         .addReg(ptrB);
12433     BB->addSuccessor(exitMBB);
12434 
12435     //  exitMBB:
12436     //   ...
12437     BB = exitMBB;
12438   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12439              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12440     // We must use 64-bit registers for addresses when targeting 64-bit,
12441     // since we're actually doing arithmetic on them.  Other registers
12442     // can be 32-bit.
12443     bool is64bit = Subtarget.isPPC64();
12444     bool isLittleEndian = Subtarget.isLittleEndian();
12445     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12446 
12447     Register dest = MI.getOperand(0).getReg();
12448     Register ptrA = MI.getOperand(1).getReg();
12449     Register ptrB = MI.getOperand(2).getReg();
12450     Register oldval = MI.getOperand(3).getReg();
12451     Register newval = MI.getOperand(4).getReg();
12452     DebugLoc dl = MI.getDebugLoc();
12453 
12454     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12455     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12456     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12457     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12458     F->insert(It, loop1MBB);
12459     F->insert(It, loop2MBB);
12460     F->insert(It, midMBB);
12461     F->insert(It, exitMBB);
12462     exitMBB->splice(exitMBB->begin(), BB,
12463                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12464     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12465 
12466     MachineRegisterInfo &RegInfo = F->getRegInfo();
12467     const TargetRegisterClass *RC =
12468         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12469     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12470 
12471     Register PtrReg = RegInfo.createVirtualRegister(RC);
12472     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12473     Register ShiftReg =
12474         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12475     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12476     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12477     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12478     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12479     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12480     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12481     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12482     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12483     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12484     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12485     Register Ptr1Reg;
12486     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12487     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12488     //  thisMBB:
12489     //   ...
12490     //   fallthrough --> loopMBB
12491     BB->addSuccessor(loop1MBB);
12492 
12493     // The 4-byte load must be aligned, while a char or short may be
12494     // anywhere in the word.  Hence all this nasty bookkeeping code.
12495     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12496     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12497     //   xori shift, shift1, 24 [16]
12498     //   rlwinm ptr, ptr1, 0, 0, 29
12499     //   slw newval2, newval, shift
12500     //   slw oldval2, oldval,shift
12501     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12502     //   slw mask, mask2, shift
12503     //   and newval3, newval2, mask
12504     //   and oldval3, oldval2, mask
12505     // loop1MBB:
12506     //   lwarx tmpDest, ptr
12507     //   and tmp, tmpDest, mask
12508     //   cmpw tmp, oldval3
12509     //   bne- midMBB
12510     // loop2MBB:
12511     //   andc tmp2, tmpDest, mask
12512     //   or tmp4, tmp2, newval3
12513     //   stwcx. tmp4, ptr
12514     //   bne- loop1MBB
12515     //   b exitBB
12516     // midMBB:
12517     //   stwcx. tmpDest, ptr
12518     // exitBB:
12519     //   srw dest, tmpDest, shift
12520     if (ptrA != ZeroReg) {
12521       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12522       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12523           .addReg(ptrA)
12524           .addReg(ptrB);
12525     } else {
12526       Ptr1Reg = ptrB;
12527     }
12528 
12529     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12530     // mode.
12531     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12532         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12533         .addImm(3)
12534         .addImm(27)
12535         .addImm(is8bit ? 28 : 27);
12536     if (!isLittleEndian)
12537       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12538           .addReg(Shift1Reg)
12539           .addImm(is8bit ? 24 : 16);
12540     if (is64bit)
12541       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12542           .addReg(Ptr1Reg)
12543           .addImm(0)
12544           .addImm(61);
12545     else
12546       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12547           .addReg(Ptr1Reg)
12548           .addImm(0)
12549           .addImm(0)
12550           .addImm(29);
12551     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12552         .addReg(newval)
12553         .addReg(ShiftReg);
12554     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12555         .addReg(oldval)
12556         .addReg(ShiftReg);
12557     if (is8bit)
12558       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12559     else {
12560       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12561       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12562           .addReg(Mask3Reg)
12563           .addImm(65535);
12564     }
12565     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12566         .addReg(Mask2Reg)
12567         .addReg(ShiftReg);
12568     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12569         .addReg(NewVal2Reg)
12570         .addReg(MaskReg);
12571     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12572         .addReg(OldVal2Reg)
12573         .addReg(MaskReg);
12574 
12575     BB = loop1MBB;
12576     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12577         .addReg(ZeroReg)
12578         .addReg(PtrReg);
12579     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12580         .addReg(TmpDestReg)
12581         .addReg(MaskReg);
12582     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12583         .addReg(TmpReg)
12584         .addReg(OldVal3Reg);
12585     BuildMI(BB, dl, TII->get(PPC::BCC))
12586         .addImm(PPC::PRED_NE)
12587         .addReg(PPC::CR0)
12588         .addMBB(midMBB);
12589     BB->addSuccessor(loop2MBB);
12590     BB->addSuccessor(midMBB);
12591 
12592     BB = loop2MBB;
12593     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12594         .addReg(TmpDestReg)
12595         .addReg(MaskReg);
12596     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12597         .addReg(Tmp2Reg)
12598         .addReg(NewVal3Reg);
12599     BuildMI(BB, dl, TII->get(PPC::STWCX))
12600         .addReg(Tmp4Reg)
12601         .addReg(ZeroReg)
12602         .addReg(PtrReg);
12603     BuildMI(BB, dl, TII->get(PPC::BCC))
12604         .addImm(PPC::PRED_NE)
12605         .addReg(PPC::CR0)
12606         .addMBB(loop1MBB);
12607     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12608     BB->addSuccessor(loop1MBB);
12609     BB->addSuccessor(exitMBB);
12610 
12611     BB = midMBB;
12612     BuildMI(BB, dl, TII->get(PPC::STWCX))
12613         .addReg(TmpDestReg)
12614         .addReg(ZeroReg)
12615         .addReg(PtrReg);
12616     BB->addSuccessor(exitMBB);
12617 
12618     //  exitMBB:
12619     //   ...
12620     BB = exitMBB;
12621     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12622         .addReg(TmpReg)
12623         .addReg(ShiftReg);
12624   } else if (MI.getOpcode() == PPC::FADDrtz) {
12625     // This pseudo performs an FADD with rounding mode temporarily forced
12626     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12627     // is not modeled at the SelectionDAG level.
12628     Register Dest = MI.getOperand(0).getReg();
12629     Register Src1 = MI.getOperand(1).getReg();
12630     Register Src2 = MI.getOperand(2).getReg();
12631     DebugLoc dl = MI.getDebugLoc();
12632 
12633     MachineRegisterInfo &RegInfo = F->getRegInfo();
12634     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12635 
12636     // Save FPSCR value.
12637     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12638 
12639     // Set rounding mode to round-to-zero.
12640     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
12641     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
12642 
12643     // Perform addition.
12644     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
12645 
12646     // Restore FPSCR value.
12647     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12648   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12649              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12650              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12651              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12652     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12653                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12654                           ? PPC::ANDI8_rec
12655                           : PPC::ANDI_rec;
12656     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12657                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12658 
12659     MachineRegisterInfo &RegInfo = F->getRegInfo();
12660     Register Dest = RegInfo.createVirtualRegister(
12661         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12662 
12663     DebugLoc Dl = MI.getDebugLoc();
12664     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12665         .addReg(MI.getOperand(1).getReg())
12666         .addImm(1);
12667     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12668             MI.getOperand(0).getReg())
12669         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12670   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12671     DebugLoc Dl = MI.getDebugLoc();
12672     MachineRegisterInfo &RegInfo = F->getRegInfo();
12673     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12674     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12675     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12676             MI.getOperand(0).getReg())
12677         .addReg(CRReg);
12678   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12679     DebugLoc Dl = MI.getDebugLoc();
12680     unsigned Imm = MI.getOperand(1).getImm();
12681     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12682     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12683             MI.getOperand(0).getReg())
12684         .addReg(PPC::CR0EQ);
12685   } else if (MI.getOpcode() == PPC::SETRNDi) {
12686     DebugLoc dl = MI.getDebugLoc();
12687     Register OldFPSCRReg = MI.getOperand(0).getReg();
12688 
12689     // Save FPSCR value.
12690     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12691 
12692     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12693     // the following settings:
12694     //   00 Round to nearest
12695     //   01 Round to 0
12696     //   10 Round to +inf
12697     //   11 Round to -inf
12698 
12699     // When the operand is immediate, using the two least significant bits of
12700     // the immediate to set the bits 62:63 of FPSCR.
12701     unsigned Mode = MI.getOperand(1).getImm();
12702     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12703       .addImm(31);
12704 
12705     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12706       .addImm(30);
12707   } else if (MI.getOpcode() == PPC::SETRND) {
12708     DebugLoc dl = MI.getDebugLoc();
12709 
12710     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12711     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12712     // If the target doesn't have DirectMove, we should use stack to do the
12713     // conversion, because the target doesn't have the instructions like mtvsrd
12714     // or mfvsrd to do this conversion directly.
12715     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12716       if (Subtarget.hasDirectMove()) {
12717         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12718           .addReg(SrcReg);
12719       } else {
12720         // Use stack to do the register copy.
12721         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12722         MachineRegisterInfo &RegInfo = F->getRegInfo();
12723         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12724         if (RC == &PPC::F8RCRegClass) {
12725           // Copy register from F8RCRegClass to G8RCRegclass.
12726           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12727                  "Unsupported RegClass.");
12728 
12729           StoreOp = PPC::STFD;
12730           LoadOp = PPC::LD;
12731         } else {
12732           // Copy register from G8RCRegClass to F8RCRegclass.
12733           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12734                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12735                  "Unsupported RegClass.");
12736         }
12737 
12738         MachineFrameInfo &MFI = F->getFrameInfo();
12739         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12740 
12741         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12742             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12743             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12744             MFI.getObjectAlign(FrameIdx));
12745 
12746         // Store the SrcReg into the stack.
12747         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12748           .addReg(SrcReg)
12749           .addImm(0)
12750           .addFrameIndex(FrameIdx)
12751           .addMemOperand(MMOStore);
12752 
12753         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12754             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12755             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12756             MFI.getObjectAlign(FrameIdx));
12757 
12758         // Load from the stack where SrcReg is stored, and save to DestReg,
12759         // so we have done the RegClass conversion from RegClass::SrcReg to
12760         // RegClass::DestReg.
12761         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12762           .addImm(0)
12763           .addFrameIndex(FrameIdx)
12764           .addMemOperand(MMOLoad);
12765       }
12766     };
12767 
12768     Register OldFPSCRReg = MI.getOperand(0).getReg();
12769 
12770     // Save FPSCR value.
12771     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12772 
12773     // When the operand is gprc register, use two least significant bits of the
12774     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12775     //
12776     // copy OldFPSCRTmpReg, OldFPSCRReg
12777     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12778     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12779     // copy NewFPSCRReg, NewFPSCRTmpReg
12780     // mtfsf 255, NewFPSCRReg
12781     MachineOperand SrcOp = MI.getOperand(1);
12782     MachineRegisterInfo &RegInfo = F->getRegInfo();
12783     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12784 
12785     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12786 
12787     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12788     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12789 
12790     // The first operand of INSERT_SUBREG should be a register which has
12791     // subregisters, we only care about its RegClass, so we should use an
12792     // IMPLICIT_DEF register.
12793     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12794     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12795       .addReg(ImDefReg)
12796       .add(SrcOp)
12797       .addImm(1);
12798 
12799     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12800     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12801       .addReg(OldFPSCRTmpReg)
12802       .addReg(ExtSrcReg)
12803       .addImm(0)
12804       .addImm(62);
12805 
12806     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12807     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12808 
12809     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12810     // bits of FPSCR.
12811     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12812       .addImm(255)
12813       .addReg(NewFPSCRReg)
12814       .addImm(0)
12815       .addImm(0);
12816   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12817              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12818     return emitProbedAlloca(MI, BB);
12819   } else {
12820     llvm_unreachable("Unexpected instr type to insert");
12821   }
12822 
12823   MI.eraseFromParent(); // The pseudo instruction is gone now.
12824   return BB;
12825 }
12826 
12827 //===----------------------------------------------------------------------===//
12828 // Target Optimization Hooks
12829 //===----------------------------------------------------------------------===//
12830 
12831 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12832   // For the estimates, convergence is quadratic, so we essentially double the
12833   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12834   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12835   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12836   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12837   if (VT.getScalarType() == MVT::f64)
12838     RefinementSteps++;
12839   return RefinementSteps;
12840 }
12841 
12842 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12843                                            int Enabled, int &RefinementSteps,
12844                                            bool &UseOneConstNR,
12845                                            bool Reciprocal) const {
12846   EVT VT = Operand.getValueType();
12847   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12848       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12849       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12850       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12851       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12852       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12853     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12854       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12855 
12856     // The Newton-Raphson computation with a single constant does not provide
12857     // enough accuracy on some CPUs.
12858     UseOneConstNR = !Subtarget.needsTwoConstNR();
12859     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12860   }
12861   return SDValue();
12862 }
12863 
12864 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12865                                             int Enabled,
12866                                             int &RefinementSteps) const {
12867   EVT VT = Operand.getValueType();
12868   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12869       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12870       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12871       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12872       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12873       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12874     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12875       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12876     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12877   }
12878   return SDValue();
12879 }
12880 
12881 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12882   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12883   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12884   // enabled for division), this functionality is redundant with the default
12885   // combiner logic (once the division -> reciprocal/multiply transformation
12886   // has taken place). As a result, this matters more for older cores than for
12887   // newer ones.
12888 
12889   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12890   // reciprocal if there are two or more FDIVs (for embedded cores with only
12891   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12892   switch (Subtarget.getCPUDirective()) {
12893   default:
12894     return 3;
12895   case PPC::DIR_440:
12896   case PPC::DIR_A2:
12897   case PPC::DIR_E500:
12898   case PPC::DIR_E500mc:
12899   case PPC::DIR_E5500:
12900     return 2;
12901   }
12902 }
12903 
12904 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12905 // collapsed, and so we need to look through chains of them.
12906 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12907                                      int64_t& Offset, SelectionDAG &DAG) {
12908   if (DAG.isBaseWithConstantOffset(Loc)) {
12909     Base = Loc.getOperand(0);
12910     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12911 
12912     // The base might itself be a base plus an offset, and if so, accumulate
12913     // that as well.
12914     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12915   }
12916 }
12917 
12918 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12919                             unsigned Bytes, int Dist,
12920                             SelectionDAG &DAG) {
12921   if (VT.getSizeInBits() / 8 != Bytes)
12922     return false;
12923 
12924   SDValue BaseLoc = Base->getBasePtr();
12925   if (Loc.getOpcode() == ISD::FrameIndex) {
12926     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12927       return false;
12928     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12929     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12930     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12931     int FS  = MFI.getObjectSize(FI);
12932     int BFS = MFI.getObjectSize(BFI);
12933     if (FS != BFS || FS != (int)Bytes) return false;
12934     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12935   }
12936 
12937   SDValue Base1 = Loc, Base2 = BaseLoc;
12938   int64_t Offset1 = 0, Offset2 = 0;
12939   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12940   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12941   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12942     return true;
12943 
12944   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12945   const GlobalValue *GV1 = nullptr;
12946   const GlobalValue *GV2 = nullptr;
12947   Offset1 = 0;
12948   Offset2 = 0;
12949   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12950   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12951   if (isGA1 && isGA2 && GV1 == GV2)
12952     return Offset1 == (Offset2 + Dist*Bytes);
12953   return false;
12954 }
12955 
12956 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12957 // not enforce equality of the chain operands.
12958 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12959                             unsigned Bytes, int Dist,
12960                             SelectionDAG &DAG) {
12961   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12962     EVT VT = LS->getMemoryVT();
12963     SDValue Loc = LS->getBasePtr();
12964     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12965   }
12966 
12967   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12968     EVT VT;
12969     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12970     default: return false;
12971     case Intrinsic::ppc_qpx_qvlfd:
12972     case Intrinsic::ppc_qpx_qvlfda:
12973       VT = MVT::v4f64;
12974       break;
12975     case Intrinsic::ppc_qpx_qvlfs:
12976     case Intrinsic::ppc_qpx_qvlfsa:
12977       VT = MVT::v4f32;
12978       break;
12979     case Intrinsic::ppc_qpx_qvlfcd:
12980     case Intrinsic::ppc_qpx_qvlfcda:
12981       VT = MVT::v2f64;
12982       break;
12983     case Intrinsic::ppc_qpx_qvlfcs:
12984     case Intrinsic::ppc_qpx_qvlfcsa:
12985       VT = MVT::v2f32;
12986       break;
12987     case Intrinsic::ppc_qpx_qvlfiwa:
12988     case Intrinsic::ppc_qpx_qvlfiwz:
12989     case Intrinsic::ppc_altivec_lvx:
12990     case Intrinsic::ppc_altivec_lvxl:
12991     case Intrinsic::ppc_vsx_lxvw4x:
12992     case Intrinsic::ppc_vsx_lxvw4x_be:
12993       VT = MVT::v4i32;
12994       break;
12995     case Intrinsic::ppc_vsx_lxvd2x:
12996     case Intrinsic::ppc_vsx_lxvd2x_be:
12997       VT = MVT::v2f64;
12998       break;
12999     case Intrinsic::ppc_altivec_lvebx:
13000       VT = MVT::i8;
13001       break;
13002     case Intrinsic::ppc_altivec_lvehx:
13003       VT = MVT::i16;
13004       break;
13005     case Intrinsic::ppc_altivec_lvewx:
13006       VT = MVT::i32;
13007       break;
13008     }
13009 
13010     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
13011   }
13012 
13013   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
13014     EVT VT;
13015     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13016     default: return false;
13017     case Intrinsic::ppc_qpx_qvstfd:
13018     case Intrinsic::ppc_qpx_qvstfda:
13019       VT = MVT::v4f64;
13020       break;
13021     case Intrinsic::ppc_qpx_qvstfs:
13022     case Intrinsic::ppc_qpx_qvstfsa:
13023       VT = MVT::v4f32;
13024       break;
13025     case Intrinsic::ppc_qpx_qvstfcd:
13026     case Intrinsic::ppc_qpx_qvstfcda:
13027       VT = MVT::v2f64;
13028       break;
13029     case Intrinsic::ppc_qpx_qvstfcs:
13030     case Intrinsic::ppc_qpx_qvstfcsa:
13031       VT = MVT::v2f32;
13032       break;
13033     case Intrinsic::ppc_qpx_qvstfiw:
13034     case Intrinsic::ppc_qpx_qvstfiwa:
13035     case Intrinsic::ppc_altivec_stvx:
13036     case Intrinsic::ppc_altivec_stvxl:
13037     case Intrinsic::ppc_vsx_stxvw4x:
13038       VT = MVT::v4i32;
13039       break;
13040     case Intrinsic::ppc_vsx_stxvd2x:
13041       VT = MVT::v2f64;
13042       break;
13043     case Intrinsic::ppc_vsx_stxvw4x_be:
13044       VT = MVT::v4i32;
13045       break;
13046     case Intrinsic::ppc_vsx_stxvd2x_be:
13047       VT = MVT::v2f64;
13048       break;
13049     case Intrinsic::ppc_altivec_stvebx:
13050       VT = MVT::i8;
13051       break;
13052     case Intrinsic::ppc_altivec_stvehx:
13053       VT = MVT::i16;
13054       break;
13055     case Intrinsic::ppc_altivec_stvewx:
13056       VT = MVT::i32;
13057       break;
13058     }
13059 
13060     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
13061   }
13062 
13063   return false;
13064 }
13065 
13066 // Return true is there is a nearyby consecutive load to the one provided
13067 // (regardless of alignment). We search up and down the chain, looking though
13068 // token factors and other loads (but nothing else). As a result, a true result
13069 // indicates that it is safe to create a new consecutive load adjacent to the
13070 // load provided.
13071 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
13072   SDValue Chain = LD->getChain();
13073   EVT VT = LD->getMemoryVT();
13074 
13075   SmallSet<SDNode *, 16> LoadRoots;
13076   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
13077   SmallSet<SDNode *, 16> Visited;
13078 
13079   // First, search up the chain, branching to follow all token-factor operands.
13080   // If we find a consecutive load, then we're done, otherwise, record all
13081   // nodes just above the top-level loads and token factors.
13082   while (!Queue.empty()) {
13083     SDNode *ChainNext = Queue.pop_back_val();
13084     if (!Visited.insert(ChainNext).second)
13085       continue;
13086 
13087     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
13088       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13089         return true;
13090 
13091       if (!Visited.count(ChainLD->getChain().getNode()))
13092         Queue.push_back(ChainLD->getChain().getNode());
13093     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
13094       for (const SDUse &O : ChainNext->ops())
13095         if (!Visited.count(O.getNode()))
13096           Queue.push_back(O.getNode());
13097     } else
13098       LoadRoots.insert(ChainNext);
13099   }
13100 
13101   // Second, search down the chain, starting from the top-level nodes recorded
13102   // in the first phase. These top-level nodes are the nodes just above all
13103   // loads and token factors. Starting with their uses, recursively look though
13104   // all loads (just the chain uses) and token factors to find a consecutive
13105   // load.
13106   Visited.clear();
13107   Queue.clear();
13108 
13109   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
13110        IE = LoadRoots.end(); I != IE; ++I) {
13111     Queue.push_back(*I);
13112 
13113     while (!Queue.empty()) {
13114       SDNode *LoadRoot = Queue.pop_back_val();
13115       if (!Visited.insert(LoadRoot).second)
13116         continue;
13117 
13118       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
13119         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13120           return true;
13121 
13122       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
13123            UE = LoadRoot->use_end(); UI != UE; ++UI)
13124         if (((isa<MemSDNode>(*UI) &&
13125             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
13126             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
13127           Queue.push_back(*UI);
13128     }
13129   }
13130 
13131   return false;
13132 }
13133 
13134 /// This function is called when we have proved that a SETCC node can be replaced
13135 /// by subtraction (and other supporting instructions) so that the result of
13136 /// comparison is kept in a GPR instead of CR. This function is purely for
13137 /// codegen purposes and has some flags to guide the codegen process.
13138 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
13139                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
13140   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13141 
13142   // Zero extend the operands to the largest legal integer. Originally, they
13143   // must be of a strictly smaller size.
13144   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
13145                          DAG.getConstant(Size, DL, MVT::i32));
13146   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
13147                          DAG.getConstant(Size, DL, MVT::i32));
13148 
13149   // Swap if needed. Depends on the condition code.
13150   if (Swap)
13151     std::swap(Op0, Op1);
13152 
13153   // Subtract extended integers.
13154   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
13155 
13156   // Move the sign bit to the least significant position and zero out the rest.
13157   // Now the least significant bit carries the result of original comparison.
13158   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
13159                              DAG.getConstant(Size - 1, DL, MVT::i32));
13160   auto Final = Shifted;
13161 
13162   // Complement the result if needed. Based on the condition code.
13163   if (Complement)
13164     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
13165                         DAG.getConstant(1, DL, MVT::i64));
13166 
13167   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
13168 }
13169 
13170 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
13171                                                   DAGCombinerInfo &DCI) const {
13172   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13173 
13174   SelectionDAG &DAG = DCI.DAG;
13175   SDLoc DL(N);
13176 
13177   // Size of integers being compared has a critical role in the following
13178   // analysis, so we prefer to do this when all types are legal.
13179   if (!DCI.isAfterLegalizeDAG())
13180     return SDValue();
13181 
13182   // If all users of SETCC extend its value to a legal integer type
13183   // then we replace SETCC with a subtraction
13184   for (SDNode::use_iterator UI = N->use_begin(),
13185        UE = N->use_end(); UI != UE; ++UI) {
13186     if (UI->getOpcode() != ISD::ZERO_EXTEND)
13187       return SDValue();
13188   }
13189 
13190   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13191   auto OpSize = N->getOperand(0).getValueSizeInBits();
13192 
13193   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
13194 
13195   if (OpSize < Size) {
13196     switch (CC) {
13197     default: break;
13198     case ISD::SETULT:
13199       return generateEquivalentSub(N, Size, false, false, DL, DAG);
13200     case ISD::SETULE:
13201       return generateEquivalentSub(N, Size, true, true, DL, DAG);
13202     case ISD::SETUGT:
13203       return generateEquivalentSub(N, Size, false, true, DL, DAG);
13204     case ISD::SETUGE:
13205       return generateEquivalentSub(N, Size, true, false, DL, DAG);
13206     }
13207   }
13208 
13209   return SDValue();
13210 }
13211 
13212 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
13213                                                   DAGCombinerInfo &DCI) const {
13214   SelectionDAG &DAG = DCI.DAG;
13215   SDLoc dl(N);
13216 
13217   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
13218   // If we're tracking CR bits, we need to be careful that we don't have:
13219   //   trunc(binary-ops(zext(x), zext(y)))
13220   // or
13221   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
13222   // such that we're unnecessarily moving things into GPRs when it would be
13223   // better to keep them in CR bits.
13224 
13225   // Note that trunc here can be an actual i1 trunc, or can be the effective
13226   // truncation that comes from a setcc or select_cc.
13227   if (N->getOpcode() == ISD::TRUNCATE &&
13228       N->getValueType(0) != MVT::i1)
13229     return SDValue();
13230 
13231   if (N->getOperand(0).getValueType() != MVT::i32 &&
13232       N->getOperand(0).getValueType() != MVT::i64)
13233     return SDValue();
13234 
13235   if (N->getOpcode() == ISD::SETCC ||
13236       N->getOpcode() == ISD::SELECT_CC) {
13237     // If we're looking at a comparison, then we need to make sure that the
13238     // high bits (all except for the first) don't matter the result.
13239     ISD::CondCode CC =
13240       cast<CondCodeSDNode>(N->getOperand(
13241         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
13242     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
13243 
13244     if (ISD::isSignedIntSetCC(CC)) {
13245       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
13246           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
13247         return SDValue();
13248     } else if (ISD::isUnsignedIntSetCC(CC)) {
13249       if (!DAG.MaskedValueIsZero(N->getOperand(0),
13250                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
13251           !DAG.MaskedValueIsZero(N->getOperand(1),
13252                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
13253         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
13254                                              : SDValue());
13255     } else {
13256       // This is neither a signed nor an unsigned comparison, just make sure
13257       // that the high bits are equal.
13258       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
13259       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
13260 
13261       // We don't really care about what is known about the first bit (if
13262       // anything), so clear it in all masks prior to comparing them.
13263       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
13264       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
13265 
13266       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
13267         return SDValue();
13268     }
13269   }
13270 
13271   // We now know that the higher-order bits are irrelevant, we just need to
13272   // make sure that all of the intermediate operations are bit operations, and
13273   // all inputs are extensions.
13274   if (N->getOperand(0).getOpcode() != ISD::AND &&
13275       N->getOperand(0).getOpcode() != ISD::OR  &&
13276       N->getOperand(0).getOpcode() != ISD::XOR &&
13277       N->getOperand(0).getOpcode() != ISD::SELECT &&
13278       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
13279       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
13280       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
13281       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
13282       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
13283     return SDValue();
13284 
13285   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
13286       N->getOperand(1).getOpcode() != ISD::AND &&
13287       N->getOperand(1).getOpcode() != ISD::OR  &&
13288       N->getOperand(1).getOpcode() != ISD::XOR &&
13289       N->getOperand(1).getOpcode() != ISD::SELECT &&
13290       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
13291       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
13292       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
13293       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
13294       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
13295     return SDValue();
13296 
13297   SmallVector<SDValue, 4> Inputs;
13298   SmallVector<SDValue, 8> BinOps, PromOps;
13299   SmallPtrSet<SDNode *, 16> Visited;
13300 
13301   for (unsigned i = 0; i < 2; ++i) {
13302     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13303           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13304           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13305           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13306         isa<ConstantSDNode>(N->getOperand(i)))
13307       Inputs.push_back(N->getOperand(i));
13308     else
13309       BinOps.push_back(N->getOperand(i));
13310 
13311     if (N->getOpcode() == ISD::TRUNCATE)
13312       break;
13313   }
13314 
13315   // Visit all inputs, collect all binary operations (and, or, xor and
13316   // select) that are all fed by extensions.
13317   while (!BinOps.empty()) {
13318     SDValue BinOp = BinOps.back();
13319     BinOps.pop_back();
13320 
13321     if (!Visited.insert(BinOp.getNode()).second)
13322       continue;
13323 
13324     PromOps.push_back(BinOp);
13325 
13326     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13327       // The condition of the select is not promoted.
13328       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13329         continue;
13330       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13331         continue;
13332 
13333       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13334             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13335             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13336            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13337           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13338         Inputs.push_back(BinOp.getOperand(i));
13339       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13340                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13341                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13342                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13343                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
13344                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13345                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13346                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13347                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
13348         BinOps.push_back(BinOp.getOperand(i));
13349       } else {
13350         // We have an input that is not an extension or another binary
13351         // operation; we'll abort this transformation.
13352         return SDValue();
13353       }
13354     }
13355   }
13356 
13357   // Make sure that this is a self-contained cluster of operations (which
13358   // is not quite the same thing as saying that everything has only one
13359   // use).
13360   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13361     if (isa<ConstantSDNode>(Inputs[i]))
13362       continue;
13363 
13364     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13365                               UE = Inputs[i].getNode()->use_end();
13366          UI != UE; ++UI) {
13367       SDNode *User = *UI;
13368       if (User != N && !Visited.count(User))
13369         return SDValue();
13370 
13371       // Make sure that we're not going to promote the non-output-value
13372       // operand(s) or SELECT or SELECT_CC.
13373       // FIXME: Although we could sometimes handle this, and it does occur in
13374       // practice that one of the condition inputs to the select is also one of
13375       // the outputs, we currently can't deal with this.
13376       if (User->getOpcode() == ISD::SELECT) {
13377         if (User->getOperand(0) == Inputs[i])
13378           return SDValue();
13379       } else if (User->getOpcode() == ISD::SELECT_CC) {
13380         if (User->getOperand(0) == Inputs[i] ||
13381             User->getOperand(1) == Inputs[i])
13382           return SDValue();
13383       }
13384     }
13385   }
13386 
13387   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13388     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13389                               UE = PromOps[i].getNode()->use_end();
13390          UI != UE; ++UI) {
13391       SDNode *User = *UI;
13392       if (User != N && !Visited.count(User))
13393         return SDValue();
13394 
13395       // Make sure that we're not going to promote the non-output-value
13396       // operand(s) or SELECT or SELECT_CC.
13397       // FIXME: Although we could sometimes handle this, and it does occur in
13398       // practice that one of the condition inputs to the select is also one of
13399       // the outputs, we currently can't deal with this.
13400       if (User->getOpcode() == ISD::SELECT) {
13401         if (User->getOperand(0) == PromOps[i])
13402           return SDValue();
13403       } else if (User->getOpcode() == ISD::SELECT_CC) {
13404         if (User->getOperand(0) == PromOps[i] ||
13405             User->getOperand(1) == PromOps[i])
13406           return SDValue();
13407       }
13408     }
13409   }
13410 
13411   // Replace all inputs with the extension operand.
13412   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13413     // Constants may have users outside the cluster of to-be-promoted nodes,
13414     // and so we need to replace those as we do the promotions.
13415     if (isa<ConstantSDNode>(Inputs[i]))
13416       continue;
13417     else
13418       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13419   }
13420 
13421   std::list<HandleSDNode> PromOpHandles;
13422   for (auto &PromOp : PromOps)
13423     PromOpHandles.emplace_back(PromOp);
13424 
13425   // Replace all operations (these are all the same, but have a different
13426   // (i1) return type). DAG.getNode will validate that the types of
13427   // a binary operator match, so go through the list in reverse so that
13428   // we've likely promoted both operands first. Any intermediate truncations or
13429   // extensions disappear.
13430   while (!PromOpHandles.empty()) {
13431     SDValue PromOp = PromOpHandles.back().getValue();
13432     PromOpHandles.pop_back();
13433 
13434     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13435         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13436         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13437         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13438       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13439           PromOp.getOperand(0).getValueType() != MVT::i1) {
13440         // The operand is not yet ready (see comment below).
13441         PromOpHandles.emplace_front(PromOp);
13442         continue;
13443       }
13444 
13445       SDValue RepValue = PromOp.getOperand(0);
13446       if (isa<ConstantSDNode>(RepValue))
13447         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13448 
13449       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13450       continue;
13451     }
13452 
13453     unsigned C;
13454     switch (PromOp.getOpcode()) {
13455     default:             C = 0; break;
13456     case ISD::SELECT:    C = 1; break;
13457     case ISD::SELECT_CC: C = 2; break;
13458     }
13459 
13460     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13461          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13462         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13463          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13464       // The to-be-promoted operands of this node have not yet been
13465       // promoted (this should be rare because we're going through the
13466       // list backward, but if one of the operands has several users in
13467       // this cluster of to-be-promoted nodes, it is possible).
13468       PromOpHandles.emplace_front(PromOp);
13469       continue;
13470     }
13471 
13472     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13473                                 PromOp.getNode()->op_end());
13474 
13475     // If there are any constant inputs, make sure they're replaced now.
13476     for (unsigned i = 0; i < 2; ++i)
13477       if (isa<ConstantSDNode>(Ops[C+i]))
13478         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13479 
13480     DAG.ReplaceAllUsesOfValueWith(PromOp,
13481       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13482   }
13483 
13484   // Now we're left with the initial truncation itself.
13485   if (N->getOpcode() == ISD::TRUNCATE)
13486     return N->getOperand(0);
13487 
13488   // Otherwise, this is a comparison. The operands to be compared have just
13489   // changed type (to i1), but everything else is the same.
13490   return SDValue(N, 0);
13491 }
13492 
13493 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13494                                                   DAGCombinerInfo &DCI) const {
13495   SelectionDAG &DAG = DCI.DAG;
13496   SDLoc dl(N);
13497 
13498   // If we're tracking CR bits, we need to be careful that we don't have:
13499   //   zext(binary-ops(trunc(x), trunc(y)))
13500   // or
13501   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13502   // such that we're unnecessarily moving things into CR bits that can more
13503   // efficiently stay in GPRs. Note that if we're not certain that the high
13504   // bits are set as required by the final extension, we still may need to do
13505   // some masking to get the proper behavior.
13506 
13507   // This same functionality is important on PPC64 when dealing with
13508   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13509   // the return values of functions. Because it is so similar, it is handled
13510   // here as well.
13511 
13512   if (N->getValueType(0) != MVT::i32 &&
13513       N->getValueType(0) != MVT::i64)
13514     return SDValue();
13515 
13516   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13517         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13518     return SDValue();
13519 
13520   if (N->getOperand(0).getOpcode() != ISD::AND &&
13521       N->getOperand(0).getOpcode() != ISD::OR  &&
13522       N->getOperand(0).getOpcode() != ISD::XOR &&
13523       N->getOperand(0).getOpcode() != ISD::SELECT &&
13524       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13525     return SDValue();
13526 
13527   SmallVector<SDValue, 4> Inputs;
13528   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13529   SmallPtrSet<SDNode *, 16> Visited;
13530 
13531   // Visit all inputs, collect all binary operations (and, or, xor and
13532   // select) that are all fed by truncations.
13533   while (!BinOps.empty()) {
13534     SDValue BinOp = BinOps.back();
13535     BinOps.pop_back();
13536 
13537     if (!Visited.insert(BinOp.getNode()).second)
13538       continue;
13539 
13540     PromOps.push_back(BinOp);
13541 
13542     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13543       // The condition of the select is not promoted.
13544       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13545         continue;
13546       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13547         continue;
13548 
13549       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13550           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13551         Inputs.push_back(BinOp.getOperand(i));
13552       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13553                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13554                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13555                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13556                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13557         BinOps.push_back(BinOp.getOperand(i));
13558       } else {
13559         // We have an input that is not a truncation or another binary
13560         // operation; we'll abort this transformation.
13561         return SDValue();
13562       }
13563     }
13564   }
13565 
13566   // The operands of a select that must be truncated when the select is
13567   // promoted because the operand is actually part of the to-be-promoted set.
13568   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13569 
13570   // Make sure that this is a self-contained cluster of operations (which
13571   // is not quite the same thing as saying that everything has only one
13572   // use).
13573   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13574     if (isa<ConstantSDNode>(Inputs[i]))
13575       continue;
13576 
13577     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13578                               UE = Inputs[i].getNode()->use_end();
13579          UI != UE; ++UI) {
13580       SDNode *User = *UI;
13581       if (User != N && !Visited.count(User))
13582         return SDValue();
13583 
13584       // If we're going to promote the non-output-value operand(s) or SELECT or
13585       // SELECT_CC, record them for truncation.
13586       if (User->getOpcode() == ISD::SELECT) {
13587         if (User->getOperand(0) == Inputs[i])
13588           SelectTruncOp[0].insert(std::make_pair(User,
13589                                     User->getOperand(0).getValueType()));
13590       } else if (User->getOpcode() == ISD::SELECT_CC) {
13591         if (User->getOperand(0) == Inputs[i])
13592           SelectTruncOp[0].insert(std::make_pair(User,
13593                                     User->getOperand(0).getValueType()));
13594         if (User->getOperand(1) == Inputs[i])
13595           SelectTruncOp[1].insert(std::make_pair(User,
13596                                     User->getOperand(1).getValueType()));
13597       }
13598     }
13599   }
13600 
13601   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13602     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13603                               UE = PromOps[i].getNode()->use_end();
13604          UI != UE; ++UI) {
13605       SDNode *User = *UI;
13606       if (User != N && !Visited.count(User))
13607         return SDValue();
13608 
13609       // If we're going to promote the non-output-value operand(s) or SELECT or
13610       // SELECT_CC, record them for truncation.
13611       if (User->getOpcode() == ISD::SELECT) {
13612         if (User->getOperand(0) == PromOps[i])
13613           SelectTruncOp[0].insert(std::make_pair(User,
13614                                     User->getOperand(0).getValueType()));
13615       } else if (User->getOpcode() == ISD::SELECT_CC) {
13616         if (User->getOperand(0) == PromOps[i])
13617           SelectTruncOp[0].insert(std::make_pair(User,
13618                                     User->getOperand(0).getValueType()));
13619         if (User->getOperand(1) == PromOps[i])
13620           SelectTruncOp[1].insert(std::make_pair(User,
13621                                     User->getOperand(1).getValueType()));
13622       }
13623     }
13624   }
13625 
13626   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13627   bool ReallyNeedsExt = false;
13628   if (N->getOpcode() != ISD::ANY_EXTEND) {
13629     // If all of the inputs are not already sign/zero extended, then
13630     // we'll still need to do that at the end.
13631     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13632       if (isa<ConstantSDNode>(Inputs[i]))
13633         continue;
13634 
13635       unsigned OpBits =
13636         Inputs[i].getOperand(0).getValueSizeInBits();
13637       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13638 
13639       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13640            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13641                                   APInt::getHighBitsSet(OpBits,
13642                                                         OpBits-PromBits))) ||
13643           (N->getOpcode() == ISD::SIGN_EXTEND &&
13644            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13645              (OpBits-(PromBits-1)))) {
13646         ReallyNeedsExt = true;
13647         break;
13648       }
13649     }
13650   }
13651 
13652   // Replace all inputs, either with the truncation operand, or a
13653   // truncation or extension to the final output type.
13654   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13655     // Constant inputs need to be replaced with the to-be-promoted nodes that
13656     // use them because they might have users outside of the cluster of
13657     // promoted nodes.
13658     if (isa<ConstantSDNode>(Inputs[i]))
13659       continue;
13660 
13661     SDValue InSrc = Inputs[i].getOperand(0);
13662     if (Inputs[i].getValueType() == N->getValueType(0))
13663       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13664     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13665       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13666         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13667     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13668       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13669         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13670     else
13671       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13672         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13673   }
13674 
13675   std::list<HandleSDNode> PromOpHandles;
13676   for (auto &PromOp : PromOps)
13677     PromOpHandles.emplace_back(PromOp);
13678 
13679   // Replace all operations (these are all the same, but have a different
13680   // (promoted) return type). DAG.getNode will validate that the types of
13681   // a binary operator match, so go through the list in reverse so that
13682   // we've likely promoted both operands first.
13683   while (!PromOpHandles.empty()) {
13684     SDValue PromOp = PromOpHandles.back().getValue();
13685     PromOpHandles.pop_back();
13686 
13687     unsigned C;
13688     switch (PromOp.getOpcode()) {
13689     default:             C = 0; break;
13690     case ISD::SELECT:    C = 1; break;
13691     case ISD::SELECT_CC: C = 2; break;
13692     }
13693 
13694     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13695          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13696         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13697          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13698       // The to-be-promoted operands of this node have not yet been
13699       // promoted (this should be rare because we're going through the
13700       // list backward, but if one of the operands has several users in
13701       // this cluster of to-be-promoted nodes, it is possible).
13702       PromOpHandles.emplace_front(PromOp);
13703       continue;
13704     }
13705 
13706     // For SELECT and SELECT_CC nodes, we do a similar check for any
13707     // to-be-promoted comparison inputs.
13708     if (PromOp.getOpcode() == ISD::SELECT ||
13709         PromOp.getOpcode() == ISD::SELECT_CC) {
13710       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13711            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13712           (SelectTruncOp[1].count(PromOp.getNode()) &&
13713            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13714         PromOpHandles.emplace_front(PromOp);
13715         continue;
13716       }
13717     }
13718 
13719     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13720                                 PromOp.getNode()->op_end());
13721 
13722     // If this node has constant inputs, then they'll need to be promoted here.
13723     for (unsigned i = 0; i < 2; ++i) {
13724       if (!isa<ConstantSDNode>(Ops[C+i]))
13725         continue;
13726       if (Ops[C+i].getValueType() == N->getValueType(0))
13727         continue;
13728 
13729       if (N->getOpcode() == ISD::SIGN_EXTEND)
13730         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13731       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13732         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13733       else
13734         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13735     }
13736 
13737     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13738     // truncate them again to the original value type.
13739     if (PromOp.getOpcode() == ISD::SELECT ||
13740         PromOp.getOpcode() == ISD::SELECT_CC) {
13741       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13742       if (SI0 != SelectTruncOp[0].end())
13743         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13744       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13745       if (SI1 != SelectTruncOp[1].end())
13746         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13747     }
13748 
13749     DAG.ReplaceAllUsesOfValueWith(PromOp,
13750       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13751   }
13752 
13753   // Now we're left with the initial extension itself.
13754   if (!ReallyNeedsExt)
13755     return N->getOperand(0);
13756 
13757   // To zero extend, just mask off everything except for the first bit (in the
13758   // i1 case).
13759   if (N->getOpcode() == ISD::ZERO_EXTEND)
13760     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13761                        DAG.getConstant(APInt::getLowBitsSet(
13762                                          N->getValueSizeInBits(0), PromBits),
13763                                        dl, N->getValueType(0)));
13764 
13765   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13766          "Invalid extension type");
13767   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13768   SDValue ShiftCst =
13769       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13770   return DAG.getNode(
13771       ISD::SRA, dl, N->getValueType(0),
13772       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13773       ShiftCst);
13774 }
13775 
13776 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13777                                         DAGCombinerInfo &DCI) const {
13778   assert(N->getOpcode() == ISD::SETCC &&
13779          "Should be called with a SETCC node");
13780 
13781   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13782   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13783     SDValue LHS = N->getOperand(0);
13784     SDValue RHS = N->getOperand(1);
13785 
13786     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13787     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13788         LHS.hasOneUse())
13789       std::swap(LHS, RHS);
13790 
13791     // x == 0-y --> x+y == 0
13792     // x != 0-y --> x+y != 0
13793     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13794         RHS.hasOneUse()) {
13795       SDLoc DL(N);
13796       SelectionDAG &DAG = DCI.DAG;
13797       EVT VT = N->getValueType(0);
13798       EVT OpVT = LHS.getValueType();
13799       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13800       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13801     }
13802   }
13803 
13804   return DAGCombineTruncBoolExt(N, DCI);
13805 }
13806 
13807 // Is this an extending load from an f32 to an f64?
13808 static bool isFPExtLoad(SDValue Op) {
13809   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13810     return LD->getExtensionType() == ISD::EXTLOAD &&
13811       Op.getValueType() == MVT::f64;
13812   return false;
13813 }
13814 
13815 /// Reduces the number of fp-to-int conversion when building a vector.
13816 ///
13817 /// If this vector is built out of floating to integer conversions,
13818 /// transform it to a vector built out of floating point values followed by a
13819 /// single floating to integer conversion of the vector.
13820 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13821 /// becomes (fptosi (build_vector ($A, $B, ...)))
13822 SDValue PPCTargetLowering::
13823 combineElementTruncationToVectorTruncation(SDNode *N,
13824                                            DAGCombinerInfo &DCI) const {
13825   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13826          "Should be called with a BUILD_VECTOR node");
13827 
13828   SelectionDAG &DAG = DCI.DAG;
13829   SDLoc dl(N);
13830 
13831   SDValue FirstInput = N->getOperand(0);
13832   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13833          "The input operand must be an fp-to-int conversion.");
13834 
13835   // This combine happens after legalization so the fp_to_[su]i nodes are
13836   // already converted to PPCSISD nodes.
13837   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13838   if (FirstConversion == PPCISD::FCTIDZ ||
13839       FirstConversion == PPCISD::FCTIDUZ ||
13840       FirstConversion == PPCISD::FCTIWZ ||
13841       FirstConversion == PPCISD::FCTIWUZ) {
13842     bool IsSplat = true;
13843     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13844       FirstConversion == PPCISD::FCTIWUZ;
13845     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13846     SmallVector<SDValue, 4> Ops;
13847     EVT TargetVT = N->getValueType(0);
13848     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13849       SDValue NextOp = N->getOperand(i);
13850       if (NextOp.getOpcode() != PPCISD::MFVSR)
13851         return SDValue();
13852       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13853       if (NextConversion != FirstConversion)
13854         return SDValue();
13855       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13856       // This is not valid if the input was originally double precision. It is
13857       // also not profitable to do unless this is an extending load in which
13858       // case doing this combine will allow us to combine consecutive loads.
13859       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13860         return SDValue();
13861       if (N->getOperand(i) != FirstInput)
13862         IsSplat = false;
13863     }
13864 
13865     // If this is a splat, we leave it as-is since there will be only a single
13866     // fp-to-int conversion followed by a splat of the integer. This is better
13867     // for 32-bit and smaller ints and neutral for 64-bit ints.
13868     if (IsSplat)
13869       return SDValue();
13870 
13871     // Now that we know we have the right type of node, get its operands
13872     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13873       SDValue In = N->getOperand(i).getOperand(0);
13874       if (Is32Bit) {
13875         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13876         // here, we know that all inputs are extending loads so this is safe).
13877         if (In.isUndef())
13878           Ops.push_back(DAG.getUNDEF(SrcVT));
13879         else {
13880           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13881                                       MVT::f32, In.getOperand(0),
13882                                       DAG.getIntPtrConstant(1, dl));
13883           Ops.push_back(Trunc);
13884         }
13885       } else
13886         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13887     }
13888 
13889     unsigned Opcode;
13890     if (FirstConversion == PPCISD::FCTIDZ ||
13891         FirstConversion == PPCISD::FCTIWZ)
13892       Opcode = ISD::FP_TO_SINT;
13893     else
13894       Opcode = ISD::FP_TO_UINT;
13895 
13896     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13897     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13898     return DAG.getNode(Opcode, dl, TargetVT, BV);
13899   }
13900   return SDValue();
13901 }
13902 
13903 /// Reduce the number of loads when building a vector.
13904 ///
13905 /// Building a vector out of multiple loads can be converted to a load
13906 /// of the vector type if the loads are consecutive. If the loads are
13907 /// consecutive but in descending order, a shuffle is added at the end
13908 /// to reorder the vector.
13909 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13910   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13911          "Should be called with a BUILD_VECTOR node");
13912 
13913   SDLoc dl(N);
13914 
13915   // Return early for non byte-sized type, as they can't be consecutive.
13916   if (!N->getValueType(0).getVectorElementType().isByteSized())
13917     return SDValue();
13918 
13919   bool InputsAreConsecutiveLoads = true;
13920   bool InputsAreReverseConsecutive = true;
13921   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13922   SDValue FirstInput = N->getOperand(0);
13923   bool IsRoundOfExtLoad = false;
13924 
13925   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13926       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13927     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13928     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13929   }
13930   // Not a build vector of (possibly fp_rounded) loads.
13931   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13932       N->getNumOperands() == 1)
13933     return SDValue();
13934 
13935   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13936     // If any inputs are fp_round(extload), they all must be.
13937     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13938       return SDValue();
13939 
13940     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13941       N->getOperand(i);
13942     if (NextInput.getOpcode() != ISD::LOAD)
13943       return SDValue();
13944 
13945     SDValue PreviousInput =
13946       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13947     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13948     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13949 
13950     // If any inputs are fp_round(extload), they all must be.
13951     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13952       return SDValue();
13953 
13954     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13955       InputsAreConsecutiveLoads = false;
13956     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13957       InputsAreReverseConsecutive = false;
13958 
13959     // Exit early if the loads are neither consecutive nor reverse consecutive.
13960     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13961       return SDValue();
13962   }
13963 
13964   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13965          "The loads cannot be both consecutive and reverse consecutive.");
13966 
13967   SDValue FirstLoadOp =
13968     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13969   SDValue LastLoadOp =
13970     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13971                        N->getOperand(N->getNumOperands()-1);
13972 
13973   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13974   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13975   if (InputsAreConsecutiveLoads) {
13976     assert(LD1 && "Input needs to be a LoadSDNode.");
13977     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13978                        LD1->getBasePtr(), LD1->getPointerInfo(),
13979                        LD1->getAlignment());
13980   }
13981   if (InputsAreReverseConsecutive) {
13982     assert(LDL && "Input needs to be a LoadSDNode.");
13983     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13984                                LDL->getBasePtr(), LDL->getPointerInfo(),
13985                                LDL->getAlignment());
13986     SmallVector<int, 16> Ops;
13987     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13988       Ops.push_back(i);
13989 
13990     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13991                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13992   }
13993   return SDValue();
13994 }
13995 
13996 // This function adds the required vector_shuffle needed to get
13997 // the elements of the vector extract in the correct position
13998 // as specified by the CorrectElems encoding.
13999 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
14000                                       SDValue Input, uint64_t Elems,
14001                                       uint64_t CorrectElems) {
14002   SDLoc dl(N);
14003 
14004   unsigned NumElems = Input.getValueType().getVectorNumElements();
14005   SmallVector<int, 16> ShuffleMask(NumElems, -1);
14006 
14007   // Knowing the element indices being extracted from the original
14008   // vector and the order in which they're being inserted, just put
14009   // them at element indices required for the instruction.
14010   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14011     if (DAG.getDataLayout().isLittleEndian())
14012       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
14013     else
14014       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
14015     CorrectElems = CorrectElems >> 8;
14016     Elems = Elems >> 8;
14017   }
14018 
14019   SDValue Shuffle =
14020       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
14021                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
14022 
14023   EVT VT = N->getValueType(0);
14024   SDValue Conv = DAG.getBitcast(VT, Shuffle);
14025 
14026   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
14027                                Input.getValueType().getVectorElementType(),
14028                                VT.getVectorNumElements());
14029   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
14030                      DAG.getValueType(ExtVT));
14031 }
14032 
14033 // Look for build vector patterns where input operands come from sign
14034 // extended vector_extract elements of specific indices. If the correct indices
14035 // aren't used, add a vector shuffle to fix up the indices and create
14036 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
14037 // during instruction selection.
14038 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
14039   // This array encodes the indices that the vector sign extend instructions
14040   // extract from when extending from one type to another for both BE and LE.
14041   // The right nibble of each byte corresponds to the LE incides.
14042   // and the left nibble of each byte corresponds to the BE incides.
14043   // For example: 0x3074B8FC  byte->word
14044   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
14045   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
14046   // For example: 0x000070F8  byte->double word
14047   // For LE: the allowed indices are: 0x0,0x8
14048   // For BE: the allowed indices are: 0x7,0xF
14049   uint64_t TargetElems[] = {
14050       0x3074B8FC, // b->w
14051       0x000070F8, // b->d
14052       0x10325476, // h->w
14053       0x00003074, // h->d
14054       0x00001032, // w->d
14055   };
14056 
14057   uint64_t Elems = 0;
14058   int Index;
14059   SDValue Input;
14060 
14061   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
14062     if (!Op)
14063       return false;
14064     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
14065         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
14066       return false;
14067 
14068     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
14069     // of the right width.
14070     SDValue Extract = Op.getOperand(0);
14071     if (Extract.getOpcode() == ISD::ANY_EXTEND)
14072       Extract = Extract.getOperand(0);
14073     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14074       return false;
14075 
14076     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
14077     if (!ExtOp)
14078       return false;
14079 
14080     Index = ExtOp->getZExtValue();
14081     if (Input && Input != Extract.getOperand(0))
14082       return false;
14083 
14084     if (!Input)
14085       Input = Extract.getOperand(0);
14086 
14087     Elems = Elems << 8;
14088     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
14089     Elems |= Index;
14090 
14091     return true;
14092   };
14093 
14094   // If the build vector operands aren't sign extended vector extracts,
14095   // of the same input vector, then return.
14096   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14097     if (!isSExtOfVecExtract(N->getOperand(i))) {
14098       return SDValue();
14099     }
14100   }
14101 
14102   // If the vector extract indicies are not correct, add the appropriate
14103   // vector_shuffle.
14104   int TgtElemArrayIdx;
14105   int InputSize = Input.getValueType().getScalarSizeInBits();
14106   int OutputSize = N->getValueType(0).getScalarSizeInBits();
14107   if (InputSize + OutputSize == 40)
14108     TgtElemArrayIdx = 0;
14109   else if (InputSize + OutputSize == 72)
14110     TgtElemArrayIdx = 1;
14111   else if (InputSize + OutputSize == 48)
14112     TgtElemArrayIdx = 2;
14113   else if (InputSize + OutputSize == 80)
14114     TgtElemArrayIdx = 3;
14115   else if (InputSize + OutputSize == 96)
14116     TgtElemArrayIdx = 4;
14117   else
14118     return SDValue();
14119 
14120   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
14121   CorrectElems = DAG.getDataLayout().isLittleEndian()
14122                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
14123                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
14124   if (Elems != CorrectElems) {
14125     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
14126   }
14127 
14128   // Regular lowering will catch cases where a shuffle is not needed.
14129   return SDValue();
14130 }
14131 
14132 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
14133                                                  DAGCombinerInfo &DCI) const {
14134   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14135          "Should be called with a BUILD_VECTOR node");
14136 
14137   SelectionDAG &DAG = DCI.DAG;
14138   SDLoc dl(N);
14139 
14140   if (!Subtarget.hasVSX())
14141     return SDValue();
14142 
14143   // The target independent DAG combiner will leave a build_vector of
14144   // float-to-int conversions intact. We can generate MUCH better code for
14145   // a float-to-int conversion of a vector of floats.
14146   SDValue FirstInput = N->getOperand(0);
14147   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
14148     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
14149     if (Reduced)
14150       return Reduced;
14151   }
14152 
14153   // If we're building a vector out of consecutive loads, just load that
14154   // vector type.
14155   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
14156   if (Reduced)
14157     return Reduced;
14158 
14159   // If we're building a vector out of extended elements from another vector
14160   // we have P9 vector integer extend instructions. The code assumes legal
14161   // input types (i.e. it can't handle things like v4i16) so do not run before
14162   // legalization.
14163   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
14164     Reduced = combineBVOfVecSExt(N, DAG);
14165     if (Reduced)
14166       return Reduced;
14167   }
14168 
14169 
14170   if (N->getValueType(0) != MVT::v2f64)
14171     return SDValue();
14172 
14173   // Looking for:
14174   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
14175   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
14176       FirstInput.getOpcode() != ISD::UINT_TO_FP)
14177     return SDValue();
14178   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
14179       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
14180     return SDValue();
14181   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
14182     return SDValue();
14183 
14184   SDValue Ext1 = FirstInput.getOperand(0);
14185   SDValue Ext2 = N->getOperand(1).getOperand(0);
14186   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14187      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14188     return SDValue();
14189 
14190   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
14191   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
14192   if (!Ext1Op || !Ext2Op)
14193     return SDValue();
14194   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
14195       Ext1.getOperand(0) != Ext2.getOperand(0))
14196     return SDValue();
14197 
14198   int FirstElem = Ext1Op->getZExtValue();
14199   int SecondElem = Ext2Op->getZExtValue();
14200   int SubvecIdx;
14201   if (FirstElem == 0 && SecondElem == 1)
14202     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
14203   else if (FirstElem == 2 && SecondElem == 3)
14204     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
14205   else
14206     return SDValue();
14207 
14208   SDValue SrcVec = Ext1.getOperand(0);
14209   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
14210     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
14211   return DAG.getNode(NodeType, dl, MVT::v2f64,
14212                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
14213 }
14214 
14215 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
14216                                               DAGCombinerInfo &DCI) const {
14217   assert((N->getOpcode() == ISD::SINT_TO_FP ||
14218           N->getOpcode() == ISD::UINT_TO_FP) &&
14219          "Need an int -> FP conversion node here");
14220 
14221   if (useSoftFloat() || !Subtarget.has64BitSupport())
14222     return SDValue();
14223 
14224   SelectionDAG &DAG = DCI.DAG;
14225   SDLoc dl(N);
14226   SDValue Op(N, 0);
14227 
14228   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
14229   // from the hardware.
14230   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
14231     return SDValue();
14232   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
14233       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
14234     return SDValue();
14235 
14236   SDValue FirstOperand(Op.getOperand(0));
14237   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
14238     (FirstOperand.getValueType() == MVT::i8 ||
14239      FirstOperand.getValueType() == MVT::i16);
14240   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
14241     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
14242     bool DstDouble = Op.getValueType() == MVT::f64;
14243     unsigned ConvOp = Signed ?
14244       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
14245       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
14246     SDValue WidthConst =
14247       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
14248                             dl, false);
14249     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
14250     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
14251     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
14252                                          DAG.getVTList(MVT::f64, MVT::Other),
14253                                          Ops, MVT::i8, LDN->getMemOperand());
14254 
14255     // For signed conversion, we need to sign-extend the value in the VSR
14256     if (Signed) {
14257       SDValue ExtOps[] = { Ld, WidthConst };
14258       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
14259       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
14260     } else
14261       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
14262   }
14263 
14264 
14265   // For i32 intermediate values, unfortunately, the conversion functions
14266   // leave the upper 32 bits of the value are undefined. Within the set of
14267   // scalar instructions, we have no method for zero- or sign-extending the
14268   // value. Thus, we cannot handle i32 intermediate values here.
14269   if (Op.getOperand(0).getValueType() == MVT::i32)
14270     return SDValue();
14271 
14272   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
14273          "UINT_TO_FP is supported only with FPCVT");
14274 
14275   // If we have FCFIDS, then use it when converting to single-precision.
14276   // Otherwise, convert to double-precision and then round.
14277   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14278                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
14279                                                             : PPCISD::FCFIDS)
14280                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
14281                                                             : PPCISD::FCFID);
14282   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14283                   ? MVT::f32
14284                   : MVT::f64;
14285 
14286   // If we're converting from a float, to an int, and back to a float again,
14287   // then we don't need the store/load pair at all.
14288   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
14289        Subtarget.hasFPCVT()) ||
14290       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
14291     SDValue Src = Op.getOperand(0).getOperand(0);
14292     if (Src.getValueType() == MVT::f32) {
14293       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
14294       DCI.AddToWorklist(Src.getNode());
14295     } else if (Src.getValueType() != MVT::f64) {
14296       // Make sure that we don't pick up a ppc_fp128 source value.
14297       return SDValue();
14298     }
14299 
14300     unsigned FCTOp =
14301       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
14302                                                         PPCISD::FCTIDUZ;
14303 
14304     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
14305     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
14306 
14307     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
14308       FP = DAG.getNode(ISD::FP_ROUND, dl,
14309                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
14310       DCI.AddToWorklist(FP.getNode());
14311     }
14312 
14313     return FP;
14314   }
14315 
14316   return SDValue();
14317 }
14318 
14319 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
14320 // builtins) into loads with swaps.
14321 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
14322                                               DAGCombinerInfo &DCI) const {
14323   SelectionDAG &DAG = DCI.DAG;
14324   SDLoc dl(N);
14325   SDValue Chain;
14326   SDValue Base;
14327   MachineMemOperand *MMO;
14328 
14329   switch (N->getOpcode()) {
14330   default:
14331     llvm_unreachable("Unexpected opcode for little endian VSX load");
14332   case ISD::LOAD: {
14333     LoadSDNode *LD = cast<LoadSDNode>(N);
14334     Chain = LD->getChain();
14335     Base = LD->getBasePtr();
14336     MMO = LD->getMemOperand();
14337     // If the MMO suggests this isn't a load of a full vector, leave
14338     // things alone.  For a built-in, we have to make the change for
14339     // correctness, so if there is a size problem that will be a bug.
14340     if (MMO->getSize() < 16)
14341       return SDValue();
14342     break;
14343   }
14344   case ISD::INTRINSIC_W_CHAIN: {
14345     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14346     Chain = Intrin->getChain();
14347     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
14348     // us what we want. Get operand 2 instead.
14349     Base = Intrin->getOperand(2);
14350     MMO = Intrin->getMemOperand();
14351     break;
14352   }
14353   }
14354 
14355   MVT VecTy = N->getValueType(0).getSimpleVT();
14356 
14357   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
14358   // aligned and the type is a vector with elements up to 4 bytes
14359   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14360       VecTy.getScalarSizeInBits() <= 32) {
14361     return SDValue();
14362   }
14363 
14364   SDValue LoadOps[] = { Chain, Base };
14365   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14366                                          DAG.getVTList(MVT::v2f64, MVT::Other),
14367                                          LoadOps, MVT::v2f64, MMO);
14368 
14369   DCI.AddToWorklist(Load.getNode());
14370   Chain = Load.getValue(1);
14371   SDValue Swap = DAG.getNode(
14372       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14373   DCI.AddToWorklist(Swap.getNode());
14374 
14375   // Add a bitcast if the resulting load type doesn't match v2f64.
14376   if (VecTy != MVT::v2f64) {
14377     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14378     DCI.AddToWorklist(N.getNode());
14379     // Package {bitcast value, swap's chain} to match Load's shape.
14380     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14381                        N, Swap.getValue(1));
14382   }
14383 
14384   return Swap;
14385 }
14386 
14387 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14388 // builtins) into stores with swaps.
14389 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14390                                                DAGCombinerInfo &DCI) const {
14391   SelectionDAG &DAG = DCI.DAG;
14392   SDLoc dl(N);
14393   SDValue Chain;
14394   SDValue Base;
14395   unsigned SrcOpnd;
14396   MachineMemOperand *MMO;
14397 
14398   switch (N->getOpcode()) {
14399   default:
14400     llvm_unreachable("Unexpected opcode for little endian VSX store");
14401   case ISD::STORE: {
14402     StoreSDNode *ST = cast<StoreSDNode>(N);
14403     Chain = ST->getChain();
14404     Base = ST->getBasePtr();
14405     MMO = ST->getMemOperand();
14406     SrcOpnd = 1;
14407     // If the MMO suggests this isn't a store of a full vector, leave
14408     // things alone.  For a built-in, we have to make the change for
14409     // correctness, so if there is a size problem that will be a bug.
14410     if (MMO->getSize() < 16)
14411       return SDValue();
14412     break;
14413   }
14414   case ISD::INTRINSIC_VOID: {
14415     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14416     Chain = Intrin->getChain();
14417     // Intrin->getBasePtr() oddly does not get what we want.
14418     Base = Intrin->getOperand(3);
14419     MMO = Intrin->getMemOperand();
14420     SrcOpnd = 2;
14421     break;
14422   }
14423   }
14424 
14425   SDValue Src = N->getOperand(SrcOpnd);
14426   MVT VecTy = Src.getValueType().getSimpleVT();
14427 
14428   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14429   // aligned and the type is a vector with elements up to 4 bytes
14430   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14431       VecTy.getScalarSizeInBits() <= 32) {
14432     return SDValue();
14433   }
14434 
14435   // All stores are done as v2f64 and possible bit cast.
14436   if (VecTy != MVT::v2f64) {
14437     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14438     DCI.AddToWorklist(Src.getNode());
14439   }
14440 
14441   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14442                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14443   DCI.AddToWorklist(Swap.getNode());
14444   Chain = Swap.getValue(1);
14445   SDValue StoreOps[] = { Chain, Swap, Base };
14446   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14447                                           DAG.getVTList(MVT::Other),
14448                                           StoreOps, VecTy, MMO);
14449   DCI.AddToWorklist(Store.getNode());
14450   return Store;
14451 }
14452 
14453 // Handle DAG combine for STORE (FP_TO_INT F).
14454 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14455                                                DAGCombinerInfo &DCI) const {
14456 
14457   SelectionDAG &DAG = DCI.DAG;
14458   SDLoc dl(N);
14459   unsigned Opcode = N->getOperand(1).getOpcode();
14460 
14461   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14462          && "Not a FP_TO_INT Instruction!");
14463 
14464   SDValue Val = N->getOperand(1).getOperand(0);
14465   EVT Op1VT = N->getOperand(1).getValueType();
14466   EVT ResVT = Val.getValueType();
14467 
14468   // Floating point types smaller than 32 bits are not legal on Power.
14469   if (ResVT.getScalarSizeInBits() < 32)
14470     return SDValue();
14471 
14472   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14473   bool ValidTypeForStoreFltAsInt =
14474         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14475          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14476 
14477   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14478       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14479     return SDValue();
14480 
14481   // Extend f32 values to f64
14482   if (ResVT.getScalarSizeInBits() == 32) {
14483     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14484     DCI.AddToWorklist(Val.getNode());
14485   }
14486 
14487   // Set signed or unsigned conversion opcode.
14488   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14489                           PPCISD::FP_TO_SINT_IN_VSR :
14490                           PPCISD::FP_TO_UINT_IN_VSR;
14491 
14492   Val = DAG.getNode(ConvOpcode,
14493                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14494   DCI.AddToWorklist(Val.getNode());
14495 
14496   // Set number of bytes being converted.
14497   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14498   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14499                     DAG.getIntPtrConstant(ByteSize, dl, false),
14500                     DAG.getValueType(Op1VT) };
14501 
14502   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14503           DAG.getVTList(MVT::Other), Ops,
14504           cast<StoreSDNode>(N)->getMemoryVT(),
14505           cast<StoreSDNode>(N)->getMemOperand());
14506 
14507   DCI.AddToWorklist(Val.getNode());
14508   return Val;
14509 }
14510 
14511 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14512   // Check that the source of the element keeps flipping
14513   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14514   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14515   for (int i = 1, e = Mask.size(); i < e; i++) {
14516     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14517       return false;
14518     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14519       return false;
14520     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14521   }
14522   return true;
14523 }
14524 
14525 static bool isSplatBV(SDValue Op) {
14526   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14527     return false;
14528   SDValue FirstOp;
14529 
14530   // Find first non-undef input.
14531   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14532     FirstOp = Op.getOperand(i);
14533     if (!FirstOp.isUndef())
14534       break;
14535   }
14536 
14537   // All inputs are undef or the same as the first non-undef input.
14538   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14539     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14540       return false;
14541   return true;
14542 }
14543 
14544 static SDValue isScalarToVec(SDValue Op) {
14545   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14546     return Op;
14547   if (Op.getOpcode() != ISD::BITCAST)
14548     return SDValue();
14549   Op = Op.getOperand(0);
14550   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14551     return Op;
14552   return SDValue();
14553 }
14554 
14555 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14556                                             int LHSMaxIdx, int RHSMinIdx,
14557                                             int RHSMaxIdx, int HalfVec) {
14558   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14559     int Idx = ShuffV[i];
14560     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14561       ShuffV[i] += HalfVec;
14562   }
14563   return;
14564 }
14565 
14566 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14567 // the original is:
14568 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14569 // In such a case, just change the shuffle mask to extract the element
14570 // from the permuted index.
14571 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) {
14572   SDLoc dl(OrigSToV);
14573   EVT VT = OrigSToV.getValueType();
14574   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14575          "Expecting a SCALAR_TO_VECTOR here");
14576   SDValue Input = OrigSToV.getOperand(0);
14577 
14578   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14579     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14580     SDValue OrigVector = Input.getOperand(0);
14581 
14582     // Can't handle non-const element indices or different vector types
14583     // for the input to the extract and the output of the scalar_to_vector.
14584     if (Idx && VT == OrigVector.getValueType()) {
14585       SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1);
14586       NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue();
14587       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14588     }
14589   }
14590   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14591                      OrigSToV.getOperand(0));
14592 }
14593 
14594 // On little endian subtargets, combine shuffles such as:
14595 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14596 // into:
14597 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14598 // because the latter can be matched to a single instruction merge.
14599 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14600 // to put the value into element zero. Adjust the shuffle mask so that the
14601 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14602 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14603                                                 SelectionDAG &DAG) const {
14604   SDValue LHS = SVN->getOperand(0);
14605   SDValue RHS = SVN->getOperand(1);
14606   auto Mask = SVN->getMask();
14607   int NumElts = LHS.getValueType().getVectorNumElements();
14608   SDValue Res(SVN, 0);
14609   SDLoc dl(SVN);
14610 
14611   // None of these combines are useful on big endian systems since the ISA
14612   // already has a big endian bias.
14613   if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14614     return Res;
14615 
14616   // If this is not a shuffle of a shuffle and the first element comes from
14617   // the second vector, canonicalize to the commuted form. This will make it
14618   // more likely to match one of the single instruction patterns.
14619   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14620       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14621     std::swap(LHS, RHS);
14622     Res = DAG.getCommutedVectorShuffle(*SVN);
14623     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14624   }
14625 
14626   // Adjust the shuffle mask if either input vector comes from a
14627   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14628   // form (to prevent the need for a swap).
14629   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14630   SDValue SToVLHS = isScalarToVec(LHS);
14631   SDValue SToVRHS = isScalarToVec(RHS);
14632   if (SToVLHS || SToVRHS) {
14633     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14634                             : SToVRHS.getValueType().getVectorNumElements();
14635     int NumEltsOut = ShuffV.size();
14636 
14637     // Initially assume that neither input is permuted. These will be adjusted
14638     // accordingly if either input is.
14639     int LHSMaxIdx = -1;
14640     int RHSMinIdx = -1;
14641     int RHSMaxIdx = -1;
14642     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14643 
14644     // Get the permuted scalar to vector nodes for the source(s) that come from
14645     // ISD::SCALAR_TO_VECTOR.
14646     if (SToVLHS) {
14647       // Set up the values for the shuffle vector fixup.
14648       LHSMaxIdx = NumEltsOut / NumEltsIn;
14649       SToVLHS = getSToVPermuted(SToVLHS, DAG);
14650       if (SToVLHS.getValueType() != LHS.getValueType())
14651         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14652       LHS = SToVLHS;
14653     }
14654     if (SToVRHS) {
14655       RHSMinIdx = NumEltsOut;
14656       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14657       SToVRHS = getSToVPermuted(SToVRHS, DAG);
14658       if (SToVRHS.getValueType() != RHS.getValueType())
14659         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14660       RHS = SToVRHS;
14661     }
14662 
14663     // Fix up the shuffle mask to reflect where the desired element actually is.
14664     // The minimum and maximum indices that correspond to element zero for both
14665     // the LHS and RHS are computed and will control which shuffle mask entries
14666     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14667     // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by
14668     // HalfVec to refer to the corresponding element in the permuted vector.
14669     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14670                                     HalfVec);
14671     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14672 
14673     // We may have simplified away the shuffle. We won't be able to do anything
14674     // further with it here.
14675     if (!isa<ShuffleVectorSDNode>(Res))
14676       return Res;
14677     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14678   }
14679 
14680   // The common case after we commuted the shuffle is that the RHS is a splat
14681   // and we have elements coming in from the splat at indices that are not
14682   // conducive to using a merge.
14683   // Example:
14684   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14685   if (!isSplatBV(RHS))
14686     return Res;
14687 
14688   // We are looking for a mask such that all even elements are from
14689   // one vector and all odd elements from the other.
14690   if (!isAlternatingShuffMask(Mask, NumElts))
14691     return Res;
14692 
14693   // Adjust the mask so we are pulling in the same index from the splat
14694   // as the index from the interesting vector in consecutive elements.
14695   // Example (even elements from first vector):
14696   // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14697   if (Mask[0] < NumElts)
14698     for (int i = 1, e = Mask.size(); i < e; i += 2)
14699       ShuffV[i] = (ShuffV[i - 1] + NumElts);
14700   // Example (odd elements from first vector):
14701   // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14702   else
14703     for (int i = 0, e = Mask.size(); i < e; i += 2)
14704       ShuffV[i] = (ShuffV[i + 1] + NumElts);
14705 
14706   // If the RHS has undefs, we need to remove them since we may have created
14707   // a shuffle that adds those instead of the splat value.
14708   SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue();
14709   RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal);
14710 
14711   Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14712   return Res;
14713 }
14714 
14715 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14716                                                 LSBaseSDNode *LSBase,
14717                                                 DAGCombinerInfo &DCI) const {
14718   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14719         "Not a reverse memop pattern!");
14720 
14721   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14722     auto Mask = SVN->getMask();
14723     int i = 0;
14724     auto I = Mask.rbegin();
14725     auto E = Mask.rend();
14726 
14727     for (; I != E; ++I) {
14728       if (*I != i)
14729         return false;
14730       i++;
14731     }
14732     return true;
14733   };
14734 
14735   SelectionDAG &DAG = DCI.DAG;
14736   EVT VT = SVN->getValueType(0);
14737 
14738   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14739     return SDValue();
14740 
14741   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14742   // See comment in PPCVSXSwapRemoval.cpp.
14743   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14744   if (!Subtarget.hasP9Vector())
14745     return SDValue();
14746 
14747   if(!IsElementReverse(SVN))
14748     return SDValue();
14749 
14750   if (LSBase->getOpcode() == ISD::LOAD) {
14751     SDLoc dl(SVN);
14752     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14753     return DAG.getMemIntrinsicNode(
14754         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14755         LSBase->getMemoryVT(), LSBase->getMemOperand());
14756   }
14757 
14758   if (LSBase->getOpcode() == ISD::STORE) {
14759     SDLoc dl(LSBase);
14760     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14761                           LSBase->getBasePtr()};
14762     return DAG.getMemIntrinsicNode(
14763         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14764         LSBase->getMemoryVT(), LSBase->getMemOperand());
14765   }
14766 
14767   llvm_unreachable("Expected a load or store node here");
14768 }
14769 
14770 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14771                                              DAGCombinerInfo &DCI) const {
14772   SelectionDAG &DAG = DCI.DAG;
14773   SDLoc dl(N);
14774   switch (N->getOpcode()) {
14775   default: break;
14776   case ISD::ADD:
14777     return combineADD(N, DCI);
14778   case ISD::SHL:
14779     return combineSHL(N, DCI);
14780   case ISD::SRA:
14781     return combineSRA(N, DCI);
14782   case ISD::SRL:
14783     return combineSRL(N, DCI);
14784   case ISD::MUL:
14785     return combineMUL(N, DCI);
14786   case ISD::FMA:
14787   case PPCISD::FNMSUB:
14788     return combineFMALike(N, DCI);
14789   case PPCISD::SHL:
14790     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14791         return N->getOperand(0);
14792     break;
14793   case PPCISD::SRL:
14794     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14795         return N->getOperand(0);
14796     break;
14797   case PPCISD::SRA:
14798     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14799       if (C->isNullValue() ||   //  0 >>s V -> 0.
14800           C->isAllOnesValue())    // -1 >>s V -> -1.
14801         return N->getOperand(0);
14802     }
14803     break;
14804   case ISD::SIGN_EXTEND:
14805   case ISD::ZERO_EXTEND:
14806   case ISD::ANY_EXTEND:
14807     return DAGCombineExtBoolTrunc(N, DCI);
14808   case ISD::TRUNCATE:
14809     return combineTRUNCATE(N, DCI);
14810   case ISD::SETCC:
14811     if (SDValue CSCC = combineSetCC(N, DCI))
14812       return CSCC;
14813     LLVM_FALLTHROUGH;
14814   case ISD::SELECT_CC:
14815     return DAGCombineTruncBoolExt(N, DCI);
14816   case ISD::SINT_TO_FP:
14817   case ISD::UINT_TO_FP:
14818     return combineFPToIntToFP(N, DCI);
14819   case ISD::VECTOR_SHUFFLE:
14820     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14821       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14822       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14823     }
14824     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14825   case ISD::STORE: {
14826 
14827     EVT Op1VT = N->getOperand(1).getValueType();
14828     unsigned Opcode = N->getOperand(1).getOpcode();
14829 
14830     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14831       SDValue Val= combineStoreFPToInt(N, DCI);
14832       if (Val)
14833         return Val;
14834     }
14835 
14836     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14837       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14838       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14839       if (Val)
14840         return Val;
14841     }
14842 
14843     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14844     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14845         N->getOperand(1).getNode()->hasOneUse() &&
14846         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14847          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14848 
14849       // STBRX can only handle simple types and it makes no sense to store less
14850       // two bytes in byte-reversed order.
14851       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14852       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14853         break;
14854 
14855       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14856       // Do an any-extend to 32-bits if this is a half-word input.
14857       if (BSwapOp.getValueType() == MVT::i16)
14858         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14859 
14860       // If the type of BSWAP operand is wider than stored memory width
14861       // it need to be shifted to the right side before STBRX.
14862       if (Op1VT.bitsGT(mVT)) {
14863         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14864         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14865                               DAG.getConstant(Shift, dl, MVT::i32));
14866         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14867         if (Op1VT == MVT::i64)
14868           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14869       }
14870 
14871       SDValue Ops[] = {
14872         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14873       };
14874       return
14875         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14876                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14877                                 cast<StoreSDNode>(N)->getMemOperand());
14878     }
14879 
14880     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14881     // So it can increase the chance of CSE constant construction.
14882     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14883         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14884       // Need to sign-extended to 64-bits to handle negative values.
14885       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14886       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14887                                     MemVT.getSizeInBits());
14888       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14889 
14890       // DAG.getTruncStore() can't be used here because it doesn't accept
14891       // the general (base + offset) addressing mode.
14892       // So we use UpdateNodeOperands and setTruncatingStore instead.
14893       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14894                              N->getOperand(3));
14895       cast<StoreSDNode>(N)->setTruncatingStore(true);
14896       return SDValue(N, 0);
14897     }
14898 
14899     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14900     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14901     if (Op1VT.isSimple()) {
14902       MVT StoreVT = Op1VT.getSimpleVT();
14903       if (Subtarget.needsSwapsForVSXMemOps() &&
14904           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14905            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14906         return expandVSXStoreForLE(N, DCI);
14907     }
14908     break;
14909   }
14910   case ISD::LOAD: {
14911     LoadSDNode *LD = cast<LoadSDNode>(N);
14912     EVT VT = LD->getValueType(0);
14913 
14914     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14915     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14916     if (VT.isSimple()) {
14917       MVT LoadVT = VT.getSimpleVT();
14918       if (Subtarget.needsSwapsForVSXMemOps() &&
14919           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14920            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14921         return expandVSXLoadForLE(N, DCI);
14922     }
14923 
14924     // We sometimes end up with a 64-bit integer load, from which we extract
14925     // two single-precision floating-point numbers. This happens with
14926     // std::complex<float>, and other similar structures, because of the way we
14927     // canonicalize structure copies. However, if we lack direct moves,
14928     // then the final bitcasts from the extracted integer values to the
14929     // floating-point numbers turn into store/load pairs. Even with direct moves,
14930     // just loading the two floating-point numbers is likely better.
14931     auto ReplaceTwoFloatLoad = [&]() {
14932       if (VT != MVT::i64)
14933         return false;
14934 
14935       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14936           LD->isVolatile())
14937         return false;
14938 
14939       //  We're looking for a sequence like this:
14940       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14941       //      t16: i64 = srl t13, Constant:i32<32>
14942       //    t17: i32 = truncate t16
14943       //  t18: f32 = bitcast t17
14944       //    t19: i32 = truncate t13
14945       //  t20: f32 = bitcast t19
14946 
14947       if (!LD->hasNUsesOfValue(2, 0))
14948         return false;
14949 
14950       auto UI = LD->use_begin();
14951       while (UI.getUse().getResNo() != 0) ++UI;
14952       SDNode *Trunc = *UI++;
14953       while (UI.getUse().getResNo() != 0) ++UI;
14954       SDNode *RightShift = *UI;
14955       if (Trunc->getOpcode() != ISD::TRUNCATE)
14956         std::swap(Trunc, RightShift);
14957 
14958       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14959           Trunc->getValueType(0) != MVT::i32 ||
14960           !Trunc->hasOneUse())
14961         return false;
14962       if (RightShift->getOpcode() != ISD::SRL ||
14963           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14964           RightShift->getConstantOperandVal(1) != 32 ||
14965           !RightShift->hasOneUse())
14966         return false;
14967 
14968       SDNode *Trunc2 = *RightShift->use_begin();
14969       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14970           Trunc2->getValueType(0) != MVT::i32 ||
14971           !Trunc2->hasOneUse())
14972         return false;
14973 
14974       SDNode *Bitcast = *Trunc->use_begin();
14975       SDNode *Bitcast2 = *Trunc2->use_begin();
14976 
14977       if (Bitcast->getOpcode() != ISD::BITCAST ||
14978           Bitcast->getValueType(0) != MVT::f32)
14979         return false;
14980       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14981           Bitcast2->getValueType(0) != MVT::f32)
14982         return false;
14983 
14984       if (Subtarget.isLittleEndian())
14985         std::swap(Bitcast, Bitcast2);
14986 
14987       // Bitcast has the second float (in memory-layout order) and Bitcast2
14988       // has the first one.
14989 
14990       SDValue BasePtr = LD->getBasePtr();
14991       if (LD->isIndexed()) {
14992         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14993                "Non-pre-inc AM on PPC?");
14994         BasePtr =
14995           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14996                       LD->getOffset());
14997       }
14998 
14999       auto MMOFlags =
15000           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
15001       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
15002                                       LD->getPointerInfo(), LD->getAlignment(),
15003                                       MMOFlags, LD->getAAInfo());
15004       SDValue AddPtr =
15005         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
15006                     BasePtr, DAG.getIntPtrConstant(4, dl));
15007       SDValue FloatLoad2 = DAG.getLoad(
15008           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
15009           LD->getPointerInfo().getWithOffset(4),
15010           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
15011 
15012       if (LD->isIndexed()) {
15013         // Note that DAGCombine should re-form any pre-increment load(s) from
15014         // what is produced here if that makes sense.
15015         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
15016       }
15017 
15018       DCI.CombineTo(Bitcast2, FloatLoad);
15019       DCI.CombineTo(Bitcast, FloatLoad2);
15020 
15021       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
15022                                     SDValue(FloatLoad2.getNode(), 1));
15023       return true;
15024     };
15025 
15026     if (ReplaceTwoFloatLoad())
15027       return SDValue(N, 0);
15028 
15029     EVT MemVT = LD->getMemoryVT();
15030     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
15031     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
15032     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
15033     Align ScalarABIAlignment = DAG.getDataLayout().getABITypeAlign(STy);
15034     if (LD->isUnindexed() && VT.isVector() &&
15035         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
15036           // P8 and later hardware should just use LOAD.
15037           !Subtarget.hasP8Vector() &&
15038           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
15039            VT == MVT::v4f32)) ||
15040          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
15041           LD->getAlign() >= ScalarABIAlignment)) &&
15042         LD->getAlign() < ABIAlignment) {
15043       // This is a type-legal unaligned Altivec or QPX load.
15044       SDValue Chain = LD->getChain();
15045       SDValue Ptr = LD->getBasePtr();
15046       bool isLittleEndian = Subtarget.isLittleEndian();
15047 
15048       // This implements the loading of unaligned vectors as described in
15049       // the venerable Apple Velocity Engine overview. Specifically:
15050       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
15051       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
15052       //
15053       // The general idea is to expand a sequence of one or more unaligned
15054       // loads into an alignment-based permutation-control instruction (lvsl
15055       // or lvsr), a series of regular vector loads (which always truncate
15056       // their input address to an aligned address), and a series of
15057       // permutations.  The results of these permutations are the requested
15058       // loaded values.  The trick is that the last "extra" load is not taken
15059       // from the address you might suspect (sizeof(vector) bytes after the
15060       // last requested load), but rather sizeof(vector) - 1 bytes after the
15061       // last requested vector. The point of this is to avoid a page fault if
15062       // the base address happened to be aligned. This works because if the
15063       // base address is aligned, then adding less than a full vector length
15064       // will cause the last vector in the sequence to be (re)loaded.
15065       // Otherwise, the next vector will be fetched as you might suspect was
15066       // necessary.
15067 
15068       // We might be able to reuse the permutation generation from
15069       // a different base address offset from this one by an aligned amount.
15070       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
15071       // optimization later.
15072       Intrinsic::ID Intr, IntrLD, IntrPerm;
15073       MVT PermCntlTy, PermTy, LDTy;
15074       if (Subtarget.hasAltivec()) {
15075         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
15076                                  Intrinsic::ppc_altivec_lvsl;
15077         IntrLD = Intrinsic::ppc_altivec_lvx;
15078         IntrPerm = Intrinsic::ppc_altivec_vperm;
15079         PermCntlTy = MVT::v16i8;
15080         PermTy = MVT::v4i32;
15081         LDTy = MVT::v4i32;
15082       } else {
15083         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
15084                                        Intrinsic::ppc_qpx_qvlpcls;
15085         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
15086                                        Intrinsic::ppc_qpx_qvlfs;
15087         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
15088         PermCntlTy = MVT::v4f64;
15089         PermTy = MVT::v4f64;
15090         LDTy = MemVT.getSimpleVT();
15091       }
15092 
15093       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
15094 
15095       // Create the new MMO for the new base load. It is like the original MMO,
15096       // but represents an area in memory almost twice the vector size centered
15097       // on the original address. If the address is unaligned, we might start
15098       // reading up to (sizeof(vector)-1) bytes below the address of the
15099       // original unaligned load.
15100       MachineFunction &MF = DAG.getMachineFunction();
15101       MachineMemOperand *BaseMMO =
15102         MF.getMachineMemOperand(LD->getMemOperand(),
15103                                 -(long)MemVT.getStoreSize()+1,
15104                                 2*MemVT.getStoreSize()-1);
15105 
15106       // Create the new base load.
15107       SDValue LDXIntID =
15108           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
15109       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
15110       SDValue BaseLoad =
15111         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15112                                 DAG.getVTList(PermTy, MVT::Other),
15113                                 BaseLoadOps, LDTy, BaseMMO);
15114 
15115       // Note that the value of IncOffset (which is provided to the next
15116       // load's pointer info offset value, and thus used to calculate the
15117       // alignment), and the value of IncValue (which is actually used to
15118       // increment the pointer value) are different! This is because we
15119       // require the next load to appear to be aligned, even though it
15120       // is actually offset from the base pointer by a lesser amount.
15121       int IncOffset = VT.getSizeInBits() / 8;
15122       int IncValue = IncOffset;
15123 
15124       // Walk (both up and down) the chain looking for another load at the real
15125       // (aligned) offset (the alignment of the other load does not matter in
15126       // this case). If found, then do not use the offset reduction trick, as
15127       // that will prevent the loads from being later combined (as they would
15128       // otherwise be duplicates).
15129       if (!findConsecutiveLoad(LD, DAG))
15130         --IncValue;
15131 
15132       SDValue Increment =
15133           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
15134       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15135 
15136       MachineMemOperand *ExtraMMO =
15137         MF.getMachineMemOperand(LD->getMemOperand(),
15138                                 1, 2*MemVT.getStoreSize()-1);
15139       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
15140       SDValue ExtraLoad =
15141         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15142                                 DAG.getVTList(PermTy, MVT::Other),
15143                                 ExtraLoadOps, LDTy, ExtraMMO);
15144 
15145       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15146         BaseLoad.getValue(1), ExtraLoad.getValue(1));
15147 
15148       // Because vperm has a big-endian bias, we must reverse the order
15149       // of the input vectors and complement the permute control vector
15150       // when generating little endian code.  We have already handled the
15151       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
15152       // and ExtraLoad here.
15153       SDValue Perm;
15154       if (isLittleEndian)
15155         Perm = BuildIntrinsicOp(IntrPerm,
15156                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
15157       else
15158         Perm = BuildIntrinsicOp(IntrPerm,
15159                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
15160 
15161       if (VT != PermTy)
15162         Perm = Subtarget.hasAltivec() ?
15163                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
15164                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
15165                                DAG.getTargetConstant(1, dl, MVT::i64));
15166                                // second argument is 1 because this rounding
15167                                // is always exact.
15168 
15169       // The output of the permutation is our loaded result, the TokenFactor is
15170       // our new chain.
15171       DCI.CombineTo(N, Perm, TF);
15172       return SDValue(N, 0);
15173     }
15174     }
15175     break;
15176     case ISD::INTRINSIC_WO_CHAIN: {
15177       bool isLittleEndian = Subtarget.isLittleEndian();
15178       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15179       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15180                                            : Intrinsic::ppc_altivec_lvsl);
15181       if ((IID == Intr ||
15182            IID == Intrinsic::ppc_qpx_qvlpcld  ||
15183            IID == Intrinsic::ppc_qpx_qvlpcls) &&
15184         N->getOperand(1)->getOpcode() == ISD::ADD) {
15185         SDValue Add = N->getOperand(1);
15186 
15187         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
15188                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
15189 
15190         if (DAG.MaskedValueIsZero(Add->getOperand(1),
15191                                   APInt::getAllOnesValue(Bits /* alignment */)
15192                                       .zext(Add.getScalarValueSizeInBits()))) {
15193           SDNode *BasePtr = Add->getOperand(0).getNode();
15194           for (SDNode::use_iterator UI = BasePtr->use_begin(),
15195                                     UE = BasePtr->use_end();
15196                UI != UE; ++UI) {
15197             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15198                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
15199               // We've found another LVSL/LVSR, and this address is an aligned
15200               // multiple of that one. The results will be the same, so use the
15201               // one we've just found instead.
15202 
15203               return SDValue(*UI, 0);
15204             }
15205           }
15206         }
15207 
15208         if (isa<ConstantSDNode>(Add->getOperand(1))) {
15209           SDNode *BasePtr = Add->getOperand(0).getNode();
15210           for (SDNode::use_iterator UI = BasePtr->use_begin(),
15211                UE = BasePtr->use_end(); UI != UE; ++UI) {
15212             if (UI->getOpcode() == ISD::ADD &&
15213                 isa<ConstantSDNode>(UI->getOperand(1)) &&
15214                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
15215                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
15216                 (1ULL << Bits) == 0) {
15217               SDNode *OtherAdd = *UI;
15218               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
15219                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
15220                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15221                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
15222                   return SDValue(*VI, 0);
15223                 }
15224               }
15225             }
15226           }
15227         }
15228       }
15229 
15230       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
15231       // Expose the vabsduw/h/b opportunity for down stream
15232       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
15233           (IID == Intrinsic::ppc_altivec_vmaxsw ||
15234            IID == Intrinsic::ppc_altivec_vmaxsh ||
15235            IID == Intrinsic::ppc_altivec_vmaxsb)) {
15236         SDValue V1 = N->getOperand(1);
15237         SDValue V2 = N->getOperand(2);
15238         if ((V1.getSimpleValueType() == MVT::v4i32 ||
15239              V1.getSimpleValueType() == MVT::v8i16 ||
15240              V1.getSimpleValueType() == MVT::v16i8) &&
15241             V1.getSimpleValueType() == V2.getSimpleValueType()) {
15242           // (0-a, a)
15243           if (V1.getOpcode() == ISD::SUB &&
15244               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
15245               V1.getOperand(1) == V2) {
15246             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
15247           }
15248           // (a, 0-a)
15249           if (V2.getOpcode() == ISD::SUB &&
15250               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
15251               V2.getOperand(1) == V1) {
15252             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15253           }
15254           // (x-y, y-x)
15255           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
15256               V1.getOperand(0) == V2.getOperand(1) &&
15257               V1.getOperand(1) == V2.getOperand(0)) {
15258             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15259           }
15260         }
15261       }
15262     }
15263 
15264     break;
15265   case ISD::INTRINSIC_W_CHAIN:
15266     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15267     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15268     if (Subtarget.needsSwapsForVSXMemOps()) {
15269       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15270       default:
15271         break;
15272       case Intrinsic::ppc_vsx_lxvw4x:
15273       case Intrinsic::ppc_vsx_lxvd2x:
15274         return expandVSXLoadForLE(N, DCI);
15275       }
15276     }
15277     break;
15278   case ISD::INTRINSIC_VOID:
15279     // For little endian, VSX stores require generating xxswapd/stxvd2x.
15280     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15281     if (Subtarget.needsSwapsForVSXMemOps()) {
15282       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15283       default:
15284         break;
15285       case Intrinsic::ppc_vsx_stxvw4x:
15286       case Intrinsic::ppc_vsx_stxvd2x:
15287         return expandVSXStoreForLE(N, DCI);
15288       }
15289     }
15290     break;
15291   case ISD::BSWAP:
15292     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
15293     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
15294         N->getOperand(0).hasOneUse() &&
15295         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
15296          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
15297           N->getValueType(0) == MVT::i64))) {
15298       SDValue Load = N->getOperand(0);
15299       LoadSDNode *LD = cast<LoadSDNode>(Load);
15300       // Create the byte-swapping load.
15301       SDValue Ops[] = {
15302         LD->getChain(),    // Chain
15303         LD->getBasePtr(),  // Ptr
15304         DAG.getValueType(N->getValueType(0)) // VT
15305       };
15306       SDValue BSLoad =
15307         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
15308                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
15309                                               MVT::i64 : MVT::i32, MVT::Other),
15310                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
15311 
15312       // If this is an i16 load, insert the truncate.
15313       SDValue ResVal = BSLoad;
15314       if (N->getValueType(0) == MVT::i16)
15315         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
15316 
15317       // First, combine the bswap away.  This makes the value produced by the
15318       // load dead.
15319       DCI.CombineTo(N, ResVal);
15320 
15321       // Next, combine the load away, we give it a bogus result value but a real
15322       // chain result.  The result value is dead because the bswap is dead.
15323       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
15324 
15325       // Return N so it doesn't get rechecked!
15326       return SDValue(N, 0);
15327     }
15328     break;
15329   case PPCISD::VCMP:
15330     // If a VCMPo node already exists with exactly the same operands as this
15331     // node, use its result instead of this node (VCMPo computes both a CR6 and
15332     // a normal output).
15333     //
15334     if (!N->getOperand(0).hasOneUse() &&
15335         !N->getOperand(1).hasOneUse() &&
15336         !N->getOperand(2).hasOneUse()) {
15337 
15338       // Scan all of the users of the LHS, looking for VCMPo's that match.
15339       SDNode *VCMPoNode = nullptr;
15340 
15341       SDNode *LHSN = N->getOperand(0).getNode();
15342       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
15343            UI != E; ++UI)
15344         if (UI->getOpcode() == PPCISD::VCMPo &&
15345             UI->getOperand(1) == N->getOperand(1) &&
15346             UI->getOperand(2) == N->getOperand(2) &&
15347             UI->getOperand(0) == N->getOperand(0)) {
15348           VCMPoNode = *UI;
15349           break;
15350         }
15351 
15352       // If there is no VCMPo node, or if the flag value has a single use, don't
15353       // transform this.
15354       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
15355         break;
15356 
15357       // Look at the (necessarily single) use of the flag value.  If it has a
15358       // chain, this transformation is more complex.  Note that multiple things
15359       // could use the value result, which we should ignore.
15360       SDNode *FlagUser = nullptr;
15361       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
15362            FlagUser == nullptr; ++UI) {
15363         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
15364         SDNode *User = *UI;
15365         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
15366           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
15367             FlagUser = User;
15368             break;
15369           }
15370         }
15371       }
15372 
15373       // If the user is a MFOCRF instruction, we know this is safe.
15374       // Otherwise we give up for right now.
15375       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
15376         return SDValue(VCMPoNode, 0);
15377     }
15378     break;
15379   case ISD::BRCOND: {
15380     SDValue Cond = N->getOperand(1);
15381     SDValue Target = N->getOperand(2);
15382 
15383     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15384         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15385           Intrinsic::loop_decrement) {
15386 
15387       // We now need to make the intrinsic dead (it cannot be instruction
15388       // selected).
15389       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15390       assert(Cond.getNode()->hasOneUse() &&
15391              "Counter decrement has more than one use");
15392 
15393       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15394                          N->getOperand(0), Target);
15395     }
15396   }
15397   break;
15398   case ISD::BR_CC: {
15399     // If this is a branch on an altivec predicate comparison, lower this so
15400     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15401     // lowering is done pre-legalize, because the legalizer lowers the predicate
15402     // compare down to code that is difficult to reassemble.
15403     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15404     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15405 
15406     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15407     // value. If so, pass-through the AND to get to the intrinsic.
15408     if (LHS.getOpcode() == ISD::AND &&
15409         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15410         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15411           Intrinsic::loop_decrement &&
15412         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15413         !isNullConstant(LHS.getOperand(1)))
15414       LHS = LHS.getOperand(0);
15415 
15416     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15417         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15418           Intrinsic::loop_decrement &&
15419         isa<ConstantSDNode>(RHS)) {
15420       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15421              "Counter decrement comparison is not EQ or NE");
15422 
15423       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15424       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15425                     (CC == ISD::SETNE && !Val);
15426 
15427       // We now need to make the intrinsic dead (it cannot be instruction
15428       // selected).
15429       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15430       assert(LHS.getNode()->hasOneUse() &&
15431              "Counter decrement has more than one use");
15432 
15433       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15434                          N->getOperand(0), N->getOperand(4));
15435     }
15436 
15437     int CompareOpc;
15438     bool isDot;
15439 
15440     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15441         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15442         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15443       assert(isDot && "Can't compare against a vector result!");
15444 
15445       // If this is a comparison against something other than 0/1, then we know
15446       // that the condition is never/always true.
15447       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15448       if (Val != 0 && Val != 1) {
15449         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15450           return N->getOperand(0);
15451         // Always !=, turn it into an unconditional branch.
15452         return DAG.getNode(ISD::BR, dl, MVT::Other,
15453                            N->getOperand(0), N->getOperand(4));
15454       }
15455 
15456       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15457 
15458       // Create the PPCISD altivec 'dot' comparison node.
15459       SDValue Ops[] = {
15460         LHS.getOperand(2),  // LHS of compare
15461         LHS.getOperand(3),  // RHS of compare
15462         DAG.getConstant(CompareOpc, dl, MVT::i32)
15463       };
15464       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15465       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
15466 
15467       // Unpack the result based on how the target uses it.
15468       PPC::Predicate CompOpc;
15469       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15470       default:  // Can't happen, don't crash on invalid number though.
15471       case 0:   // Branch on the value of the EQ bit of CR6.
15472         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15473         break;
15474       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15475         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15476         break;
15477       case 2:   // Branch on the value of the LT bit of CR6.
15478         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15479         break;
15480       case 3:   // Branch on the inverted value of the LT bit of CR6.
15481         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15482         break;
15483       }
15484 
15485       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15486                          DAG.getConstant(CompOpc, dl, MVT::i32),
15487                          DAG.getRegister(PPC::CR6, MVT::i32),
15488                          N->getOperand(4), CompNode.getValue(1));
15489     }
15490     break;
15491   }
15492   case ISD::BUILD_VECTOR:
15493     return DAGCombineBuildVector(N, DCI);
15494   case ISD::ABS:
15495     return combineABS(N, DCI);
15496   case ISD::VSELECT:
15497     return combineVSelect(N, DCI);
15498   }
15499 
15500   return SDValue();
15501 }
15502 
15503 SDValue
15504 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15505                                  SelectionDAG &DAG,
15506                                  SmallVectorImpl<SDNode *> &Created) const {
15507   // fold (sdiv X, pow2)
15508   EVT VT = N->getValueType(0);
15509   if (VT == MVT::i64 && !Subtarget.isPPC64())
15510     return SDValue();
15511   if ((VT != MVT::i32 && VT != MVT::i64) ||
15512       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
15513     return SDValue();
15514 
15515   SDLoc DL(N);
15516   SDValue N0 = N->getOperand(0);
15517 
15518   bool IsNegPow2 = (-Divisor).isPowerOf2();
15519   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15520   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15521 
15522   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15523   Created.push_back(Op.getNode());
15524 
15525   if (IsNegPow2) {
15526     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15527     Created.push_back(Op.getNode());
15528   }
15529 
15530   return Op;
15531 }
15532 
15533 //===----------------------------------------------------------------------===//
15534 // Inline Assembly Support
15535 //===----------------------------------------------------------------------===//
15536 
15537 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15538                                                       KnownBits &Known,
15539                                                       const APInt &DemandedElts,
15540                                                       const SelectionDAG &DAG,
15541                                                       unsigned Depth) const {
15542   Known.resetAll();
15543   switch (Op.getOpcode()) {
15544   default: break;
15545   case PPCISD::LBRX: {
15546     // lhbrx is known to have the top bits cleared out.
15547     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15548       Known.Zero = 0xFFFF0000;
15549     break;
15550   }
15551   case ISD::INTRINSIC_WO_CHAIN: {
15552     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15553     default: break;
15554     case Intrinsic::ppc_altivec_vcmpbfp_p:
15555     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15556     case Intrinsic::ppc_altivec_vcmpequb_p:
15557     case Intrinsic::ppc_altivec_vcmpequh_p:
15558     case Intrinsic::ppc_altivec_vcmpequw_p:
15559     case Intrinsic::ppc_altivec_vcmpequd_p:
15560     case Intrinsic::ppc_altivec_vcmpgefp_p:
15561     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15562     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15563     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15564     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15565     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15566     case Intrinsic::ppc_altivec_vcmpgtub_p:
15567     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15568     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15569     case Intrinsic::ppc_altivec_vcmpgtud_p:
15570       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15571       break;
15572     }
15573   }
15574   }
15575 }
15576 
15577 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15578   switch (Subtarget.getCPUDirective()) {
15579   default: break;
15580   case PPC::DIR_970:
15581   case PPC::DIR_PWR4:
15582   case PPC::DIR_PWR5:
15583   case PPC::DIR_PWR5X:
15584   case PPC::DIR_PWR6:
15585   case PPC::DIR_PWR6X:
15586   case PPC::DIR_PWR7:
15587   case PPC::DIR_PWR8:
15588   case PPC::DIR_PWR9:
15589   case PPC::DIR_PWR10:
15590   case PPC::DIR_PWR_FUTURE: {
15591     if (!ML)
15592       break;
15593 
15594     if (!DisableInnermostLoopAlign32) {
15595       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15596       // so that we can decrease cache misses and branch-prediction misses.
15597       // Actual alignment of the loop will depend on the hotness check and other
15598       // logic in alignBlocks.
15599       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15600         return Align(32);
15601     }
15602 
15603     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15604 
15605     // For small loops (between 5 and 8 instructions), align to a 32-byte
15606     // boundary so that the entire loop fits in one instruction-cache line.
15607     uint64_t LoopSize = 0;
15608     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15609       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15610         LoopSize += TII->getInstSizeInBytes(*J);
15611         if (LoopSize > 32)
15612           break;
15613       }
15614 
15615     if (LoopSize > 16 && LoopSize <= 32)
15616       return Align(32);
15617 
15618     break;
15619   }
15620   }
15621 
15622   return TargetLowering::getPrefLoopAlignment(ML);
15623 }
15624 
15625 /// getConstraintType - Given a constraint, return the type of
15626 /// constraint it is for this target.
15627 PPCTargetLowering::ConstraintType
15628 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15629   if (Constraint.size() == 1) {
15630     switch (Constraint[0]) {
15631     default: break;
15632     case 'b':
15633     case 'r':
15634     case 'f':
15635     case 'd':
15636     case 'v':
15637     case 'y':
15638       return C_RegisterClass;
15639     case 'Z':
15640       // FIXME: While Z does indicate a memory constraint, it specifically
15641       // indicates an r+r address (used in conjunction with the 'y' modifier
15642       // in the replacement string). Currently, we're forcing the base
15643       // register to be r0 in the asm printer (which is interpreted as zero)
15644       // and forming the complete address in the second register. This is
15645       // suboptimal.
15646       return C_Memory;
15647     }
15648   } else if (Constraint == "wc") { // individual CR bits.
15649     return C_RegisterClass;
15650   } else if (Constraint == "wa" || Constraint == "wd" ||
15651              Constraint == "wf" || Constraint == "ws" ||
15652              Constraint == "wi" || Constraint == "ww") {
15653     return C_RegisterClass; // VSX registers.
15654   }
15655   return TargetLowering::getConstraintType(Constraint);
15656 }
15657 
15658 /// Examine constraint type and operand type and determine a weight value.
15659 /// This object must already have been set up with the operand type
15660 /// and the current alternative constraint selected.
15661 TargetLowering::ConstraintWeight
15662 PPCTargetLowering::getSingleConstraintMatchWeight(
15663     AsmOperandInfo &info, const char *constraint) const {
15664   ConstraintWeight weight = CW_Invalid;
15665   Value *CallOperandVal = info.CallOperandVal;
15666     // If we don't have a value, we can't do a match,
15667     // but allow it at the lowest weight.
15668   if (!CallOperandVal)
15669     return CW_Default;
15670   Type *type = CallOperandVal->getType();
15671 
15672   // Look at the constraint type.
15673   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15674     return CW_Register; // an individual CR bit.
15675   else if ((StringRef(constraint) == "wa" ||
15676             StringRef(constraint) == "wd" ||
15677             StringRef(constraint) == "wf") &&
15678            type->isVectorTy())
15679     return CW_Register;
15680   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15681     return CW_Register; // just hold 64-bit integers data.
15682   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15683     return CW_Register;
15684   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15685     return CW_Register;
15686 
15687   switch (*constraint) {
15688   default:
15689     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15690     break;
15691   case 'b':
15692     if (type->isIntegerTy())
15693       weight = CW_Register;
15694     break;
15695   case 'f':
15696     if (type->isFloatTy())
15697       weight = CW_Register;
15698     break;
15699   case 'd':
15700     if (type->isDoubleTy())
15701       weight = CW_Register;
15702     break;
15703   case 'v':
15704     if (type->isVectorTy())
15705       weight = CW_Register;
15706     break;
15707   case 'y':
15708     weight = CW_Register;
15709     break;
15710   case 'Z':
15711     weight = CW_Memory;
15712     break;
15713   }
15714   return weight;
15715 }
15716 
15717 std::pair<unsigned, const TargetRegisterClass *>
15718 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15719                                                 StringRef Constraint,
15720                                                 MVT VT) const {
15721   if (Constraint.size() == 1) {
15722     // GCC RS6000 Constraint Letters
15723     switch (Constraint[0]) {
15724     case 'b':   // R1-R31
15725       if (VT == MVT::i64 && Subtarget.isPPC64())
15726         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15727       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15728     case 'r':   // R0-R31
15729       if (VT == MVT::i64 && Subtarget.isPPC64())
15730         return std::make_pair(0U, &PPC::G8RCRegClass);
15731       return std::make_pair(0U, &PPC::GPRCRegClass);
15732     // 'd' and 'f' constraints are both defined to be "the floating point
15733     // registers", where one is for 32-bit and the other for 64-bit. We don't
15734     // really care overly much here so just give them all the same reg classes.
15735     case 'd':
15736     case 'f':
15737       if (Subtarget.hasSPE()) {
15738         if (VT == MVT::f32 || VT == MVT::i32)
15739           return std::make_pair(0U, &PPC::GPRCRegClass);
15740         if (VT == MVT::f64 || VT == MVT::i64)
15741           return std::make_pair(0U, &PPC::SPERCRegClass);
15742       } else {
15743         if (VT == MVT::f32 || VT == MVT::i32)
15744           return std::make_pair(0U, &PPC::F4RCRegClass);
15745         if (VT == MVT::f64 || VT == MVT::i64)
15746           return std::make_pair(0U, &PPC::F8RCRegClass);
15747         if (VT == MVT::v4f64 && Subtarget.hasQPX())
15748           return std::make_pair(0U, &PPC::QFRCRegClass);
15749         if (VT == MVT::v4f32 && Subtarget.hasQPX())
15750           return std::make_pair(0U, &PPC::QSRCRegClass);
15751       }
15752       break;
15753     case 'v':
15754       if (VT == MVT::v4f64 && Subtarget.hasQPX())
15755         return std::make_pair(0U, &PPC::QFRCRegClass);
15756       if (VT == MVT::v4f32 && Subtarget.hasQPX())
15757         return std::make_pair(0U, &PPC::QSRCRegClass);
15758       if (Subtarget.hasAltivec())
15759         return std::make_pair(0U, &PPC::VRRCRegClass);
15760       break;
15761     case 'y':   // crrc
15762       return std::make_pair(0U, &PPC::CRRCRegClass);
15763     }
15764   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15765     // An individual CR bit.
15766     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15767   } else if ((Constraint == "wa" || Constraint == "wd" ||
15768              Constraint == "wf" || Constraint == "wi") &&
15769              Subtarget.hasVSX()) {
15770     return std::make_pair(0U, &PPC::VSRCRegClass);
15771   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15772     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15773       return std::make_pair(0U, &PPC::VSSRCRegClass);
15774     else
15775       return std::make_pair(0U, &PPC::VSFRCRegClass);
15776   }
15777 
15778   // If we name a VSX register, we can't defer to the base class because it
15779   // will not recognize the correct register (their names will be VSL{0-31}
15780   // and V{0-31} so they won't match). So we match them here.
15781   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15782     int VSNum = atoi(Constraint.data() + 3);
15783     assert(VSNum >= 0 && VSNum <= 63 &&
15784            "Attempted to access a vsr out of range");
15785     if (VSNum < 32)
15786       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15787     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15788   }
15789   std::pair<unsigned, const TargetRegisterClass *> R =
15790       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15791 
15792   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15793   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15794   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15795   // register.
15796   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15797   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15798   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15799       PPC::GPRCRegClass.contains(R.first))
15800     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15801                             PPC::sub_32, &PPC::G8RCRegClass),
15802                           &PPC::G8RCRegClass);
15803 
15804   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15805   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15806     R.first = PPC::CR0;
15807     R.second = &PPC::CRRCRegClass;
15808   }
15809 
15810   return R;
15811 }
15812 
15813 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15814 /// vector.  If it is invalid, don't add anything to Ops.
15815 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15816                                                      std::string &Constraint,
15817                                                      std::vector<SDValue>&Ops,
15818                                                      SelectionDAG &DAG) const {
15819   SDValue Result;
15820 
15821   // Only support length 1 constraints.
15822   if (Constraint.length() > 1) return;
15823 
15824   char Letter = Constraint[0];
15825   switch (Letter) {
15826   default: break;
15827   case 'I':
15828   case 'J':
15829   case 'K':
15830   case 'L':
15831   case 'M':
15832   case 'N':
15833   case 'O':
15834   case 'P': {
15835     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15836     if (!CST) return; // Must be an immediate to match.
15837     SDLoc dl(Op);
15838     int64_t Value = CST->getSExtValue();
15839     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15840                          // numbers are printed as such.
15841     switch (Letter) {
15842     default: llvm_unreachable("Unknown constraint letter!");
15843     case 'I':  // "I" is a signed 16-bit constant.
15844       if (isInt<16>(Value))
15845         Result = DAG.getTargetConstant(Value, dl, TCVT);
15846       break;
15847     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15848       if (isShiftedUInt<16, 16>(Value))
15849         Result = DAG.getTargetConstant(Value, dl, TCVT);
15850       break;
15851     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15852       if (isShiftedInt<16, 16>(Value))
15853         Result = DAG.getTargetConstant(Value, dl, TCVT);
15854       break;
15855     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15856       if (isUInt<16>(Value))
15857         Result = DAG.getTargetConstant(Value, dl, TCVT);
15858       break;
15859     case 'M':  // "M" is a constant that is greater than 31.
15860       if (Value > 31)
15861         Result = DAG.getTargetConstant(Value, dl, TCVT);
15862       break;
15863     case 'N':  // "N" is a positive constant that is an exact power of two.
15864       if (Value > 0 && isPowerOf2_64(Value))
15865         Result = DAG.getTargetConstant(Value, dl, TCVT);
15866       break;
15867     case 'O':  // "O" is the constant zero.
15868       if (Value == 0)
15869         Result = DAG.getTargetConstant(Value, dl, TCVT);
15870       break;
15871     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15872       if (isInt<16>(-Value))
15873         Result = DAG.getTargetConstant(Value, dl, TCVT);
15874       break;
15875     }
15876     break;
15877   }
15878   }
15879 
15880   if (Result.getNode()) {
15881     Ops.push_back(Result);
15882     return;
15883   }
15884 
15885   // Handle standard constraint letters.
15886   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15887 }
15888 
15889 // isLegalAddressingMode - Return true if the addressing mode represented
15890 // by AM is legal for this target, for a load/store of the specified type.
15891 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15892                                               const AddrMode &AM, Type *Ty,
15893                                               unsigned AS, Instruction *I) const {
15894   // PPC does not allow r+i addressing modes for vectors!
15895   if (Ty->isVectorTy() && AM.BaseOffs != 0)
15896     return false;
15897 
15898   // PPC allows a sign-extended 16-bit immediate field.
15899   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15900     return false;
15901 
15902   // No global is ever allowed as a base.
15903   if (AM.BaseGV)
15904     return false;
15905 
15906   // PPC only support r+r,
15907   switch (AM.Scale) {
15908   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15909     break;
15910   case 1:
15911     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15912       return false;
15913     // Otherwise we have r+r or r+i.
15914     break;
15915   case 2:
15916     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15917       return false;
15918     // Allow 2*r as r+r.
15919     break;
15920   default:
15921     // No other scales are supported.
15922     return false;
15923   }
15924 
15925   return true;
15926 }
15927 
15928 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15929                                            SelectionDAG &DAG) const {
15930   MachineFunction &MF = DAG.getMachineFunction();
15931   MachineFrameInfo &MFI = MF.getFrameInfo();
15932   MFI.setReturnAddressIsTaken(true);
15933 
15934   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15935     return SDValue();
15936 
15937   SDLoc dl(Op);
15938   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15939 
15940   // Make sure the function does not optimize away the store of the RA to
15941   // the stack.
15942   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15943   FuncInfo->setLRStoreRequired();
15944   bool isPPC64 = Subtarget.isPPC64();
15945   auto PtrVT = getPointerTy(MF.getDataLayout());
15946 
15947   if (Depth > 0) {
15948     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15949     SDValue Offset =
15950         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15951                         isPPC64 ? MVT::i64 : MVT::i32);
15952     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15953                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15954                        MachinePointerInfo());
15955   }
15956 
15957   // Just load the return address off the stack.
15958   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15959   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15960                      MachinePointerInfo());
15961 }
15962 
15963 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15964                                           SelectionDAG &DAG) const {
15965   SDLoc dl(Op);
15966   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15967 
15968   MachineFunction &MF = DAG.getMachineFunction();
15969   MachineFrameInfo &MFI = MF.getFrameInfo();
15970   MFI.setFrameAddressIsTaken(true);
15971 
15972   EVT PtrVT = getPointerTy(MF.getDataLayout());
15973   bool isPPC64 = PtrVT == MVT::i64;
15974 
15975   // Naked functions never have a frame pointer, and so we use r1. For all
15976   // other functions, this decision must be delayed until during PEI.
15977   unsigned FrameReg;
15978   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15979     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15980   else
15981     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15982 
15983   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15984                                          PtrVT);
15985   while (Depth--)
15986     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15987                             FrameAddr, MachinePointerInfo());
15988   return FrameAddr;
15989 }
15990 
15991 // FIXME? Maybe this could be a TableGen attribute on some registers and
15992 // this table could be generated automatically from RegInfo.
15993 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15994                                               const MachineFunction &MF) const {
15995   bool isPPC64 = Subtarget.isPPC64();
15996 
15997   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15998   if (!is64Bit && VT != LLT::scalar(32))
15999     report_fatal_error("Invalid register global variable type");
16000 
16001   Register Reg = StringSwitch<Register>(RegName)
16002                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
16003                      .Case("r2", isPPC64 ? Register() : PPC::R2)
16004                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
16005                      .Default(Register());
16006 
16007   if (Reg)
16008     return Reg;
16009   report_fatal_error("Invalid register name global variable");
16010 }
16011 
16012 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
16013   // 32-bit SVR4 ABI access everything as got-indirect.
16014   if (Subtarget.is32BitELFABI())
16015     return true;
16016 
16017   // AIX accesses everything indirectly through the TOC, which is similar to
16018   // the GOT.
16019   if (Subtarget.isAIXABI())
16020     return true;
16021 
16022   CodeModel::Model CModel = getTargetMachine().getCodeModel();
16023   // If it is small or large code model, module locals are accessed
16024   // indirectly by loading their address from .toc/.got.
16025   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
16026     return true;
16027 
16028   // JumpTable and BlockAddress are accessed as got-indirect.
16029   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
16030     return true;
16031 
16032   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
16033     return Subtarget.isGVIndirectSymbol(G->getGlobal());
16034 
16035   return false;
16036 }
16037 
16038 bool
16039 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
16040   // The PowerPC target isn't yet aware of offsets.
16041   return false;
16042 }
16043 
16044 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
16045                                            const CallInst &I,
16046                                            MachineFunction &MF,
16047                                            unsigned Intrinsic) const {
16048   switch (Intrinsic) {
16049   case Intrinsic::ppc_qpx_qvlfd:
16050   case Intrinsic::ppc_qpx_qvlfs:
16051   case Intrinsic::ppc_qpx_qvlfcd:
16052   case Intrinsic::ppc_qpx_qvlfcs:
16053   case Intrinsic::ppc_qpx_qvlfiwa:
16054   case Intrinsic::ppc_qpx_qvlfiwz:
16055   case Intrinsic::ppc_altivec_lvx:
16056   case Intrinsic::ppc_altivec_lvxl:
16057   case Intrinsic::ppc_altivec_lvebx:
16058   case Intrinsic::ppc_altivec_lvehx:
16059   case Intrinsic::ppc_altivec_lvewx:
16060   case Intrinsic::ppc_vsx_lxvd2x:
16061   case Intrinsic::ppc_vsx_lxvw4x: {
16062     EVT VT;
16063     switch (Intrinsic) {
16064     case Intrinsic::ppc_altivec_lvebx:
16065       VT = MVT::i8;
16066       break;
16067     case Intrinsic::ppc_altivec_lvehx:
16068       VT = MVT::i16;
16069       break;
16070     case Intrinsic::ppc_altivec_lvewx:
16071       VT = MVT::i32;
16072       break;
16073     case Intrinsic::ppc_vsx_lxvd2x:
16074       VT = MVT::v2f64;
16075       break;
16076     case Intrinsic::ppc_qpx_qvlfd:
16077       VT = MVT::v4f64;
16078       break;
16079     case Intrinsic::ppc_qpx_qvlfs:
16080       VT = MVT::v4f32;
16081       break;
16082     case Intrinsic::ppc_qpx_qvlfcd:
16083       VT = MVT::v2f64;
16084       break;
16085     case Intrinsic::ppc_qpx_qvlfcs:
16086       VT = MVT::v2f32;
16087       break;
16088     default:
16089       VT = MVT::v4i32;
16090       break;
16091     }
16092 
16093     Info.opc = ISD::INTRINSIC_W_CHAIN;
16094     Info.memVT = VT;
16095     Info.ptrVal = I.getArgOperand(0);
16096     Info.offset = -VT.getStoreSize()+1;
16097     Info.size = 2*VT.getStoreSize()-1;
16098     Info.align = Align(1);
16099     Info.flags = MachineMemOperand::MOLoad;
16100     return true;
16101   }
16102   case Intrinsic::ppc_qpx_qvlfda:
16103   case Intrinsic::ppc_qpx_qvlfsa:
16104   case Intrinsic::ppc_qpx_qvlfcda:
16105   case Intrinsic::ppc_qpx_qvlfcsa:
16106   case Intrinsic::ppc_qpx_qvlfiwaa:
16107   case Intrinsic::ppc_qpx_qvlfiwza: {
16108     EVT VT;
16109     switch (Intrinsic) {
16110     case Intrinsic::ppc_qpx_qvlfda:
16111       VT = MVT::v4f64;
16112       break;
16113     case Intrinsic::ppc_qpx_qvlfsa:
16114       VT = MVT::v4f32;
16115       break;
16116     case Intrinsic::ppc_qpx_qvlfcda:
16117       VT = MVT::v2f64;
16118       break;
16119     case Intrinsic::ppc_qpx_qvlfcsa:
16120       VT = MVT::v2f32;
16121       break;
16122     default:
16123       VT = MVT::v4i32;
16124       break;
16125     }
16126 
16127     Info.opc = ISD::INTRINSIC_W_CHAIN;
16128     Info.memVT = VT;
16129     Info.ptrVal = I.getArgOperand(0);
16130     Info.offset = 0;
16131     Info.size = VT.getStoreSize();
16132     Info.align = Align(1);
16133     Info.flags = MachineMemOperand::MOLoad;
16134     return true;
16135   }
16136   case Intrinsic::ppc_qpx_qvstfd:
16137   case Intrinsic::ppc_qpx_qvstfs:
16138   case Intrinsic::ppc_qpx_qvstfcd:
16139   case Intrinsic::ppc_qpx_qvstfcs:
16140   case Intrinsic::ppc_qpx_qvstfiw:
16141   case Intrinsic::ppc_altivec_stvx:
16142   case Intrinsic::ppc_altivec_stvxl:
16143   case Intrinsic::ppc_altivec_stvebx:
16144   case Intrinsic::ppc_altivec_stvehx:
16145   case Intrinsic::ppc_altivec_stvewx:
16146   case Intrinsic::ppc_vsx_stxvd2x:
16147   case Intrinsic::ppc_vsx_stxvw4x: {
16148     EVT VT;
16149     switch (Intrinsic) {
16150     case Intrinsic::ppc_altivec_stvebx:
16151       VT = MVT::i8;
16152       break;
16153     case Intrinsic::ppc_altivec_stvehx:
16154       VT = MVT::i16;
16155       break;
16156     case Intrinsic::ppc_altivec_stvewx:
16157       VT = MVT::i32;
16158       break;
16159     case Intrinsic::ppc_vsx_stxvd2x:
16160       VT = MVT::v2f64;
16161       break;
16162     case Intrinsic::ppc_qpx_qvstfd:
16163       VT = MVT::v4f64;
16164       break;
16165     case Intrinsic::ppc_qpx_qvstfs:
16166       VT = MVT::v4f32;
16167       break;
16168     case Intrinsic::ppc_qpx_qvstfcd:
16169       VT = MVT::v2f64;
16170       break;
16171     case Intrinsic::ppc_qpx_qvstfcs:
16172       VT = MVT::v2f32;
16173       break;
16174     default:
16175       VT = MVT::v4i32;
16176       break;
16177     }
16178 
16179     Info.opc = ISD::INTRINSIC_VOID;
16180     Info.memVT = VT;
16181     Info.ptrVal = I.getArgOperand(1);
16182     Info.offset = -VT.getStoreSize()+1;
16183     Info.size = 2*VT.getStoreSize()-1;
16184     Info.align = Align(1);
16185     Info.flags = MachineMemOperand::MOStore;
16186     return true;
16187   }
16188   case Intrinsic::ppc_qpx_qvstfda:
16189   case Intrinsic::ppc_qpx_qvstfsa:
16190   case Intrinsic::ppc_qpx_qvstfcda:
16191   case Intrinsic::ppc_qpx_qvstfcsa:
16192   case Intrinsic::ppc_qpx_qvstfiwa: {
16193     EVT VT;
16194     switch (Intrinsic) {
16195     case Intrinsic::ppc_qpx_qvstfda:
16196       VT = MVT::v4f64;
16197       break;
16198     case Intrinsic::ppc_qpx_qvstfsa:
16199       VT = MVT::v4f32;
16200       break;
16201     case Intrinsic::ppc_qpx_qvstfcda:
16202       VT = MVT::v2f64;
16203       break;
16204     case Intrinsic::ppc_qpx_qvstfcsa:
16205       VT = MVT::v2f32;
16206       break;
16207     default:
16208       VT = MVT::v4i32;
16209       break;
16210     }
16211 
16212     Info.opc = ISD::INTRINSIC_VOID;
16213     Info.memVT = VT;
16214     Info.ptrVal = I.getArgOperand(1);
16215     Info.offset = 0;
16216     Info.size = VT.getStoreSize();
16217     Info.align = Align(1);
16218     Info.flags = MachineMemOperand::MOStore;
16219     return true;
16220   }
16221   default:
16222     break;
16223   }
16224 
16225   return false;
16226 }
16227 
16228 /// It returns EVT::Other if the type should be determined using generic
16229 /// target-independent logic.
16230 EVT PPCTargetLowering::getOptimalMemOpType(
16231     const MemOp &Op, const AttributeList &FuncAttributes) const {
16232   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
16233     // When expanding a memset, require at least two QPX instructions to cover
16234     // the cost of loading the value to be stored from the constant pool.
16235     if (Subtarget.hasQPX() && Op.size() >= 32 &&
16236         (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) &&
16237         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
16238       return MVT::v4f64;
16239     }
16240 
16241     // We should use Altivec/VSX loads and stores when available. For unaligned
16242     // addresses, unaligned VSX loads are only fast starting with the P8.
16243     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
16244         (Op.isAligned(Align(16)) ||
16245          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
16246       return MVT::v4i32;
16247   }
16248 
16249   if (Subtarget.isPPC64()) {
16250     return MVT::i64;
16251   }
16252 
16253   return MVT::i32;
16254 }
16255 
16256 /// Returns true if it is beneficial to convert a load of a constant
16257 /// to just the constant itself.
16258 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16259                                                           Type *Ty) const {
16260   assert(Ty->isIntegerTy());
16261 
16262   unsigned BitSize = Ty->getPrimitiveSizeInBits();
16263   return !(BitSize == 0 || BitSize > 64);
16264 }
16265 
16266 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16267   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16268     return false;
16269   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16270   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16271   return NumBits1 == 64 && NumBits2 == 32;
16272 }
16273 
16274 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16275   if (!VT1.isInteger() || !VT2.isInteger())
16276     return false;
16277   unsigned NumBits1 = VT1.getSizeInBits();
16278   unsigned NumBits2 = VT2.getSizeInBits();
16279   return NumBits1 == 64 && NumBits2 == 32;
16280 }
16281 
16282 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16283   // Generally speaking, zexts are not free, but they are free when they can be
16284   // folded with other operations.
16285   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
16286     EVT MemVT = LD->getMemoryVT();
16287     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
16288          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
16289         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
16290          LD->getExtensionType() == ISD::ZEXTLOAD))
16291       return true;
16292   }
16293 
16294   // FIXME: Add other cases...
16295   //  - 32-bit shifts with a zext to i64
16296   //  - zext after ctlz, bswap, etc.
16297   //  - zext after and by a constant mask
16298 
16299   return TargetLowering::isZExtFree(Val, VT2);
16300 }
16301 
16302 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
16303   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
16304          "invalid fpext types");
16305   // Extending to float128 is not free.
16306   if (DestVT == MVT::f128)
16307     return false;
16308   return true;
16309 }
16310 
16311 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16312   return isInt<16>(Imm) || isUInt<16>(Imm);
16313 }
16314 
16315 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16316   return isInt<16>(Imm) || isUInt<16>(Imm);
16317 }
16318 
16319 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
16320                                                        unsigned,
16321                                                        unsigned,
16322                                                        MachineMemOperand::Flags,
16323                                                        bool *Fast) const {
16324   if (DisablePPCUnaligned)
16325     return false;
16326 
16327   // PowerPC supports unaligned memory access for simple non-vector types.
16328   // Although accessing unaligned addresses is not as efficient as accessing
16329   // aligned addresses, it is generally more efficient than manual expansion,
16330   // and generally only traps for software emulation when crossing page
16331   // boundaries.
16332 
16333   if (!VT.isSimple())
16334     return false;
16335 
16336   if (VT.isFloatingPoint() && !VT.isVector() &&
16337       !Subtarget.allowsUnalignedFPAccess())
16338     return false;
16339 
16340   if (VT.getSimpleVT().isVector()) {
16341     if (Subtarget.hasVSX()) {
16342       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
16343           VT != MVT::v4f32 && VT != MVT::v4i32)
16344         return false;
16345     } else {
16346       return false;
16347     }
16348   }
16349 
16350   if (VT == MVT::ppcf128)
16351     return false;
16352 
16353   if (Fast)
16354     *Fast = true;
16355 
16356   return true;
16357 }
16358 
16359 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16360                                                    EVT VT) const {
16361   return isFMAFasterThanFMulAndFAdd(
16362       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
16363 }
16364 
16365 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
16366                                                    Type *Ty) const {
16367   switch (Ty->getScalarType()->getTypeID()) {
16368   case Type::FloatTyID:
16369   case Type::DoubleTyID:
16370     return true;
16371   case Type::FP128TyID:
16372     return EnableQuadPrecision && Subtarget.hasP9Vector();
16373   default:
16374     return false;
16375   }
16376 }
16377 
16378 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist.
16379 // FIXME: add more patterns which are profitable to hoist.
16380 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
16381   if (I->getOpcode() != Instruction::FMul)
16382     return true;
16383 
16384   if (!I->hasOneUse())
16385     return true;
16386 
16387   Instruction *User = I->user_back();
16388   assert(User && "A single use instruction with no uses.");
16389 
16390   if (User->getOpcode() != Instruction::FSub &&
16391       User->getOpcode() != Instruction::FAdd)
16392     return true;
16393 
16394   const TargetOptions &Options = getTargetMachine().Options;
16395   const Function *F = I->getFunction();
16396   const DataLayout &DL = F->getParent()->getDataLayout();
16397   Type *Ty = User->getOperand(0)->getType();
16398 
16399   return !(
16400       isFMAFasterThanFMulAndFAdd(*F, Ty) &&
16401       isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
16402       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
16403 }
16404 
16405 const MCPhysReg *
16406 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
16407   // LR is a callee-save register, but we must treat it as clobbered by any call
16408   // site. Hence we include LR in the scratch registers, which are in turn added
16409   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
16410   // to CTR, which is used by any indirect call.
16411   static const MCPhysReg ScratchRegs[] = {
16412     PPC::X12, PPC::LR8, PPC::CTR8, 0
16413   };
16414 
16415   return ScratchRegs;
16416 }
16417 
16418 Register PPCTargetLowering::getExceptionPointerRegister(
16419     const Constant *PersonalityFn) const {
16420   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
16421 }
16422 
16423 Register PPCTargetLowering::getExceptionSelectorRegister(
16424     const Constant *PersonalityFn) const {
16425   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
16426 }
16427 
16428 bool
16429 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
16430                      EVT VT , unsigned DefinedValues) const {
16431   if (VT == MVT::v2i64)
16432     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
16433 
16434   if (Subtarget.hasVSX() || Subtarget.hasQPX())
16435     return true;
16436 
16437   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
16438 }
16439 
16440 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16441   if (DisableILPPref || Subtarget.enableMachineScheduler())
16442     return TargetLowering::getSchedulingPreference(N);
16443 
16444   return Sched::ILP;
16445 }
16446 
16447 // Create a fast isel object.
16448 FastISel *
16449 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16450                                   const TargetLibraryInfo *LibInfo) const {
16451   return PPC::createFastISel(FuncInfo, LibInfo);
16452 }
16453 
16454 // 'Inverted' means the FMA opcode after negating one multiplicand.
16455 // For example, (fma -a b c) = (fnmsub a b c)
16456 static unsigned invertFMAOpcode(unsigned Opc) {
16457   switch (Opc) {
16458   default:
16459     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16460   case ISD::FMA:
16461     return PPCISD::FNMSUB;
16462   case PPCISD::FNMSUB:
16463     return ISD::FMA;
16464   }
16465 }
16466 
16467 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16468                                                 bool LegalOps, bool OptForSize,
16469                                                 NegatibleCost &Cost,
16470                                                 unsigned Depth) const {
16471   if (Depth > SelectionDAG::MaxRecursionDepth)
16472     return SDValue();
16473 
16474   unsigned Opc = Op.getOpcode();
16475   EVT VT = Op.getValueType();
16476   SDNodeFlags Flags = Op.getNode()->getFlags();
16477 
16478   switch (Opc) {
16479   case PPCISD::FNMSUB:
16480     // TODO: QPX subtarget is deprecated. No transformation here.
16481     if (!Op.hasOneUse() || !isTypeLegal(VT) || Subtarget.hasQPX())
16482       break;
16483 
16484     const TargetOptions &Options = getTargetMachine().Options;
16485     SDValue N0 = Op.getOperand(0);
16486     SDValue N1 = Op.getOperand(1);
16487     SDValue N2 = Op.getOperand(2);
16488     SDLoc Loc(Op);
16489 
16490     NegatibleCost N2Cost = NegatibleCost::Expensive;
16491     SDValue NegN2 =
16492         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16493 
16494     if (!NegN2)
16495       return SDValue();
16496 
16497     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16498     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16499     // These transformations may change sign of zeroes. For example,
16500     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16501     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16502       // Try and choose the cheaper one to negate.
16503       NegatibleCost N0Cost = NegatibleCost::Expensive;
16504       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16505                                            N0Cost, Depth + 1);
16506 
16507       NegatibleCost N1Cost = NegatibleCost::Expensive;
16508       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16509                                            N1Cost, Depth + 1);
16510 
16511       if (NegN0 && N0Cost <= N1Cost) {
16512         Cost = std::min(N0Cost, N2Cost);
16513         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16514       } else if (NegN1) {
16515         Cost = std::min(N1Cost, N2Cost);
16516         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16517       }
16518     }
16519 
16520     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16521     if (isOperationLegal(ISD::FMA, VT)) {
16522       Cost = N2Cost;
16523       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16524     }
16525 
16526     break;
16527   }
16528 
16529   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16530                                               Cost, Depth);
16531 }
16532 
16533 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16534 bool PPCTargetLowering::useLoadStackGuardNode() const {
16535   if (!Subtarget.isTargetLinux())
16536     return TargetLowering::useLoadStackGuardNode();
16537   return true;
16538 }
16539 
16540 // Override to disable global variable loading on Linux.
16541 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16542   if (!Subtarget.isTargetLinux())
16543     return TargetLowering::insertSSPDeclarations(M);
16544 }
16545 
16546 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16547                                      bool ForCodeSize) const {
16548   if (!VT.isSimple() || !Subtarget.hasVSX())
16549     return false;
16550 
16551   switch(VT.getSimpleVT().SimpleTy) {
16552   default:
16553     // For FP types that are currently not supported by PPC backend, return
16554     // false. Examples: f16, f80.
16555     return false;
16556   case MVT::f32:
16557   case MVT::f64:
16558     if (Subtarget.hasPrefixInstrs()) {
16559       // With prefixed instructions, we can materialize anything that can be
16560       // represented with a 32-bit immediate, not just positive zero.
16561       APFloat APFloatOfImm = Imm;
16562       return convertToNonDenormSingle(APFloatOfImm);
16563     }
16564     LLVM_FALLTHROUGH;
16565   case MVT::ppcf128:
16566     return Imm.isPosZero();
16567   }
16568 }
16569 
16570 // For vector shift operation op, fold
16571 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16572 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16573                                   SelectionDAG &DAG) {
16574   SDValue N0 = N->getOperand(0);
16575   SDValue N1 = N->getOperand(1);
16576   EVT VT = N0.getValueType();
16577   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16578   unsigned Opcode = N->getOpcode();
16579   unsigned TargetOpcode;
16580 
16581   switch (Opcode) {
16582   default:
16583     llvm_unreachable("Unexpected shift operation");
16584   case ISD::SHL:
16585     TargetOpcode = PPCISD::SHL;
16586     break;
16587   case ISD::SRL:
16588     TargetOpcode = PPCISD::SRL;
16589     break;
16590   case ISD::SRA:
16591     TargetOpcode = PPCISD::SRA;
16592     break;
16593   }
16594 
16595   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16596       N1->getOpcode() == ISD::AND)
16597     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16598       if (Mask->getZExtValue() == OpSizeInBits - 1)
16599         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16600 
16601   return SDValue();
16602 }
16603 
16604 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16605   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16606     return Value;
16607 
16608   SDValue N0 = N->getOperand(0);
16609   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16610   if (!Subtarget.isISA3_0() ||
16611       N0.getOpcode() != ISD::SIGN_EXTEND ||
16612       N0.getOperand(0).getValueType() != MVT::i32 ||
16613       CN1 == nullptr || N->getValueType(0) != MVT::i64)
16614     return SDValue();
16615 
16616   // We can't save an operation here if the value is already extended, and
16617   // the existing shift is easier to combine.
16618   SDValue ExtsSrc = N0.getOperand(0);
16619   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16620       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16621     return SDValue();
16622 
16623   SDLoc DL(N0);
16624   SDValue ShiftBy = SDValue(CN1, 0);
16625   // We want the shift amount to be i32 on the extswli, but the shift could
16626   // have an i64.
16627   if (ShiftBy.getValueType() == MVT::i64)
16628     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16629 
16630   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16631                          ShiftBy);
16632 }
16633 
16634 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16635   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16636     return Value;
16637 
16638   return SDValue();
16639 }
16640 
16641 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16642   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16643     return Value;
16644 
16645   return SDValue();
16646 }
16647 
16648 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16649 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16650 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16651 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16652 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16653                                  const PPCSubtarget &Subtarget) {
16654   if (!Subtarget.isPPC64())
16655     return SDValue();
16656 
16657   SDValue LHS = N->getOperand(0);
16658   SDValue RHS = N->getOperand(1);
16659 
16660   auto isZextOfCompareWithConstant = [](SDValue Op) {
16661     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16662         Op.getValueType() != MVT::i64)
16663       return false;
16664 
16665     SDValue Cmp = Op.getOperand(0);
16666     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16667         Cmp.getOperand(0).getValueType() != MVT::i64)
16668       return false;
16669 
16670     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
16671       int64_t NegConstant = 0 - Constant->getSExtValue();
16672       // Due to the limitations of the addi instruction,
16673       // -C is required to be [-32768, 32767].
16674       return isInt<16>(NegConstant);
16675     }
16676 
16677     return false;
16678   };
16679 
16680   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
16681   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16682 
16683   // If there is a pattern, canonicalize a zext operand to the RHS.
16684   if (LHSHasPattern && !RHSHasPattern)
16685     std::swap(LHS, RHS);
16686   else if (!LHSHasPattern && !RHSHasPattern)
16687     return SDValue();
16688 
16689   SDLoc DL(N);
16690   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16691   SDValue Cmp = RHS.getOperand(0);
16692   SDValue Z = Cmp.getOperand(0);
16693   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
16694 
16695   assert(Constant && "Constant Should not be a null pointer.");
16696   int64_t NegConstant = 0 - Constant->getSExtValue();
16697 
16698   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16699   default: break;
16700   case ISD::SETNE: {
16701     //                                 when C == 0
16702     //                             --> addze X, (addic Z, -1).carry
16703     //                            /
16704     // add X, (zext(setne Z, C))--
16705     //                            \    when -32768 <= -C <= 32767 && C != 0
16706     //                             --> addze X, (addic (addi Z, -C), -1).carry
16707     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16708                               DAG.getConstant(NegConstant, DL, MVT::i64));
16709     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16710     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16711                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16712     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16713                        SDValue(Addc.getNode(), 1));
16714     }
16715   case ISD::SETEQ: {
16716     //                                 when C == 0
16717     //                             --> addze X, (subfic Z, 0).carry
16718     //                            /
16719     // add X, (zext(sete  Z, C))--
16720     //                            \    when -32768 <= -C <= 32767 && C != 0
16721     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16722     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16723                               DAG.getConstant(NegConstant, DL, MVT::i64));
16724     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16725     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16726                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16727     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16728                        SDValue(Subc.getNode(), 1));
16729     }
16730   }
16731 
16732   return SDValue();
16733 }
16734 
16735 // Transform
16736 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16737 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16738 // In this case both C1 and C2 must be known constants.
16739 // C1+C2 must fit into a 34 bit signed integer.
16740 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16741                                           const PPCSubtarget &Subtarget) {
16742   if (!Subtarget.isUsingPCRelativeCalls())
16743     return SDValue();
16744 
16745   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16746   // If we find that node try to cast the Global Address and the Constant.
16747   SDValue LHS = N->getOperand(0);
16748   SDValue RHS = N->getOperand(1);
16749 
16750   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16751     std::swap(LHS, RHS);
16752 
16753   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16754     return SDValue();
16755 
16756   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16757   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16758   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16759 
16760   // Check that both casts succeeded.
16761   if (!GSDN || !ConstNode)
16762     return SDValue();
16763 
16764   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16765   SDLoc DL(GSDN);
16766 
16767   // The signed int offset needs to fit in 34 bits.
16768   if (!isInt<34>(NewOffset))
16769     return SDValue();
16770 
16771   // The new global address is a copy of the old global address except
16772   // that it has the updated Offset.
16773   SDValue GA =
16774       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16775                                  NewOffset, GSDN->getTargetFlags());
16776   SDValue MatPCRel =
16777       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16778   return MatPCRel;
16779 }
16780 
16781 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16782   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16783     return Value;
16784 
16785   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16786     return Value;
16787 
16788   return SDValue();
16789 }
16790 
16791 // Detect TRUNCATE operations on bitcasts of float128 values.
16792 // What we are looking for here is the situtation where we extract a subset
16793 // of bits from a 128 bit float.
16794 // This can be of two forms:
16795 // 1) BITCAST of f128 feeding TRUNCATE
16796 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16797 // The reason this is required is because we do not have a legal i128 type
16798 // and so we want to prevent having to store the f128 and then reload part
16799 // of it.
16800 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16801                                            DAGCombinerInfo &DCI) const {
16802   // If we are using CRBits then try that first.
16803   if (Subtarget.useCRBits()) {
16804     // Check if CRBits did anything and return that if it did.
16805     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16806       return CRTruncValue;
16807   }
16808 
16809   SDLoc dl(N);
16810   SDValue Op0 = N->getOperand(0);
16811 
16812   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
16813   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
16814     EVT VT = N->getValueType(0);
16815     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16816       return SDValue();
16817     SDValue Sub = Op0.getOperand(0);
16818     if (Sub.getOpcode() == ISD::SUB) {
16819       SDValue SubOp0 = Sub.getOperand(0);
16820       SDValue SubOp1 = Sub.getOperand(1);
16821       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16822           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16823         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16824                                SubOp1.getOperand(0),
16825                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16826       }
16827     }
16828   }
16829 
16830   // Looking for a truncate of i128 to i64.
16831   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16832     return SDValue();
16833 
16834   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16835 
16836   // SRL feeding TRUNCATE.
16837   if (Op0.getOpcode() == ISD::SRL) {
16838     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16839     // The right shift has to be by 64 bits.
16840     if (!ConstNode || ConstNode->getZExtValue() != 64)
16841       return SDValue();
16842 
16843     // Switch the element number to extract.
16844     EltToExtract = EltToExtract ? 0 : 1;
16845     // Update Op0 past the SRL.
16846     Op0 = Op0.getOperand(0);
16847   }
16848 
16849   // BITCAST feeding a TRUNCATE possibly via SRL.
16850   if (Op0.getOpcode() == ISD::BITCAST &&
16851       Op0.getValueType() == MVT::i128 &&
16852       Op0.getOperand(0).getValueType() == MVT::f128) {
16853     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16854     return DCI.DAG.getNode(
16855         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16856         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16857   }
16858   return SDValue();
16859 }
16860 
16861 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16862   SelectionDAG &DAG = DCI.DAG;
16863 
16864   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16865   if (!ConstOpOrElement)
16866     return SDValue();
16867 
16868   // An imul is usually smaller than the alternative sequence for legal type.
16869   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16870       isOperationLegal(ISD::MUL, N->getValueType(0)))
16871     return SDValue();
16872 
16873   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16874     switch (this->Subtarget.getCPUDirective()) {
16875     default:
16876       // TODO: enhance the condition for subtarget before pwr8
16877       return false;
16878     case PPC::DIR_PWR8:
16879       //  type        mul     add    shl
16880       // scalar        4       1      1
16881       // vector        7       2      2
16882       return true;
16883     case PPC::DIR_PWR9:
16884     case PPC::DIR_PWR10:
16885     case PPC::DIR_PWR_FUTURE:
16886       //  type        mul     add    shl
16887       // scalar        5       2      2
16888       // vector        7       2      2
16889 
16890       // The cycle RATIO of related operations are showed as a table above.
16891       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16892       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16893       // are 4, it is always profitable; but for 3 instrs patterns
16894       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16895       // So we should only do it for vector type.
16896       return IsAddOne && IsNeg ? VT.isVector() : true;
16897     }
16898   };
16899 
16900   EVT VT = N->getValueType(0);
16901   SDLoc DL(N);
16902 
16903   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16904   bool IsNeg = MulAmt.isNegative();
16905   APInt MulAmtAbs = MulAmt.abs();
16906 
16907   if ((MulAmtAbs - 1).isPowerOf2()) {
16908     // (mul x, 2^N + 1) => (add (shl x, N), x)
16909     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16910 
16911     if (!IsProfitable(IsNeg, true, VT))
16912       return SDValue();
16913 
16914     SDValue Op0 = N->getOperand(0);
16915     SDValue Op1 =
16916         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16917                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16918     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16919 
16920     if (!IsNeg)
16921       return Res;
16922 
16923     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16924   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16925     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16926     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16927 
16928     if (!IsProfitable(IsNeg, false, VT))
16929       return SDValue();
16930 
16931     SDValue Op0 = N->getOperand(0);
16932     SDValue Op1 =
16933         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16934                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16935 
16936     if (!IsNeg)
16937       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16938     else
16939       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16940 
16941   } else {
16942     return SDValue();
16943   }
16944 }
16945 
16946 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16947 // in combiner since we need to check SD flags and other subtarget features.
16948 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16949                                           DAGCombinerInfo &DCI) const {
16950   SDValue N0 = N->getOperand(0);
16951   SDValue N1 = N->getOperand(1);
16952   SDValue N2 = N->getOperand(2);
16953   SDNodeFlags Flags = N->getFlags();
16954   EVT VT = N->getValueType(0);
16955   SelectionDAG &DAG = DCI.DAG;
16956   const TargetOptions &Options = getTargetMachine().Options;
16957   unsigned Opc = N->getOpcode();
16958   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16959   bool LegalOps = !DCI.isBeforeLegalizeOps();
16960   SDLoc Loc(N);
16961 
16962   // TODO: QPX subtarget is deprecated. No transformation here.
16963   if (Subtarget.hasQPX() || !isOperationLegal(ISD::FMA, VT))
16964     return SDValue();
16965 
16966   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16967   // since (fnmsub a b c)=-0 while c-ab=+0.
16968   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16969     return SDValue();
16970 
16971   // (fma (fneg a) b c) => (fnmsub a b c)
16972   // (fnmsub (fneg a) b c) => (fma a b c)
16973   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16974     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16975 
16976   // (fma a (fneg b) c) => (fnmsub a b c)
16977   // (fnmsub a (fneg b) c) => (fma a b c)
16978   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16979     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16980 
16981   return SDValue();
16982 }
16983 
16984 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16985   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16986   if (!Subtarget.is64BitELFABI())
16987     return false;
16988 
16989   // If not a tail call then no need to proceed.
16990   if (!CI->isTailCall())
16991     return false;
16992 
16993   // If sibling calls have been disabled and tail-calls aren't guaranteed
16994   // there is no reason to duplicate.
16995   auto &TM = getTargetMachine();
16996   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16997     return false;
16998 
16999   // Can't tail call a function called indirectly, or if it has variadic args.
17000   const Function *Callee = CI->getCalledFunction();
17001   if (!Callee || Callee->isVarArg())
17002     return false;
17003 
17004   // Make sure the callee and caller calling conventions are eligible for tco.
17005   const Function *Caller = CI->getParent()->getParent();
17006   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
17007                                            CI->getCallingConv()))
17008       return false;
17009 
17010   // If the function is local then we have a good chance at tail-calling it
17011   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
17012 }
17013 
17014 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
17015   if (!Subtarget.hasVSX())
17016     return false;
17017   if (Subtarget.hasP9Vector() && VT == MVT::f128)
17018     return true;
17019   return VT == MVT::f32 || VT == MVT::f64 ||
17020     VT == MVT::v4f32 || VT == MVT::v2f64;
17021 }
17022 
17023 bool PPCTargetLowering::
17024 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
17025   const Value *Mask = AndI.getOperand(1);
17026   // If the mask is suitable for andi. or andis. we should sink the and.
17027   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
17028     // Can't handle constants wider than 64-bits.
17029     if (CI->getBitWidth() > 64)
17030       return false;
17031     int64_t ConstVal = CI->getZExtValue();
17032     return isUInt<16>(ConstVal) ||
17033       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
17034   }
17035 
17036   // For non-constant masks, we can always use the record-form and.
17037   return true;
17038 }
17039 
17040 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
17041 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
17042 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
17043 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
17044 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
17045 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
17046   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
17047   assert(Subtarget.hasP9Altivec() &&
17048          "Only combine this when P9 altivec supported!");
17049   EVT VT = N->getValueType(0);
17050   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17051     return SDValue();
17052 
17053   SelectionDAG &DAG = DCI.DAG;
17054   SDLoc dl(N);
17055   if (N->getOperand(0).getOpcode() == ISD::SUB) {
17056     // Even for signed integers, if it's known to be positive (as signed
17057     // integer) due to zero-extended inputs.
17058     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
17059     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
17060     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
17061          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
17062         (SubOpcd1 == ISD::ZERO_EXTEND ||
17063          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
17064       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17065                          N->getOperand(0)->getOperand(0),
17066                          N->getOperand(0)->getOperand(1),
17067                          DAG.getTargetConstant(0, dl, MVT::i32));
17068     }
17069 
17070     // For type v4i32, it can be optimized with xvnegsp + vabsduw
17071     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
17072         N->getOperand(0).hasOneUse()) {
17073       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17074                          N->getOperand(0)->getOperand(0),
17075                          N->getOperand(0)->getOperand(1),
17076                          DAG.getTargetConstant(1, dl, MVT::i32));
17077     }
17078   }
17079 
17080   return SDValue();
17081 }
17082 
17083 // For type v4i32/v8ii16/v16i8, transform
17084 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
17085 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
17086 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
17087 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
17088 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
17089                                           DAGCombinerInfo &DCI) const {
17090   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
17091   assert(Subtarget.hasP9Altivec() &&
17092          "Only combine this when P9 altivec supported!");
17093 
17094   SelectionDAG &DAG = DCI.DAG;
17095   SDLoc dl(N);
17096   SDValue Cond = N->getOperand(0);
17097   SDValue TrueOpnd = N->getOperand(1);
17098   SDValue FalseOpnd = N->getOperand(2);
17099   EVT VT = N->getOperand(1).getValueType();
17100 
17101   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
17102       FalseOpnd.getOpcode() != ISD::SUB)
17103     return SDValue();
17104 
17105   // ABSD only available for type v4i32/v8i16/v16i8
17106   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17107     return SDValue();
17108 
17109   // At least to save one more dependent computation
17110   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
17111     return SDValue();
17112 
17113   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17114 
17115   // Can only handle unsigned comparison here
17116   switch (CC) {
17117   default:
17118     return SDValue();
17119   case ISD::SETUGT:
17120   case ISD::SETUGE:
17121     break;
17122   case ISD::SETULT:
17123   case ISD::SETULE:
17124     std::swap(TrueOpnd, FalseOpnd);
17125     break;
17126   }
17127 
17128   SDValue CmpOpnd1 = Cond.getOperand(0);
17129   SDValue CmpOpnd2 = Cond.getOperand(1);
17130 
17131   // SETCC CmpOpnd1 CmpOpnd2 cond
17132   // TrueOpnd = CmpOpnd1 - CmpOpnd2
17133   // FalseOpnd = CmpOpnd2 - CmpOpnd1
17134   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
17135       TrueOpnd.getOperand(1) == CmpOpnd2 &&
17136       FalseOpnd.getOperand(0) == CmpOpnd2 &&
17137       FalseOpnd.getOperand(1) == CmpOpnd1) {
17138     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
17139                        CmpOpnd1, CmpOpnd2,
17140                        DAG.getTargetConstant(0, dl, MVT::i32));
17141   }
17142 
17143   return SDValue();
17144 }
17145